diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..0b3aa2389 --- /dev/null +++ b/.clang-format @@ -0,0 +1,99 @@ +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: None +AlignOperands: Align +AllowAllArgumentsOnNextLine: false +AllowAllConstructorInitializersOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Always +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: TopLevelDefinitions +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: ['__capability', '__output', '__ununsed', '_U_'] +BinPackArguments: false +BinPackParameters: false +BitFieldColonSpacing: None +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: false +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ContinuationIndentWidth: 8 +IndentCaseLabels: false +IndentCaseBlocks: false +IncludeBlocks: Merge +IncludeCategories: + # First three defines are order sensitive. + #defines.h is first + - Regex: '^[<\"](defines\.h)' + Priority: 1 + # config.h is second + - Regex: '^[<\"](config\.h)' + Priority: 2 + # common.h is third + - Regex: '^[<\"](common\.h)' + Priority: 3 + # Headers in "" with extension. + - Regex: '^"([A-Za-z0-9.\Q/-_\E])+"' + Priority: 4 + # Headers in <> from project libraries. + - Regex: '^<(lib|libopts|test)\/' + Priority: 5 + # Headers in <> with extension. + - Regex: '^<([A-Za-z0-9.\Q/-_\E])+>' + Priority: 6 +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 4 +KeepEmptyLinesAtTheStartOfBlocks: false +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PointerAlignment: Right +ReflowComments: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +TabWidth: 8 +UseCRLF: false +UseTab: Never diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..0147acde7 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,146 @@ +--- +Checks: '-*, +bugprone-argument-comment, +bugprone-assert-side-effect, +bugprone-bad-signal-to-kill-thread, +bugprone-branch-clone, +bugprone-copy-constructor-init, +bugprone-dangling-handle, +bugprone-dynamic-static-initializers, +bugprone-fold-init-type, +bugprone-forward-declaration-namespace, +bugprone-forwarding-reference-overload, +bugprone-inaccurate-erase, +bugprone-incorrect-roundings, +bugprone-integer-division, +bugprone-lambda-function-name, +bugprone-macro-parentheses, +bugprone-macro-repeated-side-effects, +bugprone-misplaced-operator-in-strlen-in-alloc, +bugprone-misplaced-pointer-arithmetic-in-alloc, +bugprone-misplaced-widening-cast, +bugprone-move-forwarding-reference, +bugprone-multiple-statement-macro, +bugprone-no-escape, +bugprone-not-null-terminated-result, +bugprone-parent-virtual-call, +bugprone-posix-return, +bugprone-reserved-identifier, +bugprone-sizeof-container, +bugprone-sizeof-expression, +bugprone-spuriously-wake-up-functions, +bugprone-string-constructor, +bugprone-string-integer-assignment, +bugprone-string-literal-with-embedded-nul, +bugprone-suspicious-enum-usage, +bugprone-suspicious-include, +bugprone-suspicious-memory-comparison, +bugprone-suspicious-memset-usage, +bugprone-suspicious-missing-comma, +bugprone-suspicious-semicolon, +bugprone-suspicious-string-compare, +bugprone-swapped-arguments, +bugprone-terminating-continue, +bugprone-throw-keyword-missing, +bugprone-too-small-loop-variable, +bugprone-undefined-memory-manipulation, +bugprone-undelegated-constructor, +bugprone-unhandled-self-assignment, +bugprone-unused-raii, +bugprone-unused-return-value, +bugprone-use-after-move, +bugprone-virtual-near-miss, +cert-dcl21-cpp, +cert-dcl58-cpp, +cert-err34-c, +cert-err52-cpp, +cert-err60-cpp, +cert-flp30-c, +cert-msc50-cpp, +cert-msc51-cpp, +cert-str34-c, +cppcoreguidelines-interfaces-global-init, +cppcoreguidelines-narrowing-conversions, +cppcoreguidelines-pro-type-member-init, +cppcoreguidelines-pro-type-static-cast-downcast, +cppcoreguidelines-slicing, +google-default-arguments, +google-explicit-constructor, +google-runtime-operator, +hicpp-exception-baseclass, +hicpp-multiway-paths-covered, +misc-misplaced-const, +misc-new-delete-overloads, +misc-no-recursion, +misc-non-copyable-objects, +misc-throw-by-value-catch-by-reference, +misc-unconventional-assign-operator, +misc-uniqueptr-reset-release, +modernize-avoid-bind, +modernize-concat-nested-namespaces, +modernize-deprecated-headers, +modernize-deprecated-ios-base-aliases, +modernize-loop-convert, +modernize-make-shared, +modernize-make-unique, +modernize-pass-by-value, +modernize-raw-string-literal, +modernize-redundant-void-arg, +modernize-replace-auto-ptr, +modernize-replace-disallow-copy-and-assign-macro, +modernize-replace-random-shuffle, +modernize-return-braced-init-list, +modernize-shrink-to-fit, +modernize-unary-static-assert, +modernize-use-auto, +modernize-use-bool-literals, +modernize-use-emplace, +modernize-use-equals-default, +modernize-use-equals-delete, +modernize-use-nodiscard, +modernize-use-noexcept, +modernize-use-nullptr, +modernize-use-override, +modernize-use-transparent-functors, +modernize-use-uncaught-exceptions, +mpi-buffer-deref, +mpi-type-mismatch, +openmp-use-default-none, +performance-faster-string-find, +performance-for-range-copy, +performance-implicit-conversion-in-loop, +performance-inefficient-algorithm, +performance-inefficient-string-concatenation, +performance-inefficient-vector-operation, +performance-move-const-arg, +performance-move-constructor-init, +performance-no-automatic-move, +performance-noexcept-move-constructor, +performance-trivially-destructible, +performance-type-promotion-in-math-fn, +performance-unnecessary-copy-initialization, +performance-unnecessary-value-param, +portability-simd-intrinsics, +readability-avoid-const-params-in-decls, +readability-const-return-type, +readability-container-size-empty, +readability-convert-member-functions-to-static, +readability-delete-null-pointer, +readability-deleted-default, +readability-inconsistent-declaration-parameter-name, +readability-make-member-function-const, +readability-misleading-indentation, +readability-misplaced-array-index, +readability-non-const-parameter, +readability-redundant-control-flow, +readability-redundant-declaration, +readability-redundant-function-ptr-dereference, +readability-redundant-smartptr-get, +readability-redundant-string-cstr, +readability-redundant-string-init, +readability-simplify-subscript-expr, +readability-static-accessed-through-instance, +readability-static-definition-in-anonymous-namespace, +readability-string-compare, +readability-uniqueptr-delete-release, +readability-use-anyofallof' diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..c8860546f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +# ignore clang-formatter and clang-tidy commit +8f3761d212d39d82a3f2cad39f9f92c1ebc3ca5c + diff --git a/.github/workflows/c-linter.yml b/.github/workflows/c-linter.yml new file mode 100644 index 000000000..30d9293f0 --- /dev/null +++ b/.github/workflows/c-linter.yml @@ -0,0 +1,31 @@ +name: cpp-linter + +on: pull_request + +jobs: + cpp-linter: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - run: | + echo "Build Application" + sudo apt-get -y install libpcap-dev autogen + ./autogen.sh + ./configure --disable-local-libopts + - uses: cpp-linter/cpp-linter-action@v2 + id: linter + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + style: file + version: 14 + lines-changed-only: true + files-changed-only: false + ignore: .github|docs|scripts + + - name: Fail fast?! + if: steps.linter.outputs.checks-failed > 0 + # for testing... + # run: echo "Some files failed the linting checks!" + # for actual deployment... + run: exit 1 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..6349571ad --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,70 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "master" ] + schedule: + - cron: '41 18 * * 0' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'cpp' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Use only 'java' to analyze code written in Java, Kotlin or both + # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # ℹī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + - run: | + echo "Build Application" + sudo apt-get -y install libpcap-dev autogen + ./autogen.sh + ./configure --disable-local-libopts + make + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/github-actions-ci.yml b/.github/workflows/github-actions-ci.yml new file mode 100644 index 000000000..21b5e2480 --- /dev/null +++ b/.github/workflows/github-actions-ci.yml @@ -0,0 +1,32 @@ +name: GitHub Actions Tests +run-name: ${{ github.actor }} is running tests using GitHub Actions +on: [push] +jobs: + tests: + runs-on: ubuntu-latest + steps: + - run: echo "The job was automatically triggered by a ${{ github.event_name }} event." + - run: echo "This job is now running on a ${{ runner.os }} server hosted by GitHub!" + - run: echo "The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}." + - name: Check out repository code + uses: actions/checkout@v3 + - run: echo "The ${{ github.repository }} repository has been cloned to the runner." + - name: List interfaces + run: ip a + - name: Install prereqs + run: sudo apt -y install autogen libpcap-dev + - name: Create configure script + run: ./autogen.sh + - name: configure + run: ./configure --with-testnic=eth0 --disable-local-libopts + - name: make + run: make + - name: make dist + run: make dist + - name: make dist-xz + run: make dist-xz + - name: List files in the repository + run: ls ${{ github.workspace }} + - name: tests + run: sudo make test + - run: echo "This test's status is ${{ job.status }}." diff --git a/.gitignore b/.gitignore index d3f872b61..ded2050b7 100644 --- a/.gitignore +++ b/.gitignore @@ -94,3 +94,6 @@ pcapsend test/*1 COPYING .vscode/ +.idea/ +build*/ +.run/ diff --git a/Makefile.am b/Makefile.am index 2d6f420c7..9f7e20876 100644 --- a/Makefile.am +++ b/Makefile.am @@ -59,6 +59,6 @@ DISTCLEANFILES = .tm_project.cache stamp-h1 *.tar.* MAINTAINERCLEANFILES = Makefile.in configure *.bak -EXTRA_DIST = doxygen.cfg.in autogen.sh \ +EXTRA_DIST = doxygen.cfg.in \ m4/libtool.m4 m4/ltoptions.m4 m4/ltsugar.m4 \ m4/ltversion.m4 m4/lt~obsolete.m4 acinclude.m4 diff --git a/README.md b/README.md index 552ac6ba2..cdf995923 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ Tcpreplay ========= [![Build Status](https://travis-ci.org/appneta/tcpreplay.svg?branch=master)](https://travis-ci.org/appneta/tcpreplay) +[![Test Status](https://github.com/appneta/tcpreplay/actions/workflows/github-actions-ci.yml/badge.svg)](https://github.com/appneta/tcpreplay/actions/workflows/github-actions-ci.yml) [![Coverity Scan Build Status](https://scan.coverity.com/projects/12017/badge.svg)](https://scan.coverity.com/projects/12017) [![Website](https://img.shields.io/website-up-down-green-red/http/shields.io.svg)](http://tcpreplay.appneta.com) +[![CodeQL](https://github.com/appneta/tcpreplay/actions/workflows/codeql.yml/badge.svg)](https://github.com/appneta/tcpreplay/actions/workflows/codeql.yml) +[![cpp-linter](https://github.com/appneta/tcpreplay/actions/workflows/c-linter.yml/badge.svg)](https://github.com/appneta/tcpreplay/actions/workflows/c-linter.yml) Tcpreplay is a suite of [GPLv3] licensed utilities for UNIX (and Win32 under [Cygwin]) operating systems for editing and replaying network traffic which diff --git a/configure.ac b/configure.ac index 11a1e4eaa..387219deb 100644 --- a/configure.ac +++ b/configure.ac @@ -4,7 +4,7 @@ dnl $Id$ AC_PREREQ([2.69]) dnl Set version info here! -AC_INIT([tcpreplay],[4.4.1],[https://github.com/appneta/tcpreplay/issues],[tcpreplay],[http://tcpreplay.sourceforge.net/]) +AC_INIT([tcpreplay],[4.4.4],[https://github.com/appneta/tcpreplay/issues],[tcpreplay],[http://tcpreplay.sourceforge.net/]) AC_CONFIG_SRCDIR([src/tcpreplay.c]) AC_CONFIG_HEADERS([src/config.h]) AC_CONFIG_AUX_DIR(config) @@ -14,7 +14,7 @@ AM_WITH_DMALLOC dnl People building from GitHub need the same version of Autogen as I'm using dnl or specify --disable-local-libopts to force using the locally-installed dnl copy of libopts rather than the source in the `./libopts/` directory. -MAINTAINER_AUTOGEN_VERSION=5.18.12 +MAINTAINER_AUTOGEN_VERSION=5.18.16 AC_CONFIG_MACRO_DIR([m4]) @@ -405,12 +405,28 @@ if test "x$enable_asan" = "xyes"; then [AC_MSG_ERROR([libasan.so not found, this is required for --enable-asan])]) CFLAGS="${CFLAGS} -O1 -g -fsanitize=address -fno-omit-frame-pointer" dnl -lasan always need to be the first library - LDFLAGS="-lasan ${LDFLAGS}" + LDFLAGS="-fsanitize=address ${LDFLAGS}" else build_asan=no fi AC_SUBST(build_asan) +AC_ARG_ENABLE([tsan], + AS_HELP_STRING([--enable-tsan],[Enable Thread Sanitizer support])) +if test "x$enable_tsan" = "xyes"; then + build_tsan=yes + CFLAGS="${CFLAGS} -O1 -g -fsanitize=thread -fno-omit-frame-pointer" + dnl -ltsan always need to be the first library + LDFLAGS="-fsanitize=thread ${LDFLAGS}" +else + build_tsan=no +fi +AC_SUBST(build_tsan) + +if test "$build_asan" = "yes" -a "$build_tsan" = "yes" ; then + AC_MSG_ERROR([--enable-asan and --eanble-tsan are mutually exclusive]) +fi + dnl Enable debugging in code/compiler options debug=no debug_flag=NDEBUG @@ -658,7 +674,8 @@ AC_ARG_WITH(libpcap, for dir in . lib lib64 lib/${host_cpu}-${host_os} ${host_cpu}-${host_os} lib/${MULTIARCH} ${MULTIARCH}; do sharefile=$(ls ${testdir}/$dir/libpcap${ext}* 2> /dev/null | sort | head -n1) if test -n "${sharefile}"; then - LPCAPLIB="-L$(dirname ${sharefile}) -lpcap" + LPCAP_LD_LIBRARY_PATH="$(dirname ${sharefile})" + LPCAPLIB="-L$LPCAP_LD_LIBRARY_PATH -lpcap" foundpcap=$testdir break fi @@ -682,36 +699,6 @@ AC_ARG_WITH(libpcap, fi done - if ! test $foundpcap = no; then - ## could be PF_RING - # - # library is static and in PF_RING build tree - # - # Need access to libpfring library - # and must find an associated libpfring.a - if test -n "${with_pfring_lib}"; then - if test -f ${with_pfring_lib}; then - pf_ring_lib=${with_pfring_lib} - pf_ring_found=yes - else - AC_MSG_ERROR(["Unable to find PF_RING library ${with_pfring_lib}"]) - fi - else - ## search locally for most likely PF_RING library - for lib in ${foundpcap}/../lib/libs/libpfring_zc_${host_cpu}.a \ - ${foundpcap}/../lib/libs/libpfring_dna_${host_cpu}.a \ - ${foundpcap}/../lib/libs/libpfring_zero_${host_cpu}.a \ - ${foundpcap}/../lib/libs/libpfring_nt_${host_cpu}.a \ - ${foundpcap}/../lib/libpfring.a; do - if test -f "${lib}"; then - pf_ring_lib=${lib} - pf_ring_found=yes - break - fi - done - fi - break - fi done fi @@ -732,13 +719,13 @@ AC_ARG_WITH(libpcap, # and was created to address portability issues. Unfortunately, the script is not updated properly # outside of the base distribution. Examples: PF_RING requires 'pthreads', 'numa' and 'rt', but # this is not reflect that in the script. OS X Xcode 10.11 SDK creates its own very broken - # 'pcap-config' script that only occasionally works for dynamic definitions, and defintely + # 'pcap-config' script that only occasionally works for dynamic definitions, and definitely # does not work for static. # # The ability to enable this script exists for corner cases where libpcap distributions starts # using even more libraries than I am currently not aware of. Originally, you only had to worry # about 'nl', but now we have to be prepared to add 'nl-3', 'nl-genl-3' and 'dbus-1' to make - # libpcap fucntional. In the future, there may be more. + # libpcap functional. In the future, there may be more. # # (sigh) # @@ -838,6 +825,21 @@ else AC_MSG_RESULT($foundpcap) fi +## could be PF_RING +# +# library is static and in PF_RING build tree +# +# Need access to libpfring library +# and must find an associated libpfring.a +if test -n "${with_pfring_lib}"; then + if test -f ${with_pfring_lib}; then + pf_ring_lib=${with_pfring_lib} + pf_ring_found=yes + else + AC_MSG_ERROR(["Unable to find PF_RING library ${with_pfring_lib}"]) + fi +fi + # libpcap can require libnl AC_SEARCH_LIBS([nl_handle_alloc], [nl], [AC_MSG_NOTICE([Unable to find nl library - may be needed by libpcap])]) @@ -886,11 +888,19 @@ if test -n "$LPCAPINCDIR"; then else OLDCFLAGS="$CFLAGS" LPCAPINCDIR=$(echo $CFLAGS | sed -e 's/^\-I//') - LPCAPINC="$LPCAPINCDIR/pcap.h" + if test -d "$LPCAPINCDIR/pcap"; then + LPCAPINC="$LPCAPINCDIR/pcap/pcap.h" + else + LPCAPINC="$LPCAPINCDIR/pcap.h" + fi fi LIBS="$LPCAPLIB" -AC_SEARCH_LIBS([pcap_get_pfring_id], [pcap], AC_DEFINE([HAVE_PF_RING_PCAP], [1], [Do we have PF_RING libpcap support?])) +AC_SEARCH_LIBS([pcap_get_pfring_id], + [pcap], + AC_DEFINE([HAVE_PF_RING_PCAP], + , + [${with_pfring_lib} numa pthread rt])) ## Does libpcap work with selected libraries? AC_SEARCH_LIBS([pcap_close], [pcap], @@ -901,107 +911,55 @@ AC_SUBST(LPCAPLIB) dnl Check to see what version of libpcap -dnl this code has been reduced a lot, but probably still could be -dnl reduced quite a bit more if we chose too -AC_MSG_CHECKING(for libpcap version) - -dnl 0.9.6 (which is still thinks it is 0.9.5 due to a bug) introduces an important -dnl fix for OSX. See: http://tcpreplay.synfin.net/trac/ticket/167 -AC_RUN_IFELSE([AC_LANG_PROGRAM([[ -#include -#include -#include -#include "$LPCAPINC" -#define PCAP_TEST "0.9.6" -]], [[ -/* - * simple proggy to test the version of libpcap - * returns zero if version >= 0.9.6 - * or one otherwise - */ - if (strncmp(pcap_lib_version(), PCAP_TEST, 3) >= 0) - exit(0); - - if (strncmp(pcap_lib_version(), PCAP_TEST, 5) >= 0) { - printf("%s ", pcap_lib_version()); - exit(0); - } - - exit(1); -]])], - [libpcap_version_096=yes], - [libpcap_version_096=no], - [libpcap_version_096=yes] -) - -AC_RUN_IFELSE([AC_LANG_PROGRAM([[ -#include -#include -#include -#include "$LPCAPINC" -#define PCAP_TEST "0.8" -]], [[ -/* - * simple proggy to test the version of libpcap - * returns zero if version >= 0.8.0 - * or one otherwise - */ - if (strncmp(pcap_lib_version(), PCAP_TEST, 3) >= 0) - exit(0); - - /* winpcap? */ - if (strncmp(pcap_lib_version(), "WinPcap", 7) == 0) - exit(0); - - exit(1); -]])], - [libpcap_ver8=yes], - [libpcap_ver8=no], - [libpcap_ver8=yes] -) - -AC_RUN_IFELSE([AC_LANG_PROGRAM([[ +AC_MSG_CHECKING(libpcap version) +libpcap_version=unknown +libpcap_version_096=no +cat >conftest.c < -#include #include #include "$LPCAPINC" -#define PCAP_TEST "0.7.2" -extern const char pcap_version[[]]; /* double up since autoconf escapes things */ -]], [[ /* - * simple proggy to test the version of libpcap - * returns zero if version >= 0.7.2 - * or one otherwise + * simple proggy to get the version of libpcap */ - if (strncmp(pcap_lib_version(), PCAP_TEST, 3) >= 0) - exit(0); - - if (strncmp(pcap_version, PCAP_TEST, 5) >= 0) - exit(0); + int main() { + printf("%s\n", pcap_lib_version()); + return 0; +} +EOF +${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LPCAPLIB \ + conftest.c $LIBS >/dev/null 2>&1 +if test -x conftest ; then + full_libpcap_version=$(LD_LIBRARY_PATH="$LPCAP_LD_LIBRARY_PATH" ./conftest) + libpcap_version=$(echo "$full_libpcap_version" | ${CUT} -d' ' -f3) + pcap_version_ok=yes +fi +AC_MSG_RESULT([$libpcap_version]) +rm -rf conftest.* core core.conftest 2>&1 > /dev/null + +AC_MSG_CHECKING(for valid libpcap version) +if test x$libpcap_version != xunknown; then + libpcap_major=$(echo ${libpcap_version} | ${CUT} -d '.' -f1) + libpcap_minor=$(echo ${libpcap_version} | ${CUT} -d '.' -f2) + libpcap_build=$(echo ${libpcap_version} | ${CUT} -d '.' -f3) + if test $libpcap_major -eq 0 && \ + (test $libpcap_minor -lt 7 || \ + (test $libpcap_minor -eq 7 && test $libpcap_build -lt 2)) + then + AC_MSG_ERROR([Libpcap versions < 0.7.2 are not supported + Please upgrade to version 0.7.2 or better. Your version is $libpcap_version]) + fi - exit(1); -]])], - [libpcap_ver7=yes], - [libpcap_ver7=no], - [libpcap_ver7=yes] -) + dnl 0.9.6 (which is still thinks it is 0.9.5 due to a bug) introduces an important + dnl fix for OSX. See: http://tcpreplay.synfin.net/trac/ticket/167 + if test $libpcap_major -gt 0 || \ + (test $libpcap_minor -eq 9 && test $libpcap_build -ge 6) + then + libpcap_version_096=yes + fi -if test x$libpcap_ver8 = xyes ; then - AC_MSG_RESULT(>= 0.8.0) -elif test x$libpcap_ver7 = xyes ; then - AC_MSG_RESULT(>= 0.7.2) + AC_MSG_RESULT([yes]) else - AC_MSG_ERROR([Libpcap versions < 0.7.2 are not supported - Please upgrade to version 0.7.2 or better]) -fi - -libpcap_version=unknown -if test x$libpcap_version_096 = xyes ; then - libpcap_version=">= 0.9.6" -elif test x$libpcap_ver8 = xyes ; then - libpcap_version=">= 0.8.0" -elif test x$libcap_ver7 = xyes ; then - libpcap_version=">= 0.7.0" + AC_MSG_RESULT([unknown]) fi dnl Check for pcap_setnonblock() @@ -1681,8 +1639,8 @@ int main (int argc, char *argv[]) { if (strncmp(PCAPNAV_VERSION, PCAPNAV_TEST, 3) >= 0) - exit(0); - exit(1); + return 0; + return 1; } ]])],[libpcapnav_ver=yes AC_MSG_RESULT(>= 0.4)],[libpcapnav_ver=no AC_MSG_RESULT(< 0.4)],[libpcapnav_ver=no @@ -1717,7 +1675,7 @@ case "$host_os" in case "$host_cpu" in # XXX: should also check that they don't do weird things - alpha*|hp*|mips*|sparc*|ia64) + alpha*|arm*|hp*|mips*|sparc*|ia64) unaligned_cv_fail=yes ;; @@ -1726,26 +1684,27 @@ case "$host_os" in #include #include #include + #include unsigned char a[[5]] = { 1, 2, 3, 4, 5 }; - main() { + int main() { unsigned int i; pid_t pid; int status; /* avoid "core dumped" message */ pid = fork(); if (pid < 0) - exit(2); + return 2; if (pid > 0) { /* parent */ pid = waitpid(pid, &status, 0); if (pid < 0) - exit(3); - exit(!WIFEXITED(status)); + return 3; + return !WIFEXITED(status); } /* child */ i = *(unsigned int *)&a[[1]]; printf("%d\n", i); - exit(0); + return 0; } EOF ${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS \ @@ -1808,7 +1767,7 @@ fi dnl No 'make test' when cross compile AC_MSG_CHECKING(for 'make test' profile) -if test "$host" == "$build" ; then +if test "$host" = "$build" ; then AC_MSG_RESULT([yes]) else AC_MSG_WARN(Unable to do tests when cross-compiling) diff --git a/docs/CHANGELOG b/docs/CHANGELOG index 410a07e52..ca8129e82 100644 --- a/docs/CHANGELOG +++ b/docs/CHANGELOG @@ -1,3 +1,33 @@ +06/04/2023 Version 4.4.4 + - overflow check fix for parse_mpls (#795) + - tcpreplay-edit: prevent L2 flooding of ipv6 unicast packets (#793) + - CVE-2023-27786 bugs caused by strtok_r (#782 #784 #785 #786 #787 #788) + - CVE-2023-27783 reachable assert in tcpedit_dlt_cleanup (#780) + - add CI and C/C++ Linter and CodeQL (#773) + - reachable assert in fast_edit_packet (#772) + +01/01/2023 Version 4.4.3 + - upgrade autogen/libopts to version 5.18.16 (#759) + - avoid implicit int in configure.ac (#757) + - remove invalid assert in tree (#756) + - program exit after send error (#751) + - make libpcap version test more robust (#750) + - looping inflates some packet counters (#749) + +08/28/2022 Version 4.4.2 + - fix tests when building in a directory outside source tree (#767) + - remove autogen.sh from distribution tarballs (#745) + - CVE-2022-37048 heap-overflow in get_l2len_protocol (#735) + - replaying on a loopback interface is broken (#732) + - replay edit with both --loop and --preload_pcap options (#729) + - test suite bus error on armhf (#725) + - CVE-2022-28487 format string vulnerability in fix_ipv6_checksums (#723) + - CVE-2022-27942 heap-overflow in parse_mpls (#719) + - CVE-2022-27940 CVE-2022-37047 CVE-2022-37049 heap-overflow in get_ipv6_next (#718) + - CVE-2022-27939 reachable assertion in get_layer4_v6 (#717) + - CVE-2022-25484 CVE-2022-27941 heap buffer overflow in get_l2len_protocol (#716) + - remove bash-only test in configure script (#714) + 02/12/2022 Version 4.4.1 - fix support for piping PCAP files from STDIN (#708) - build failures Debian/kfreebsd (#706) diff --git a/docs/CREDIT b/docs/CREDIT index 36349ad47..467e076cb 100644 --- a/docs/CREDIT +++ b/docs/CREDIT @@ -105,5 +105,11 @@ Dave Craig Vincent Bernat - tcprewrite: fix DLT name for DLT_C_JNPR_ETHER in documentation -Halver +Halver - specify directories as files + +Florian Weimer + - Avoid implicit int in configure.ac + +David Guti + - prevent L2 flooding of ipv6 unicast packets for tcpreplay-edit diff --git a/lib/strlcat.c b/lib/strlcat.c index c94e90dee..260a7aa2e 100644 --- a/lib/strlcat.c +++ b/lib/strlcat.c @@ -16,7 +16,6 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include #include /* @@ -29,27 +28,27 @@ size_t strlcat(char *dst, const char *src, size_t dsize) { - const char *odst = dst; - const char *osrc = src; - size_t n = dsize; - size_t dlen; + const char *odst = dst; + const char *osrc = src; + size_t n = dsize; + size_t dlen; - /* Find the end of dst and adjust bytes left but don't go past end. */ - while (n-- != 0 && *dst != '\0') - dst++; - dlen = dst - odst; - n = dsize - dlen; + /* Find the end of dst and adjust bytes left but don't go past end. */ + while (n-- != 0 && *dst != '\0') + dst++; + dlen = dst - odst; + n = dsize - dlen; - if (n-- == 0) - return(dlen + strlen(src)); - while (*src != '\0') { - if (n != 0) { - *dst++ = *src; - n--; - } - src++; - } - *dst = '\0'; + if (n-- == 0) + return (dlen + strlen(src)); + while (*src != '\0') { + if (n != 0) { + *dst++ = *src; + n--; + } + src++; + } + *dst = '\0'; - return(dlen + (src - osrc)); /* count does not include NUL */ + return (dlen + (src - osrc)); /* count does not include NUL */ } diff --git a/lib/strlcpy.c b/lib/strlcpy.c index 2fa498c39..c8d9d3e80 100644 --- a/lib/strlcpy.c +++ b/lib/strlcpy.c @@ -16,7 +16,6 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include #include /* @@ -27,24 +26,24 @@ size_t strlcpy(char *dst, const char *src, size_t dsize) { - const char *osrc = src; - size_t nleft = dsize; + const char *osrc = src; + size_t nleft = dsize; - /* Copy as many bytes as will fit. */ - if (nleft != 0) { - while (--nleft != 0) { - if ((*dst++ = *src++) == '\0') - break; - } - } + /* Copy as many bytes as will fit. */ + if (nleft != 0) { + while (--nleft != 0) { + if ((*dst++ = *src++) == '\0') + break; + } + } - /* Not enough room in dst, add NUL and traverse rest of src. */ - if (nleft == 0) { - if (dsize != 0) - *dst = '\0'; /* NUL-terminate dst */ - while (*src++) - ; - } + /* Not enough room in dst, add NUL and traverse rest of src. */ + if (nleft == 0) { + if (dsize != 0) + *dst = '\0'; /* NUL-terminate dst */ + while (*src++) + ; + } - return(src - osrc - 1); /* count does not include NUL */ + return (src - osrc - 1); /* count does not include NUL */ } diff --git a/libopts/COPYING.gplv3 b/libopts/COPYING.gplv3 index 26d6fd2e7..7718bd18f 100644 --- a/libopts/COPYING.gplv3 +++ b/libopts/COPYING.gplv3 @@ -1,7 +1,7 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + Copyright (C) 1992-2018 by Bruce Korb - all rights reserved Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. diff --git a/libopts/COPYING.lgplv3 b/libopts/COPYING.lgplv3 index b6db23288..f7b8c6397 100644 --- a/libopts/COPYING.lgplv3 +++ b/libopts/COPYING.lgplv3 @@ -1,7 +1,7 @@ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + Copyright (C) 1992-2018 by Bruce Korb - all rights reserved Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -10,7 +10,7 @@ the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. - 0. Additional Definitions. + 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU @@ -111,7 +111,7 @@ the following: a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked - Version. + Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the diff --git a/libopts/COPYING.mbsd b/libopts/COPYING.mbsd index 74948befa..b74eb0027 100644 --- a/libopts/COPYING.mbsd +++ b/libopts/COPYING.mbsd @@ -1,4 +1,4 @@ -Copyright (C) 1992-2015 by Bruce Korb - all rights reserved +Copyright (C) 1992-2018 by Bruce Korb - all rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/libopts/Makefile.am b/libopts/Makefile.am index 689e51b32..8248ba76a 100644 --- a/libopts/Makefile.am +++ b/libopts/Makefile.am @@ -7,19 +7,19 @@ noinst_LTLIBRARIES = libopts.la endif libopts_la_SOURCES = libopts.c libopts_la_CPPFLAGS = -I$(srcdir) -#libopts_la_LDFLAGS = -version-info 41:1:16 +libopts_la_LDFLAGS = -version-info 42:1:17 EXTRA_DIST = BUILT_SOURCES = MOSTLYCLEANFILES = libopts.c: $(BUILT_SOURCES) - @: do-nothing rule to avoid default SCCS get +@: do-nothing rule to avoid default SCCS get # Makefile fragment from gnulib-s stdnoreturn module: # -_NORETURN_H=$(srcdir)/compat/_Noreturn.h -EXTRA_DIST += $(srcdir)/compat/_Noreturn.h +_NORETURN_H=$(srcdir)/_Noreturn.h +EXTRA_DIST += _Noreturn.h BUILT_SOURCES += $(STDNORETURN_H) if GL_GENERATE_STDNORETURN_H stdnoreturn.h: stdnoreturn.in.h $(top_builddir)/config.status $(_NORETURN_H) @@ -38,11 +38,11 @@ EXTRA_DIST += stdnoreturn.in.h EXTRA_DIST += \ COPYING.gplv3 COPYING.lgplv3 COPYING.mbsd \ - MakeDefs.inc README ag-char-map.h \ - alias.c ao-strs.c ao-strs.h \ - autoopts.c autoopts.h autoopts/options.h \ - autoopts/project.h autoopts/usage-txt.h boolean.c \ - check.c compat/_Noreturn.h compat/compat.h \ + MakeDefs.inc README _Noreturn.h \ + ag-char-map.h alias.c ao-strs.c \ + ao-strs.h autoopts.c autoopts.h \ + autoopts/options.h autoopts/project.h autoopts/usage-txt.h \ + boolean.c check.c compat/compat.h \ compat/pathfind.c compat/snprintf.c compat/strchr.c \ compat/strdup.c compat/windows-config.h configfile.c \ cook.c enum.c env.c \ @@ -54,7 +54,8 @@ EXTRA_DIST += \ option-value-type.h option-xat-attribute.c option-xat-attribute.h \ parse-duration.c parse-duration.h pgusage.c \ proto.h putshell.c reset.c \ - restore.c save.c sort.c \ - stack.c stdnoreturn.in.h streqvcmp.c \ - text_mmap.c time.c tokenize.c \ - usage.c version.c + restore.c save-flags.c save-flags.h \ + save.c sort.c stack.c \ + stdnoreturn.in.h streqvcmp.c text_mmap.c \ + time.c tokenize.c usage.c \ + version.c diff --git a/libopts/README b/libopts/README index 98e4f3c67..5c8b9d767 100644 --- a/libopts/README +++ b/libopts/README @@ -115,7 +115,7 @@ These macros work as follows: LICENSING: -This material is Copyright (C) 1992-2015 by Bruce Korb. You are +This material is Copyright (C) 1992-2018 by Bruce Korb. You are licensed to use this under the terms of either the GNU Lesser General Public License (see: COPYING.lgpl), or, at your option, the modified Berkeley Software Distribution License (see: COPYING.mbsd). Both of diff --git a/libopts/compat/_Noreturn.h b/libopts/_Noreturn.h similarity index 100% rename from libopts/compat/_Noreturn.h rename to libopts/_Noreturn.h diff --git a/libopts/ag-char-map.h b/libopts/ag-char-map.h index b386e4e86..cced2303a 100644 --- a/libopts/ag-char-map.h +++ b/libopts/ag-char-map.h @@ -1,6 +1,6 @@ /* * 29 bits for 46 character classifications - * generated by char-mapper on 08/29/16 at 14:35:22 + * generated by char-mapper on 08/26/18 at 10:44:22 * * This file contains the character classifications * used by AutoGen and AutoOpts for identifying tokens. @@ -8,7 +8,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/alias.c b/libopts/alias.c index 85a90cc8c..231f275d5 100644 --- a/libopts/alias.c +++ b/libopts/alias.c @@ -12,7 +12,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -31,7 +31,7 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -LOCAL tSuccess +static tSuccess too_many_occurrences(tOptions * opts, tOptDesc * od) { if ((opts->fOptSet & OPTPROC_ERRSTOP) != 0) { diff --git a/libopts/ao-strs.c b/libopts/ao-strs.c index 514eedc43..7f5937260 100644 --- a/libopts/ao-strs.c +++ b/libopts/ao-strs.c @@ -6,7 +6,7 @@ * From the definitions ao-strs.def * and the template file strings * - * Copyright (C) 2011-2015 Bruce Korb, all rights reserved. + * Copyright (C) 2011-2018 Bruce Korb, all rights reserved. * This is free software. It is licensed for use, modification and * redistribution under the terms of the * Modified (3 clause) Berkeley Software Distribution License @@ -38,160 +38,164 @@ */ #include "ao-strs.h" -char const ao_strs_strtable[6670] = +char const ao_strs_strtable[6714] = /* 0 */ "-_^\0" /* 4 */ " %s%s\n\0" -/* 12 */ "auto-options\0" -/* 25 */ "program\0" -/* 33 */ "%%-%ds %%s\n\0" -/* 45 */ "\n" +/* 12 */ "\n\0" +/* 64 */ "\n" "%s\n\n\0" -/* 51 */ "=file\0" -/* 57 */ "=Mbr\0" -/* 62 */ "=Cplx\0" -/* 68 */ "[=arg]\0" -/* 75 */ "--%2$s%1$s\0" -/* 86 */ "=Tim\0" -/* 91 */ "none\0" -/* 96 */ "# preset/initialization file\n" +/* 70 */ "=file\0" +/* 76 */ "=Mbr\0" +/* 81 */ "=Cplx\0" +/* 87 */ "[=arg]\0" +/* 94 */ "--%2$s%1$s\0" +/* 105 */ "=Tim\0" +/* 110 */ "none\0" +/* 115 */ "# preset/initialization file\n" "# %s#\n\0" -/* 134 */ " %3s %-14s %s\0" -/* 148 */ "%s\0" -/* 151 */ "T/F\0" -/* 155 */ "\n" +/* 153 */ " %3s %-14s %s\0" +/* 167 */ "%s\0" +/* 170 */ "T/F\0" +/* 174 */ "\n" "%s\n\n" "%s\0" -/* 163 */ "Fil\0" -/* 167 */ "KWd\0" -/* 171 */ "Mbr\0" -/* 175 */ "Cpx\0" -/* 179 */ "no \0" -/* 183 */ "Num\0" -/* 187 */ "opt\0" -/* 191 */ "YES\0" -/* 195 */ "Str\0" -/* 199 */ "Tim\0" -/* 203 */ "\t\t\t\t- \0" -/* 210 */ "\t\t\t\t \0" -/* 217 */ "\t\t\t\t-- and \0" -/* 229 */ "\t\t\t\t%s\n\0" -/* 237 */ " \0" -/* 244 */ " \0" -/* 250 */ " \0" -/* 254 */ " \0" -/* 257 */ "all\0" -/* 261 */ " \t\n" +/* 182 */ "Fil\0" +/* 186 */ "KWd\0" +/* 190 */ "Mbr\0" +/* 194 */ "Cpx\0" +/* 198 */ "no \0" +/* 202 */ "Num\0" +/* 206 */ "opt\0" +/* 210 */ "YES\0" +/* 214 */ "Str\0" +/* 218 */ "Tim\0" +/* 222 */ "\t\t\t\t- \0" +/* 229 */ "\t\t\t\t \0" +/* 236 */ "\t\t\t\t-- and \0" +/* 248 */ "\t\t\t\t%s\n\0" +/* 256 */ " \0" +/* 263 */ " \0" +/* 269 */ " \0" +/* 273 */ " \0" +/* 276 */ "all\0" +/* 280 */ " \t\n" ":=\0" -/* 267 */ "%s_%s_%d=\0" -/* 277 */ "''\0" -/* 280 */ " ;;\n\n\0" -/* 293 */ "'\n\n\0" -/* 297 */ "\n\0" -/* 304 */ " %s\n\0" -/* 310 */ "%%-%ds\0" -/* 317 */ "\n" +/* 286 */ "%s_%s_%d=\0" +/* 296 */ "''\0" +/* 299 */ " ;;\n\n\0" +/* 312 */ "'\n\n\0" +/* 316 */ "\n\0" +/* 323 */ " %s\n\0" +/* 329 */ "%%-%ds\0" +/* 336 */ "\n" "export %s_%s_%d\n\0" -/* 335 */ "false\0" -/* 341 */ " -* )\n\0" -/* 351 */ "flag\0" -/* 356 */ "INVALID-%d\0" -/* 367 */ "*INVALID*\0" -/* 377 */ "\\n\\\n\0" -/* 382 */ " --* )\n\0" -/* 393 */ "--\0" -/* 396 */ "LONGUSAGE\0" -/* 406 */ " %s\n\0" -/* 422 */ "\\%03o\0" -/* 428 */ "more\0" -/* 433 */ "<%s type=nested>\n\0" -/* 451 */ "%s\n\0" -/* 455 */ "%s\n" +/* 354 */ "false\0" +/* 360 */ " -* )\n\0" +/* 370 */ "flag\0" +/* 375 */ "INVALID-%d\0" +/* 386 */ "*INVALID*\0" +/* 396 */ "\\n\\\n\0" +/* 401 */ " --* )\n\0" +/* 412 */ "--\0" +/* 415 */ "LONGUSAGE\0" +/* 425 */ " %s\n\0" +/* 441 */ "\\%03o\0" +/* 447 */ "more\0" +/* 452 */ "<%s type=nested>\n\0" +/* 470 */ "%s\n\0" +/* 474 */ "%s\n" " \0" -/* 461 */ "OPT_ARG_NEEDED=NO\0" -/* 479 */ "<%s/>\n\0" -/* 486 */ "OPT_ARG_NEEDED=OK\0" -/* 504 */ "\t\0" -/* 506 */ "<%s>\0" -/* 511 */ "option\0" -/* 518 */ "\n" +/* 480 */ "OPT_ARG_NEEDED=NO\0" +/* 498 */ "<%s/>\n\0" +/* 505 */ "OPT_ARG_NEEDED=OK\0" +/* 523 */ "\t\0" +/* 525 */ "<%s>\0" +/* 530 */ "option\0" +/* 537 */ "\n" "export %s_%s\n\0" -/* 533 */ "%s_%s=\0" -/* 540 */ " | \0" -/* 544 */ "PAGER\0" -/* 550 */ "%1$s %2$s ; rm -f %2$s\0" -/* 573 */ " + \0" -/* 577 */ " puts(_(%s));\n\0" -/* 593 */ "\\'\0" -/* 596 */ "'%s'\0" -/* 601 */ " -- %s\0" -/* 608 */ "%s_%s_TEXT='\0" -/* 621 */ "#! %s\n\0" -/* 628 */ "\n" +/* 552 */ "%s_%s=\0" +/* 559 */ " | \0" +/* 563 */ "PAGER\0" +/* 569 */ "%1$s %2$s ; rm -f %2$s\0" +/* 592 */ " + \0" +/* 596 */ " puts(_(%s));\n\0" +/* 612 */ "\\'\0" +/* 615 */ "'%s'\0" +/* 620 */ " -- %s\0" +/* 627 */ "%s_%s_TEXT='\0" +/* 640 */ "#! %s\n\0" +/* 647 */ "\n" "env | grep '^%s_'\n\0" -/* 648 */ "=%1$lu # 0x%1$lX\n\0" -/* 666 */ "stdout\0" -/* 673 */ "%A %B %e, %Y at %r %Z\0" -/* 695 */ "TMPDIR\0" -/* 702 */ "%s/use-%u.XXXXXX\0" -/* 719 */ "true\0" -/* 724 */ "<%s type=%s>\0" -/* 737 */ "VERSION\0" -/* 745 */ "#x%02X;\0" -/* 753 */ "OPT_ARG_NEEDED=YES\0" -/* 772 */ "'\\''\0" -/* 777 */ " '%s'\0" -/* 783 */ "libopts misguessed length of string\n\0" -/* 820 */ "\n" +/* 667 */ "=%1$lu # 0x%1$lX\n\0" +/* 685 */ "stdout\0" +/* 692 */ "%A %B %e, %Y at %r %Z\0" +/* 714 */ "TMPDIR\0" +/* 721 */ "%s/use-%u.XXXXXX\0" +/* 738 */ "true\0" +/* 743 */ "<%s type=%s>\0" +/* 756 */ "VERSION\0" +/* 764 */ "#x%02X;\0" +/* 772 */ "OPT_ARG_NEEDED=YES\0" +/* 791 */ "\n" + "# %s -- %s\n\0" +/* 804 */ "# DEFAULT: \0" +/* 816 */ "'\\''\0" +/* 821 */ " '%s'\0" +/* 827 */ "libopts misguessed length of string\n\0" +/* 864 */ "\n" "OPTION_CT=0\n\0" -/* 834 */ "set --\0" -/* 841 */ "/tmp\0" -/* 846 */ " ;;\n\n\0" -/* 863 */ " '%c' )\n\0" -/* 879 */ " '%s' )\n\0" -/* 895 */ " '%s' | \\\n\0" -/* 913 */ "<%1$s type=boolean>%2$s\n\0" -/* 945 */ "# From the %s option definitions\n" +/* 878 */ "set --\0" +/* 885 */ "/tmp\0" +/* 890 */ " ;;\n\n\0" +/* 907 */ " '%c' )\n\0" +/* 923 */ " '%s' )\n\0" +/* 939 */ " '%s' | \\\n\0" +/* 957 */ "<%1$s type=boolean>%2$s\n\0" +/* 989 */ "# From the %s option definitions\n" "#\n\0" -/* 982 */ "echo 'Warning: Cannot load options files' >&2\0" -/* 1029 */ "echo 'Warning: Cannot save options files' >&2\0" -/* 1076 */ "echo 'Warning: Cannot suppress the loading of options files' >&2\0" -/* 1142 */ "<%1$s type=integer>0x%2$lX\n\0" -/* 1177 */ "%1$s_%2$s_TEXT='no %2$s text'\n\0" -/* 1208 */ "%1$s_%2$s_MODE='%3$s'\n" +/* 1026 */ "echo 'Warning: Cannot load options files' >&2\0" +/* 1073 */ "echo 'Warning: Cannot save options files' >&2\0" +/* 1120 */ "echo 'Warning: Cannot suppress the loading of options files' >&2\0" +/* 1186 */ "<%1$s type=integer>0x%2$lX\n\0" +/* 1221 */ "%1$s_%2$s_TEXT='no %2$s text'\n\0" +/* 1252 */ "%1$s_%2$s_MODE='%3$s'\n" "export %1$s_%2$s_MODE\n\0" -/* 1253 */ "%1$s_%2$s='%3$s'\n" +/* 1297 */ "%1$s_%2$s='%3$s'\n" "export %1$s_%2$s\n\0" -/* 1288 */ "%1$s_%2$s_CT=%3$d\n" +/* 1332 */ "%1$s_%2$s_CT=%3$d\n" "export %1$s_%2$s_CT\n\0" -/* 1327 */ "OPTION_CT=%d\n" +/* 1371 */ "OPTION_CT=%d\n" "export OPTION_CT\n\0" -/* 1358 */ "%1$s_%2$s=%3$s\n" +/* 1402 */ "%1$s_%2$s=%3$s\n" "export %1$s_%2$s\n\0" -/* 1391 */ "%1$s_%2$s=%3$d # 0x%3$X\n" +/* 1435 */ "%1$s_%2$s=%3$d # 0x%3$X\n" "export %1$s_%2$s\n\0" -/* 1433 */ " case \"${OPT_CODE}\" in\n\0" -/* 1464 */ " if [ $%1$s_%2$s_CT -gt %3$u ] ; then\n" +/* 1477 */ " case \"${OPT_CODE}\" in\n\0" +/* 1508 */ " if [ $%1$s_%2$s_CT -gt %3$u ] ; then\n" " echo 'Error: more than %3$d %2$s options'\n" " echo \"$%1$s_USAGE_TEXT\"\n" " exit 1\n" " fi >&2\n\0" -/* 1655 */ "test ${%1$s_%2$s_CT-0} -ge %3$u || {\n" +/* 1699 */ "test ${%1$s_%2$s_CT-0} -ge %3$u || {\n" " echo %1$s_%2$s has not been set\n" " exit 1\n" "} 1>&2\n\0" -/* 1747 */ "test -n \"$%1$s_%2$s\" || {\n" +/* 1791 */ "test -n \"$%1$s_%2$s\" || {\n" " echo %1$s_%2$s has not been set\n" " exit 1\n" "} 1>&2\n\0" -/* 1828 */ " echo \"$%s_%s_TEXT\"\n" +/* 1872 */ " echo \"$%s_%s_TEXT\"\n" " exit 0\n\0" -/* 1879 */ "\n" +/* 1923 */ "\n" "# # # # # # # # # #\n" "#\n" "# END OF AUTOMATED OPTION PROCESSING\n" "#\n" "# # # # # # # # # # -- do not modify this marker --\n\0" -/* 1995 */ " if [ -n \"${OPT_ARG_VAL}\" ]\n" +/* 2039 */ " if [ -n \"${OPT_ARG_VAL}\" ]\n" " then\n" " eval %1$s_${OPT_NAME}${OPT_ELEMENT}=\"'${OPT_ARG_VAL}'\"\n" " export %1$s_${OPT_NAME}${OPT_ELEMENT}\n" @@ -206,15 +210,15 @@ char const ao_strs_strtable[6670] = "unset OPT_NAME || :\n" "unset OPT_CODE || :\n" "unset OPT_ARG_VAL || :\n\0" -/* 2374 */ " OPT_CODE=`echo \"X${OPT_ARG}\"|sed 's/^X-*//'`\n" +/* 2418 */ " OPT_CODE=`echo \"X${OPT_ARG}\"|sed 's/^X-*//'`\n" " shift\n" " OPT_ARG=$1\n" " case \"${OPT_CODE}\" in *=* )\n" " OPT_ARG_VAL=`echo \"${OPT_CODE}\"|sed 's/^[^=]*=//'`\n" " OPT_CODE=`echo \"${OPT_CODE}\"|sed 's/=.*$//'` ;; esac\n\0" -/* 2625 */ " OPT_CODE=`echo \"X${OPT_ARG}\" | sed 's/X-\\(.\\).*/\\1/'`\n" +/* 2669 */ " OPT_CODE=`echo \"X${OPT_ARG}\" | sed 's/X-\\(.\\).*/\\1/'`\n" " OPT_ARG=` echo \"X${OPT_ARG}\" | sed 's/X-.//'`\n\0" -/* 2742 */ "\n" +/* 2786 */ "\n" "ARG_COUNT=$#\n" "OPT_PROCESS=true\n" "OPT_ARG=$1\n" @@ -227,7 +231,7 @@ char const ao_strs_strtable[6670] = " OPT_PROCESS=false\n" " shift\n" " ;;\n\0" -/* 2949 */ " case \"${OPT_ARG_NEEDED}\" in\n" +/* 2993 */ " case \"${OPT_ARG_NEEDED}\" in\n" " NO )\n" " OPT_ARG_VAL=''\n" " ;;\n" @@ -255,10 +259,10 @@ char const ao_strs_strtable[6670] = " fi\n" " ;;\n" " esac\n\0" -/* 3728 */ " %1$s_%2$s_CT=`expr ${%1$s_%2$s_CT} + 1`\n" +/* 3772 */ " %1$s_%2$s_CT=`expr ${%1$s_%2$s_CT} + 1`\n" " OPT_ELEMENT=\"_${%1$s_%2$s_CT}\"\n" " OPT_NAME='%2$s'\n\0" -/* 3852 */ "\n" +/* 3896 */ "\n" "if test -z \"${%1$s_%2$s}\"\n" "then\n" " %1$s_%2$s_CT=0\n" @@ -268,16 +272,16 @@ char const ao_strs_strtable[6670] = " %1$s_%2$s_1=${%1$s_%2$s}\n" " export %1$s_%2$s_CT %1$s_%2$s_1\n" "fi\n\0" -/* 4010 */ " * )\n" +/* 4054 */ " * )\n" " OPT_PROCESS=false\n" " ;;\n" " esac\n\0" -/* 4067 */ " %1$s_%2$s_CT=0\n" +/* 4111 */ " %1$s_%2$s_CT=0\n" " OPT_ELEMENT=''\n" " %1$s_%2$s='%3$s'\n" " export %1$s_%2$s\n" " OPT_NAME='%2$s'\n\0" -/* 4208 */ " if [ -n \"${%1$s_%2$s}\" ] && ${%1$s_%2$s_set} ; then\n" +/* 4252 */ " if [ -n \"${%1$s_%2$s}\" ] && ${%1$s_%2$s_set} ; then\n" " echo 'Error: duplicate %2$s option'\n" " echo \"$%1$s_USAGE_TEXT\"\n" " exit 1\n" @@ -286,7 +290,7 @@ char const ao_strs_strtable[6670] = " %1$s_%2$s='%3$s'\n" " export %1$s_%2$s\n" " OPT_NAME='%2$s'\n\0" -/* 4525 */ "\n" +/* 4569 */ "\n" "ARG_COUNT=$#\n" "OPT_ARG=$1\n" "while [ $# -gt 0 ]\n" @@ -294,7 +298,7 @@ char const ao_strs_strtable[6670] = " OPT_ELEMENT=''\n" " OPT_ARG_VAL=''\n" " OPT_ARG=${1}\n\0" -/* 4628 */ " case \"${OPT_ARG_NEEDED}\" in\n" +/* 4672 */ " case \"${OPT_ARG_NEEDED}\" in\n" " NO )\n" " if [ -n \"${OPT_ARG}\" ]\n" " then\n" @@ -339,33 +343,33 @@ char const ao_strs_strtable[6670] = " fi\n" " ;;\n" " esac\n\0" -/* 5782 */ " echo \"$%s_LONGUSAGE_TEXT\" | ${PAGER-more}\n" +/* 5826 */ " echo \"$%s_LONGUSAGE_TEXT\" | ${PAGER-more}\n" " exit 0\n\0" -/* 5856 */ "%s OF %s\n" +/* 5900 */ "%s OF %s\n" "#\n" "# From here to the next `-- do not modify this marker --',\n" "# the text has been generated %s\n\0" -/* 5962 */ " eval %1$s_%2$s${OPT_ELEMENT}=true\n" +/* 6006 */ " eval %1$s_%2$s${OPT_ELEMENT}=true\n" " export %1$s_%2$s${OPT_ELEMENT}\n\0" -/* 6052 */ " if [ -n \"${%1$s_%2$s}\" ] && ${%1$s_%2$s_set} ; then\n" +/* 6096 */ " if [ -n \"${%1$s_%2$s}\" ] && ${%1$s_%2$s_set} ; then\n" " echo 'Error: duplicate %2$s option'\n" " echo \"$%1$s_USAGE_TEXT\"\n" " exit 1\n" " fi >&2\n" " %1$s_%2$s_set=true\n" " OPT_NAME='%2$s'\n\0" -/* 6311 */ "\n" +/* 6355 */ "\n" "%1$s_%2$s=${%1$s_%2$s-'%3$s'}\n" "%1$s_%2$s_set=false\n" "export %1$s_%2$s\n\0" -/* 6380 */ "\n" +/* 6424 */ "\n" "%1$s_%2$s=${%1$s_%2$s}\n" "%1$s_%2$s_set=false\n" "export %1$s_%2$s\n\0" -/* 6442 */ "# # # # # # # # # # -- do not modify this marker --\n" +/* 6486 */ "# # # # # # # # # # -- do not modify this marker --\n" "#\n" "# DO NOT EDIT THIS SECTION\n\0" -/* 6525 */ " * )\n" +/* 6569 */ " * )\n" " echo Unknown %s: \"${OPT_CODE}\" >&2\n" " echo \"$%s_USAGE_TEXT\" >&2\n" " exit 1\n" diff --git a/libopts/ao-strs.h b/libopts/ao-strs.h index f9377e285..95036ef72 100644 --- a/libopts/ao-strs.h +++ b/libopts/ao-strs.h @@ -6,7 +6,7 @@ * From the definitions ao-strs.def * and the template file strings * - * Copyright (C) 2011-2015 Bruce Korb, all rights reserved. + * Copyright (C) 2011-2018 Bruce Korb, all rights reserved. * This is free software. It is licensed for use, modification and * redistribution under the terms of the * Modified (3 clause) Berkeley Software Distribution License @@ -39,294 +39,300 @@ #ifndef STRINGS_AO_STRS_H_GUARD #define STRINGS_AO_STRS_H_GUARD 1 /* - * 143 strings in ao_strs_strtable string table + * 146 strings in ao_strs_strtable string table */ -#define ARG_BREAK_STR (ao_strs_strtable+261) +#define ARG_BREAK_STR (ao_strs_strtable+280) #define ARG_BREAK_STR_LEN 5 -#define ARG_BY_NUM_FMT (ao_strs_strtable+267) +#define ARG_BY_NUM_FMT (ao_strs_strtable+286) #define ARG_BY_NUM_FMT_LEN 9 -#define BOOL_ATR_FMT (ao_strs_strtable+913) +#define BOOL_ATR_FMT (ao_strs_strtable+957) #define BOOL_ATR_FMT_LEN 31 -#define CHK_MAX_COUNT (ao_strs_strtable+1464) +#define CHK_MAX_COUNT (ao_strs_strtable+1508) #define CHK_MAX_COUNT_LEN 190 -#define CHK_MIN_COUNT (ao_strs_strtable+1655) +#define CHK_MIN_COUNT (ao_strs_strtable+1699) #define CHK_MIN_COUNT_LEN 91 -#define CHK_ONE_REQUIRED (ao_strs_strtable+1747) +#define CHK_ONE_REQUIRED (ao_strs_strtable+1791) #define CHK_ONE_REQUIRED_LEN 80 -#define ECHO_N_EXIT (ao_strs_strtable+1828) +#define ECHO_N_EXIT (ao_strs_strtable+1872) #define ECHO_N_EXIT_LEN 50 -#define EMPTY_ARG (ao_strs_strtable+277) +#define EMPTY_ARG (ao_strs_strtable+296) #define EMPTY_ARG_LEN 2 -#define END_MARK (ao_strs_strtable+1879) +#define END_MARK (ao_strs_strtable+1923) #define END_MARK_LEN 115 -#define END_OPT_SEL_STR (ao_strs_strtable+280) +#define END_OPT_SEL_STR (ao_strs_strtable+299) #define END_OPT_SEL_STR_LEN 12 -#define END_PRE_FMT (ao_strs_strtable+945) +#define END_PRE_FMT (ao_strs_strtable+989) #define END_PRE_FMT_LEN 36 -#define END_SET_TEXT (ao_strs_strtable+293) +#define END_SET_TEXT (ao_strs_strtable+312) #define END_SET_TEXT_LEN 3 -#define END_XML_FMT (ao_strs_strtable+297) +#define END_XML_FMT (ao_strs_strtable+316) #define END_XML_FMT_LEN 6 -#define ENUM_ERR_LINE (ao_strs_strtable+304) +#define ENUM_ERR_LINE (ao_strs_strtable+323) #define ENUM_ERR_LINE_LEN 5 -#define ENUM_ERR_WIDTH (ao_strs_strtable+310) +#define ENUM_ERR_WIDTH (ao_strs_strtable+329) #define ENUM_ERR_WIDTH_LEN 6 -#define EXPORT_ARG_FMT (ao_strs_strtable+317) +#define EXPORT_ARG_FMT (ao_strs_strtable+336) #define EXPORT_ARG_FMT_LEN 17 -#define FALSE_STR (ao_strs_strtable+335) +#define FALSE_STR (ao_strs_strtable+354) #define FALSE_STR_LEN 5 -#define FINISH_LOOP (ao_strs_strtable+1995) +#define FINISH_LOOP (ao_strs_strtable+2039) #define FINISH_LOOP_LEN 378 -#define FLAG_OPT_MARK (ao_strs_strtable+341) +#define FLAG_OPT_MARK (ao_strs_strtable+360) #define FLAG_OPT_MARK_LEN 9 -#define FLAG_STR (ao_strs_strtable+351) +#define FLAG_STR (ao_strs_strtable+370) #define FLAG_STR_LEN 4 -#define INIT_LOPT_STR (ao_strs_strtable+2374) +#define INIT_LOPT_STR (ao_strs_strtable+2418) #define INIT_LOPT_STR_LEN 250 -#define INIT_OPT_STR (ao_strs_strtable+2625) +#define INIT_OPT_STR (ao_strs_strtable+2669) #define INIT_OPT_STR_LEN 116 -#define INVALID_FMT (ao_strs_strtable+356) +#define INVALID_FMT (ao_strs_strtable+375) #define INVALID_FMT_LEN 10 -#define INVALID_STR (ao_strs_strtable+367) +#define INVALID_STR (ao_strs_strtable+386) #define INVALID_STR_LEN 9 -#define LINE_SPLICE (ao_strs_strtable+377) +#define LINE_SPLICE (ao_strs_strtable+396) #define LINE_SPLICE_LEN 4 -#define LONG_OPT_MARK (ao_strs_strtable+382) -#define LONG_OPT_MARKER (ao_strs_strtable+393) +#define LONG_OPT_MARK (ao_strs_strtable+401) +#define LONG_OPT_MARKER (ao_strs_strtable+412) #define LONG_OPT_MARKER_LEN 2 #define LONG_OPT_MARK_LEN 10 -#define LONG_USE_STR (ao_strs_strtable+396) +#define LONG_USE_STR (ao_strs_strtable+415) #define LONG_USE_STR_LEN 9 -#define LOOP_STR (ao_strs_strtable+2742) +#define LOOP_STR (ao_strs_strtable+2786) #define LOOP_STR_LEN 206 -#define LOPT_ARG_FMT (ao_strs_strtable+2949) +#define LOPT_ARG_FMT (ao_strs_strtable+2993) #define LOPT_ARG_FMT_LEN 778 -#define LVL3_CMD (ao_strs_strtable+406) +#define LVL3_CMD (ao_strs_strtable+425) #define LVL3_CMD_LEN 15 -#define MK_STR_OCT_FMT (ao_strs_strtable+422) +#define MK_STR_OCT_FMT (ao_strs_strtable+441) #define MK_STR_OCT_FMT_LEN 5 -#define MORE_STR (ao_strs_strtable+428) +#define MORE_STR (ao_strs_strtable+447) #define MORE_STR_LEN 4 -#define MULTI_ARG_FMT (ao_strs_strtable+3728) +#define MULTI_ARG_FMT (ao_strs_strtable+3772) #define MULTI_ARG_FMT_LEN 123 -#define MULTI_DEF_FMT (ao_strs_strtable+3852) +#define MULTI_DEF_FMT (ao_strs_strtable+3896) #define MULTI_DEF_FMT_LEN 157 -#define NESTED_OPT_FMT (ao_strs_strtable+433) +#define NESTED_OPT_FMT (ao_strs_strtable+452) #define NESTED_OPT_FMT_LEN 17 -#define NLSTR_FMT (ao_strs_strtable+451) +#define NLSTR_FMT (ao_strs_strtable+470) #define NLSTR_FMT_LEN 3 -#define NLSTR_SPACE_FMT (ao_strs_strtable+455) +#define NLSTR_SPACE_FMT (ao_strs_strtable+474) #define NLSTR_SPACE_FMT_LEN 5 -#define NONE_STR (ao_strs_strtable+91) +#define NONE_STR (ao_strs_strtable+110) #define NONE_STR_LEN 4 -#define NOT_FOUND_STR (ao_strs_strtable+4010) +#define NOT_FOUND_STR (ao_strs_strtable+4054) #define NOT_FOUND_STR_LEN 56 -#define NO_ARG_NEEDED (ao_strs_strtable+461) +#define NO_ARG_NEEDED (ao_strs_strtable+480) #define NO_ARG_NEEDED_LEN 17 -#define NO_LOAD_WARN (ao_strs_strtable+982) +#define NO_LOAD_WARN (ao_strs_strtable+1026) #define NO_LOAD_WARN_LEN 46 -#define NO_MULTI_ARG_FMT (ao_strs_strtable+4067) +#define NO_MULTI_ARG_FMT (ao_strs_strtable+4111) #define NO_MULTI_ARG_FMT_LEN 140 -#define NO_SAVE_OPTS (ao_strs_strtable+1029) +#define NO_SAVE_OPTS (ao_strs_strtable+1073) #define NO_SAVE_OPTS_LEN 46 -#define NO_SGL_ARG_FMT (ao_strs_strtable+4208) +#define NO_SGL_ARG_FMT (ao_strs_strtable+4252) #define NO_SGL_ARG_FMT_LEN 316 -#define NO_SUPPRESS_LOAD (ao_strs_strtable+1076) +#define NO_SUPPRESS_LOAD (ao_strs_strtable+1120) #define NO_SUPPRESS_LOAD_LEN 65 -#define NULL_ATR_FMT (ao_strs_strtable+479) +#define NULL_ATR_FMT (ao_strs_strtable+498) #define NULL_ATR_FMT_LEN 6 -#define NUMB_ATR_FMT (ao_strs_strtable+1142) +#define NUMB_ATR_FMT (ao_strs_strtable+1186) #define NUMB_ATR_FMT_LEN 34 -#define OK_NEED_OPT_ARG (ao_strs_strtable+486) +#define OK_NEED_OPT_ARG (ao_strs_strtable+505) #define OK_NEED_OPT_ARG_LEN 17 -#define ONE_TAB_STR (ao_strs_strtable+504) +#define ONE_TAB_STR (ao_strs_strtable+523) #define ONE_TAB_STR_LEN 1 -#define ONLY_OPTS_LOOP (ao_strs_strtable+4525) +#define ONLY_OPTS_LOOP (ao_strs_strtable+4569) #define ONLY_OPTS_LOOP_LEN 102 -#define OPEN_CLOSE_FMT (ao_strs_strtable+479) +#define OPEN_CLOSE_FMT (ao_strs_strtable+498) #define OPEN_CLOSE_FMT_LEN 6 -#define OPEN_XML_FMT (ao_strs_strtable+506) +#define OPEN_XML_FMT (ao_strs_strtable+525) #define OPEN_XML_FMT_LEN 4 -#define OPTION_STR (ao_strs_strtable+511) +#define OPTION_STR (ao_strs_strtable+530) #define OPTION_STR_LEN 6 -#define OPT_ARG_FMT (ao_strs_strtable+4628) +#define OPT_ARG_FMT (ao_strs_strtable+4672) #define OPT_ARG_FMT_LEN 1153 -#define OPT_END_FMT (ao_strs_strtable+518) +#define OPT_END_FMT (ao_strs_strtable+537) #define OPT_END_FMT_LEN 14 -#define OPT_VAL_FMT (ao_strs_strtable+533) +#define OPT_VAL_FMT (ao_strs_strtable+552) #define OPT_VAL_FMT_LEN 6 -#define OR_STR (ao_strs_strtable+540) +#define OR_STR (ao_strs_strtable+559) #define OR_STR_LEN 3 -#define PAGER_NAME (ao_strs_strtable+544) +#define PAGER_NAME (ao_strs_strtable+563) #define PAGER_NAME_LEN 5 -#define PAGE_USAGE_FMT (ao_strs_strtable+550) +#define PAGE_USAGE_FMT (ao_strs_strtable+569) #define PAGE_USAGE_FMT_LEN 22 -#define PAGE_USAGE_TEXT (ao_strs_strtable+5782) +#define PAGE_USAGE_TEXT (ao_strs_strtable+5826) #define PAGE_USAGE_TEXT_LEN 73 -#define PLUS_STR (ao_strs_strtable+573) +#define PLUS_STR (ao_strs_strtable+592) #define PLUS_STR_LEN 3 -#define PREAMBLE_FMT (ao_strs_strtable+5856) +#define PREAMBLE_FMT (ao_strs_strtable+5900) #define PREAMBLE_FMT_LEN 105 -#define PUTS_FMT (ao_strs_strtable+577) +#define PUTS_FMT (ao_strs_strtable+596) #define PUTS_FMT_LEN 15 -#define QUOT_APOS (ao_strs_strtable+593) +#define QUOT_APOS (ao_strs_strtable+612) #define QUOT_APOS_LEN 2 -#define QUOT_ARG_FMT (ao_strs_strtable+596) +#define QUOT_ARG_FMT (ao_strs_strtable+615) #define QUOT_ARG_FMT_LEN 4 -#define SET_MULTI_ARG (ao_strs_strtable+5962) +#define SET_MULTI_ARG (ao_strs_strtable+6006) #define SET_MULTI_ARG_LEN 89 -#define SET_NO_TEXT_FMT (ao_strs_strtable+1177) +#define SET_NO_TEXT_FMT (ao_strs_strtable+1221) #define SET_NO_TEXT_FMT_LEN 30 -#define SET_OFF_FMT (ao_strs_strtable+601) +#define SET_OFF_FMT (ao_strs_strtable+620) #define SET_OFF_FMT_LEN 6 -#define SET_TEXT_FMT (ao_strs_strtable+608) +#define SET_TEXT_FMT (ao_strs_strtable+627) #define SET_TEXT_FMT_LEN 12 -#define SGL_ARG_FMT (ao_strs_strtable+6052) +#define SGL_ARG_FMT (ao_strs_strtable+6096) #define SGL_ARG_FMT_LEN 258 -#define SGL_DEF_FMT (ao_strs_strtable+6311) +#define SGL_DEF_FMT (ao_strs_strtable+6355) #define SGL_DEF_FMT_LEN 68 -#define SGL_NO_DEF_FMT (ao_strs_strtable+6380) +#define SGL_NO_DEF_FMT (ao_strs_strtable+6424) #define SGL_NO_DEF_FMT_LEN 61 -#define SHELL_MAGIC (ao_strs_strtable+621) +#define SHELL_MAGIC (ao_strs_strtable+640) #define SHELL_MAGIC_LEN 6 -#define SHOW_PROG_ENV (ao_strs_strtable+628) +#define SHOW_PROG_ENV (ao_strs_strtable+647) #define SHOW_PROG_ENV_LEN 19 -#define SHOW_VAL_FMT (ao_strs_strtable+648) +#define SHOW_VAL_FMT (ao_strs_strtable+667) #define SHOW_VAL_FMT_LEN 17 -#define START_MARK (ao_strs_strtable+6442) +#define START_MARK (ao_strs_strtable+6486) #define START_MARK_LEN 82 -#define STDOUT (ao_strs_strtable+666) +#define STDOUT (ao_strs_strtable+685) #define STDOUT_LEN 6 -#define TIME_FMT (ao_strs_strtable+673) +#define TIME_FMT (ao_strs_strtable+692) #define TIME_FMT_LEN 21 -#define TMPDIR (ao_strs_strtable+695) +#define TMPDIR (ao_strs_strtable+714) #define TMPDIR_LEN 6 -#define TMP_FILE_FMT (ao_strs_strtable+702) +#define TMP_FILE_FMT (ao_strs_strtable+721) #define TMP_FILE_FMT_LEN 16 -#define TMP_USAGE_FMT (ao_strs_strtable+702) +#define TMP_USAGE_FMT (ao_strs_strtable+721) #define TMP_USAGE_FMT_LEN 16 -#define TRUE_STR (ao_strs_strtable+719) +#define TRUE_STR (ao_strs_strtable+738) #define TRUE_STR_LEN 4 -#define TWO_SPACES_STR (ao_strs_strtable+254) +#define TWO_SPACES_STR (ao_strs_strtable+273) #define TWO_SPACES_STR_LEN 2 -#define TYPE_ATR_FMT (ao_strs_strtable+724) +#define TYPE_ATR_FMT (ao_strs_strtable+743) #define TYPE_ATR_FMT_LEN 12 -#define UNK_OPT_FMT (ao_strs_strtable+6525) +#define UNK_OPT_FMT (ao_strs_strtable+6569) #define UNK_OPT_FMT_LEN 144 -#define VER_STR (ao_strs_strtable+737) +#define VER_STR (ao_strs_strtable+756) #define VER_STR_LEN 7 -#define XML_HEX_BYTE_FMT (ao_strs_strtable+745) +#define XML_HEX_BYTE_FMT (ao_strs_strtable+764) #define XML_HEX_BYTE_FMT_LEN 7 -#define YES_NEED_OPT_ARG (ao_strs_strtable+753) +#define YES_NEED_OPT_ARG (ao_strs_strtable+772) #define YES_NEED_OPT_ARG_LEN 18 -#define apostrophe (ao_strs_strtable+772) +#define ao_default_use (ao_strs_strtable+804) +#define ao_default_use_LEN 11 +#define ao_name_use_fmt (ao_strs_strtable+791) +#define ao_name_use_fmt_LEN 12 +#define apostrophe (ao_strs_strtable+816) #define apostrophe_LEN 4 -#define arg_fmt (ao_strs_strtable+777) +#define arg_fmt (ao_strs_strtable+821) #define arg_fmt_LEN 5 -#define init_optct (ao_strs_strtable+820) +#define init_optct (ao_strs_strtable+864) #define init_optct_LEN 13 -#define misguess_len (ao_strs_strtable+783) +#define misguess_len (ao_strs_strtable+827) #define misguess_len_LEN 36 -#define set_dash (ao_strs_strtable+834) +#define set_dash (ao_strs_strtable+878) #define set_dash_LEN 6 -#define tmp_dir (ao_strs_strtable+841) +#define tmp_dir (ao_strs_strtable+885) #define tmp_dir_LEN 4 -#define zAll (ao_strs_strtable+257) +#define zAll (ao_strs_strtable+276) #define zAll_LEN 3 #define zCfgAO_Flags (ao_strs_strtable+12) -#define zCfgAO_Flags_LEN 12 -#define zCfgProg (ao_strs_strtable+25) -#define zCfgProg_LEN 7 -#define zEquivMode (ao_strs_strtable+1208) +#define zCfgAO_Flags_LEN 14 +#define zCfgProg (ao_strs_strtable+27) +#define zCfgProg_LEN 9 +#define zEquivMode (ao_strs_strtable+1252) #define zEquivMode_LEN 44 -#define zFiveSpaces (ao_strs_strtable+244) +#define zFiveSpaces (ao_strs_strtable+263) #define zFiveSpaces_LEN 5 -#define zFmtFmt (ao_strs_strtable+33) +#define zFmtFmt (ao_strs_strtable+37) #define zFmtFmt_LEN 11 -#define zFullOptFmt (ao_strs_strtable+1253) +#define zFmtProg (ao_strs_strtable+49) +#define zFmtProg_LEN 14 +#define zFullOptFmt (ao_strs_strtable+1297) #define zFullOptFmt_LEN 34 -#define zGnuBreak (ao_strs_strtable+45) +#define zGnuBreak (ao_strs_strtable+64) #define zGnuBreak_LEN 5 -#define zGnuFileArg (ao_strs_strtable+51) +#define zGnuFileArg (ao_strs_strtable+70) #define zGnuFileArg_LEN 5 -#define zGnuKeyLArg (ao_strs_strtable+57) +#define zGnuKeyLArg (ao_strs_strtable+76) #define zGnuKeyLArg_LEN 4 -#define zGnuNestArg (ao_strs_strtable+62) +#define zGnuNestArg (ao_strs_strtable+81) #define zGnuNestArg_LEN 5 -#define zGnuOptArg (ao_strs_strtable+68) +#define zGnuOptArg (ao_strs_strtable+87) #define zGnuOptArg_LEN 6 -#define zGnuOptFmt (ao_strs_strtable+75) +#define zGnuOptFmt (ao_strs_strtable+94) #define zGnuOptFmt_LEN 10 -#define zGnuTimeArg (ao_strs_strtable+86) +#define zGnuTimeArg (ao_strs_strtable+105) #define zGnuTimeArg_LEN 4 -#define zNone (ao_strs_strtable+91) +#define zNone (ao_strs_strtable+110) #define zNone_LEN 4 -#define zOptCookieCt (ao_strs_strtable+1288) +#define zOptCookieCt (ao_strs_strtable+1332) #define zOptCookieCt_LEN 38 -#define zOptCtFmt (ao_strs_strtable+1327) +#define zOptCtFmt (ao_strs_strtable+1371) #define zOptCtFmt_LEN 30 -#define zOptDisabl (ao_strs_strtable+1358) +#define zOptDisabl (ao_strs_strtable+1402) #define zOptDisabl_LEN 32 -#define zOptNumFmt (ao_strs_strtable+1391) +#define zOptNumFmt (ao_strs_strtable+1435) #define zOptNumFmt_LEN 41 -#define zOptionCase (ao_strs_strtable+1433) +#define zOptionCase (ao_strs_strtable+1477) #define zOptionCase_LEN 30 -#define zOptionEndSelect (ao_strs_strtable+846) +#define zOptionEndSelect (ao_strs_strtable+890) #define zOptionEndSelect_LEN 16 -#define zOptionFlag (ao_strs_strtable+863) +#define zOptionFlag (ao_strs_strtable+907) #define zOptionFlag_LEN 15 -#define zOptionFullName (ao_strs_strtable+879) +#define zOptionFullName (ao_strs_strtable+923) #define zOptionFullName_LEN 15 -#define zOptionPartName (ao_strs_strtable+895) +#define zOptionPartName (ao_strs_strtable+939) #define zOptionPartName_LEN 17 -#define zPresetFile (ao_strs_strtable+96) +#define zPresetFile (ao_strs_strtable+115) #define zPresetFile_LEN 37 -#define zReqOptFmt (ao_strs_strtable+134) +#define zReqOptFmt (ao_strs_strtable+153) #define zReqOptFmt_LEN 13 #define zSepChars (ao_strs_strtable+0) #define zSepChars_LEN 3 -#define zShrtGnuOptFmt (ao_strs_strtable+148) +#define zShrtGnuOptFmt (ao_strs_strtable+167) #define zShrtGnuOptFmt_LEN 2 -#define zSixSpaces (ao_strs_strtable+237) +#define zSixSpaces (ao_strs_strtable+256) #define zSixSpaces_LEN 6 -#define zStdBoolArg (ao_strs_strtable+151) +#define zStdBoolArg (ao_strs_strtable+170) #define zStdBoolArg_LEN 3 -#define zStdBreak (ao_strs_strtable+155) +#define zStdBreak (ao_strs_strtable+174) #define zStdBreak_LEN 7 -#define zStdFileArg (ao_strs_strtable+163) +#define zStdFileArg (ao_strs_strtable+182) #define zStdFileArg_LEN 3 -#define zStdKeyArg (ao_strs_strtable+167) +#define zStdKeyArg (ao_strs_strtable+186) #define zStdKeyArg_LEN 3 -#define zStdKeyLArg (ao_strs_strtable+171) +#define zStdKeyLArg (ao_strs_strtable+190) #define zStdKeyLArg_LEN 3 -#define zStdNestArg (ao_strs_strtable+175) +#define zStdNestArg (ao_strs_strtable+194) #define zStdNestArg_LEN 3 -#define zStdNoArg (ao_strs_strtable+179) +#define zStdNoArg (ao_strs_strtable+198) #define zStdNoArg_LEN 3 -#define zStdNumArg (ao_strs_strtable+183) +#define zStdNumArg (ao_strs_strtable+202) #define zStdNumArg_LEN 3 -#define zStdOptArg (ao_strs_strtable+187) +#define zStdOptArg (ao_strs_strtable+206) #define zStdOptArg_LEN 3 -#define zStdReqArg (ao_strs_strtable+191) +#define zStdReqArg (ao_strs_strtable+210) #define zStdReqArg_LEN 3 -#define zStdStrArg (ao_strs_strtable+195) +#define zStdStrArg (ao_strs_strtable+214) #define zStdStrArg_LEN 3 -#define zStdTimeArg (ao_strs_strtable+199) +#define zStdTimeArg (ao_strs_strtable+218) #define zStdTimeArg_LEN 3 -#define zTabHyp (ao_strs_strtable+203) -#define zTabHypAnd (ao_strs_strtable+217) +#define zTabHyp (ao_strs_strtable+222) +#define zTabHypAnd (ao_strs_strtable+236) #define zTabHypAnd_LEN 11 #define zTabHyp_LEN 6 -#define zTabSpace (ao_strs_strtable+210) +#define zTabSpace (ao_strs_strtable+229) #define zTabSpace_LEN 6 -#define zTabout (ao_strs_strtable+229) +#define zTabout (ao_strs_strtable+248) #define zTabout_LEN 7 -#define zThreeSpaces (ao_strs_strtable+250) +#define zThreeSpaces (ao_strs_strtable+269) #define zThreeSpaces_LEN 3 -#define zTwoSpaces (ao_strs_strtable+254) +#define zTwoSpaces (ao_strs_strtable+273) #define zTwoSpaces_LEN 2 #define zambig_file (ao_strs_strtable+4) #define zambig_file_LEN 7 -extern char const ao_strs_strtable[6670]; +extern char const ao_strs_strtable[6714]; #endif /* STRINGS_AO_STRS_H_GUARD */ diff --git a/libopts/autoopts.c b/libopts/autoopts.c index 7e2323873..643d27723 100644 --- a/libopts/autoopts.c +++ b/libopts/autoopts.c @@ -13,7 +13,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -35,7 +35,7 @@ /** * The number of tab characters to skip when printing continuation lines. */ -static unsigned int tab_skip_ct = 0; + static unsigned int tab_skip_ct = 0; #ifndef HAVE_PATHFIND # define pathfind(_p, _n, _m) option_pathfind(_p, _n, _m) @@ -59,7 +59,7 @@ static unsigned int tab_skip_ct = 0; # include "compat/strchr.c" #endif -LOCAL void * +static void * ao_malloc(size_t sz) { void * res = malloc(sz); @@ -69,10 +69,8 @@ ao_malloc(size_t sz) } return res; } -#undef malloc -#define malloc(_s) ao_malloc(_s) -LOCAL void * +static void * ao_realloc(void *p, size_t sz) { void * res = (p == NULL) ? malloc(sz) : realloc(p, sz); @@ -82,10 +80,8 @@ ao_realloc(void *p, size_t sz) } return res; } -#undef realloc -#define realloc(_p,_s) ao_realloc(_p,_s) -LOCAL char * +static char * ao_strdup(char const *str) { char * res = strdup(str); @@ -95,8 +91,6 @@ ao_strdup(char const *str) } return res; } -#undef strdup -#define strdup(_p) ao_strdup(_p) /** * handle an option. @@ -104,7 +98,7 @@ ao_strdup(char const *str) * This routine handles equivalencing, sets the option state flags and * invokes the handler procedure, if any. */ -LOCAL tSuccess +static tSuccess handle_opt(tOptions * opts, tOptState * o_st) { /* @@ -217,7 +211,7 @@ handle_opt(tOptions * opts, tOptState * o_st) * @param opts the program option descriptor * @param o_st the state of the next found option */ -LOCAL tSuccess +static tSuccess next_opt(tOptions * opts, tOptState * o_st) { { @@ -244,7 +238,7 @@ next_opt(tOptions * opts, tOptState * o_st) * @param[in,out] opts program options descriptor * @returns SUCCESS or FAILURE */ -LOCAL tSuccess +static tSuccess regular_opts(tOptions * opts) { /* assert: opts->fOptSet & OPTPROC_IMMEDIATE == 0 */ diff --git a/libopts/autoopts.h b/libopts/autoopts.h index b90e1a303..0c146710d 100644 --- a/libopts/autoopts.h +++ b/libopts/autoopts.h @@ -11,7 +11,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -455,7 +455,7 @@ typedef enum { AOFLAG_TABLE } ao_flags_t; #undef _aof_ static char const zNil[] = ""; -static arg_types_t argTypes = { NULL }; +static arg_types_t argTypes; static char line_fmt_buf[32]; static bool displayEnum = false; static char const pkgdatadir_default[] = PKGDATADIR; @@ -463,6 +463,13 @@ static char const * program_pkgdatadir = pkgdatadir_default; static tOptionLoadMode option_load_mode = OPTION_LOAD_UNCOOKED; static tePagerState pagerState = PAGER_STATE_INITIAL; +static noreturn void option_exits(int exit_code); +static noreturn void fserr_exit(char const * prog, char const * op, + char const * fname); +static void fserr_warn(char const * prog, char const * op, + char const * fname); +static noreturn void ao_bug(char const * msg); + FILE * option_usage_fp = NULL; static char const * pz_enum_err_fmt; diff --git a/libopts/autoopts/options.h b/libopts/autoopts/options.h index 8c4802a1d..08dc54621 100644 --- a/libopts/autoopts/options.h +++ b/libopts/autoopts/options.h @@ -9,11 +9,11 @@ * This file defines all the global structures and special values * used in the automated option processing library. * - * Automated Options Copyright (C) 1992-2016 by Bruce Korb + * Automated Options Copyright (C) 1992-2018 by Bruce Korb * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -40,9 +40,40 @@ */ #include #include -#include -#include -#include + +#ifndef COMPAT_H_GUARD +/* + * This is needed for test compilations where the "compat.h" + * header is not usually available. + */ +# if defined(HAVE_STDINT_H) +# include +# elif defined(HAVE_INTTYPES_H) +# include +# endif /* HAVE_STDINT/INTTYPES_H */ + +# if defined(HAVE_LIMITS_H) +# include +# elif defined(HAVE_SYS_LIMITS_H) +# include +# endif /* HAVE_LIMITS/SYS_LIMITS_H */ + +# if defined(HAVE_SYSEXITS_H) +# include +# endif /* HAVE_SYSEXITS_H */ + +# if defined(HAVE_STDBOOL_H) +# include +# elif ! defined(bool) + typedef enum { false = 0, true = 1 } _Bool; +# define bool _Bool + + /* The other macros must be usable in preprocessor directives. */ +# define false 0 +# define true 1 +# endif /* HAVE_SYSEXITS_H */ +#endif /* COMPAT_H_GUARD */ +// END-CONFIGURED-HEADERS /** * Defined to abnormal value of EX_USAGE. Used to indicate that paged usage @@ -78,15 +109,15 @@ * @{ */ /// autoopts structure version -#define OPTIONS_STRUCT_VERSION 167937 +#define OPTIONS_STRUCT_VERSION 172033 /// autoopts structure version string -#define OPTIONS_VERSION_STRING "41:1:16" +#define OPTIONS_VERSION_STRING "42:1:17" /// minimum version the autoopts library supports #define OPTIONS_MINIMUM_VERSION 102400 /// minimum version the autoopts library supports as a string #define OPTIONS_MIN_VER_STRING "25:0:0" /// the display version of the autoopts library, as a string -#define OPTIONS_DOTTED_VERSION "41.1" +#define OPTIONS_DOTTED_VERSION "42.1" /// convert a version/release number pair to an integer value #define OPTIONS_VER_TO_NUM(_v, _r) (((_v) * 4096) + (_r)) /// @} @@ -109,7 +140,8 @@ typedef enum { OPARG_TYPE_FLOAT = 9, ///< opt arg is a floating point num OPARG_TYPE_DOUBLE = 10, ///< opt arg is a double prec. float OPARG_TYPE_LONG_DOUBLE = 11, ///< opt arg is a long double prec. - OPARG_TYPE_LONG_LONG = 12 ///< opt arg is a long long int + OPARG_TYPE_LONG_LONG = 12, ///< opt arg is a long long int + OPARG_TYPE_STATIC = 13 ///< } teOptArgType; /** @@ -610,6 +642,7 @@ struct options { void * pSavedState; /// The procedure to call to print usage text + /* __attribute__((__noreturn__)) */ // coverity[+kill] tpUsageProc pUsageProc; /// The procedure to call to translate translatable option messages @@ -808,7 +841,7 @@ extern int optionFileLoad(tOptions *, char const *); /** - * optionFindNextValue - find a hierarchically valued option instance + * optionFindNextValue - find a hierarcicaly valued option instance * * This routine will find the next entry in a nested value option or * configurable. It will search through the list and return the next entry @@ -825,7 +858,7 @@ extern const tOptionValue * optionFindNextValue(const tOptDesc *, const tOptionV /** - * optionFindValue - find a hierarchically valued option instance + * optionFindValue - find a hierarcicaly valued option instance * * This routine will find an entry in a nested value option or configurable. * It will search through the list and return a matching entry. diff --git a/libopts/autoopts/project.h b/libopts/autoopts/project.h index bfdc13cca..1f196efa0 100644 --- a/libopts/autoopts/project.h +++ b/libopts/autoopts/project.h @@ -4,7 +4,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -71,6 +71,10 @@ typedef int tSuccess; # define MODE extern #endif +#undef NUL +#define NUL '\0' + +#define MOD_LOCAL static #define parse_duration option_parse_duration #endif /* AUTOGEN_PROJECT_H */ diff --git a/libopts/autoopts/usage-txt.h b/libopts/autoopts/usage-txt.h index 6a17c7799..e94337d69 100644 --- a/libopts/autoopts/usage-txt.h +++ b/libopts/autoopts/usage-txt.h @@ -8,7 +8,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2017 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -29,7 +29,7 @@ /** @file usage-txt.h * * This file handles all the bookkeeping required for tracking all the little - * tiny strings used by the AutoOpts library. There are 108 + * tiny strings used by the AutoOpts library. There are 107 * of them. This is not versioned because it is entirely internal to the * library and accessed by client code only in a very well-controlled way: * they may substitute translated strings using a procedure that steps through @@ -47,7 +47,7 @@ typedef struct { char * utpz_GnuKeyArg; char * utpz_GnuNumArg; char * utpz_GnuStrArg; - char const * apz_str[104]; + char const * apz_str[103]; } usage_text_t; /* @@ -55,7 +55,7 @@ typedef struct { * strings and the text array containing untranslatable strings. */ extern usage_text_t option_xlateable_txt; -extern char const option_lib_text[4285]; +extern char const option_lib_text[4267]; #if defined(AUTOOPTS_INTERNAL) /* @@ -110,67 +110,66 @@ extern char const option_lib_text[4285]; #define zNoState (option_xlateable_txt.apz_str[ 40]) #define zNotCmdOpt (option_xlateable_txt.apz_str[ 41]) #define zNotDate (option_xlateable_txt.apz_str[ 42]) -#define zNotDef (option_xlateable_txt.apz_str[ 43]) -#define zNotDuration (option_xlateable_txt.apz_str[ 44]) -#define zneed_more (option_xlateable_txt.apz_str[ 45]) -#define zNotNumber (option_xlateable_txt.apz_str[ 46]) -#define znum_too_large (option_xlateable_txt.apz_str[ 47]) -#define zoffer_usage_fmt (option_xlateable_txt.apz_str[ 48]) -#define zonly_one (option_xlateable_txt.apz_str[ 49]) -#define zstdout_name (option_xlateable_txt.apz_str[ 50]) -#define zstderr_name (option_xlateable_txt.apz_str[ 51]) -#define zwriting (option_xlateable_txt.apz_str[ 52]) -#define zRangeErr (option_xlateable_txt.apz_str[ 53]) -#define zneed_fmt (option_xlateable_txt.apz_str[ 54]) -#define zsave_warn (option_xlateable_txt.apz_str[ 55]) -#define zalt_opt (option_xlateable_txt.apz_str[ 56]) -#define zAuto (option_xlateable_txt.apz_str[ 57]) -#define zDefaultOpt (option_xlateable_txt.apz_str[ 58]) -#define zDis (option_xlateable_txt.apz_str[ 59]) -#define zDisabledOpt (option_xlateable_txt.apz_str[ 60]) -#define zDisabledWhy (option_xlateable_txt.apz_str[ 61]) -#define zEnab (option_xlateable_txt.apz_str[ 62]) -#define ztoo_often_fmt (option_xlateable_txt.apz_str[ 63]) -#define zExamineFmt (option_xlateable_txt.apz_str[ 64]) -#define zFileCannotExist (option_xlateable_txt.apz_str[ 65]) -#define zFileMustExist (option_xlateable_txt.apz_str[ 66]) -#define zFlagOkay (option_xlateable_txt.apz_str[ 67]) -#define zGenshell (option_xlateable_txt.apz_str[ 68]) -#define zLowerBits (option_xlateable_txt.apz_str[ 69]) -#define zMembers (option_xlateable_txt.apz_str[ 70]) -#define zMust (option_xlateable_txt.apz_str[ 71]) -#define zNoFlags (option_xlateable_txt.apz_str[ 72]) -#define zNoLim (option_xlateable_txt.apz_str[ 73]) -#define zNoPreset (option_xlateable_txt.apz_str[ 74]) -#define zNoRq_NoShrtTtl (option_xlateable_txt.apz_str[ 75]) -#define zNoRq_ShrtTtl (option_xlateable_txt.apz_str[ 76]) -#define zNrmOptFmt (option_xlateable_txt.apz_str[ 77]) -#define zNumberOpt (option_xlateable_txt.apz_str[ 78]) -#define zOptsOnly (option_xlateable_txt.apz_str[ 79]) -#define zPathFmt (option_xlateable_txt.apz_str[ 80]) -#define zPlsSendBugs (option_xlateable_txt.apz_str[ 81]) -#define zPreset (option_xlateable_txt.apz_str[ 82]) -#define zPresetIntro (option_xlateable_txt.apz_str[ 83]) -#define zProhib (option_xlateable_txt.apz_str[ 84]) -#define zProhibOne (option_xlateable_txt.apz_str[ 85]) -#define zRange (option_xlateable_txt.apz_str[ 86]) -#define zRangeAbove (option_xlateable_txt.apz_str[ 87]) -#define zRangeExact (option_xlateable_txt.apz_str[ 88]) -#define zRangeLie (option_xlateable_txt.apz_str[ 89]) -#define zRangeOnly (option_xlateable_txt.apz_str[ 90]) -#define zRangeOr (option_xlateable_txt.apz_str[ 91]) -#define zRangeScaled (option_xlateable_txt.apz_str[ 92]) -#define zRangeUpto (option_xlateable_txt.apz_str[ 93]) -#define zReorder (option_xlateable_txt.apz_str[ 94]) -#define zReqOne (option_xlateable_txt.apz_str[ 95]) -#define zReqThese (option_xlateable_txt.apz_str[ 96]) -#define zReq_NoShrtTtl (option_xlateable_txt.apz_str[ 97]) -#define zReq_ShrtTtl (option_xlateable_txt.apz_str[ 98]) -#define zSetMemberSettings (option_xlateable_txt.apz_str[ 99]) -#define zUpTo (option_xlateable_txt.apz_str[100]) -#define zValidKeys (option_xlateable_txt.apz_str[101]) -#define zVendIntro (option_xlateable_txt.apz_str[102]) -#define zVendOptsAre (option_xlateable_txt.apz_str[103]) +#define zNotDuration (option_xlateable_txt.apz_str[ 43]) +#define zneed_more (option_xlateable_txt.apz_str[ 44]) +#define zNotNumber (option_xlateable_txt.apz_str[ 45]) +#define znum_too_large (option_xlateable_txt.apz_str[ 46]) +#define zoffer_usage_fmt (option_xlateable_txt.apz_str[ 47]) +#define zonly_one (option_xlateable_txt.apz_str[ 48]) +#define zstdout_name (option_xlateable_txt.apz_str[ 49]) +#define zstderr_name (option_xlateable_txt.apz_str[ 50]) +#define zwriting (option_xlateable_txt.apz_str[ 51]) +#define zRangeErr (option_xlateable_txt.apz_str[ 52]) +#define zneed_fmt (option_xlateable_txt.apz_str[ 53]) +#define zsave_warn (option_xlateable_txt.apz_str[ 54]) +#define zalt_opt (option_xlateable_txt.apz_str[ 55]) +#define zAuto (option_xlateable_txt.apz_str[ 56]) +#define zDefaultOpt (option_xlateable_txt.apz_str[ 57]) +#define zDis (option_xlateable_txt.apz_str[ 58]) +#define zDisabledOpt (option_xlateable_txt.apz_str[ 59]) +#define zDisabledWhy (option_xlateable_txt.apz_str[ 60]) +#define zEnab (option_xlateable_txt.apz_str[ 61]) +#define ztoo_often_fmt (option_xlateable_txt.apz_str[ 62]) +#define zExamineFmt (option_xlateable_txt.apz_str[ 63]) +#define zFileCannotExist (option_xlateable_txt.apz_str[ 64]) +#define zFileMustExist (option_xlateable_txt.apz_str[ 65]) +#define zFlagOkay (option_xlateable_txt.apz_str[ 66]) +#define zGenshell (option_xlateable_txt.apz_str[ 67]) +#define zLowerBits (option_xlateable_txt.apz_str[ 68]) +#define zMembers (option_xlateable_txt.apz_str[ 69]) +#define zMust (option_xlateable_txt.apz_str[ 70]) +#define zNoFlags (option_xlateable_txt.apz_str[ 71]) +#define zNoLim (option_xlateable_txt.apz_str[ 72]) +#define zNoPreset (option_xlateable_txt.apz_str[ 73]) +#define zNoRq_NoShrtTtl (option_xlateable_txt.apz_str[ 74]) +#define zNoRq_ShrtTtl (option_xlateable_txt.apz_str[ 75]) +#define zNrmOptFmt (option_xlateable_txt.apz_str[ 76]) +#define zNumberOpt (option_xlateable_txt.apz_str[ 77]) +#define zOptsOnly (option_xlateable_txt.apz_str[ 78]) +#define zPathFmt (option_xlateable_txt.apz_str[ 79]) +#define zPlsSendBugs (option_xlateable_txt.apz_str[ 80]) +#define zPreset (option_xlateable_txt.apz_str[ 81]) +#define zPresetIntro (option_xlateable_txt.apz_str[ 82]) +#define zProhib (option_xlateable_txt.apz_str[ 83]) +#define zProhibOne (option_xlateable_txt.apz_str[ 84]) +#define zRange (option_xlateable_txt.apz_str[ 85]) +#define zRangeAbove (option_xlateable_txt.apz_str[ 86]) +#define zRangeExact (option_xlateable_txt.apz_str[ 87]) +#define zRangeLie (option_xlateable_txt.apz_str[ 88]) +#define zRangeOnly (option_xlateable_txt.apz_str[ 89]) +#define zRangeOr (option_xlateable_txt.apz_str[ 90]) +#define zRangeScaled (option_xlateable_txt.apz_str[ 91]) +#define zRangeUpto (option_xlateable_txt.apz_str[ 92]) +#define zReorder (option_xlateable_txt.apz_str[ 93]) +#define zReqOne (option_xlateable_txt.apz_str[ 94]) +#define zReqThese (option_xlateable_txt.apz_str[ 95]) +#define zReq_NoShrtTtl (option_xlateable_txt.apz_str[ 96]) +#define zReq_ShrtTtl (option_xlateable_txt.apz_str[ 97]) +#define zSetMemberSettings (option_xlateable_txt.apz_str[ 98]) +#define zUpTo (option_xlateable_txt.apz_str[ 99]) +#define zValidKeys (option_xlateable_txt.apz_str[100]) +#define zVendIntro (option_xlateable_txt.apz_str[101]) +#define zVendOptsAre (option_xlateable_txt.apz_str[102]) /* * First, set up the strings. Some of these are writable. These are all in @@ -181,7 +180,7 @@ static char eng_zGnuBoolArg[] = "=T/F"; static char eng_zGnuKeyArg[] = "=KWd"; static char eng_zGnuNumArg[] = "=num"; static char eng_zGnuStrArg[] = "=str"; -char const option_lib_text[4285] = +char const option_lib_text[4267] = /* 0 */ "allocation of %d bytes failed\n\0" /* 31 */ "AutoOpts function called without option descriptor\n\0" /* 83 */ "\tThis exceeds the compiled library version: \0" @@ -190,7 +189,7 @@ char const option_lib_text[4285] = /* 228 */ "realloc of %d bytes at 0x%p failed\n\0" /* 264 */ "\tThis is less than the minimum library version: \0" /* 314 */ "Automated Options version %s\n" - "\tCopyright (C) 1999-2014 by Bruce Korb - all rights reserved\n\0" + "\tCopyright (C) 1999-2017 by Bruce Korb - all rights reserved\n\0" /* 405 */ "(AutoOpts bug): %s.\n\0" /* 427 */ "optionResetOpt() called, but reset-option not configured\0" /* 484 */ "could not locate the 'help' option\0" @@ -231,76 +230,75 @@ char const option_lib_text[4285] = /* 1771 */ "%s error: no saved option state\n\0" /* 1804 */ "'%s' is not a command line option.\n\0" /* 1840 */ "%s error: '%s' is not a recognizable date/time.\n\0" -/* 1890 */ "'%s' not defined\n\0" -/* 1908 */ "%s error: '%s' is not a recognizable time duration.\n\0" -/* 1962 */ "%s error: The %s option must appear %d times.\n\0" -/* 2010 */ "%s error: '%s' is not a recognizable number.\n\0" -/* 2057 */ "%s error: %s exceeds %s keyword count\n\0" -/* 2097 */ "Try '%s %s' for more information.\n\0" -/* 2132 */ "one %s%s option allowed\n\0" -/* 2157 */ "standard output\0" -/* 2173 */ "standard error\0" -/* 2188 */ "write\0" -/* 2194 */ "%s error: %s option value %ld is out of range.\n\0" -/* 2243 */ "%s error: %s option requires the %s option\n\0" -/* 2288 */ "%s warning: cannot save options - %s not regular file\n\0" -/* 2344 */ "\t\t\t\t- an alternate for '%s'\n\0" -/* 2373 */ "Version, usage and configuration options:\0" -/* 2415 */ "\t\t\t\t- default option for unnamed options\n\0" -/* 2457 */ "\t\t\t\t- disabled as '--%s'\n\0" -/* 2483 */ " --- %-14s %s\n\0" -/* 2498 */ "This option has been disabled\0" -/* 2528 */ "\t\t\t\t- enabled by default\n\0" -/* 2554 */ "%s error: only \0" -/* 2571 */ " - examining environment variables named %s_*\n\0" -/* 2618 */ "\t\t\t\t- file must not pre-exist\n\0" -/* 2649 */ "\t\t\t\t- file must pre-exist\n\0" -/* 2676 */ "Options are specified by doubled hyphens and their name or by a single\n" +/* 1890 */ "%s error: '%s' is not a recognizable time duration.\n\0" +/* 1944 */ "%s error: The %s option must appear %d times.\n\0" +/* 1992 */ "%s error: '%s' is not a recognizable number.\n\0" +/* 2039 */ "%s error: %s exceeds %s keyword count\n\0" +/* 2079 */ "Try '%s %s' for more information.\n\0" +/* 2114 */ "one %s%s option allowed\n\0" +/* 2139 */ "standard output\0" +/* 2155 */ "standard error\0" +/* 2170 */ "write\0" +/* 2176 */ "%s error: %s option value %ld is out of range.\n\0" +/* 2225 */ "%s error: %s option requires the %s option\n\0" +/* 2270 */ "%s warning: cannot save options - %s not regular file\n\0" +/* 2326 */ "\t\t\t\t- an alternate for '%s'\n\0" +/* 2355 */ "Version, usage and configuration options:\0" +/* 2397 */ "\t\t\t\t- default option for unnamed options\n\0" +/* 2439 */ "\t\t\t\t- disabled as '--%s'\n\0" +/* 2465 */ " --- %-14s %s\n\0" +/* 2480 */ "This option has been disabled\0" +/* 2510 */ "\t\t\t\t- enabled by default\n\0" +/* 2536 */ "%s error: only \0" +/* 2553 */ " - examining environment variables named %s_*\n\0" +/* 2600 */ "\t\t\t\t- file must not pre-exist\n\0" +/* 2631 */ "\t\t\t\t- file must pre-exist\n\0" +/* 2658 */ "Options are specified by doubled hyphens and their name or by a single\n" "hyphen and the flag character.\n\0" -/* 2779 */ "\n" +/* 2761 */ "\n" "= = = = = = = =\n\n" "This incarnation of genshell will produce\n" "a shell script to parse the options for %s:\n\n\0" -/* 2885 */ " or an integer mask with any of the lower %d bits set\n\0" -/* 2941 */ "\t\t\t\t- is a set membership option\n\0" -/* 2975 */ "\t\t\t\t- must appear between %d and %d times\n\0" -/* 3018 */ "Options are specified by single or double hyphens and their name.\n\0" -/* 3085 */ "\t\t\t\t- may appear multiple times\n\0" -/* 3118 */ "\t\t\t\t- may not be preset\n\0" -/* 3143 */ " Arg Option-Name Description\n\0" -/* 3178 */ " Flg Arg Option-Name Description\n\0" -/* 3216 */ " %3s %s\0" -/* 3224 */ "The '-#' option may omit the hash char\n\0" -/* 3272 */ "All arguments are named options.\n\0" -/* 3306 */ " - reading file %s\0" -/* 3325 */ "\n" +/* 2867 */ " or an integer mask with any of the lower %d bits set\n\0" +/* 2923 */ "\t\t\t\t- is a set membership option\n\0" +/* 2957 */ "\t\t\t\t- must appear between %d and %d times\n\0" +/* 3000 */ "Options are specified by single or double hyphens and their name.\n\0" +/* 3067 */ "\t\t\t\t- may appear multiple times\n\0" +/* 3100 */ "\t\t\t\t- may not be preset\n\0" +/* 3125 */ " Arg Option-Name Description\n\0" +/* 3160 */ " Flg Arg Option-Name Description\n\0" +/* 3198 */ " %3s %s\0" +/* 3206 */ "The '-#' option may omit the hash char\n\0" +/* 3254 */ "All arguments are named options.\n\0" +/* 3288 */ " - reading file %s\0" +/* 3307 */ "\n" "Please send bug reports to: <%s>\n\0" -/* 3361 */ "\t\t\t\t- may NOT appear - preset only\n\0" -/* 3397 */ "\n" +/* 3343 */ "\t\t\t\t- may NOT appear - preset only\n\0" +/* 3379 */ "\n" "The following option preset mechanisms are supported:\n\0" -/* 3453 */ "prohibits these options:\n\0" -/* 3479 */ "prohibits the option '%s'\n\0" -/* 3506 */ "%s%ld to %ld\0" -/* 3519 */ "%sgreater than or equal to %ld\0" -/* 3550 */ "%s%ld exactly\0" -/* 3564 */ "%sit must lie in one of the ranges:\n\0" -/* 3601 */ "%sit must be in the range:\n\0" -/* 3629 */ ", or\n\0" -/* 3635 */ "%sis scalable with a suffix: k/K/m/M/g/G/t/T\n\0" -/* 3681 */ "%sless than or equal to %ld\0" -/* 3709 */ "Operands and options may be intermixed. They will be reordered.\n\0" -/* 3775 */ "requires the option '%s'\n\0" -/* 3801 */ "requires these options:\n\0" -/* 3826 */ " Arg Option-Name Req? Description\n\0" -/* 3866 */ " Flg Arg Option-Name Req? Description\n\0" -/* 3909 */ "or you may use a numeric representation. Preceding these with a '!'\n" +/* 3435 */ "prohibits these options:\n\0" +/* 3461 */ "prohibits the option '%s'\n\0" +/* 3488 */ "%s%ld to %ld\0" +/* 3501 */ "%sgreater than or equal to %ld\0" +/* 3532 */ "%s%ld exactly\0" +/* 3546 */ "%sit must lie in one of the ranges:\n\0" +/* 3583 */ "%sit must be in the range:\n\0" +/* 3611 */ ", or\n\0" +/* 3617 */ "%sis scalable with a suffix: k/K/m/M/g/G/t/T\n\0" +/* 3663 */ "%sless than or equal to %ld\0" +/* 3691 */ "Operands and options may be intermixed. They will be reordered.\n\0" +/* 3757 */ "requires the option '%s'\n\0" +/* 3783 */ "requires these options:\n\0" +/* 3808 */ " Arg Option-Name Req? Description\n\0" +/* 3848 */ " Flg Arg Option-Name Req? Description\n\0" +/* 3891 */ "or you may use a numeric representation. Preceding these with a '!'\n" "will clear the bits, specifying 'none' will clear all bits, and 'all'\n" "will set them all. Multiple entries may be passed as an option\n" "argument list.\n\0" -/* 4128 */ "\t\t\t\t- may appear up to %d times\n\0" -/* 4161 */ "The valid \"%s\" option keywords are:\n\0" -/* 4198 */ "The next option supports vendor supported extra options:\0" -/* 4255 */ "These additional options are:"; +/* 4110 */ "\t\t\t\t- may appear up to %d times\n\0" +/* 4143 */ "The valid \"%s\" option keywords are:\n\0" +/* 4180 */ "The next option supports vendor supported extra options:\0" +/* 4237 */ "These additional options are:"; /* * Now, define (and initialize) the structure that contains @@ -308,7 +306,7 @@ char const option_lib_text[4285] = * Aren't you glad you don't maintain this by hand? */ usage_text_t option_xlateable_txt = { - 108, + 107, eng_zGnuBoolArg, eng_zGnuKeyArg, eng_zGnuNumArg, eng_zGnuStrArg, { option_lib_text + 0, option_lib_text + 31, option_lib_text + 83, @@ -325,27 +323,27 @@ usage_text_t option_xlateable_txt = { option_lib_text + 1490, option_lib_text + 1528, option_lib_text + 1574, option_lib_text + 1619, option_lib_text + 1646, option_lib_text + 1695, option_lib_text + 1744, option_lib_text + 1771, option_lib_text + 1804, - option_lib_text + 1840, option_lib_text + 1890, option_lib_text + 1908, - option_lib_text + 1962, option_lib_text + 2010, option_lib_text + 2057, - option_lib_text + 2097, option_lib_text + 2132, option_lib_text + 2157, - option_lib_text + 2173, option_lib_text + 2188, option_lib_text + 2194, - option_lib_text + 2243, option_lib_text + 2288, option_lib_text + 2344, - option_lib_text + 2373, option_lib_text + 2415, option_lib_text + 2457, - option_lib_text + 2483, option_lib_text + 2498, option_lib_text + 2528, - option_lib_text + 2554, option_lib_text + 2571, option_lib_text + 2618, - option_lib_text + 2649, option_lib_text + 2676, option_lib_text + 2779, - option_lib_text + 2885, option_lib_text + 2941, option_lib_text + 2975, - option_lib_text + 3018, option_lib_text + 3085, option_lib_text + 3118, - option_lib_text + 3143, option_lib_text + 3178, option_lib_text + 3216, - option_lib_text + 3224, option_lib_text + 3272, option_lib_text + 3306, - option_lib_text + 3325, option_lib_text + 3361, option_lib_text + 3397, - option_lib_text + 3453, option_lib_text + 3479, option_lib_text + 3506, - option_lib_text + 3519, option_lib_text + 3550, option_lib_text + 3564, - option_lib_text + 3601, option_lib_text + 3629, option_lib_text + 3635, - option_lib_text + 3681, option_lib_text + 3709, option_lib_text + 3775, - option_lib_text + 3801, option_lib_text + 3826, option_lib_text + 3866, - option_lib_text + 3909, option_lib_text + 4128, option_lib_text + 4161, - option_lib_text + 4198, option_lib_text + 4255 + option_lib_text + 1840, option_lib_text + 1890, option_lib_text + 1944, + option_lib_text + 1992, option_lib_text + 2039, option_lib_text + 2079, + option_lib_text + 2114, option_lib_text + 2139, option_lib_text + 2155, + option_lib_text + 2170, option_lib_text + 2176, option_lib_text + 2225, + option_lib_text + 2270, option_lib_text + 2326, option_lib_text + 2355, + option_lib_text + 2397, option_lib_text + 2439, option_lib_text + 2465, + option_lib_text + 2480, option_lib_text + 2510, option_lib_text + 2536, + option_lib_text + 2553, option_lib_text + 2600, option_lib_text + 2631, + option_lib_text + 2658, option_lib_text + 2761, option_lib_text + 2867, + option_lib_text + 2923, option_lib_text + 2957, option_lib_text + 3000, + option_lib_text + 3067, option_lib_text + 3100, option_lib_text + 3125, + option_lib_text + 3160, option_lib_text + 3198, option_lib_text + 3206, + option_lib_text + 3254, option_lib_text + 3288, option_lib_text + 3307, + option_lib_text + 3343, option_lib_text + 3379, option_lib_text + 3435, + option_lib_text + 3461, option_lib_text + 3488, option_lib_text + 3501, + option_lib_text + 3532, option_lib_text + 3546, option_lib_text + 3583, + option_lib_text + 3611, option_lib_text + 3617, option_lib_text + 3663, + option_lib_text + 3691, option_lib_text + 3757, option_lib_text + 3783, + option_lib_text + 3808, option_lib_text + 3848, option_lib_text + 3891, + option_lib_text + 4110, option_lib_text + 4143, option_lib_text + 4180, + option_lib_text + 4237 } }; #endif /* AUTOOPTS_INTERNAL */ @@ -364,234 +362,230 @@ static void dummy_func(void) { /* LIBOPTS-MESSAGES: */ #line 67 "../autoopts.c" puts(_("allocation of %d bytes failed\n")); -#line 93 "../autoopts.c" +#line 89 "../autoopts.c" puts(_("allocation of %d bytes failed\n")); -#line 53 "../init.c" +#line 48 "../init.c" puts(_("AutoOpts function called without option descriptor\n")); -#line 86 "../init.c" +#line 81 "../init.c" puts(_("\tThis exceeds the compiled library version: ")); -#line 84 "../init.c" +#line 79 "../init.c" puts(_("Automated Options Processing Error!\n" "\t%s called AutoOpts function with structure version %d:%d:%d.\n")); -#line 80 "../autoopts.c" +#line 78 "../autoopts.c" puts(_("realloc of %d bytes at 0x%p failed\n")); -#line 88 "../init.c" +#line 83 "../init.c" puts(_("\tThis is less than the minimum library version: ")); #line 121 "../version.c" puts(_("Automated Options version %s\n" - "\tCopyright (C) 1999-2014 by Bruce Korb - all rights reserved\n")); -#line 87 "../makeshell.c" + "\tCopyright (C) 1999-2017 by Bruce Korb - all rights reserved\n")); +#line 49 "../makeshell.c" puts(_("(AutoOpts bug): %s.\n")); #line 90 "../reset.c" puts(_("optionResetOpt() called, but reset-option not configured")); -#line 295 "../usage.c" +#line 241 "../usage.c" puts(_("could not locate the 'help' option")); -#line 336 "../autoopts.c" +#line 330 "../autoopts.c" puts(_("optionProcess() was called with invalid data")); -#line 751 "../usage.c" +#line 697 "../usage.c" puts(_("invalid argument type specified")); -#line 598 "../find.c" +#line 568 "../find.c" puts(_("defaulted to option with optional arg")); #line 76 "../alias.c" puts(_("aliasing option is out of range.")); -#line 235 "../enum.c" +#line 210 "../enum.c" puts(_("%s error: the keyword '%s' is ambiguous for %s\n")); -#line 108 "../find.c" +#line 78 "../find.c" puts(_(" The following options match:\n")); -#line 293 "../find.c" +#line 263 "../find.c" puts(_("%s: ambiguous option name: %s (matches %d options)\n")); #line 161 "../check.c" puts(_("%s: Command line arguments required\n")); #line 43 "../alias.c" puts(_("%d %s%s options allowed\n")); -#line 94 "../makeshell.c" +#line 56 "../makeshell.c" puts(_("%s error %d (%s) calling %s for '%s'\n")); -#line 306 "../makeshell.c" +#line 268 "../makeshell.c" puts(_("interprocess pipe")); -#line 168 "../version.c" +#line 171 "../version.c" puts(_("error: version option argument '%c' invalid. Use:\n" "\t'v' - version only\n" "\t'c' - version and copyright\n" "\t'n' - version and full copyright notice\n")); #line 58 "../check.c" puts(_("%s error: the '%s' and '%s' options conflict\n")); -#line 217 "../find.c" +#line 187 "../find.c" puts(_("%s: The '%s' option has been disabled.")); -#line 430 "../find.c" +#line 400 "../find.c" puts(_("%s: The '%s' option has been disabled.")); #line 38 "../alias.c" puts(_("-equivalence")); -#line 469 "../find.c" +#line 439 "../find.c" puts(_("%s: illegal option -- %c\n")); #line 110 "../reset.c" puts(_("%s: illegal option -- %c\n")); -#line 271 "../find.c" +#line 241 "../find.c" puts(_("%s: illegal option -- %s\n")); -#line 755 "../find.c" +#line 740 "../find.c" puts(_("%s: illegal option -- %s\n")); #line 118 "../reset.c" puts(_("%s: illegal option -- %s\n")); -#line 335 "../find.c" +#line 305 "../find.c" puts(_("%s: unknown vendor extension option -- %s\n")); -#line 160 "../enum.c" +#line 135 "../enum.c" puts(_(" or an integer from %d through %d\n")); -#line 170 "../enum.c" +#line 145 "../enum.c" puts(_(" or an integer from %d through %d\n")); -#line 750 "../usage.c" +#line 696 "../usage.c" puts(_("%s error: invalid option descriptor for %s\n")); -#line 1084 "../usage.c" +#line 1030 "../usage.c" puts(_("%s error: invalid option descriptor for %s\n")); -#line 385 "../find.c" +#line 355 "../find.c" puts(_("%s: invalid option name: %s\n")); -#line 527 "../find.c" +#line 497 "../find.c" puts(_("%s: The '%s' option requires an argument.\n")); -#line 156 "../autoopts.c" +#line 150 "../autoopts.c" puts(_("(AutoOpts bug): Equivalenced option '%s' was equivalenced to both\n" "\t'%s' and '%s'.")); #line 94 "../check.c" puts(_("%s error: The %s option is required\n")); -#line 632 "../find.c" +#line 602 "../find.c" puts(_("%s: The '%s' option cannot have an argument.\n")); #line 151 "../check.c" puts(_("%s: Command line arguments are not allowed.\n")); -#line 536 "../save.c" +#line 568 "../save.c" puts(_("error %d (%s) creating %s\n")); -#line 235 "../enum.c" +#line 210 "../enum.c" puts(_("%s error: '%s' does not match any %s keywords.\n")); #line 93 "../reset.c" puts(_("%s error: The '%s' option requires an argument.\n")); -#line 186 "../save.c" +#line 122 "../save.c" puts(_("error %d (%s) stat-ing %s\n")); -#line 239 "../save.c" +#line 175 "../save.c" puts(_("error %d (%s) stat-ing %s\n")); #line 143 "../restore.c" puts(_("%s error: no saved option state\n")); -#line 231 "../autoopts.c" +#line 225 "../autoopts.c" puts(_("'%s' is not a command line option.\n")); #line 113 "../time.c" puts(_("%s error: '%s' is not a recognizable date/time.\n")); -#line 131 "../save.c" - puts(_("'%s' not defined\n")); #line 50 "../time.c" puts(_("%s error: '%s' is not a recognizable time duration.\n")); #line 92 "../check.c" puts(_("%s error: The %s option must appear %d times.\n")); #line 165 "../numeric.c" puts(_("%s error: '%s' is not a recognizable number.\n")); -#line 201 "../enum.c" +#line 176 "../enum.c" puts(_("%s error: %s exceeds %s keyword count\n")); -#line 333 "../usage.c" +#line 279 "../usage.c" puts(_("Try '%s %s' for more information.\n")); #line 45 "../alias.c" puts(_("one %s%s option allowed\n")); -#line 208 "../makeshell.c" +#line 170 "../makeshell.c" puts(_("standard output")); -#line 943 "../makeshell.c" +#line 905 "../makeshell.c" puts(_("standard output")); -#line 277 "../usage.c" +#line 223 "../usage.c" puts(_("standard output")); -#line 418 "../usage.c" +#line 364 "../usage.c" puts(_("standard output")); -#line 628 "../usage.c" +#line 574 "../usage.c" puts(_("standard output")); -#line 175 "../version.c" +#line 178 "../version.c" puts(_("standard output")); -#line 277 "../usage.c" +#line 223 "../usage.c" puts(_("standard error")); -#line 418 "../usage.c" +#line 364 "../usage.c" puts(_("standard error")); -#line 628 "../usage.c" +#line 574 "../usage.c" puts(_("standard error")); -#line 175 "../version.c" +#line 178 "../version.c" puts(_("standard error")); -#line 208 "../makeshell.c" +#line 170 "../makeshell.c" puts(_("write")); -#line 943 "../makeshell.c" +#line 905 "../makeshell.c" puts(_("write")); -#line 276 "../usage.c" +#line 222 "../usage.c" puts(_("write")); -#line 417 "../usage.c" +#line 363 "../usage.c" puts(_("write")); -#line 627 "../usage.c" +#line 573 "../usage.c" puts(_("write")); -#line 174 "../version.c" +#line 177 "../version.c" puts(_("write")); #line 60 "../numeric.c" puts(_("%s error: %s option value %ld is out of range.\n")); #line 44 "../check.c" puts(_("%s error: %s option requires the %s option\n")); -#line 130 "../save.c" +#line 121 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 185 "../save.c" +#line 174 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 238 "../save.c" +#line 193 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 257 "../save.c" - puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 535 "../save.c" +#line 567 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); /* END-LIBOPTS-MESSAGES */ /* USAGE-TEXT: */ -#line 876 "../usage.c" +#line 822 "../usage.c" puts(_("\t\t\t\t- an alternate for '%s'\n")); -#line 1151 "../usage.c" +#line 1097 "../usage.c" puts(_("Version, usage and configuration options:")); -#line 927 "../usage.c" +#line 873 "../usage.c" puts(_("\t\t\t\t- default option for unnamed options\n")); -#line 840 "../usage.c" +#line 786 "../usage.c" puts(_("\t\t\t\t- disabled as '--%s'\n")); -#line 1120 "../usage.c" +#line 1066 "../usage.c" puts(_(" --- %-14s %s\n")); -#line 1118 "../usage.c" +#line 1064 "../usage.c" puts(_("This option has been disabled")); -#line 867 "../usage.c" +#line 813 "../usage.c" puts(_("\t\t\t\t- enabled by default\n")); #line 40 "../alias.c" puts(_("%s error: only ")); -#line 1197 "../usage.c" +#line 1143 "../usage.c" puts(_(" - examining environment variables named %s_*\n")); #line 168 "../file.c" puts(_("\t\t\t\t- file must not pre-exist\n")); #line 172 "../file.c" puts(_("\t\t\t\t- file must pre-exist\n")); -#line 383 "../usage.c" +#line 329 "../usage.c" puts(_("Options are specified by doubled hyphens and their name or by a single\n" "hyphen and the flag character.\n")); -#line 921 "../makeshell.c" +#line 882 "../makeshell.c" puts(_("\n" "= = = = = = = =\n\n" "This incarnation of genshell will produce\n" "a shell script to parse the options for %s:\n\n")); -#line 167 "../enum.c" +#line 142 "../enum.c" puts(_(" or an integer mask with any of the lower %d bits set\n")); -#line 900 "../usage.c" +#line 846 "../usage.c" puts(_("\t\t\t\t- is a set membership option\n")); -#line 921 "../usage.c" +#line 867 "../usage.c" puts(_("\t\t\t\t- must appear between %d and %d times\n")); -#line 385 "../usage.c" +#line 331 "../usage.c" puts(_("Options are specified by single or double hyphens and their name.\n")); -#line 907 "../usage.c" +#line 853 "../usage.c" puts(_("\t\t\t\t- may appear multiple times\n")); -#line 894 "../usage.c" +#line 840 "../usage.c" puts(_("\t\t\t\t- may not be preset\n")); -#line 1312 "../usage.c" +#line 1258 "../usage.c" puts(_(" Arg Option-Name Description\n")); -#line 1248 "../usage.c" +#line 1194 "../usage.c" puts(_(" Flg Arg Option-Name Description\n")); -#line 1306 "../usage.c" +#line 1252 "../usage.c" puts(_(" Flg Arg Option-Name Description\n")); -#line 1307 "../usage.c" +#line 1253 "../usage.c" puts(_(" %3s %s")); -#line 1313 "../usage.c" +#line 1259 "../usage.c" puts(_(" %3s %s")); -#line 390 "../usage.c" +#line 336 "../usage.c" puts(_("The '-#' option may omit the hash char\n")); -#line 386 "../usage.c" +#line 332 "../usage.c" puts(_("All arguments are named options.\n")); -#line 974 "../usage.c" +#line 920 "../usage.c" puts(_(" - reading file %s")); -#line 412 "../usage.c" +#line 358 "../usage.c" puts(_("\n" "Please send bug reports to: <%s>\n")); #line 100 "../version.c" @@ -600,17 +594,17 @@ static void dummy_func(void) { #line 129 "../version.c" puts(_("\n" "Please send bug reports to: <%s>\n")); -#line 906 "../usage.c" +#line 852 "../usage.c" puts(_("\t\t\t\t- may NOT appear - preset only\n")); -#line 947 "../usage.c" +#line 893 "../usage.c" puts(_("\n" "The following option preset mechanisms are supported:\n")); -#line 1195 "../usage.c" +#line 1141 "../usage.c" puts(_("\n" "The following option preset mechanisms are supported:\n")); -#line 685 "../usage.c" +#line 631 "../usage.c" puts(_("prohibits these options:\n")); -#line 680 "../usage.c" +#line 626 "../usage.c" puts(_("prohibits the option '%s'\n")); #line 81 "../numeric.c" puts(_("%s%ld to %ld")); @@ -628,28 +622,28 @@ static void dummy_func(void) { puts(_("%sis scalable with a suffix: k/K/m/M/g/G/t/T\n")); #line 77 "../numeric.c" puts(_("%sless than or equal to %ld")); -#line 393 "../usage.c" +#line 339 "../usage.c" puts(_("Operands and options may be intermixed. They will be reordered.\n")); -#line 655 "../usage.c" +#line 601 "../usage.c" puts(_("requires the option '%s'\n")); -#line 658 "../usage.c" +#line 604 "../usage.c" puts(_("requires these options:\n")); -#line 1324 "../usage.c" +#line 1270 "../usage.c" puts(_(" Arg Option-Name Req? Description\n")); -#line 1318 "../usage.c" +#line 1264 "../usage.c" puts(_(" Flg Arg Option-Name Req? Description\n")); -#line 168 "../enum.c" +#line 143 "../enum.c" puts(_("or you may use a numeric representation. Preceding these with a '!'\n" "will clear the bits, specifying 'none' will clear all bits, and 'all'\n" "will set them all. Multiple entries may be passed as an option\n" "argument list.\n")); -#line 913 "../usage.c" +#line 859 "../usage.c" puts(_("\t\t\t\t- may appear up to %d times\n")); -#line 77 "../enum.c" +#line 52 "../enum.c" puts(_("The valid \"%s\" option keywords are:\n")); -#line 1155 "../usage.c" +#line 1101 "../usage.c" puts(_("The next option supports vendor supported extra options:")); -#line 776 "../usage.c" +#line 722 "../usage.c" puts(_("These additional options are:")); /* END-USAGE-TEXT */ } diff --git a/libopts/boolean.c b/libopts/boolean.c index d62888e9e..80e0b0e97 100644 --- a/libopts/boolean.c +++ b/libopts/boolean.c @@ -13,7 +13,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -65,7 +65,7 @@ optionBooleanVal(tOptions * opts, tOptDesc * od) if ((val != 0) || (*pz != NUL)) break; } - /* fall through */ + /* FALLTHROUGH */ case 'N': case 'n': case 'F': diff --git a/libopts/check.c b/libopts/check.c index 9caaf8c3c..7e75e7eca 100644 --- a/libopts/check.c +++ b/libopts/check.c @@ -9,7 +9,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -100,7 +100,7 @@ occurs_enough(tOptions * pOpts, tOptDesc * pOD) * * Make sure that the argument list passes our consistency tests. */ -LOCAL bool +static bool is_consistent(tOptions * pOpts) { tOptDesc * pOD = pOpts->pOptDesc; diff --git a/libopts/compat/compat.h b/libopts/compat/compat.h index 561d55db3..70a5652a2 100644 --- a/libopts/compat/compat.h +++ b/libopts/compat/compat.h @@ -1,9 +1,9 @@ -/* -*- Mode: C -*- +/* -*- Mode: C -*- * * compat.h is free software. * This file is part of AutoGen and AutoOpts. * - * AutoGen Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoGen Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -182,9 +182,9 @@ # include #endif -#ifdef HAVE_STDBOOL_H +#if defined(HAVE_STDBOOL_H) # include -#else +#elif ! defined(bool) typedef enum { false = 0, true = 1 } _Bool; # define bool _Bool diff --git a/libopts/compat/windows-config.h b/libopts/compat/windows-config.h index fb4e048e6..7ce163641 100644 --- a/libopts/compat/windows-config.h +++ b/libopts/compat/windows-config.h @@ -9,7 +9,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/configfile.c b/libopts/configfile.c index 8f802bc25..783a9d8ac 100644 --- a/libopts/configfile.c +++ b/libopts/configfile.c @@ -9,7 +9,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -28,50 +28,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static void -file_preset(tOptions * opts, char const * fname, int dir); - -static char * -handle_comment(char * txt); - -static char * -handle_cfg(tOptions * opts, tOptState * ost, char * txt, int dir); - -static char * -handle_directive(tOptions * opts, char * txt); - -static char * -aoflags_directive(tOptions * opts, char * txt); - -static char * -program_directive(tOptions * opts, char * txt); - -static char * -handle_section(tOptions * opts, char * txt); - -static int -parse_xml_encoding(char ** ppz); - -static char * -trim_xml_text(char * intxt, char const * pznm, tOptionLoadMode mode); - -static void -cook_xml_text(char * pzData); - -static char * -handle_struct(tOptions * opts, tOptState * ost, char * txt, int dir); - -static char const * -parse_keyword(tOptions * opts, char const * txt, tOptionValue * typ); - -static char const * -parse_set_mem(tOptions * opts, char const * txt, tOptionValue * typ); - -static char const * -parse_value(char const * txt, tOptionValue * typ); -/* = = = END-STATIC-FORWARD = = = */ - /** * Skip over some unknown attribute * @param[in] txt start of skpped text @@ -145,7 +101,7 @@ configFileLoad(char const * fname) /*=export_func optionFindValue * - * what: find a hierarchically valued option instance + * what: find a hierarcicaly valued option instance * arg: + const tOptDesc * + odesc + an option with a nested arg type + * arg: + char const * + name + name of value to find + * arg: + char const * + val + the matching value + @@ -220,7 +176,7 @@ optionFindValue(const tOptDesc * odesc, char const * name, char const * val) * * FIXME: the handling of 'pzName' and 'pzVal' is just wrong. * - * what: find a hierarchically valued option instance + * what: find a hierarcicaly valued option instance * arg: + const tOptDesc * + odesc + an option with a nested arg type + * arg: + const tOptionValue * + pPrevVal + the last entry + * arg: + char const * + name + name of value to find + @@ -466,7 +422,8 @@ file_preset(tOptions * opts, char const * fname, int dir) ftext = strchr(ftext + 2, '>'); if (ftext++ != NULL) break; - /* fall through */ + /* FALLTHROUGH */ + default: ftext = NULL; } @@ -626,9 +583,9 @@ handle_directive(tOptions * opts, char * txt) for (ix = 0; ix < dir_ct; ix++) { size_t len = strlen(dir_names[ix]); - if ( (strncmp(txt + 2, dir_names[ix], len) == 0) - && (! IS_VALUE_NAME_CHAR(txt[len+2])) ) - return dir_disp[ix](opts, txt + len + 2); + if ( (strncmp(txt, dir_names[ix], len) == 0) + && (! IS_VALUE_NAME_CHAR(txt[len])) ) + return dir_disp[ix](opts, txt + len); } /* @@ -681,38 +638,28 @@ aoflags_directive(tOptions * opts, char * txt) static char * program_directive(tOptions * opts, char * txt) { - static char const ttlfmt[] = "pzProgName); - memcpy(ttl, ttlfmt, sizeof(ttlfmt) - 1); - memcpy(ttl + sizeof(ttlfmt) - 1, zCfgProg, ttl_len - (sizeof(ttlfmt) - 1)); - - do { - txt = SPN_WHITESPACE_CHARS(txt+1); + for (;; txt += zCfgProg_LEN) { + txt = SPN_WHITESPACE_CHARS(txt); if ( (strneqvcmp(txt, opts->pzProgName, (int)name_len) == 0) - && (IS_END_XML_TOKEN_CHAR(txt[name_len])) ) { - txt += name_len; - break; - } + && (IS_END_XML_TOKEN_CHAR(txt[name_len])) ) - txt = strstr(txt, ttl); - } while (txt != NULL); + return txt + name_len; - AGFREE(ttl); - if (txt != NULL) - for (;;) { - if (*txt == NUL) { - txt = NULL; - break; - } - if (*(txt++) == '>') - break; - } + txt = strstr(txt, zCfgProg); + if (txt == NULL) + return txt; + } - return txt; + for (;;) { + if (*txt == NUL) + return NULL; + + if (*(txt++) == '>') + return txt; + } } /** @@ -1006,7 +953,7 @@ handle_struct(tOptions * opts, tOptState * ost, char * txt, int dir) * scanning the "homerc" list, or from a specific file request. * (see "optionFileLoad()", the implementation for --load-opts) */ -LOCAL void +static void intern_file_load(tOptions * opts) { uint32_t svfl; @@ -1207,7 +1154,7 @@ optionLoadOpt(tOptions * opts, tOptDesc * odesc) * * @returns NULL on failure, otherwise the scan point */ -LOCAL char const * +static char const * parse_attrs(tOptions * opts, char const * txt, tOptionLoadMode * pMode, tOptionValue * pType) { diff --git a/libopts/cook.c b/libopts/cook.c index d5af56f8d..5240540f3 100644 --- a/libopts/cook.c +++ b/libopts/cook.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -29,14 +29,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static char * -nl_count(char * start, char * end, int * lnct_p); - -static bool -contiguous_quote(char ** pps, char * pq, int * lnct_p); -/* = = = END-STATIC-FORWARD = = = */ - /*=export_func ao_string_cook_escape_char * private: * diff --git a/libopts/enum.c b/libopts/enum.c index 25aac0d9c..25c431a58 100644 --- a/libopts/enum.c +++ b/libopts/enum.c @@ -14,7 +14,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -33,31 +33,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static void -enum_err(tOptions * pOpts, tOptDesc * pOD, - char const * const * paz_names, int name_ct); - -static uintptr_t -find_name(char const * name, tOptions * pOpts, tOptDesc * pOD, - char const * const * paz_names, unsigned int name_ct); - -static void -set_memb_shell(tOptions * pOpts, tOptDesc * pOD, char const * const * paz_names, - unsigned int name_ct); - -static void -set_memb_names(tOptions * opts, tOptDesc * od, char const * const * nm_list, - unsigned int nm_ct); - -static uintptr_t -check_membership_start(tOptDesc * od, char const ** argp, bool * invert); - -static uintptr_t -find_member_bit(tOptions * opts, tOptDesc * od, char const * pz, int len, - char const * const * nm_list, unsigned int nm_ct); -/* = = = END-STATIC-FORWARD = = = */ - static void enum_err(tOptions * pOpts, tOptDesc * pOD, char const * const * paz_names, int name_ct) @@ -254,7 +229,8 @@ find_name(char const * name, tOptions * pOpts, tOptDesc * pOD, char const * optionKeywordName(tOptDesc * pOD, unsigned int enum_val) { - tOptDesc od = { 0 }; + tOptDesc od; + memset(&od, 0, sizeof(od)); od.optArg.argEnum = enum_val; (*(pOD->pOptProc))(OPTPROC_RETURN_VALNAME, &od ); diff --git a/libopts/env.c b/libopts/env.c index 37db9c0cd..16f0e9513 100644 --- a/libopts/env.c +++ b/libopts/env.c @@ -13,7 +13,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -32,19 +32,13 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static void -do_env_opt(tOptState * os, char * env_name, - tOptions * pOpts, teEnvPresetType type); -/* = = = END-STATIC-FORWARD = = = */ - /* * doPrognameEnv - check for preset values from the ${PROGNAME} * environment variable. This is accomplished by parsing the text into * tokens, temporarily replacing the arg vector and calling * immediate_opts and/or regular_opts. */ -LOCAL void +static void doPrognameEnv(tOptions * pOpts, teEnvPresetType type) { char const * env_opts = getenv(pOpts->pzPROGNAME); @@ -187,7 +181,7 @@ do_env_opt(tOptState * os, char * env_name, * env_presets - check for preset values from the envrionment * This routine should process in all, immediate or normal modes.... */ -LOCAL void +static void env_presets(tOptions * pOpts, teEnvPresetType type) { int ct; diff --git a/libopts/file.c b/libopts/file.c index ddb2e324e..14efe8fe3 100644 --- a/libopts/file.c +++ b/libopts/file.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/find.c b/libopts/find.c index c836b1e24..03ae10373 100644 --- a/libopts/find.c +++ b/libopts/find.c @@ -12,7 +12,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -31,36 +31,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static int -parse_opt(char const ** nm_pp, char ** arg_pp, char * buf, size_t bufsz); - -static void -opt_ambiguities(tOptions * opts, char const * name, int nm_len); - -static int -opt_match_ct(tOptions * opts, char const * name, int nm_len, - int * ixp, bool * disable); - -static tSuccess -opt_set(tOptions * opts, char * arg, int idx, bool disable, tOptState * st); - -static tSuccess -opt_unknown(tOptions * opts, char const * name, char * arg, tOptState * st); - -static tSuccess -opt_ambiguous(tOptions * opts, char const * name, int match_ct); - -static tSuccess -get_opt_arg_must(tOptions * opts, tOptState * o_st); - -static tSuccess -get_opt_arg_may(tOptions * pOpts, tOptState * o_st); - -static tSuccess -get_opt_arg_none(tOptions * pOpts, tOptState * o_st); -/* = = = END-STATIC-FORWARD = = = */ - /** * find the name and name length we are looking for */ @@ -367,7 +337,7 @@ optionVendorOption(tOptions * pOpts, tOptDesc * pOD) * * @return success status */ -LOCAL tSuccess +static tSuccess opt_find_long(tOptions * opts, char const * opt_name, tOptState * state) { char name_buf[128]; @@ -408,7 +378,7 @@ opt_find_long(tOptions * opts, char const * opt_name, tOptState * state) * @param optValue option flag character * @param pOptState state about current option */ -LOCAL tSuccess +static tSuccess opt_find_short(tOptions * pOpts, uint_t optValue, tOptState * pOptState) { tOptDesc * pRes = pOpts->pOptDesc; @@ -638,6 +608,7 @@ get_opt_arg_none(tOptions * pOpts, tOptState * o_st) */ else pOpts->pzCurOpt = NULL; + return SUCCESS; } @@ -648,7 +619,7 @@ get_opt_arg_none(tOptions * pOpts, tOptState * o_st) * @param[in,out] o_st the option processing state * @returns SUCCESS or FAILURE */ -LOCAL tSuccess +static tSuccess get_opt_arg(tOptions * opts, tOptState * o_st) { o_st->flags |= (o_st->pOD->fOptState & OPTST_PERSISTENT_MASK); @@ -658,10 +629,24 @@ get_opt_arg(tOptions * opts, tOptState * o_st) * are handled with the "none" procedure. Otherwise, check the * optional flag and call either the "may" or "must" function. */ - if ( ((o_st->flags & OPTST_DISABLED) != 0) - || (OPTST_GET_ARGTYPE(o_st->flags) == OPARG_TYPE_NONE)) + if ((o_st->flags & OPTST_DISABLED) != 0) return get_opt_arg_none(opts, o_st); - + + switch (OPTST_GET_ARGTYPE(o_st->flags)) { + case OPARG_TYPE_STATIC: + { + /* + * Propagate the static arg + */ + tSuccess res = get_opt_arg_none(opts, o_st); + o_st->pzOptArg = o_st->pOD->optArg.argString; + return res; + } + + case OPARG_TYPE_NONE: + return get_opt_arg_none(opts, o_st); + } + if (o_st->flags & OPTST_ARG_OPTIONAL) return get_opt_arg_may( opts, o_st); @@ -675,7 +660,7 @@ get_opt_arg(tOptions * opts, tOptState * o_st) * @param[in,out] o_st the option processing state * @returns SUCCESS or FAILURE */ -LOCAL tSuccess +static tSuccess find_opt(tOptions * opts, tOptState * o_st) { /* diff --git a/libopts/genshell.c b/libopts/genshell.c index 418116b86..05182a601 100644 --- a/libopts/genshell.c +++ b/libopts/genshell.c @@ -6,7 +6,7 @@ * From the definitions genshell.def * and the template file options * - * Generated from AutoOpts 41:1:16 templates. + * Generated from AutoOpts 42:1:17 templates. * * AutoOpts is a copyrighted work. This source file is not encumbered * by AutoOpts licensing, but is provided under the licensing terms chosen @@ -19,7 +19,7 @@ * The genshellopt program is copyrighted and licensed * under the following terms: * - * Copyright (C) 1999-2014 Bruce Korb, all rights reserved. + * Copyright (C) 1999-2018 Bruce Korb, all rights reserved. * This is free software. It is licensed for use, modification and * redistribution under the terms of the GNU Lesser General Public License, * version 2 or later @@ -43,10 +43,15 @@ #define OPTION_CODE_COMPILE 1 #include "genshell.h" #include +#include +#include +#include #include #include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -66,7 +71,7 @@ extern tUsageProc genshelloptUsage; */ static char const genshellopt_opt_strs[1769] = /* 0 */ "genshellopt 1\n" - "Copyright (C) 1999-2014 Bruce Korb, all rights reserved.\n" + "Copyright (C) 1999-2018 Bruce Korb, all rights reserved.\n" "This is free software. It is licensed for use, modification and\n" "redistribution under the terms of the GNU Lesser General Public License,\n" "version 2 or later \n\0" @@ -258,7 +263,7 @@ static tOptDesc optDesc[GENSHELL_OPTION_CT] = { #define zDetail (genshellopt_opt_strs+1534) /** The full version string for genshellopt. */ #define zFullVersion (genshellopt_opt_strs+1755) -/* extracted from optcode.tlib near line 364 */ +/* extracted from optcode.tlib near line 342 */ #if defined(ENABLE_NLS) # define OPTPROC_BASE OPTPROC_TRANSLATE @@ -481,19 +486,19 @@ static void bogus_function(void) { extract the correct strings. These strings are actually referenced by a field name in the genshelloptOptions structure noted in the comments below. The literal text is defined in genshellopt_opt_strs. - + NOTE: the strings below are segmented with respect to the source string genshellopt_opt_strs. The strings above are handed off for translation at run time a paragraph at a time. Consequently, they are presented here for translation a paragraph at a time. - + ALSO: often the description for an option will reference another option by name. These are set off with apostrophe quotes (I hope). Do not translate option names. */ /* referenced via genshelloptOptions.pzCopyright */ puts(_("genshellopt 1\n\ -Copyright (C) 1999-2014 Bruce Korb, all rights reserved.\n\ +Copyright (C) 1999-2018 Bruce Korb, all rights reserved.\n\ This is free software. It is licensed for use, modification and\n\ redistribution under the terms of the GNU Lesser General Public License,\n\ version 2 or later \n")); @@ -551,234 +556,230 @@ by the newly generated text. The first '#!' line will be regenerated.\n")); /* LIBOPTS-MESSAGES: */ #line 67 "../autoopts.c" puts(_("allocation of %d bytes failed\n")); -#line 93 "../autoopts.c" +#line 89 "../autoopts.c" puts(_("allocation of %d bytes failed\n")); -#line 53 "../init.c" +#line 48 "../init.c" puts(_("AutoOpts function called without option descriptor\n")); -#line 86 "../init.c" +#line 81 "../init.c" puts(_("\tThis exceeds the compiled library version: ")); -#line 84 "../init.c" +#line 79 "../init.c" puts(_("Automated Options Processing Error!\n" "\t%s called AutoOpts function with structure version %d:%d:%d.\n")); -#line 80 "../autoopts.c" +#line 78 "../autoopts.c" puts(_("realloc of %d bytes at 0x%p failed\n")); -#line 88 "../init.c" +#line 83 "../init.c" puts(_("\tThis is less than the minimum library version: ")); #line 121 "../version.c" puts(_("Automated Options version %s\n" - "\tCopyright (C) 1999-2014 by Bruce Korb - all rights reserved\n")); -#line 87 "../makeshell.c" + "\tCopyright (C) 1999-2017 by Bruce Korb - all rights reserved\n")); +#line 49 "../makeshell.c" puts(_("(AutoOpts bug): %s.\n")); #line 90 "../reset.c" puts(_("optionResetOpt() called, but reset-option not configured")); -#line 295 "../usage.c" +#line 241 "../usage.c" puts(_("could not locate the 'help' option")); -#line 336 "../autoopts.c" +#line 330 "../autoopts.c" puts(_("optionProcess() was called with invalid data")); -#line 751 "../usage.c" +#line 697 "../usage.c" puts(_("invalid argument type specified")); -#line 598 "../find.c" +#line 568 "../find.c" puts(_("defaulted to option with optional arg")); #line 76 "../alias.c" puts(_("aliasing option is out of range.")); -#line 235 "../enum.c" +#line 210 "../enum.c" puts(_("%s error: the keyword '%s' is ambiguous for %s\n")); -#line 108 "../find.c" +#line 78 "../find.c" puts(_(" The following options match:\n")); -#line 293 "../find.c" +#line 263 "../find.c" puts(_("%s: ambiguous option name: %s (matches %d options)\n")); #line 161 "../check.c" puts(_("%s: Command line arguments required\n")); #line 43 "../alias.c" puts(_("%d %s%s options allowed\n")); -#line 94 "../makeshell.c" +#line 56 "../makeshell.c" puts(_("%s error %d (%s) calling %s for '%s'\n")); -#line 306 "../makeshell.c" +#line 268 "../makeshell.c" puts(_("interprocess pipe")); -#line 168 "../version.c" +#line 171 "../version.c" puts(_("error: version option argument '%c' invalid. Use:\n" "\t'v' - version only\n" "\t'c' - version and copyright\n" "\t'n' - version and full copyright notice\n")); #line 58 "../check.c" puts(_("%s error: the '%s' and '%s' options conflict\n")); -#line 217 "../find.c" +#line 187 "../find.c" puts(_("%s: The '%s' option has been disabled.")); -#line 430 "../find.c" +#line 400 "../find.c" puts(_("%s: The '%s' option has been disabled.")); #line 38 "../alias.c" puts(_("-equivalence")); -#line 469 "../find.c" +#line 439 "../find.c" puts(_("%s: illegal option -- %c\n")); #line 110 "../reset.c" puts(_("%s: illegal option -- %c\n")); -#line 271 "../find.c" +#line 241 "../find.c" puts(_("%s: illegal option -- %s\n")); -#line 755 "../find.c" +#line 740 "../find.c" puts(_("%s: illegal option -- %s\n")); #line 118 "../reset.c" puts(_("%s: illegal option -- %s\n")); -#line 335 "../find.c" +#line 305 "../find.c" puts(_("%s: unknown vendor extension option -- %s\n")); -#line 160 "../enum.c" +#line 135 "../enum.c" puts(_(" or an integer from %d through %d\n")); -#line 170 "../enum.c" +#line 145 "../enum.c" puts(_(" or an integer from %d through %d\n")); -#line 750 "../usage.c" +#line 696 "../usage.c" puts(_("%s error: invalid option descriptor for %s\n")); -#line 1084 "../usage.c" +#line 1030 "../usage.c" puts(_("%s error: invalid option descriptor for %s\n")); -#line 385 "../find.c" +#line 355 "../find.c" puts(_("%s: invalid option name: %s\n")); -#line 527 "../find.c" +#line 497 "../find.c" puts(_("%s: The '%s' option requires an argument.\n")); -#line 156 "../autoopts.c" +#line 150 "../autoopts.c" puts(_("(AutoOpts bug): Equivalenced option '%s' was equivalenced to both\n" "\t'%s' and '%s'.")); #line 94 "../check.c" puts(_("%s error: The %s option is required\n")); -#line 632 "../find.c" +#line 602 "../find.c" puts(_("%s: The '%s' option cannot have an argument.\n")); #line 151 "../check.c" puts(_("%s: Command line arguments are not allowed.\n")); -#line 536 "../save.c" +#line 568 "../save.c" puts(_("error %d (%s) creating %s\n")); -#line 235 "../enum.c" +#line 210 "../enum.c" puts(_("%s error: '%s' does not match any %s keywords.\n")); #line 93 "../reset.c" puts(_("%s error: The '%s' option requires an argument.\n")); -#line 186 "../save.c" +#line 122 "../save.c" puts(_("error %d (%s) stat-ing %s\n")); -#line 239 "../save.c" +#line 175 "../save.c" puts(_("error %d (%s) stat-ing %s\n")); #line 143 "../restore.c" puts(_("%s error: no saved option state\n")); -#line 231 "../autoopts.c" +#line 225 "../autoopts.c" puts(_("'%s' is not a command line option.\n")); #line 113 "../time.c" puts(_("%s error: '%s' is not a recognizable date/time.\n")); -#line 131 "../save.c" - puts(_("'%s' not defined\n")); #line 50 "../time.c" puts(_("%s error: '%s' is not a recognizable time duration.\n")); #line 92 "../check.c" puts(_("%s error: The %s option must appear %d times.\n")); #line 165 "../numeric.c" puts(_("%s error: '%s' is not a recognizable number.\n")); -#line 201 "../enum.c" +#line 176 "../enum.c" puts(_("%s error: %s exceeds %s keyword count\n")); -#line 333 "../usage.c" +#line 279 "../usage.c" puts(_("Try '%s %s' for more information.\n")); #line 45 "../alias.c" puts(_("one %s%s option allowed\n")); -#line 208 "../makeshell.c" +#line 170 "../makeshell.c" puts(_("standard output")); -#line 943 "../makeshell.c" +#line 905 "../makeshell.c" puts(_("standard output")); -#line 277 "../usage.c" +#line 223 "../usage.c" puts(_("standard output")); -#line 418 "../usage.c" +#line 364 "../usage.c" puts(_("standard output")); -#line 628 "../usage.c" +#line 574 "../usage.c" puts(_("standard output")); -#line 175 "../version.c" +#line 178 "../version.c" puts(_("standard output")); -#line 277 "../usage.c" +#line 223 "../usage.c" puts(_("standard error")); -#line 418 "../usage.c" +#line 364 "../usage.c" puts(_("standard error")); -#line 628 "../usage.c" +#line 574 "../usage.c" puts(_("standard error")); -#line 175 "../version.c" +#line 178 "../version.c" puts(_("standard error")); -#line 208 "../makeshell.c" +#line 170 "../makeshell.c" puts(_("write")); -#line 943 "../makeshell.c" +#line 905 "../makeshell.c" puts(_("write")); -#line 276 "../usage.c" +#line 222 "../usage.c" puts(_("write")); -#line 417 "../usage.c" +#line 363 "../usage.c" puts(_("write")); -#line 627 "../usage.c" +#line 573 "../usage.c" puts(_("write")); -#line 174 "../version.c" +#line 177 "../version.c" puts(_("write")); #line 60 "../numeric.c" puts(_("%s error: %s option value %ld is out of range.\n")); #line 44 "../check.c" puts(_("%s error: %s option requires the %s option\n")); -#line 130 "../save.c" - puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 185 "../save.c" +#line 121 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 238 "../save.c" +#line 174 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 257 "../save.c" +#line 193 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); -#line 535 "../save.c" +#line 567 "../save.c" puts(_("%s warning: cannot save options - %s not regular file\n")); /* END-LIBOPTS-MESSAGES */ /* USAGE-TEXT: */ -#line 876 "../usage.c" +#line 822 "../usage.c" puts(_("\t\t\t\t- an alternate for '%s'\n")); -#line 1151 "../usage.c" +#line 1097 "../usage.c" puts(_("Version, usage and configuration options:")); -#line 927 "../usage.c" +#line 873 "../usage.c" puts(_("\t\t\t\t- default option for unnamed options\n")); -#line 840 "../usage.c" +#line 786 "../usage.c" puts(_("\t\t\t\t- disabled as '--%s'\n")); -#line 1120 "../usage.c" +#line 1066 "../usage.c" puts(_(" --- %-14s %s\n")); -#line 1118 "../usage.c" +#line 1064 "../usage.c" puts(_("This option has been disabled")); -#line 867 "../usage.c" +#line 813 "../usage.c" puts(_("\t\t\t\t- enabled by default\n")); #line 40 "../alias.c" puts(_("%s error: only ")); -#line 1197 "../usage.c" +#line 1143 "../usage.c" puts(_(" - examining environment variables named %s_*\n")); #line 168 "../file.c" puts(_("\t\t\t\t- file must not pre-exist\n")); #line 172 "../file.c" puts(_("\t\t\t\t- file must pre-exist\n")); -#line 383 "../usage.c" +#line 329 "../usage.c" puts(_("Options are specified by doubled hyphens and their name or by a single\n" "hyphen and the flag character.\n")); -#line 921 "../makeshell.c" +#line 882 "../makeshell.c" puts(_("\n" "= = = = = = = =\n\n" "This incarnation of genshell will produce\n" "a shell script to parse the options for %s:\n\n")); -#line 167 "../enum.c" +#line 142 "../enum.c" puts(_(" or an integer mask with any of the lower %d bits set\n")); -#line 900 "../usage.c" +#line 846 "../usage.c" puts(_("\t\t\t\t- is a set membership option\n")); -#line 921 "../usage.c" +#line 867 "../usage.c" puts(_("\t\t\t\t- must appear between %d and %d times\n")); -#line 385 "../usage.c" +#line 331 "../usage.c" puts(_("Options are specified by single or double hyphens and their name.\n")); -#line 907 "../usage.c" +#line 853 "../usage.c" puts(_("\t\t\t\t- may appear multiple times\n")); -#line 894 "../usage.c" +#line 840 "../usage.c" puts(_("\t\t\t\t- may not be preset\n")); -#line 1312 "../usage.c" +#line 1258 "../usage.c" puts(_(" Arg Option-Name Description\n")); -#line 1248 "../usage.c" +#line 1194 "../usage.c" puts(_(" Flg Arg Option-Name Description\n")); -#line 1306 "../usage.c" +#line 1252 "../usage.c" puts(_(" Flg Arg Option-Name Description\n")); -#line 1307 "../usage.c" +#line 1253 "../usage.c" puts(_(" %3s %s")); -#line 1313 "../usage.c" +#line 1259 "../usage.c" puts(_(" %3s %s")); -#line 390 "../usage.c" +#line 336 "../usage.c" puts(_("The '-#' option may omit the hash char\n")); -#line 386 "../usage.c" +#line 332 "../usage.c" puts(_("All arguments are named options.\n")); -#line 974 "../usage.c" +#line 920 "../usage.c" puts(_(" - reading file %s")); -#line 412 "../usage.c" +#line 358 "../usage.c" puts(_("\n" "Please send bug reports to: <%s>\n")); #line 100 "../version.c" @@ -787,17 +788,17 @@ by the newly generated text. The first '#!' line will be regenerated.\n")); #line 129 "../version.c" puts(_("\n" "Please send bug reports to: <%s>\n")); -#line 906 "../usage.c" +#line 852 "../usage.c" puts(_("\t\t\t\t- may NOT appear - preset only\n")); -#line 947 "../usage.c" +#line 893 "../usage.c" puts(_("\n" "The following option preset mechanisms are supported:\n")); -#line 1195 "../usage.c" +#line 1141 "../usage.c" puts(_("\n" "The following option preset mechanisms are supported:\n")); -#line 685 "../usage.c" +#line 631 "../usage.c" puts(_("prohibits these options:\n")); -#line 680 "../usage.c" +#line 626 "../usage.c" puts(_("prohibits the option '%s'\n")); #line 81 "../numeric.c" puts(_("%s%ld to %ld")); @@ -815,28 +816,28 @@ by the newly generated text. The first '#!' line will be regenerated.\n")); puts(_("%sis scalable with a suffix: k/K/m/M/g/G/t/T\n")); #line 77 "../numeric.c" puts(_("%sless than or equal to %ld")); -#line 393 "../usage.c" +#line 339 "../usage.c" puts(_("Operands and options may be intermixed. They will be reordered.\n")); -#line 655 "../usage.c" +#line 601 "../usage.c" puts(_("requires the option '%s'\n")); -#line 658 "../usage.c" +#line 604 "../usage.c" puts(_("requires these options:\n")); -#line 1324 "../usage.c" +#line 1270 "../usage.c" puts(_(" Arg Option-Name Req? Description\n")); -#line 1318 "../usage.c" +#line 1264 "../usage.c" puts(_(" Flg Arg Option-Name Req? Description\n")); -#line 168 "../enum.c" +#line 143 "../enum.c" puts(_("or you may use a numeric representation. Preceding these with a '!'\n" "will clear the bits, specifying 'none' will clear all bits, and 'all'\n" "will set them all. Multiple entries may be passed as an option\n" "argument list.\n")); -#line 913 "../usage.c" +#line 859 "../usage.c" puts(_("\t\t\t\t- may appear up to %d times\n")); -#line 77 "../enum.c" +#line 52 "../enum.c" puts(_("The valid \"%s\" option keywords are:\n")); -#line 1155 "../usage.c" +#line 1101 "../usage.c" puts(_("The next option supports vendor supported extra options:")); -#line 776 "../usage.c" +#line 722 "../usage.c" puts(_("These additional options are:")); /* END-USAGE-TEXT */ } diff --git a/libopts/genshell.h b/libopts/genshell.h index c371f528d..994af1690 100644 --- a/libopts/genshell.h +++ b/libopts/genshell.h @@ -6,7 +6,7 @@ * From the definitions genshell.def * and the template file options * - * Generated from AutoOpts 41:1:16 templates. + * Generated from AutoOpts 42:1:17 templates. * * AutoOpts is a copyrighted work. This header file is not encumbered * by AutoOpts licensing, but is provided under the licensing terms chosen @@ -19,7 +19,7 @@ * The genshellopt program is copyrighted and licensed * under the following terms: * - * Copyright (C) 1999-2014 Bruce Korb, all rights reserved. + * Copyright (C) 1999-2018 Bruce Korb, all rights reserved. * This is free software. It is licensed for use, modification and * redistribution under the terms of the GNU Lesser General Public License, * version 2 or later @@ -47,6 +47,8 @@ #ifndef AUTOOPTS_GENSHELL_H_GUARD #define AUTOOPTS_GENSHELL_H_GUARD 1 #include +#include +#include /** * Ensure that the library used for compiling this generated header is at @@ -55,13 +57,19 @@ * tolerable version is at least as old as what was current when the header * template was released. */ -#define AO_TEMPLATE_VERSION 167937 +#define AO_TEMPLATE_VERSION 172033 #if (AO_TEMPLATE_VERSION < OPTIONS_MINIMUM_VERSION) \ || (AO_TEMPLATE_VERSION > OPTIONS_STRUCT_VERSION) # error option template version mismatches autoopts/options.h header Choke Me. #endif +#if GCC_VERSION > 40400 +#define NOT_REACHED __builtin_unreachable(); +#else +#define NOT_REACHED +#endif + /** * Enumeration of each option type for genshellopt */ @@ -150,6 +158,12 @@ typedef enum { #ifdef __cplusplus extern "C" { #endif +/* + * global exported definitions + */ +#define ch_t unsigned char +#define cc_t const unsigned char +#define cch_t char const /* * * * * * @@ -201,6 +215,7 @@ static inline char* aoGetsText(char const* pz) { # endif #endif /* ENABLE_NLS */ + #ifdef __cplusplus } #endif diff --git a/libopts/gettext.h b/libopts/gettext.h index 4aa138ea1..87ec81930 100644 --- a/libopts/gettext.h +++ b/libopts/gettext.h @@ -1,5 +1,5 @@ /* Convenience header for conditional use of GNU . - Copyright (C) 1995-1998, 2000-2002, 2004-2006, 2009-2016 Free Software + Copyright (C) 1995-1998, 2000-2002, 2004-2006, 2009-2018 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify @@ -13,13 +13,14 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along - with this program; if not, see . */ + with this program; if not, see . */ #ifndef _LIBGETTEXT_H #define _LIBGETTEXT_H 1 -/* NLS can be disabled through the configure --disable-nls option. */ -#if ENABLE_NLS +/* NLS can be disabled through the configure --disable-nls option + or through "#define ENABLE NLS 0" before including this file. */ +#if defined ENABLE_NLS && ENABLE_NLS /* Get declarations of GNU message catalog functions. */ # include @@ -184,7 +185,8 @@ npgettext_aux (const char *domain, #include #if (((__GNUC__ >= 3 || __GNUG__ >= 2) && !defined __STRICT_ANSI__) \ - /* || __STDC_VERSION__ >= 199901L */ ) + /* || __STDC_VERSION__ == 199901L + || (__STDC_VERSION__ >= 201112L && !defined __STDC_NO_VLA__) */ ) # define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 1 #else # define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS 0 diff --git a/libopts/init.c b/libopts/init.c index 62bd283da..b65e59391 100644 --- a/libopts/init.c +++ b/libopts/init.c @@ -9,7 +9,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -28,11 +28,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static tSuccess -do_presets(tOptions * opts); -/* = = = END-STATIC-FORWARD = = = */ - /** * Make sure the option descriptor is there and that we understand it. * This should be called from any user entry point where one needs to @@ -46,7 +41,7 @@ do_presets(tOptions * opts); * @param[in] pname name of program, from argv[] * @returns SUCCESS or FAILURE */ -LOCAL tSuccess +static tSuccess validate_struct(tOptions * opts, char const * pname) { if (opts == NULL) { @@ -142,7 +137,7 @@ validate_struct(tOptions * opts, char const * pname) * @param pOpts program options descriptor * @returns SUCCESS or FAILURE */ -LOCAL tSuccess +static tSuccess immediate_opts(tOptions * opts) { tSuccess res; @@ -247,7 +242,7 @@ do_presets(tOptions * opts) * @param[in] a_ct program argument count * @param[in] a_v program argument vector */ -LOCAL bool +static bool ao_initialize(tOptions * opts, int a_ct, char ** a_v) { if ((opts->fOptSet & OPTPROC_INITDONE) != 0) diff --git a/libopts/intprops.h b/libopts/intprops.h index 65bbfffce..af456ff58 100644 --- a/libopts/intprops.h +++ b/libopts/intprops.h @@ -1,6 +1,6 @@ /* intprops.h -- properties of integer types - Copyright (C) 2001-2016 Free Software Foundation, Inc. + Copyright (C) 2001-2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published @@ -13,7 +13,7 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . */ + along with this program. If not, see . */ /* Written by Paul Eggert. */ @@ -26,7 +26,7 @@ #define _GL_INT_CONVERT(e, v) (0 * (e) + (v)) /* Act like _GL_INT_CONVERT (E, -V) but work around a bug in IRIX 6.5 cc; see - . */ + . */ #define _GL_INT_NEGATE_CONVERT(e, v) (0 * (e) - (v)) /* The extra casts in the following macros work around compiler bugs, @@ -46,12 +46,16 @@ /* Minimum and maximum values for integer types and expressions. */ +/* The width in bits of the integer type or expression T. + Padding bits are not supported; this is checked at compile-time below. */ +#define TYPE_WIDTH(t) (sizeof (t) * CHAR_BIT) + /* The maximum and minimum values for the integer type T. */ #define TYPE_MINIMUM(t) ((t) ~ TYPE_MAXIMUM (t)) #define TYPE_MAXIMUM(t) \ ((t) (! TYPE_SIGNED (t) \ ? (t) -1 \ - : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1))) + : ((((t) 1 << (TYPE_WIDTH (t) - 2)) - 1) * 2 + 1))) /* The maximum and minimum values for the type of the expression E, after integer promotion. E should not have side effects. */ @@ -64,12 +68,23 @@ ? _GL_SIGNED_INT_MAXIMUM (e) \ : _GL_INT_NEGATE_CONVERT (e, 1)) #define _GL_SIGNED_INT_MAXIMUM(e) \ - (((_GL_INT_CONVERT (e, 1) << (sizeof ((e) + 0) * CHAR_BIT - 2)) - 1) * 2 + 1) + (((_GL_INT_CONVERT (e, 1) << (TYPE_WIDTH ((e) + 0) - 2)) - 1) * 2 + 1) + +/* Work around OpenVMS incompatibility with C99. */ +#if !defined LLONG_MAX && defined __INT64_MAX +# define LLONG_MAX __INT64_MAX +# define LLONG_MIN __INT64_MIN +#endif +/* This include file assumes that signed types are two's complement without + padding bits; the above macros have undefined behavior otherwise. + If this is a problem for you, please let us know how to fix it for your host. + This assumption is tested by the intprops-tests module. */ /* Does the __typeof__ keyword work? This could be done by 'configure', but for now it's easier to do it by hand. */ -#if (2 <= __GNUC__ || defined __IBM__TYPEOF__ \ +#if (2 <= __GNUC__ \ + || (1210 <= __IBMC__ && defined __IBM__TYPEOF__) \ || (0x5110 <= __SUNPRO_C && !__STDC__)) # define _GL_HAVE___TYPEOF__ 1 #else @@ -98,8 +113,7 @@ signed, this macro may overestimate the true bound by one byte when applied to unsigned types of size 2, 4, 16, ... bytes. */ #define INT_STRLEN_BOUND(t) \ - (INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT \ - - _GL_SIGNED_TYPE_OR_EXPR (t)) \ + (INT_BITS_STRLEN_BOUND (TYPE_WIDTH (t) - _GL_SIGNED_TYPE_OR_EXPR (t)) \ + _GL_SIGNED_TYPE_OR_EXPR (t)) /* Bound on buffer size needed to represent an integer type or expression T, @@ -165,7 +179,7 @@ /* Return 1 if A * B would overflow in [MIN,MAX] arithmetic. See above for restrictions. Avoid && and || as they tickle bugs in Sun C 5.11 2010/08/13 and other compilers; see - . */ + . */ #define INT_MULTIPLY_RANGE_OVERFLOW(a, b, min, max) \ ((b) < 0 \ ? ((a) < 0 \ @@ -204,24 +218,42 @@ ? (a) < (min) >> (b) \ : (max) >> (b) < (a)) +/* True if __builtin_add_overflow (A, B, P) works when P is non-null. */ +#if 5 <= __GNUC__ && !defined __ICC +# define _GL_HAS_BUILTIN_OVERFLOW 1 +#else +# define _GL_HAS_BUILTIN_OVERFLOW 0 +#endif + +/* True if __builtin_add_overflow_p (A, B, C) works. */ +#define _GL_HAS_BUILTIN_OVERFLOW_P (7 <= __GNUC__) /* The _GL*_OVERFLOW macros have the same restrictions as the *_RANGE_OVERFLOW macros, except that they do not assume that operands (e.g., A and B) have the same type as MIN and MAX. Instead, they assume that the result (e.g., A + B) has that type. */ -#define _GL_ADD_OVERFLOW(a, b, min, max) \ - ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max) \ - : (a) < 0 ? (b) <= (a) + (b) \ - : (b) < 0 ? (a) <= (a) + (b) \ - : (a) + (b) < (b)) -#define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \ - ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max) \ - : (a) < 0 ? 1 \ - : (b) < 0 ? (a) - (b) <= (a) \ - : (a) < (b)) -#define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \ - (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a)))) \ - || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max)) +#if _GL_HAS_BUILTIN_OVERFLOW_P +# define _GL_ADD_OVERFLOW(a, b, min, max) \ + __builtin_add_overflow_p (a, b, (__typeof__ ((a) + (b))) 0) +# define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \ + __builtin_sub_overflow_p (a, b, (__typeof__ ((a) - (b))) 0) +# define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \ + __builtin_mul_overflow_p (a, b, (__typeof__ ((a) * (b))) 0) +#else +# define _GL_ADD_OVERFLOW(a, b, min, max) \ + ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max) \ + : (a) < 0 ? (b) <= (a) + (b) \ + : (b) < 0 ? (a) <= (a) + (b) \ + : (a) + (b) < (b)) +# define _GL_SUBTRACT_OVERFLOW(a, b, min, max) \ + ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max) \ + : (a) < 0 ? 1 \ + : (b) < 0 ? (a) - (b) <= (a) \ + : (a) < (b)) +# define _GL_MULTIPLY_OVERFLOW(a, b, min, max) \ + (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a)))) \ + || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max)) +#endif #define _GL_DIVIDE_OVERFLOW(a, b, min, max) \ ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max) \ : (a) < 0 ? (b) <= (a) + (b) - 1 \ @@ -286,8 +318,12 @@ _GL_BINARY_OP_OVERFLOW (a, b, _GL_ADD_OVERFLOW) #define INT_SUBTRACT_OVERFLOW(a, b) \ _GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW) -#define INT_NEGATE_OVERFLOW(a) \ - INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a)) +#if _GL_HAS_BUILTIN_OVERFLOW_P +# define INT_NEGATE_OVERFLOW(a) INT_SUBTRACT_OVERFLOW (0, a) +#else +# define INT_NEGATE_OVERFLOW(a) \ + INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a)) +#endif #define INT_MULTIPLY_OVERFLOW(a, b) \ _GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW) #define INT_DIVIDE_OVERFLOW(a, b) \ @@ -307,7 +343,7 @@ _GL_INT_MINIMUM (0 * (b) + (a)), \ _GL_INT_MAXIMUM (0 * (b) + (a))) -/* Compute A + B, A - B, A * B, respectively, storing the result into *R. +/* Store the low-order bits of A + B, A - B, A * B, respectively, into *R. Return 1 if the result overflows. See above for restrictions. */ #define INT_ADD_WRAPV(a, b, r) \ _GL_INT_OP_WRAPV (a, b, r, +, __builtin_add_overflow, INT_ADD_OVERFLOW) @@ -316,10 +352,6 @@ #define INT_MULTIPLY_WRAPV(a, b, r) \ _GL_INT_OP_WRAPV (a, b, r, *, __builtin_mul_overflow, INT_MULTIPLY_OVERFLOW) -#ifndef __has_builtin -# define __has_builtin(x) 0 -#endif - /* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390. See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68193 https://llvm.org/bugs/show_bug.cgi?id=25390 @@ -332,20 +364,21 @@ # define _GL__GENERIC_BOGUS 0 #endif -/* Store A B into *R, where OP specifies the operation. - BUILTIN is the builtin operation, and OVERFLOW the overflow predicate. - See above for restrictions. */ -#if 5 <= __GNUC__ || __has_builtin (__builtin_add_overflow) +/* Store the low-order bits of A B into *R, where OP specifies + the operation. BUILTIN is the builtin operation, and OVERFLOW the + overflow predicate. Return 1 if the result overflows. See above + for restrictions. */ +#if _GL_HAS_BUILTIN_OVERFLOW # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) builtin (a, b, r) #elif 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \ (_Generic \ (*(r), \ signed char: \ - _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \ + _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ signed char, SCHAR_MIN, SCHAR_MAX), \ short int: \ - _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \ + _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ short int, SHRT_MIN, SHRT_MAX), \ int: \ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ @@ -359,10 +392,10 @@ #else # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \ (sizeof *(r) == sizeof (signed char) \ - ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \ + ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ signed char, SCHAR_MIN, SCHAR_MAX) \ : sizeof *(r) == sizeof (short int) \ - ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \ + ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ short int, SHRT_MIN, SHRT_MAX) \ : sizeof *(r) == sizeof (int) \ ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \ @@ -378,14 +411,14 @@ # else # define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \ _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \ - long int, LONG_MIN, LONG_MAX)) + long int, LONG_MIN, LONG_MAX) # endif #endif /* Store the low-order bits of A B into *R, where the operation is given by OP. Use the unsigned type UT for calculation to avoid - overflow problems. *R's type is T, with extremal values TMIN and - TMAX. T must be a signed integer type. */ + overflow problems. *R's type is T, with extrema TMIN and TMAX. + T must be a signed integer type. Return 1 if the result overflows. */ #define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \ (sizeof ((a) op (b)) < sizeof (t) \ ? _GL_INT_OP_CALC1 ((t) (a), (t) (b), r, op, overflow, ut, t, tmin, tmax) \ @@ -394,17 +427,27 @@ ((overflow (a, b) \ || (EXPR_SIGNED ((a) op (b)) && ((a) op (b)) < (tmin)) \ || (tmax) < ((a) op (b))) \ - ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 1) \ - : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 0)) - -/* Return A B, where the operation is given by OP. Use the - unsigned type UT for calculation to avoid overflow problems. - Convert the result to type T without overflow by subtracting TMIN - from large values before converting, and adding it afterwards. - Compilers can optimize all the operations except OP. */ -#define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t, tmin, tmax) \ - (((ut) (a) op (ut) (b)) <= (tmax) \ - ? (t) ((ut) (a) op (ut) (b)) \ - : ((t) (((ut) (a) op (ut) (b)) - (tmin)) + (tmin))) + ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 1) \ + : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 0)) + +/* Return the low-order bits of A B, where the operation is given + by OP. Use the unsigned type UT for calculation to avoid undefined + behavior on signed integer overflow, and convert the result to type T. + UT is at least as wide as T and is no narrower than unsigned int, + T is two's complement, and there is no padding or trap representations. + Assume that converting UT to T yields the low-order bits, as is + done in all known two's-complement C compilers. E.g., see: + https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html + + According to the C standard, converting UT to T yields an + implementation-defined result or signal for values outside T's + range. However, code that works around this theoretical problem + runs afoul of a compiler bug in Oracle Studio 12.3 x86. See: + https://lists.gnu.org/r/bug-gnulib/2017-04/msg00049.html + As the compiler bug is real, don't try to work around the + theoretical problem. */ + +#define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t) \ + ((t) ((ut) (a) op (ut) (b))) #endif /* _GL_INTPROPS_H */ diff --git a/libopts/libopts.c b/libopts/libopts.c index a26c9248a..457edc433 100644 --- a/libopts/libopts.c +++ b/libopts/libopts.c @@ -1,9 +1,9 @@ #define AUTOOPTS_INTERNAL 1 #include "autoopts/project.h" -#define LOCAL static + #include "ao-strs.h" static char const ao_ver_string[] = - "41:1:16\n"; + "42:1:17\n"; #include "autoopts/options.h" #include "autoopts/usage-txt.h" #include "genshell.h" @@ -11,12 +11,14 @@ static char const ao_ver_string[] = #include "option-value-type.h" #include "ao-strs.h" #include "ag-char-map.h" +#include "save-flags.h" #include "autoopts.h" #include "proto.h" #include "parse-duration.c" #include "ao-strs.c" #include "option-value-type.c" #include "option-xat-attribute.c" +#include "save-flags.c" #include "autoopts.c" #include "alias.c" #include "boolean.c" diff --git a/libopts/load.c b/libopts/load.c index 0702caeb7..59d124ebd 100644 --- a/libopts/load.c +++ b/libopts/load.c @@ -12,7 +12,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -31,26 +31,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static bool -get_realpath(char * buf, size_t b_sz); - -static bool -add_prog_path(char * buf, int b_sz, char const * fname, char const * prg_path); - -static bool -add_env_val(char * buf, int buf_sz, char const * name); - -static char * -assemble_arg_val(char * txt, tOptionLoadMode mode); - -static char * -trim_quotes(char * arg); - -static bool -direction_ok(opt_state_mask_t f, int dir); -/* = = = END-STATIC-FORWARD = = = */ - static bool get_realpath(char * buf, size_t b_sz) { @@ -314,7 +294,7 @@ add_env_val(char * buf, int buf_sz, char const * name) * @param[in,out] txt the input and output string * @param[in] mode the handling mode (cooking method) */ -LOCAL void +static void munge_str(char * txt, tOptionLoadMode mode) { char * end; @@ -445,7 +425,7 @@ direction_ok(opt_state_mask_t f, int dir) if (PRESETTING(dir)) { /* * We are in the presetting direction with an option we handle - * immediately for disablement, but normally for disablement. + * immediately for disablement, but normally for handling. * Therefore, skip if NOT disabled. */ if ((f & OPTST_DISABLED) != 0) @@ -453,7 +433,7 @@ direction_ok(opt_state_mask_t f, int dir) } else { /* * We are in the processing direction with an option we handle - * immediately for disablement, but normally for disablement. + * immediately for disablement, but normally for handling. * Therefore, skip if disabled. */ if ((f & OPTST_DISABLED) == 0) @@ -486,7 +466,7 @@ direction_ok(opt_state_mask_t f, int dir) * @param[in] direction current processing direction (preset or not) * @param[in] load_mode option loading mode (OPTION_LOAD_*) */ -LOCAL void +static void load_opt_line(tOptions * opts, tOptState * opt_state, char * line, tDirection direction, tOptionLoadMode load_mode ) { diff --git a/libopts/m4/libopts.m4 b/libopts/m4/libopts.m4 index cfbd477a5..23738cab4 100644 --- a/libopts/m4/libopts.m4 +++ b/libopts/m4/libopts.m4 @@ -1,14 +1,8 @@ -dnl -*- buffer-read-only: t -*- vi: set ro: -dnl -dnl DO NOT EDIT THIS FILE (libopts.m4) -dnl -dnl It has been AutoGen-ed -dnl From the definitions libopts.def -dnl and the template file conftest.tpl -dnl + dnl do always before generated macros: dnl AC_DEFUN([INVOKE_LIBOPTS_MACROS_FIRST],[ + AC_REQUIRE([AC_HEADER_STDC]) AC_HEADER_DIRENT # ================= @@ -113,6 +107,7 @@ AC_DEFUN([INVOKE_LIBOPTS_MACROS_FIRST],[ AC_PROG_SED [while : do + test -x "$POSIX_SHELL" && break POSIX_SHELL=`which bash` test -x "$POSIX_SHELL" && break POSIX_SHELL=`which dash` @@ -234,9 +229,9 @@ int main() { fputs( "error: regex -->.<-- did not match\n", stderr ); return 1; } - return 0; }])], + return 0; }] )], [libopts_cv_with_libregex=yes], [libopts_cv_with_libregex=no], - [libopts_cv_with_libregex=no]) # end of AC_RUN_IFELSE + [libopts_cv_with_libregex=no]) # end of AC_RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_with_libregex fi ## disabled by request AC_MSG_RESULT([${libopts_cv_with_libregex}]) @@ -264,7 +259,7 @@ AC_DEFUN([LIBOPTS_RUN_PATHFIND],[ int main (int argc, char ** argv) { char * pz = pathfind( getenv( "PATH" ), "sh", "x" ); return (pz == 0) ? 1 : 0; -}])], +}] )], [libopts_cv_run_pathfind=yes],[libopts_cv_run_pathfind=no],[libopts_cv_run_pathfind=no] ) # end of RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_run_pathfind @@ -312,7 +307,7 @@ choke me!! @%:@endif char *pz = realpath(argv@<:@0@:>@, zPath); return (pz == zPath) ? 0 : 1; -}])], +}] )], [libopts_cv_run_realpath=yes],[libopts_cv_run_realpath=no],[libopts_cv_run_realpath=no] ) # end of RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_run_realpath @@ -345,7 +340,7 @@ int main() { tm.tm_yday = 239; /* days since January 1 @<:@0, 365@:>@ */ tm.tm_isdst = 1; /* flag for daylight savings time */ strftime( t_buf, sizeof( t_buf ), "%A %b %d %j", &tm ); - return (strcmp( t_buf, z ) != 0); }])], + return (strcmp( t_buf, z ) != 0); }] )], [libopts_cv_run_strftime=yes],[libopts_cv_run_strftime=no],[libopts_cv_run_strftime=no] ) # end of RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_run_strftime @@ -365,7 +360,7 @@ AC_DEFUN([LIBOPTS_RUN_FOPEN_BINARY],[ AC_RUN_IFELSE([AC_LANG_SOURCE([@%:@include int main (int argc, char ** argv) { FILE * fp = fopen("conftest.@S|@ac_ext", "rb"); -return (fp == NULL) ? 1 : fclose(fp); }])], +return (fp == NULL) ? 1 : fclose(fp); }] )], [libopts_cv_run_fopen_binary=yes],[libopts_cv_run_fopen_binary=no],[libopts_cv_run_fopen_binary=no] ) # end of RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_run_fopen_binary @@ -388,7 +383,7 @@ AC_DEFUN([LIBOPTS_RUN_FOPEN_TEXT],[ AC_RUN_IFELSE([AC_LANG_SOURCE([@%:@include int main (int argc, char ** argv) { FILE * fp = fopen("conftest.@S|@ac_ext", "rt"); -return (fp == NULL) ? 1 : fclose(fp); }])], +return (fp == NULL) ? 1 : fclose(fp); }] )], [libopts_cv_run_fopen_text=yes],[libopts_cv_run_fopen_text=no],[libopts_cv_run_fopen_text=no] ) # end of RUN_IFELSE ]) # end of AC_CACHE_VAL for libopts_cv_run_fopen_text @@ -460,7 +455,7 @@ dnl the config tests that the library needs. Invoke the dnl "INVOKE_LIBOPTS_MACROS" macro iff we are building libopts. dnl dnl This file is part of AutoGen. -dnl AutoGen Copyright (C) 1992-2015 by Bruce Korb - all rights reserved +dnl AutoGen Copyright (C) 1992-2018 by Bruce Korb - all rights reserved dnl dnl AutoGen is free software: you can redistribute it and/or modify it dnl under the terms of the GNU General Public License as published by the @@ -483,7 +478,8 @@ AC_DEFUN([LIBOPTS_CHECK_COMMON],[ m4_pushdef([AO_Libopts_Dir], [ifelse($1, , [libopts], [$1])]) AC_ARG_ENABLE([local-libopts], - AS_HELP_STRING([--enable-local-libopts],[Use the supplied libopts tearoff code]),[ + AC_HELP_STRING([--enable-local-libopts], + [Use the supplied libopts tearoff code]),[ if test x$enableval = xyes ; then AC_MSG_NOTICE([Using supplied libopts tearoff]) LIBOPTS_CFLAGS='-I$(top_srcdir)/AO_Libopts_Dir' @@ -492,13 +488,15 @@ AC_DEFUN([LIBOPTS_CHECK_COMMON],[ fi]) AC_ARG_ENABLE([libopts-install], - AS_HELP_STRING([--enable-libopts-install],[Install libopts with client installation])) + AC_HELP_STRING([--enable-libopts-install], + [Install libopts with client installation])) AM_CONDITIONAL([INSTALL_LIBOPTS],[test "X${enable_libopts_install}" = Xyes]) [if test -z "${NEED_LIBOPTS_DIR}" ; then] AC_MSG_CHECKING([whether autoopts-config can be found]) AC_ARG_WITH([autoopts-config], - AS_HELP_STRING([--with-autoopts-config],[specify the config-info script]), + AC_HELP_STRING([--with-autoopts-config], + [specify the config-info script]), [lo_cv_with_autoopts_config=${with_autoopts_config}], AC_CACHE_CHECK([whether autoopts-config is specified], [lo_cv_with_autoopts_config], diff --git a/libopts/m4/liboptschk.m4 b/libopts/m4/liboptschk.m4 index 34d5658c2..9d107d696 100644 --- a/libopts/m4/liboptschk.m4 +++ b/libopts/m4/liboptschk.m4 @@ -1,5 +1,5 @@ # liboptschk.m4 serial 2 (autogen - 5.11.4) -dnl Copyright (C) 2005-2015 by Bruce Korb - all rights reserved +dnl Copyright (C) 2005-2018 by Bruce Korb - all rights reserved dnl dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, diff --git a/libopts/m4/stdnoreturn.m4 b/libopts/m4/stdnoreturn.m4 index 27c582765..a7ce37642 100644 --- a/libopts/m4/stdnoreturn.m4 +++ b/libopts/m4/stdnoreturn.m4 @@ -1,6 +1,6 @@ # Check for stdnoreturn.h that conforms to C11. -dnl Copyright 2012-2016 Free Software Foundation, Inc. +dnl Copyright 2012-2018 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. @@ -9,33 +9,43 @@ dnl with or without modifications, as long as this notice is preserved. AC_DEFUN([gl_STDNORETURN_H], [ - AC_CACHE_CHECK([for working stdnoreturn.h], - [gl_cv_header_working_stdnoreturn_h], - [AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - [[#include - #include - /* Do not check for 'noreturn' after the return type. - C11 allows it, but it's rarely done that way - and circa-2012 bleeding-edge GCC rejects it when given - -Werror=old-style-declaration. */ - noreturn void foo1 (void) { exit (0); } - _Noreturn void foo2 (void) { exit (0); } - int testit (int argc, char **argv) { - if (argc & 1) - return 0; - (argv[0][0] ? foo1 : foo2) (); - } - ]])], - [gl_cv_header_working_stdnoreturn_h=yes], - [gl_cv_header_working_stdnoreturn_h=no])]) - - if test $gl_cv_header_working_stdnoreturn_h = yes; then - STDNORETURN_H='' - else - STDNORETURN_H='stdnoreturn.h' - fi - + AC_REQUIRE([AC_CANONICAL_HOST]) + case "$host_os" in + cygwin*) + dnl Regardless whether a working exists or not, + dnl we need our own , because of the definition + dnl of _Noreturn done by gnulib-common.m4. + STDNORETURN_H='stdnoreturn.h' + ;; + *) + AC_CACHE_CHECK([for working stdnoreturn.h], + [gl_cv_header_working_stdnoreturn_h], + [AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM( + [[#include + #include + /* Do not check for 'noreturn' after the return type. + C11 allows it, but it's rarely done that way + and circa-2012 bleeding-edge GCC rejects it when given + -Werror=old-style-declaration. */ + noreturn void foo1 (void) { exit (0); } + _Noreturn void foo2 (void) { exit (0); } + int testit (int argc, char **argv) + { + if (argc & 1) + return 0; + (argv[0][0] ? foo1 : foo2) (); + } + ]])], + [gl_cv_header_working_stdnoreturn_h=yes], + [gl_cv_header_working_stdnoreturn_h=no])]) + if test $gl_cv_header_working_stdnoreturn_h = yes; then + STDNORETURN_H='' + else + STDNORETURN_H='stdnoreturn.h' + fi + ;; + esac AC_SUBST([STDNORETURN_H]) AM_CONDITIONAL([GL_GENERATE_STDNORETURN_H], [test -n "$STDNORETURN_H"]) ]) diff --git a/libopts/makeshell.c b/libopts/makeshell.c index b8bfa804b..10ed12005 100644 --- a/libopts/makeshell.c +++ b/libopts/makeshell.c @@ -11,7 +11,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -35,45 +35,7 @@ #define UPPER(_c) (toupper(to_uchar(_c))) #define LOWER(_c) (tolower(to_uchar(_c))) -/* = = = START-STATIC-FORWARD = = = */ -static void -emit_var_text(char const * prog, char const * var, int fdin); - -static void -text_to_var(tOptions * opts, teTextTo which, tOptDesc * od); - -static void -emit_usage(tOptions * opts); - -static void -emit_wrapup(tOptions * opts); - -static void -emit_setup(tOptions * opts); - -static void -emit_action(tOptions * opts, tOptDesc * od); - -static void -emit_inaction(tOptions * opts, tOptDesc * od); - -static void -emit_flag(tOptions * opts); - -static void -emit_match_expr(char const * name, tOptDesc * cod, tOptions * opts); - -static void -emit_long(tOptions * opts); - -static char * -load_old_output(char const * fname, char const * pname); - -static void -open_out(char const * fname, char const * pname); -/* = = = END-STATIC-FORWARD = = = */ - -LOCAL noreturn void +noreturn static void option_exits(int exit_code) { if (print_exit) @@ -81,21 +43,21 @@ option_exits(int exit_code) exit(exit_code); } -LOCAL noreturn void +noreturn static void ao_bug(char const * msg) { fprintf(stderr, zao_bug_msg, msg); option_exits(EX_SOFTWARE); } -LOCAL void +static void fserr_warn(char const * prog, char const * op, char const * fname) { fprintf(stderr, zfserr_fmt, prog, errno, strerror(errno), op, fname); } -LOCAL noreturn void +noreturn static void fserr_exit(char const * prog, char const * op, char const * fname) { fserr_warn(prog, op, fname); @@ -322,11 +284,11 @@ text_to_var(tOptions * opts, teTextTo which, tOptDesc * od) switch (which) { case TT_LONGUSAGE: (*(opts->pUsageProc))(opts, EXIT_SUCCESS); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ case TT_USAGE: (*(opts->pUsageProc))(opts, EXIT_FAILURE); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ case TT_VERSION: if (od->fOptState & OPTST_ALLOC_ARG) { @@ -335,13 +297,13 @@ text_to_var(tOptions * opts, teTextTo which, tOptDesc * od) } od->optArg.argString = "c"; optionPrintVersion(opts, od); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ default: option_exits(EXIT_FAILURE); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ } - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ default: close(fdpair[1]); @@ -885,14 +847,12 @@ genshelloptUsage(tOptions * opts, int exit_cd) switch (fork()) { case -1: optionUsage(opts, EXIT_FAILURE); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ case 0: pagerState = PAGER_STATE_CHILD; optionUsage(opts, EXIT_SUCCESS); - /* NOTREACHED */ - _exit(EXIT_FAILURE); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ default: { @@ -928,10 +888,11 @@ genshelloptUsage(tOptions * opts, int exit_cd) switch (fork()) { case 0: pagerState = PAGER_STATE_CHILD; - /* fall through */ + /*FALLTHROUGH*/ case -1: optionUsage(optionParseShellOptions, EXIT_FAILURE); - /* fall through */ + /* FALLTHROUGH */ /* NOTREACHED */ + default: { int sts; diff --git a/libopts/nested.c b/libopts/nested.c index 1c047ff58..e76045067 100644 --- a/libopts/nested.c +++ b/libopts/nested.c @@ -12,7 +12,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -37,7 +37,7 @@ typedef struct { char xml_txt[8]; } xml_xlate_t; -static xml_xlate_t const xml_xlate[] = { + static xml_xlate_t const xml_xlate[] = { { '&', 4, "amp;" }, { '<', 3, "lt;" }, { '>', 3, "gt;" }, @@ -49,48 +49,6 @@ static xml_xlate_t const xml_xlate[] = { #define ENOMSG ENOENT #endif -/* = = = START-STATIC-FORWARD = = = */ -static void -remove_continuation(char * src); - -static char const * -scan_q_str(char const * pzTxt); - -static tOptionValue * -add_string(void ** pp, char const * name, size_t nm_len, - char const * val, size_t d_len); - -static tOptionValue * -add_bool(void ** pp, char const * name, size_t nm_len, - char const * val, size_t d_len); - -static tOptionValue * -add_number(void ** pp, char const * name, size_t nm_len, - char const * val, size_t d_len); - -static tOptionValue * -add_nested(void ** pp, char const * name, size_t nm_len, - char * val, size_t d_len); - -static char const * -scan_name(char const * name, tOptionValue * res); - -static char const * -unnamed_xml(char const * txt); - -static char const * -scan_xml_name(char const * name, size_t * nm_len, tOptionValue * val); - -static char const * -find_end_xml(char const * src, size_t nm_len, char const * val, size_t * len); - -static char const * -scan_xml(char const * xml_name, tOptionValue * res_val); - -static void -sort_list(tArgList * arg_list); -/* = = = END-STATIC-FORWARD = = = */ - /** * Backslashes are used for line continuations. We keep the newline * characters, but trim out the backslash: @@ -638,7 +596,7 @@ scan_xml(char const * xml_name, tOptionValue * res_val) * an internal call, so it is not validated. The caller is responsible for * knowing what they are doing. */ -LOCAL void +static void unload_arg_list(tArgList * arg_list) { int ct = arg_list->useCt; @@ -743,7 +701,7 @@ sort_list(tArgList * arg_list) * @code{ENOMSG} no configuration values were found * @end itemize =*/ -LOCAL tOptionValue * +static tOptionValue * optionLoadNested(char const * text, char const * name, size_t nm_len) { tOptionValue * res_val; @@ -866,7 +824,7 @@ optionNestedVal(tOptions * opts, tOptDesc * od) /** * get_special_char */ -LOCAL int +static int get_special_char(char const ** ppz, int * ct) { char const * pz = *ppz; @@ -918,7 +876,7 @@ get_special_char(char const ** ppz, int * ct) /** * emit_special_char */ -LOCAL void +static void emit_special_char(FILE * fp, int ch) { int ctr = sizeof(xml_xlate) / sizeof(xml_xlate[0]); diff --git a/libopts/numeric.c b/libopts/numeric.c index 501948627..bbb43ccdc 100644 --- a/libopts/numeric.c +++ b/libopts/numeric.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -136,20 +136,14 @@ optionNumericVal(tOptions * opts, tOptDesc * od) if ((od->fOptState & OPTST_SCALED_NUM) != 0) switch (*(pz++)) { case NUL: pz--; break; - case 't': val *= 1000; - /* fall through */ - case 'g': val *= 1000; - /* fall through */ - case 'm': val *= 1000; - /* fall through */ + case 't': val *= 1000; /* FALLTHROUGH */ + case 'g': val *= 1000; /* FALLTHROUGH */ + case 'm': val *= 1000; /* FALLTHROUGH */ case 'k': val *= 1000; break; - case 'T': val *= 1024; - /* fall through */ - case 'G': val *= 1024; - /* fall through */ - case 'M': val *= 1024; - /* fall through */ + case 'T': val *= 1024; /* FALLTHROUGH */ + case 'G': val *= 1024; /* FALLTHROUGH */ + case 'M': val *= 1024; /* FALLTHROUGH */ case 'K': val *= 1024; break; default: goto bad_number; diff --git a/libopts/option-value-type.c b/libopts/option-value-type.c index 5f676408a..2bc864280 100644 --- a/libopts/option-value-type.c +++ b/libopts/option-value-type.c @@ -31,7 +31,7 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "option-value-type.h" -/* ANSI-C code produced by gperf version 3.0.4 */ +/* ANSI-C code produced by gperf version 3.1 */ /* Command-line: gperf option-value-type.gp */ /* Computed positions: -k'1' */ @@ -64,7 +64,7 @@ typedef struct { /* maximum key range = 15, duplicates = 0 */ static unsigned int -option_value_type_hash (register const char *str, register unsigned int len) +option_value_type_hash (register const char *str, register size_t len) { static const unsigned char asso_values[] = { @@ -119,13 +119,13 @@ static const option_value_type_map_t option_value_type_table[] = }; static inline const option_value_type_map_t * -find_option_value_type_name (register const char *str, register unsigned int len) +find_option_value_type_name (register const char *str, register size_t len) { if (len <= 14 && len >= 3) { - register int key = (int)option_value_type_hash (str, len); + register unsigned int key = (int)option_value_type_hash (str, len); - if (key <= 17 && key >= 0) + if (key <= 17) { register const char *s = option_value_type_table[key].vtp_name; diff --git a/libopts/option-xat-attribute.c b/libopts/option-xat-attribute.c index be86041fd..a34ab1b5b 100644 --- a/libopts/option-xat-attribute.c +++ b/libopts/option-xat-attribute.c @@ -31,7 +31,7 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "option-xat-attribute.h" -/* ANSI-C code produced by gperf version 3.0.4 */ +/* ANSI-C code produced by gperf version 3.1 */ /* Command-line: gperf option-xat-attribute.gp */ /* Computed positions: -k'1' */ @@ -64,7 +64,7 @@ typedef struct { /* maximum key range = 6, duplicates = 0 */ static unsigned int -option_xat_attribute_hash (register const char *str, register unsigned int len) +option_xat_attribute_hash (register const char *str, register size_t len) { static const unsigned char asso_values[] = { @@ -111,13 +111,13 @@ static const option_xat_attribute_map_t option_xat_attribute_table[] = }; static inline const option_xat_attribute_map_t * -find_option_xat_attribute_name (register const char *str, register unsigned int len) +find_option_xat_attribute_name (register const char *str, register size_t len) { if (len <= 8 && len >= 4) { - register int key = (int)option_xat_attribute_hash (str, len); + register unsigned int key = (int)option_xat_attribute_hash (str, len); - if (key <= 9 && key >= 0) + if (key <= 9) { register const char *s = option_xat_attribute_table[key].xat_name; diff --git a/libopts/parse-duration.c b/libopts/parse-duration.c index 5b75f5be7..0f4a05634 100644 --- a/libopts/parse-duration.c +++ b/libopts/parse-duration.c @@ -1,5 +1,5 @@ /* Parse a time duration and return a seconds count - Copyright (C) 2008-2016 Free Software Foundation, Inc. + Copyright (C) 2008-2018 Free Software Foundation, Inc. Written by Bruce Korb , 2008. This program is free software: you can redistribute it and/or modify @@ -13,7 +13,7 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . */ + along with this program. If not, see . */ #include diff --git a/libopts/parse-duration.h b/libopts/parse-duration.h index a270a7561..9a7bcd5e1 100644 --- a/libopts/parse-duration.h +++ b/libopts/parse-duration.h @@ -1,5 +1,5 @@ /* Parse a time duration and return a seconds count - Copyright (C) 2008-2016 Free Software Foundation, Inc. + Copyright (C) 2008-2018 Free Software Foundation, Inc. Written by Bruce Korb , 2008. This program is free software: you can redistribute it and/or modify @@ -13,7 +13,7 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . */ + along with this program. If not, see . */ /* @@ -22,7 +22,7 @@ At the time of writing, this worked: - http://en.wikipedia.org/wiki/ISO_8601#Durations + https://en.wikipedia.org/wiki/ISO_8601#Durations The string must start with a 'P', 'T' or a digit. diff --git a/libopts/pgusage.c b/libopts/pgusage.c index d72203ef5..f895b3bb5 100644 --- a/libopts/pgusage.c +++ b/libopts/pgusage.c @@ -13,7 +13,7 @@ * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/proto.h b/libopts/proto.h index 464e02da6..437e81ed9 100644 --- a/libopts/proto.h +++ b/libopts/proto.h @@ -1,19 +1,20 @@ /* -*- buffer-read-only: t -*- vi: set ro: * * Prototypes for autoopts - * Generated Mon Aug 29 14:35:37 PDT 2016 + * Generated Sun Aug 26 10:44:39 PDT 2018 */ #ifndef AUTOOPTS_PROTO_H_GUARD #define AUTOOPTS_PROTO_H_GUARD 1 + /* - * Extracted from alias.c + * Static declarations from alias.c */ static tSuccess too_many_occurrences(tOptions * opts, tOptDesc * od); /* - * Extracted from autoopts.c + * Static declarations from autoopts.c */ static void * ao_malloc(size_t sz); @@ -34,14 +35,53 @@ static tSuccess regular_opts(tOptions * opts); /* - * Extracted from check.c + * Static declarations from check.c */ +static bool +has_conflict(tOptions * pOpts, tOptDesc * od); + +static bool +occurs_enough(tOptions * pOpts, tOptDesc * pOD); + static bool is_consistent(tOptions * pOpts); /* - * Extracted from configfile.c + * Static declarations from configfile.c */ +static void +file_preset(tOptions * opts, char const * fname, int dir); + +static char * +handle_comment(char * txt); + +static char * +handle_cfg(tOptions * opts, tOptState * ost, char * txt, int dir); + +static char * +handle_directive(tOptions * opts, char * txt); + +static char * +aoflags_directive(tOptions * opts, char * txt); + +static char * +program_directive(tOptions * opts, char * txt); + +static char * +handle_section(tOptions * opts, char * txt); + +static int +parse_xml_encoding(char ** ppz); + +static char * +trim_xml_text(char * intxt, char const * pznm, tOptionLoadMode mode); + +static void +cook_xml_text(char * pzData); + +static char * +handle_struct(tOptions * opts, tOptState * ost, char * txt, int dir); + static void intern_file_load(tOptions * opts); @@ -49,24 +89,112 @@ static char const * parse_attrs(tOptions * opts, char const * txt, tOptionLoadMode * pMode, tOptionValue * pType); +static char const * +parse_keyword(tOptions * opts, char const * txt, tOptionValue * typ); + +static char const * +parse_set_mem(tOptions * opts, char const * txt, tOptionValue * typ); + +static char const * +parse_value(char const * txt, tOptionValue * typ); + +/* + * Static declarations from cook.c + */ +static char * +nl_count(char * start, char * end, int * lnct_p); + +static bool +contiguous_quote(char ** pps, char * pq, int * lnct_p); + +/* + * Static declarations from enum.c + */ +static void +enum_err(tOptions * pOpts, tOptDesc * pOD, + char const * const * paz_names, int name_ct); + +static uintptr_t +find_name(char const * name, tOptions * pOpts, tOptDesc * pOD, + char const * const * paz_names, unsigned int name_ct); + +static void +set_memb_shell(tOptions * pOpts, tOptDesc * pOD, char const * const * paz_names, + unsigned int name_ct); + +static void +set_memb_names(tOptions * opts, tOptDesc * od, char const * const * nm_list, + unsigned int nm_ct); + +static uintptr_t +check_membership_start(tOptDesc * od, char const ** argp, bool * invert); + +static uintptr_t +find_member_bit(tOptions * opts, tOptDesc * od, char const * pz, int len, + char const * const * nm_list, unsigned int nm_ct); + /* - * Extracted from env.c + * Static declarations from env.c */ static void doPrognameEnv(tOptions * pOpts, teEnvPresetType type); +static void +do_env_opt(tOptState * os, char * env_name, + tOptions * pOpts, teEnvPresetType type); + static void env_presets(tOptions * pOpts, teEnvPresetType type); /* - * Extracted from find.c + * Static declarations from file.c */ +static void +check_existence(teOptFileType ftype, tOptions * pOpts, tOptDesc * pOD); + +static void +open_file_fd(tOptions * pOpts, tOptDesc * pOD, tuFileMode mode); + +static void +fopen_file_fp(tOptions * pOpts, tOptDesc * pOD, tuFileMode mode); + +/* + * Static declarations from find.c + */ +static int +parse_opt(char const ** nm_pp, char ** arg_pp, char * buf, size_t bufsz); + +static void +opt_ambiguities(tOptions * opts, char const * name, int nm_len); + +static int +opt_match_ct(tOptions * opts, char const * name, int nm_len, + int * ixp, bool * disable); + +static tSuccess +opt_set(tOptions * opts, char * arg, int idx, bool disable, tOptState * st); + +static tSuccess +opt_unknown(tOptions * opts, char const * name, char * arg, tOptState * st); + +static tSuccess +opt_ambiguous(tOptions * opts, char const * name, int match_ct); + static tSuccess opt_find_long(tOptions * opts, char const * opt_name, tOptState * state); static tSuccess opt_find_short(tOptions * pOpts, uint_t optValue, tOptState * pOptState); +static tSuccess +get_opt_arg_must(tOptions * opts, tOptState * o_st); + +static tSuccess +get_opt_arg_may(tOptions * pOpts, tOptState * o_st); + +static tSuccess +get_opt_arg_none(tOptions * pOpts, tOptState * o_st); + static tSuccess get_opt_arg(tOptions * opts, tOptState * o_st); @@ -74,7 +202,7 @@ static tSuccess find_opt(tOptions * opts, tOptState * o_st); /* - * Extracted from init.c + * Static declarations from init.c */ static tSuccess validate_struct(tOptions * opts, char const * pname); @@ -82,40 +210,137 @@ validate_struct(tOptions * opts, char const * pname); static tSuccess immediate_opts(tOptions * opts); +static tSuccess +do_presets(tOptions * opts); + static bool ao_initialize(tOptions * opts, int a_ct, char ** a_v); /* - * Extracted from load.c + * Static declarations from load.c */ +static bool +get_realpath(char * buf, size_t b_sz); + +static bool +add_prog_path(char * buf, int b_sz, char const * fname, char const * prg_path); + +static bool +add_env_val(char * buf, int buf_sz, char const * name); + static void munge_str(char * txt, tOptionLoadMode mode); +static char * +assemble_arg_val(char * txt, tOptionLoadMode mode); + +static char * +trim_quotes(char * arg); + +static bool +direction_ok(opt_state_mask_t f, int dir); + static void load_opt_line(tOptions * opts, tOptState * opt_state, char * line, tDirection direction, tOptionLoadMode load_mode ); /* - * Extracted from makeshell.c + * Static declarations from makeshell.c */ -static noreturn void +noreturn static void option_exits(int exit_code); -static noreturn void +noreturn static void ao_bug(char const * msg); static void fserr_warn(char const * prog, char const * op, char const * fname); -static noreturn void +noreturn static void fserr_exit(char const * prog, char const * op, char const * fname); +static void +emit_var_text(char const * prog, char const * var, int fdin); + +static void +text_to_var(tOptions * opts, teTextTo which, tOptDesc * od); + +static void +emit_usage(tOptions * opts); + +static void +emit_wrapup(tOptions * opts); + +static void +emit_setup(tOptions * opts); + +static void +emit_action(tOptions * opts, tOptDesc * od); + +static void +emit_inaction(tOptions * opts, tOptDesc * od); + +static void +emit_flag(tOptions * opts); + +static void +emit_match_expr(char const * name, tOptDesc * cod, tOptions * opts); + +static void +emit_long(tOptions * opts); + +static char * +load_old_output(char const * fname, char const * pname); + +static void +open_out(char const * fname, char const * pname); + /* - * Extracted from nested.c + * Static declarations from nested.c */ +static void +remove_continuation(char * src); + +static char const * +scan_q_str(char const * pzTxt); + +static tOptionValue * +add_string(void ** pp, char const * name, size_t nm_len, + char const * val, size_t d_len); + +static tOptionValue * +add_bool(void ** pp, char const * name, size_t nm_len, + char const * val, size_t d_len); + +static tOptionValue * +add_number(void ** pp, char const * name, size_t nm_len, + char const * val, size_t d_len); + +static tOptionValue * +add_nested(void ** pp, char const * name, size_t nm_len, + char * val, size_t d_len); + +static char const * +scan_name(char const * name, tOptionValue * res); + +static char const * +unnamed_xml(char const * txt); + +static char const * +scan_xml_name(char const * name, size_t * nm_len, tOptionValue * val); + +static char const * +find_end_xml(char const * src, size_t nm_len, char const * val, size_t * len); + +static char const * +scan_xml(char const * xml_name, tOptionValue * res_val); + static void unload_arg_list(tArgList * arg_list); +static void +sort_list(tArgList * arg_list); + static tOptionValue * optionLoadNested(char const * text, char const * name, size_t nm_len); @@ -126,21 +351,270 @@ static void emit_special_char(FILE * fp, int ch); /* - * Extracted from sort.c + * Static declarations from parse-duration.c */ +static unsigned long +str_const_to_ul (cch_t * str, cch_t ** ppz, int base); + +static long +str_const_to_l (cch_t * str, cch_t ** ppz, int base); + +static time_t +scale_n_add (time_t base, time_t val, int scale); + +static time_t +parse_hr_min_sec (time_t start, cch_t * pz); + +static time_t +parse_scaled_value (time_t base, cch_t ** ppz, cch_t * endp, int scale); + +static time_t +parse_year_month_day (cch_t * pz, cch_t * ps); + +static time_t +parse_yearmonthday (cch_t * in_pz); + +static time_t +parse_YMWD (cch_t * pz); + +static time_t +parse_hour_minute_second (cch_t * pz, cch_t * ps); + +static time_t +parse_hourminutesecond (cch_t * in_pz); + +static time_t +parse_HMS (cch_t * pz); + +static time_t +parse_time (cch_t * pz); + +static char * +trim (char * pz); + +static time_t +parse_period (cch_t * in_pz); + +static time_t +parse_non_iso8601 (cch_t * pz); + +/* + * Static declarations from pgusage.c + */ +static inline FILE * +open_tmp_usage(char ** buf); + +static inline char * +mk_pager_cmd(char const * fname); + +/* + * Static declarations from putshell.c + */ +static size_t +string_size(char const * scan, size_t nl_len); + +static char const * +print_quoted_apostrophes(char const * str); + +static void +print_quot_str(char const * str); + +static void +print_enumeration(tOptions * pOpts, tOptDesc * pOD); + +static void +print_membership(tOptions * pOpts, tOptDesc * pOD); + +static void +print_stacked_arg(tOptions * pOpts, tOptDesc * pOD); + +static void +print_reordering(tOptions * opts); + +/* + * Static declarations from reset.c + */ +static void +optionReset(tOptions * pOpts, tOptDesc * pOD); + +static void +optionResetEverything(tOptions * pOpts); + +/* + * Static declarations from restore.c + */ +static void +fixupSavedOptionArgs(tOptions * pOpts); + +/* + * Static declarations from save.c + */ +static char const * +find_dir_name(tOptions * opts, int * p_free); + +static char const * +find_file_name(tOptions * opts, int * p_free_name); + +static void +prt_entry(FILE * fp, tOptDesc * od, char const * l_arg, save_flags_mask_t save_fl); + +static void +prt_value(FILE * fp, int depth, tOptDesc * od, tOptionValue const * ovp); + +static void +prt_string(FILE * fp, char const * name, char const * pz); + +static void +prt_val_list(FILE * fp, char const * name, tArgList * al); + +static void +prt_nested(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl); + +static void +remove_settings(tOptions * opts, char const * fname); + +static FILE * +open_sv_file(tOptions * opts, save_flags_mask_t save_fl); + +static void +prt_no_arg_opt(FILE * fp, tOptDesc * vod, tOptDesc * pod, save_flags_mask_t save_fl); + +static void +prt_str_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl); + +static void +prt_enum_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl); + +static void +prt_set_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl); + +static void +prt_file_arg(FILE * fp, tOptDesc * od, tOptions * opts, save_flags_mask_t save_fl); + +/* + * Static declarations from sort.c + */ +static tSuccess +must_arg(tOptions * opts, char * arg_txt, tOptState * pOS, + char ** opt_txt, uint32_t * opt_idx); + +static tSuccess +maybe_arg(tOptions * opts, char * arg_txt, tOptState * pOS, + char ** opt_txt, uint32_t * opt_idx); + +static tSuccess +short_opt_ck(tOptions * opts, char * arg_txt, tOptState * pOS, + char ** opt_txt, uint32_t * opt_idx); + static void optionSort(tOptions * opts); /* - * Extracted from stack.c + * Static declarations from stack.c */ static void addArgListEntry(void ** ppAL, void * entry); /* - * Extracted from usage.c + * Static declarations from text_mmap.c */ +static void +load_text_file(tmap_info_t * mapinfo, char const * pzFile); + +static void +validate_mmap(char const * fname, int prot, int flags, tmap_info_t * mapinfo); + +static void +close_mmap_files(tmap_info_t * mi); + +/* + * Static declarations from tokenize.c + */ +static void +copy_cooked(ch_t ** ppDest, char const ** ppSrc); + +static void +copy_raw(ch_t ** ppDest, char const ** ppSrc); + +static token_list_t * +alloc_token_list(char const * str); + +/* + * Static declarations from usage.c + */ +static unsigned int +parse_usage_flags(ao_flag_names_t const * fnt, char const * txt); + static void set_usage_flags(tOptions * opts, char const * flg_txt); +static inline bool +do_gnu_usage(tOptions * pOpts); + +static inline bool +skip_misuse_usage(tOptions * pOpts); + +static void +print_offer_usage(tOptions * opts); + +static void +print_usage_details(tOptions * opts, int exit_code); + +static void +print_one_paragraph(char const * text, bool plain, FILE * fp); + +static void +prt_conflicts(tOptions * opts, tOptDesc * od); + +static void +prt_one_vendor(tOptions * opts, tOptDesc * od, + arg_types_t * argtp, char const * usefmt); + +static void +prt_vendor_opts(tOptions * opts, char const * title); + +static void +prt_extd_usage(tOptions * opts, tOptDesc * od, char const * title); + +static void +prt_ini_list(char const * const * papz, char const * ini_file, + char const * path_nm); + +static void +prt_preamble(tOptions * opts, tOptDesc * od, arg_types_t * at); + +static void +prt_one_usage(tOptions * opts, tOptDesc * od, arg_types_t * at); + +static void +prt_opt_usage(tOptions * opts, int ex_code, char const * title); + +static void +prt_prog_detail(tOptions * opts); + +static int +setGnuOptFmts(tOptions * opts, char const ** ptxt); + +static int +setStdOptFmts(tOptions * opts, char const ** ptxt); + +/* + * Static declarations from version.c + */ +static void +emit_first_line( + FILE * fp, char const * alt1, char const * alt2, char const * alt3); + +static void +emit_simple_ver(tOptions * o, FILE * fp); + +static void +emit_copy_full(tOptions * o, FILE * fp); + +static void +emit_copy_note(tOptions * opts, FILE * fp); + +static void +print_ver(tOptions * opts, tOptDesc * od, FILE * fp, bool call_exit); + #endif /* AUTOOPTS_PROTO_H_GUARD */ diff --git a/libopts/putshell.c b/libopts/putshell.c index 7e6411a86..84463dd40 100644 --- a/libopts/putshell.c +++ b/libopts/putshell.c @@ -12,7 +12,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -31,29 +31,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static size_t -string_size(char const * scan, size_t nl_len); - -static char const * -print_quoted_apostrophes(char const * str); - -static void -print_quot_str(char const * str); - -static void -print_enumeration(tOptions * pOpts, tOptDesc * pOD); - -static void -print_membership(tOptions * pOpts, tOptDesc * pOD); - -static void -print_stacked_arg(tOptions * pOpts, tOptDesc * pOD); - -static void -print_reordering(tOptions * opts); -/* = = = END-STATIC-FORWARD = = = */ - /** * Count the number of bytes required to represent a string as a * compilable string. diff --git a/libopts/reset.c b/libopts/reset.c index 6bd1c3f0a..f7b58e8d1 100644 --- a/libopts/reset.c +++ b/libopts/reset.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/restore.c b/libopts/restore.c index 9fbcbb0bd..36ebbce1a 100644 --- a/libopts/restore.c +++ b/libopts/restore.c @@ -12,7 +12,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -34,7 +34,7 @@ /* * optionFixupSavedOpts Really, it just wipes out option state for * options that are troublesome to copy. viz., stacked strings and - * hierarchically valued option args. We do duplicate string args that + * hierarcicaly valued option args. We do duplicate string args that * have been marked as allocated though. */ static void diff --git a/libopts/save-flags.c b/libopts/save-flags.c new file mode 100644 index 000000000..d295170ed --- /dev/null +++ b/libopts/save-flags.c @@ -0,0 +1,248 @@ +/* -*- buffer-read-only: t -*- vi: set ro: + * + * DO NOT EDIT THIS FILE (save-flags.c) + * + * It has been AutoGen-ed + * From the definitions /tmp/.ag-ufBbQe/save-flags.def + * and the template file str2enum + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name ``Bruce Korb'' nor the name of any other + * contributor may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * str2enum IS PROVIDED BY Bruce Korb ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL Bruce Korb OR ANY OTHER CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "save-flags.h" +#include +#ifndef MISSING_INTTYPES_H +# include +#endif + +typedef enum { + SVFL_BNM_DEFAULT = 0, + SVFL_BNM_USAGE = 1, + SVFL_BNM_UPDATE = 2, + SVFL_COUNT_BNM +} save_flags_enum_t; + +static save_flags_enum_t +find_save_flags_bnm(char const * str, size_t len); + + +#include +#include +#ifndef NUL +#define NUL '\0' +#endif + +/* ANSI-C code produced by gperf version 3.1 */ +/* Command-line: gperf save-flags.gp */ +/* Computed positions: -k'' */ + + +# if 0 /* gperf build options: */ +// %struct-type +// %language=ANSI-C +// %includes +// %global-table +// %omit-struct-type +// %readonly-tables +// %compare-strncmp +// +// %define slot-name svfl_name +// %define hash-function-name save_flags_hash +// %define lookup-function-name find_save_flags_name +// %define word-array-name save_flags_table +// %define initializer-suffix ,SVFL_COUNT_BNM +// +# endif + +#include "save-flags.h" +typedef struct { + char const * svfl_name; + save_flags_enum_t svfl_id; +} save_flags_map_t; +#include + +/* maximum key range = 3, duplicates = 0 */ + +static unsigned int +save_flags_hash (register const char *str, register size_t len) +{ + (void)str; + (void)len; + return len; +} + +static const save_flags_map_t save_flags_table[] = + { + {"",SVFL_COUNT_BNM}, {"",SVFL_COUNT_BNM}, + {"",SVFL_COUNT_BNM}, {"",SVFL_COUNT_BNM}, + {"",SVFL_COUNT_BNM}, + {"usage", SVFL_BNM_USAGE}, + {"update", SVFL_BNM_UPDATE}, + {"default", SVFL_BNM_DEFAULT} + }; + +static inline const save_flags_map_t * +find_save_flags_name (register const char *str, register size_t len) +{ + if (len <= 7 && len >= 5) + { + register unsigned int key = (int)save_flags_hash (str, len); + + if (key <= 7) + { + register const char *s = save_flags_table[key].svfl_name; + + if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0') + return &save_flags_table[key]; + } + } + return 0; +} + +/** + * Convert a command (keyword) to a save_flags_enum_t enumeration value. + * + * @param[in] str a string that should start with a known key word. + * @param[in] len the provided length of the keyword at \a str. + * @returns the enumeration value. + * If not found, that value is SVFL_COUNT_BNM. + */ +static save_flags_enum_t +find_save_flags_bnm(char const * str, size_t len) +{ + save_flags_map_t const * map; + + map = find_save_flags_name(str, (unsigned int)len); + if (map != NULL) + return map->svfl_id; + /* Check for a partial match */ + { + /* + * Indexes of valid save_flags_table entries in sorted order: + */ + static unsigned int const ix_map[] = { + 7, 6, 5 }; + save_flags_enum_t res = SVFL_COUNT_BNM; + static int const HI = (sizeof(ix_map) / sizeof(ix_map[0])) - 1; + int lo = 0; + int hi = HI; + int av; + int cmp; + + for (;;) { + av = (hi + lo) / 2; + map = save_flags_table + ix_map[av]; + cmp = strncmp(map->svfl_name, str, len); + if (cmp == 0) break; + if (cmp > 0) + hi = av - 1; + else lo = av + 1; + if (lo > hi) + return SVFL_COUNT_BNM; + } + res = map->svfl_id; + /* + * If we have an exact match, accept it. + */ + if (map->svfl_name[len] == NUL) + return res; + /* + * Check for a duplicate partial match (a partial match + * with a higher or lower index than "av". + */ + if (av < HI) { + map = save_flags_table + ix_map[av + 1]; + if (strncmp(map->svfl_name, str, len) == 0) + return SVFL_COUNT_BNM; + } + if (av > 0) { + map = save_flags_table + ix_map[av - 1]; + if (strncmp(map->svfl_name, str, len) == 0) + return SVFL_COUNT_BNM; + } + return res; + } +} + +/** + * Convert a string to a save_flags_mask_t mask. + * Bit names prefixed with a hyphen have the bit removed from the mask. + * If the string starts with a '-', '+' or '|' character, then + * the old value is used as a base, otherwise the result mask + * is initialized to zero. Separating bit names with '+' or '|' + * characters is optional. By default, the bits are "or"-ed into the + * result. + * + * @param[in] str string with a list of bit names + * @param[in] old previous value, used if \a str starts with a '+' or '-'. + * + * @returns an unsigned integer with the bits set. + */ +save_flags_mask_t +save_flags_str2mask(char const * str, save_flags_mask_t old) +{ + static char const white[] = ", \t\f"; + static char const name_chars[] = + "adefglpstu" + "ADEFGLPSTU"; + + save_flags_mask_t res = 0; + int have_data = 0; + + for (;;) { + save_flags_enum_t val; + unsigned int val_len; + unsigned int invert = 0; + + str += strspn(str, white); + switch (*str) { + case NUL: return res; + case '-': case '~': + invert = 1; + /* FALLTHROUGH */ + + case '+': case '|': + if (have_data == 0) + res = old; + + str += 1 + strspn(str + 1, white); + if (*str == NUL) + return 0; + } + + val_len = strspn(str, name_chars); + if (val_len == 0) + return 0; + val = find_save_flags_bnm(str, val_len); + if (val == SVFL_COUNT_BNM) + return 0; + if (invert) + res &= ~((save_flags_mask_t)1 << val); + else + res |= (save_flags_mask_t)1 << val; + have_data = 1; + str += val_len; + } +} +/* end of save-flags.c */ diff --git a/libopts/save-flags.h b/libopts/save-flags.h new file mode 100644 index 000000000..dcfe0c9ae --- /dev/null +++ b/libopts/save-flags.h @@ -0,0 +1,68 @@ +/* -*- buffer-read-only: t -*- vi: set ro: + * + * DO NOT EDIT THIS FILE (save-flags.h) + * + * It has been AutoGen-ed + * From the definitions /tmp/.ag-ufBbQe/save-flags.def + * and the template file str2enum + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name ``Bruce Korb'' nor the name of any other + * contributor may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * str2enum IS PROVIDED BY Bruce Korb ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL Bruce Korb OR ANY OTHER CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Command/Keyword Dispatcher + */ +#ifndef STR2ENUM_SAVE_FLAGS_H_GUARD +#define STR2ENUM_SAVE_FLAGS_H_GUARD 1 +#include +#include + +/** integral type for holding save_flags masks */ +typedef uint32_t save_flags_mask_t; + +/** bits defined for save_flags_mask_t */ +/** include default values in commentary */ +#define SVFL_DEFAULT 0x0001U +/** include usage text in commentary */ +#define SVFL_USAGE 0x0002U +/** replace or append state */ +#define SVFL_UPDATE 0x0004U + +/** bits in USAGE_DEFAULT mask: + * usage default */ +#define SVFL_USAGE_DEFAULT_MASK 0x0003U + +/** all bits in save_flags_mask_t masks */ +#define SVFL_MASK_ALL 0x0007U + +/** no bits in save_flags_mask_t */ +#define SVFL_NONE 0x0000U + +/** buffer size needed to hold all bit names for save_flags_mask_t masks */ +#define MAX_SAVE_FLAGS_NAME_SIZE 21 + +extern save_flags_mask_t +save_flags_str2mask(char const * str, save_flags_mask_t old); + +#endif /* STR2ENUM_SAVE_FLAGS_H_GUARD */ +/* end of save-flags.h */ diff --git a/libopts/save.c b/libopts/save.c index af5dbe03b..ba342070a 100644 --- a/libopts/save.c +++ b/libopts/save.c @@ -12,7 +12,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -30,133 +30,70 @@ * 4379e7444a0e2ce2b12dd6f5a52a27a4d02d39d247901d3285c88cf0d37f477b COPYING.lgplv3 * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ - -/* = = = START-STATIC-FORWARD = = = */ -static char const * -find_dir_name(tOptions * opts, int * p_free); - -static char const * -find_file_name(tOptions * opts, int * p_free_name); - -static void -prt_entry(FILE * fp, tOptDesc * od, char const * l_arg); - -static void -prt_value(FILE * fp, int depth, tOptDesc * pOD, tOptionValue const * ovp); - -static void -prt_string(FILE * fp, char const * name, char const * pz); - -static void -prt_val_list(FILE * fp, char const * name, tArgList * al); - -static void -prt_nested(FILE * fp, tOptDesc * p); - -static FILE * -open_sv_file(tOptions * opts); - -static void -prt_no_arg_opt(FILE * fp, tOptDesc * p, tOptDesc * pOD); - -static void -prt_str_arg(FILE * fp, tOptDesc * pOD); - -static void -prt_enum_arg(FILE * fp, tOptDesc * od); - -static void -prt_set_arg(FILE * fp, tOptDesc * od); - -static void -prt_file_arg(FILE * fp, tOptDesc * od, tOptions * opts); -/* = = = END-STATIC-FORWARD = = = */ +#include "save-flags.h" /** + * find the config file directory name + * + * @param opts the options descriptor + * @param p_free tell caller if name was allocated or not */ static char const * find_dir_name(tOptions * opts, int * p_free) { char const * dir; + int idx; if ( (opts->specOptIdx.save_opts == NO_EQUIVALENT) || (opts->specOptIdx.save_opts == 0)) return NULL; dir = opts->pOptDesc[ opts->specOptIdx.save_opts ].optArg.argString; - if ((dir != NULL) && (*dir != NUL)) - return dir; + if ((dir != NULL) && (*dir != NUL)) { + char const * pz = strchr(dir, '>'); + if (pz == NULL) + return dir; + while (*(++pz) == '>') ; + pz += strspn(pz, " \t"); + dir = pz; + if (*dir != NUL) + return dir; + } + + if (opts->papzHomeList == NULL) + return NULL; /* * This function only works if there is a directory where * we can stash the RC (INI) file. */ - { - char const * const * papz = opts->papzHomeList; - if (papz == NULL) - return NULL; - - while (papz[1] != NULL) papz++; - dir = *papz; - } - - /* - * IF it does not require deciphering an env value, then just copy it - */ - if (*dir != '$') - return dir; - - { - char const * end = strchr(++dir, DIRCH); - char * env; + for (idx = 0;; idx++) { + char f_name[ AG_PATH_MAX+1 ]; - if (end != NULL) { - char z[ AO_NAME_SIZE ]; - if ((end - dir) > AO_NAME_LIMIT ) - return NULL; - memcpy(z, dir, (size_t)(end - dir)); - z[end - dir] = NUL; - env = getenv(z); - } else { - - /* - * Make sure we can get the env value (after stripping off - * any trailing directory or file names) - */ - env = getenv(dir); - } + dir = opts->papzHomeList[idx]; - if (env == NULL) { - fprintf(stderr, zsave_warn, opts->pzProgName); - fprintf(stderr, zNotDef, dir); - return NULL; + switch (*dir) { + case '$': + break; + case NUL: + continue; + default: + return dir; } - - if (end == NULL) - return env; - - /* - * we will be returning an allocated result - */ - *p_free = 1; - - { - size_t env_len = strlen(env); - size_t end_len = strlen(end); - char * p; - char * res = p = (char *)AGALOC(env_len + end_len + 2, "dir name"); - - memcpy(p, env, env_len); - p += env_len; - *(p++) = '/'; - memcpy(p, end, end_len + 1); - - return res; + if (optionMakePath(f_name, (int)sizeof(f_name), dir, opts->pzProgPath)) { + *p_free = true; + AGDUPSTR(dir, f_name, "homerc"); + return dir; } } + return NULL; } /** + * Find the name of the save-the-options file + * + * @param opts the options descriptor + * @param p_free_name tell caller if name was allocated or not */ static char const * find_file_name(tOptions * opts, int * p_free_name) @@ -164,15 +101,15 @@ find_file_name(tOptions * opts, int * p_free_name) struct stat stBuf; int free_dir_name = 0; - char const * pzDir = find_dir_name(opts, &free_dir_name); - if (pzDir == NULL) - return NULL; + char const * res = find_dir_name(opts, &free_dir_name); + if (res == NULL) + return res; /* * See if we can find the specified directory. We use a once-only loop * structure so we can bail out early. */ - if (stat(pzDir, &stBuf) != 0) do { + if (stat(res, &stBuf) != 0) do { char z[AG_PATH_MAX]; char * dirchp; @@ -182,10 +119,10 @@ find_file_name(tOptions * opts, int * p_free_name) */ if (errno != ENOENT) { bogus_name: - fprintf(stderr, zsave_warn, opts->pzProgName); - fprintf(stderr, zNoStat, errno, strerror(errno), pzDir); + fprintf(stderr, zsave_warn, opts->pzProgName, res); + fprintf(stderr, zNoStat, errno, strerror(errno), res); if (free_dir_name) - AGFREE(pzDir); + AGFREE(res); return NULL; } @@ -193,17 +130,17 @@ find_file_name(tOptions * opts, int * p_free_name) * Strip off the last component, stat the remaining string and * that string must name a directory */ - dirchp = strrchr(pzDir, DIRCH); + dirchp = strrchr(res, DIRCH); if (dirchp == NULL) { stBuf.st_mode = S_IFREG; break; /* found directory -- viz., "." */ } - if ((size_t)(dirchp - pzDir) >= sizeof(z)) + if ((size_t)(dirchp - res) >= sizeof(z)) goto bogus_name; - memcpy(z, pzDir, (size_t)(dirchp - pzDir)); - z[dirchp - pzDir] = NUL; + memcpy(z, res, (size_t)(dirchp - res)); + z[dirchp - res] = NUL; if ((stat(z, &stBuf) != 0) || ! S_ISDIR(stBuf.st_mode)) goto bogus_name; @@ -217,15 +154,15 @@ find_file_name(tOptions * opts, int * p_free_name) if (S_ISDIR(stBuf.st_mode)) { { - size_t sz = strlen(pzDir) + strlen(opts->pzRcName) + 2; + size_t sz = strlen(res) + strlen(opts->pzRcName) + 2; char * pzPath = (char *)AGALOC(sz, "file name"); - if ( snprintf(pzPath, sz, "%s/%s", pzDir, opts->pzRcName) + if ( snprintf(pzPath, sz, "%s/%s", res, opts->pzRcName) >= (int)sz) option_exits(EXIT_FAILURE); if (free_dir_name) - AGFREE(pzDir); - pzDir = pzPath; + AGFREE(res); + res = pzPath; free_dir_name = 1; } @@ -233,12 +170,12 @@ find_file_name(tOptions * opts, int * p_free_name) * IF we cannot stat the object for any reason other than * it does not exist, then we bail out */ - if (stat(pzDir, &stBuf) != 0) { + if (stat(res, &stBuf) != 0) { if (errno != ENOENT) { - fprintf(stderr, zsave_warn, opts->pzProgName); + fprintf(stderr, zsave_warn, opts->pzProgName, res); fprintf(stderr, zNoStat, errno, strerror(errno), - pzDir); - AGFREE(pzDir); + res); + AGFREE(res); return NULL; } @@ -254,32 +191,37 @@ find_file_name(tOptions * opts, int * p_free_name) * or will soon be a file. */ if (! S_ISREG(stBuf.st_mode)) { - fprintf(stderr, zsave_warn, opts->pzProgName, pzDir); + fprintf(stderr, zsave_warn, opts->pzProgName, res); if (free_dir_name) - AGFREE(pzDir); + AGFREE(res); return NULL; } /* * Get rid of the old file */ - unlink(pzDir); *p_free_name = free_dir_name; - return pzDir; + return res; } /** * print one option entry to the save file. * - * @param[in] fp the file pointer for the save file - * @param[in] od the option descriptor to print - * @param[in] l_arg the last argument for the option + * @param[in] fp the file pointer for the save file + * @param[in] od the option descriptor to print + * @param[in] l_arg the last argument for the option + * @param[in] save_fl include usage in comments */ static void -prt_entry(FILE * fp, tOptDesc * od, char const * l_arg) +prt_entry(FILE * fp, tOptDesc * od, char const * l_arg, save_flags_mask_t save_fl) { int space_ct; + if (save_fl & SVFL_USAGE) + fprintf(fp, ao_name_use_fmt, od->pz_Name, od->pzText); + if (UNUSED_OPT(od) && (save_fl & SVFL_DEFAULT)) + fputs(ao_default_use, fp); + /* * There is an argument. Pad the name so values line up. * Not disabled *OR* this got equivalenced to another opt, @@ -288,9 +230,14 @@ prt_entry(FILE * fp, tOptDesc * od, char const * l_arg) */ { char const * pz = - (! DISABLED_OPT(od) || (od->optEquivIndex != NO_EQUIVALENT)) + (od->pz_DisableName == NULL) ? od->pz_Name - : od->pz_DisableName; + : (DISABLED_OPT(od) + ? od->pz_DisableName + : ((od->optEquivIndex == NO_EQUIVALENT) + ? od->pz_Name : od->pz_DisableName) + ); + space_ct = 17 - strlen(pz); fputs(pz, fp); } @@ -339,9 +286,13 @@ prt_entry(FILE * fp, tOptDesc * od, char const * l_arg) } /** + * print an option's value + * + * @param[in] fp the file pointer for the save file + * @param[in] od the option descriptor to print */ static void -prt_value(FILE * fp, int depth, tOptDesc * pOD, tOptionValue const * ovp) +prt_value(FILE * fp, int depth, tOptDesc * od, tOptionValue const * ovp) { while (--depth >= 0) putc(' ', fp), putc(' ', fp); @@ -358,9 +309,9 @@ prt_value(FILE * fp, int depth, tOptDesc * pOD, tOptionValue const * ovp) case OPARG_TYPE_ENUMERATION: case OPARG_TYPE_MEMBERSHIP: - if (pOD != NULL) { - uint32_t opt_state = pOD->fOptState; - uintptr_t val = pOD->optArg.argEnum; + if (od != NULL) { + uint32_t opt_state = od->fOptState; + uintptr_t val = od->optArg.argEnum; char const * typ = (ovp->valType == OPARG_TYPE_ENUMERATION) ? "keyword" : "set-membership"; @@ -370,20 +321,20 @@ prt_value(FILE * fp, int depth, tOptDesc * pOD, tOptionValue const * ovp) * This is a magic incantation that will convert the * bit flag values back into a string suitable for printing. */ - (*(pOD->pOptProc))(OPTPROC_RETURN_VALNAME, pOD ); - if (pOD->optArg.argString != NULL) { - fputs(pOD->optArg.argString, fp); + (*(od->pOptProc))(OPTPROC_RETURN_VALNAME, od ); + if (od->optArg.argString != NULL) { + fputs(od->optArg.argString, fp); if (ovp->valType != OPARG_TYPE_ENUMERATION) { /* * set membership strings get allocated */ - AGFREE(pOD->optArg.argString); + AGFREE(od->optArg.argString); } } - pOD->optArg.argEnum = val; - pOD->fOptState = opt_state; + od->optArg.argEnum = val; + od->fOptState = opt_state; fprintf(fp, END_XML_FMT, ovp->pzName); break; } @@ -405,6 +356,9 @@ prt_value(FILE * fp, int depth, tOptDesc * pOD, tOptionValue const * ovp) } /** + * Print a string value in XML format + * + * @param[in] fp the file pointer for the save file */ static void prt_string(FILE * fp, char const * name, char const * pz) @@ -441,6 +395,9 @@ prt_string(FILE * fp, char const * name, char const * pz) } /** + * Print an option that can have multiple values in XML format + * + * @param[in] fp file pointer */ static void prt_val_list(FILE * fp, char const * name, tArgList * al) @@ -477,15 +434,26 @@ prt_val_list(FILE * fp, char const * name, tArgList * al) } /** + * printed a nested/hierarchical value + * + * @param[in] fp file pointer + * @param[in] od option descriptor + * @param[in] save_fl include usage in comments */ static void -prt_nested(FILE * fp, tOptDesc * p) +prt_nested(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl) { int opt_ct; - tArgList * al = p->optCookie; + tArgList * al = od->optCookie; void ** opt_list; - if (al == NULL) + if (save_fl & SVFL_USAGE) + fprintf(fp, ao_name_use_fmt, od->pz_Name, od->pzText); + + /* + * Never show a default value if a hierarchical value is empty. + */ + if (UNUSED_OPT(od) || (al == NULL)) return; opt_ct = al->useCt; @@ -501,48 +469,128 @@ prt_nested(FILE * fp, tOptDesc * p) if (ovp == NULL) continue; - fprintf(fp, NESTED_OPT_FMT, p->pz_Name); + fprintf(fp, NESTED_OPT_FMT, od->pz_Name); do { - prt_value(fp, 1, p, ovp); + prt_value(fp, 1, od, ovp); } while (ovp = optionNextValue(base, ovp), ovp != NULL); - fprintf(fp, "\n", p->pz_Name); + fprintf(fp, "\n", od->pz_Name); } while (--opt_ct > 0); } /** - * open the file for saving option state. + * remove the current program settings * * @param[in] opts the program options structure + * @param[in] fname the save file name + */ +static void +remove_settings(tOptions * opts, char const * fname) +{ + size_t const name_len = strlen(opts->pzProgName); + tmap_info_t map_info; + char * text = text_mmap(fname, PROT_READ|PROT_WRITE, MAP_PRIVATE, &map_info); + char * scan = text; + + for (;;) { + char * next = scan = strstr(scan, zCfgProg); + if (scan == NULL) + goto leave; + + scan = SPN_WHITESPACE_CHARS(scan + zCfgProg_LEN); + if ( (strneqvcmp(scan, opts->pzProgName, (int)name_len) == 0) + && (IS_END_XML_TOKEN_CHAR(scan[name_len])) ) { + + scan = next; + break; + } + } + + /* + * If not NULL, "scan" points to the "pzProgName); - fprintf(stderr, zNoCreat, errno, strerror(errno), pzFName); + fprintf(stderr, zsave_warn, opts->pzProgName, fname); + fprintf(stderr, zNoCreat, errno, strerror(errno), fname); if (free_name) - AGFREE(pzFName); + AGFREE(fname); return fp; } if (free_name) - AGFREE(pzFName); + AGFREE(fname); } + do { + struct stat sbuf; + if (fstat(fileno(fp), &sbuf) < 0) + break; + + if (sbuf.st_size > zPresetFile_LEN) { + /* non-zero size implies save_fl is non-zero */ + fprintf(fp, zFmtProg, opts->pzProgName); + return fp; + } + } while (false); + + /* + * We have a new file. Insert a header + */ fputs("# ", fp); { char const * e = strchr(opts->pzUsageTitle, NL); @@ -564,40 +612,63 @@ open_sv_file(tOptions * opts) AGFREE(time_str); #endif } - + if (save_fl != 0) + fprintf(fp, zFmtProg, opts->pzProgName); return fp; } /** + * print option without an arg + * + * @param[in] fp file pointer + * @param[in] vod value option descriptor + * @param[in] pod primary option descriptor + * @param[in] save_fl include usage in comments */ static void -prt_no_arg_opt(FILE * fp, tOptDesc * p, tOptDesc * pOD) +prt_no_arg_opt(FILE * fp, tOptDesc * vod, tOptDesc * pod, save_flags_mask_t save_fl) { /* * The aliased to argument indicates whether or not the option * is "disabled". However, the original option has the name - * string, so we get that there, not with "p". + * string, so we get that there, not with "vod". */ char const * pznm = - (DISABLED_OPT(p)) ? pOD->pz_DisableName : pOD->pz_Name; + (DISABLED_OPT(vod)) ? pod->pz_DisableName : pod->pz_Name; /* * If the option was disabled and the disablement name is NULL, * then the disablement was caused by aliasing. * Use the name as the string to emit. */ if (pznm == NULL) - pznm = pOD->pz_Name; + pznm = pod->pz_Name; + + if (save_fl & SVFL_USAGE) + fprintf(fp, ao_name_use_fmt, pod->pz_Name, pod->pzText); + if (UNUSED_OPT(pod) && (save_fl & SVFL_DEFAULT)) + fputs(ao_default_use, fp); fprintf(fp, "%s\n", pznm); } /** + * print the string valued argument(s). + * + * @param[in] fp file pointer + * @param[in] od value option descriptor + * @param[in] save_fl include usage in comments */ static void -prt_str_arg(FILE * fp, tOptDesc * pOD) +prt_str_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl) { - if (pOD->fOptState & OPTST_STACKED) { - tArgList * pAL = (tArgList *)pOD->optCookie; + if (UNUSED_OPT(od) || ((od->fOptState & OPTST_STACKED) == 0)) { + char const * arg = od->optArg.argString; + if (arg == NULL) + arg = "''"; + prt_entry(fp, od, arg, save_fl); + + } else { + tArgList * pAL = (tArgList *)od->optCookie; int uct = pAL->useCt; char const ** ppz = pAL->apzArgs; @@ -605,23 +676,24 @@ prt_str_arg(FILE * fp, tOptDesc * pOD) * un-disable multiple copies of disabled options. */ if (uct > 1) - pOD->fOptState &= ~OPTST_DISABLED; + od->fOptState &= ~OPTST_DISABLED; - while (uct-- > 0) - prt_entry(fp, pOD, *(ppz++)); - } else { - prt_entry(fp, pOD, pOD->optArg.argString); + while (uct-- > 0) { + prt_entry(fp, od, *(ppz++), save_fl); + save_fl &= ~SVFL_USAGE; + } } } /** * print the string value of an enumeration. * - * @param[in] fp the file pointer to write to - * @param[in] od the option descriptor with the enumerated value + * @param[in] fp the file pointer to write to + * @param[in] od the option descriptor with the enumerated value + * @param[in] save_fl include usage in comments */ static void -prt_enum_arg(FILE * fp, tOptDesc * od) +prt_enum_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl) { uintptr_t val = od->optArg.argEnum; @@ -630,29 +702,31 @@ prt_enum_arg(FILE * fp, tOptDesc * od) * bit flag values back into a string suitable for printing. */ (*(od->pOptProc))(OPTPROC_RETURN_VALNAME, od); - prt_entry(fp, od, VOIDP(od->optArg.argString)); + prt_entry(fp, od, VOIDP(od->optArg.argString), save_fl); od->optArg.argEnum = val; } /** * Print the bits set in a bit mask option. + * * We call the option handling function with a magic value for * the options pointer and it allocates and fills in the string. * We print that with a call to prt_entry(). * - * @param[in] fp the file pointer to write to - * @param[in] od the option descriptor with a bit mask value type + * @param[in] fp the file pointer to write to + * @param[in] od the option descriptor with a bit mask value type + * @param[in] save_fl include usage in comments */ static void -prt_set_arg(FILE * fp, tOptDesc * od) +prt_set_arg(FILE * fp, tOptDesc * od, save_flags_mask_t save_fl) { char * list = optionMemberList(od); size_t len = strlen(list); char * buf = (char *)AGALOC(len + 3, "dir name"); *buf= '='; memcpy(buf+1, list, len + 1); - prt_entry(fp, od, buf); + prt_entry(fp, od, buf, save_fl); AGFREE(buf); AGFREE(list); } @@ -661,29 +735,35 @@ prt_set_arg(FILE * fp, tOptDesc * od) * figure out what the option file name argument is. * If one can be found, call prt_entry() to emit it. * - * @param[in] fp the file pointer to write to. - * @param[in] od the option descriptor with a bit mask value type - * @param[in] opts the program options descriptor + * @param[in] fp the file pointer to write to. + * @param[in] od the option descriptor with a bit mask value type + * @param[in] opts the program options descriptor + * @param[in] save_fl include usage in comments */ static void -prt_file_arg(FILE * fp, tOptDesc * od, tOptions * opts) +prt_file_arg(FILE * fp, tOptDesc * od, tOptions * opts, save_flags_mask_t save_fl) { /* * If the cookie is not NULL, then it has the file name, period. * Otherwise, if we have a non-NULL string argument, then.... */ if (od->optCookie != NULL) - prt_entry(fp, od, od->optCookie); + prt_entry(fp, od, od->optCookie, save_fl); else if (HAS_originalOptArgArray(opts)) { char const * orig = opts->originalOptArgArray[od->optIndex].argString; - if (od->optArg.argString == orig) + if (od->optArg.argString == orig) { + if (save_fl) + fprintf(fp, ao_name_use_fmt, od->pz_Name, od->pzText); return; + } - prt_entry(fp, od, od->optArg.argString); - } + prt_entry(fp, od, od->optArg.argString, save_fl); + + } else if (save_fl) + fprintf(fp, ao_name_use_fmt, od->pz_Name, od->pzText); } /*=export_func optionSaveFile @@ -720,8 +800,32 @@ optionSaveFile(tOptions * opts) { tOptDesc * od; int ct; - FILE * fp = open_sv_file(opts); + FILE * fp; + save_flags_mask_t save_flags = SVFL_NONE; + + do { + char * temp_str; + char const * dir = opts->pOptDesc[ opts->specOptIdx.save_opts ].optArg.argString; + size_t flen; + if (dir == NULL) + break; + temp_str = strchr(dir, '>'); + if (temp_str == NULL) + break; + if (temp_str[1] == '>') + save_flags = SVFL_UPDATE; + flen = (temp_str - dir); + if (flen == 0) + break; + temp_str = AGALOC(flen + 1, "flag search str"); + memcpy(temp_str, dir, flen); + temp_str[flen] = NUL; + save_flags |= save_flags_str2mask(temp_str, SVFL_NONE); + AGFREE(temp_str); + } while (false); + + fp = open_sv_file(opts, save_flags & SVFL_UPDATE); if (fp == NULL) return; @@ -731,20 +835,20 @@ optionSaveFile(tOptions * opts) ct = opts->presetOptCt; od = opts->pOptDesc; do { - tOptDesc * p; + tOptDesc * vod; /* - * IF the option has not been defined - * OR it does not take an initialization value - * OR it is equivalenced to another option - * THEN continue (ignore it) - * * Equivalenced options get picked up when the equivalenced-to - * option is processed. + * option is processed. And do not save options with any state + * bits in the DO_NOT_SAVE collection + * + * ** option cannot be preset + * #define OPTST_NO_INIT 0x0000100U + * ** disable from cmd line + * #define OPTST_NO_COMMAND 0x2000000U + * ** alias for other option + * #define OPTST_ALIAS 0x8000000U */ - if (UNUSED_OPT(od)) - continue; - if ((od->fOptState & OPTST_DO_NOT_SAVE_MASK) != 0) continue; @@ -752,45 +856,48 @@ optionSaveFile(tOptions * opts) && (od->optEquivIndex != od->optIndex)) continue; + if (UNUSED_OPT(od) && ((save_flags & SVFL_USAGE_DEFAULT_MASK) == SVFL_NONE)) + continue; + /* * The option argument data are found at the equivalenced-to option, * but the actual option argument type comes from the original * option descriptor. Be careful! */ - p = ((od->fOptState & OPTST_EQUIVALENCE) != 0) - ? (opts->pOptDesc + od->optActualIndex) : od; + vod = ((od->fOptState & OPTST_EQUIVALENCE) != 0) + ? (opts->pOptDesc + od->optActualIndex) : od; switch (OPTST_GET_ARGTYPE(od->fOptState)) { case OPARG_TYPE_NONE: - prt_no_arg_opt(fp, p, od); + prt_no_arg_opt(fp, vod, od, save_flags); break; case OPARG_TYPE_NUMERIC: - prt_entry(fp, p, VOIDP(p->optArg.argInt)); + prt_entry(fp, vod, VOIDP(vod->optArg.argInt), save_flags); break; case OPARG_TYPE_STRING: - prt_str_arg(fp, p); + prt_str_arg(fp, vod, save_flags); break; case OPARG_TYPE_ENUMERATION: - prt_enum_arg(fp, p); + prt_enum_arg(fp, vod, save_flags); break; case OPARG_TYPE_MEMBERSHIP: - prt_set_arg(fp, p); + prt_set_arg(fp, vod, save_flags); break; case OPARG_TYPE_BOOLEAN: - prt_entry(fp, p, p->optArg.argBool ? "true" : "false"); + prt_entry(fp, vod, vod->optArg.argBool ? "true" : "false", save_flags); break; case OPARG_TYPE_HIERARCHY: - prt_nested(fp, p); + prt_nested(fp, vod, save_flags); break; case OPARG_TYPE_FILE: - prt_file_arg(fp, p, opts); + prt_file_arg(fp, vod, opts, save_flags); break; default: diff --git a/libopts/sort.c b/libopts/sort.c index 1ef85bc0d..b4bd5cb7e 100644 --- a/libopts/sort.c +++ b/libopts/sort.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -29,20 +29,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -/* = = = START-STATIC-FORWARD = = = */ -static tSuccess -must_arg(tOptions * opts, char * arg_txt, tOptState * pOS, - char ** opt_txt, uint32_t * opt_idx); - -static tSuccess -maybe_arg(tOptions * opts, char * arg_txt, tOptState * pOS, - char ** opt_txt, uint32_t * opt_idx); - -static tSuccess -short_opt_ck(tOptions * opts, char * arg_txt, tOptState * pOS, - char ** opt_txt, uint32_t * opt_idx); -/* = = = END-STATIC-FORWARD = = = */ - /* * "must_arg" and "maybe_arg" are really similar. The biggest * difference is that "may" will consume the next argument only if it @@ -178,7 +164,7 @@ short_opt_ck(tOptions * opts, char * arg_txt, tOptState * pOS, * If the program wants sorted options (separated operands and options), * then this routine will to the trick. */ -LOCAL void +static void optionSort(tOptions * opts) { char ** opt_txt; diff --git a/libopts/stack.c b/libopts/stack.c index 55bc6a530..39a328a85 100644 --- a/libopts/stack.c +++ b/libopts/stack.c @@ -11,7 +11,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -176,7 +176,7 @@ optionUnstackArg(tOptions * opts, tOptDesc * od) * a pointer to the argument list structure. It gets passed around * as an opaque address. */ -LOCAL void +static void addArgListEntry(void ** ppAL, void * entry) { tArgList * pAL = *(void **)ppAL; diff --git a/libopts/stdnoreturn.in.h b/libopts/stdnoreturn.in.h index 735f99c93..bf46c0883 100644 --- a/libopts/stdnoreturn.in.h +++ b/libopts/stdnoreturn.in.h @@ -1,6 +1,6 @@ /* A substitute for ISO C11 . - Copyright 2012-2016 Free Software Foundation, Inc. + Copyright 2012-2018 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -13,7 +13,7 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License - along with this program; if not, see . */ + along with this program; if not, see . */ /* Written by Paul Eggert. */ @@ -28,15 +28,25 @@ /* The definition of _Noreturn is copied here. */ -#if 1200 <= _MSC_VER -/* Standard include files on this platform contain declarations like - "__declspec (noreturn) void abort (void);". "#define noreturn - _Noreturn" would cause this declaration to be rewritten to the - invalid "__declspec (__declspec (noreturn)) void abort (void);". - Instead, define noreturn to empty, so that such declarations are - rewritten to "__declspec () void abort (void);", which is - equivalent to "void abort (void);"; this gives up on noreturn's - advice to the compiler but at least it is valid code. */ +#if 1200 <= _MSC_VER || defined __CYGWIN__ +/* On MSVC, standard include files contain declarations like + __declspec (noreturn) void abort (void); + "#define noreturn _Noreturn" would cause this declaration to be rewritten + to the invalid + __declspec (__declspec (noreturn)) void abort (void); + + Similarly, on Cygwin, standard include files contain declarations like + void __cdecl abort (void) __attribute__ ((noreturn)); + "#define noreturn _Noreturn" would cause this declaration to be rewritten + to the invalid + void __cdecl abort (void) __attribute__ ((__attribute__ ((__noreturn__)))); + + Instead, define noreturn to empty, so that such declarations are rewritten to + __declspec () void abort (void); + or + void __cdecl abort (void) __attribute__ (()); + respectively. This gives up on noreturn's advice to the compiler but at + least it is valid code. */ # define noreturn /*empty*/ #else # define noreturn _Noreturn diff --git a/libopts/streqvcmp.c b/libopts/streqvcmp.c index 01517308e..53477d65f 100644 --- a/libopts/streqvcmp.c +++ b/libopts/streqvcmp.c @@ -15,7 +15,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -37,7 +37,7 @@ * together for a case independent comparison. The mappings are * based upon ascii character sequences. */ -static unsigned char charmap[] = { + static unsigned char charmap[] = { NUL, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, '\a', '\b', '\t', NL, '\v', '\f', '\r', 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, diff --git a/libopts/text_mmap.c b/libopts/text_mmap.c index 60b79efa3..11093082e 100644 --- a/libopts/text_mmap.c +++ b/libopts/text_mmap.c @@ -9,7 +9,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -189,7 +189,7 @@ validate_mmap(char const * fname, int prot, int flags, tmap_info_t * mapinfo) #ifdef _WIN32 O_BINARY | #endif - ((FILE_WRITABLE(prot, flags)) ? O_RDWR : O_RDONLY); + FILE_WRITABLE(prot, flags) ? O_RDWR : O_RDONLY; /* * If you're not sharing the file and you are writing to it, diff --git a/libopts/time.c b/libopts/time.c index d88189e83..debaa7aed 100644 --- a/libopts/time.c +++ b/libopts/time.c @@ -8,7 +8,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control diff --git a/libopts/tokenize.c b/libopts/tokenize.c index cbff7fba4..7489e3d52 100644 --- a/libopts/tokenize.c +++ b/libopts/tokenize.c @@ -9,7 +9,7 @@ * This file defines the string_tokenize interface * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -28,23 +28,6 @@ * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ -#include -#include - -#define cc_t const unsigned char -#define ch_t unsigned char - -/* = = = START-STATIC-FORWARD = = = */ -static void -copy_cooked(ch_t ** ppDest, char const ** ppSrc); - -static void -copy_raw(ch_t ** ppDest, char const ** ppSrc); - -static token_list_t * -alloc_token_list(char const * str); -/* = = = END-STATIC-FORWARD = = = */ - static void copy_cooked(ch_t ** ppDest, char const ** ppSrc) { diff --git a/libopts/usage.c b/libopts/usage.c index 42f1622c1..8df3591e6 100644 --- a/libopts/usage.c +++ b/libopts/usage.c @@ -18,7 +18,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -40,61 +40,6 @@ #define GRAPH_CH(_ch) \ ((((unsigned)_ch) <= 0x7E) && (((unsigned)_ch) > ' ')) -/* = = = START-STATIC-FORWARD = = = */ -static unsigned int -parse_usage_flags(ao_flag_names_t const * fnt, char const * txt); - -static inline bool -do_gnu_usage(tOptions * pOpts); - -static inline bool -skip_misuse_usage(tOptions * pOpts); - -static void -print_offer_usage(tOptions * opts); - -static void -print_usage_details(tOptions * opts, int exit_code); - -static void -print_one_paragraph(char const * text, bool plain, FILE * fp); - -static void -prt_conflicts(tOptions * opts, tOptDesc * od); - -static void -prt_one_vendor(tOptions * opts, tOptDesc * od, - arg_types_t * argtp, char const * usefmt); - -static void -prt_vendor_opts(tOptions * opts, char const * title); - -static void -prt_extd_usage(tOptions * opts, tOptDesc * od, char const * title); - -static void -prt_ini_list(char const * const * papz, char const * ini_file, - char const * path_nm); - -static void -prt_preamble(tOptions * opts, tOptDesc * od, arg_types_t * at); - -static void -prt_one_usage(tOptions * opts, tOptDesc * od, arg_types_t * at); - -static void -prt_opt_usage(tOptions * opts, int ex_code, char const * title); - -static void -prt_prog_detail(tOptions * opts); - -static int -setGnuOptFmts(tOptions * opts, char const ** ptxt); - -static int -setStdOptFmts(tOptions * opts, char const ** ptxt); -/* = = = END-STATIC-FORWARD = = = */ - /** * Parse the option usage flags string. Any parsing problems yield * a zero (no flags set) result. This function is internal to @@ -154,6 +99,7 @@ parse_usage_flags(ao_flag_names_t const * fnt, char const * txt) case ',': txt = SPN_WHITESPACE_CHARS(txt + 1); /* Something must follow the comma */ + /* FALLTHROUGH */ default: continue; @@ -170,7 +116,7 @@ parse_usage_flags(ao_flag_names_t const * fnt, char const * txt) * environment variable is parsed. * @param[in,out] opts the program option descriptor */ -LOCAL void +static void set_usage_flags(tOptions * opts, char const * flg_txt) { # define _aof_(_n, _f) { sizeof(#_n)-1, _f, #_n }, @@ -307,7 +253,7 @@ print_offer_usage(tOptions * opts) help[0] = help[1] = '-'; strncpy(help + 2, od->pz_Name, 20); break; - + case 0: strncpy(help, od->pz_Name, 20); break; @@ -323,7 +269,7 @@ print_offer_usage(tOptions * opts) case (OPTPROC_LONGOPT | OPTPROC_SHORTOPT): strcpy(help, "--help"); break; - + case 0: strcpy(help, "help"); break; @@ -441,7 +387,7 @@ print_one_paragraph(char const * text, bool plain, FILE * fp) AGFREE(t); } } - + /*=export_func optionPrintParagraphs * private: * @@ -568,7 +514,7 @@ optionPrintParagraphs(char const * text, bool plain, FILE * fp) * If "exitCode" is "AO_EXIT_REQ_USAGE" (normally 64), then output will to * to stdout and the actual exit code will be "EXIT_SUCCESS". =*/ -void +noreturn void optionUsage(tOptions * opts, int usage_exit_code) { int exit_code = (usage_exit_code == AO_EXIT_REQ_USAGE) @@ -620,7 +566,7 @@ optionUsage(tOptions * opts, int usage_exit_code) print_usage_details(opts, usage_exit_code); else print_offer_usage(opts); - + flush_and_exit: fflush(option_usage_fp); if (ferror(option_usage_fp) != 0) diff --git a/libopts/version.c b/libopts/version.c index 8a8de75db..cd46be3a4 100644 --- a/libopts/version.c +++ b/libopts/version.c @@ -10,7 +10,7 @@ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. - * AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved + * AutoOpts is Copyright (C) 1992-2018 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control @@ -90,7 +90,7 @@ emit_copy_full(tOptions * o, FILE * fp) else emit_first_line(fp, o->pzUsageTitle, NULL, NULL); - + if (HAS_pzPkgDataDir(o) && (o->pzPackager != NULL)) { fputc(NL, fp); fputs(o->pzPackager, fp); @@ -119,7 +119,7 @@ emit_copy_note(tOptions * opts, FILE * fp) fputc(NL, fp); fprintf(fp, zao_ver_fmt, optionVersion()); - + if (HAS_pzPkgDataDir(opts) && (opts->pzPackager != NULL)) { fputc(NL, fp); fputs(opts->pzPackager, fp); @@ -153,7 +153,10 @@ print_ver(tOptions * opts, tOptDesc * od, FILE * fp, bool call_exit) ch = od->optArg.argString[0]; - else { + else if (OPTST_GET_ARGTYPE(od->fOptState) == OPARG_TYPE_STATIC) { + ch = od->optArg.argString[0]; + + } else { set_usage_flags(opts, NULL); ch = (opts->fOptSet & OPTPROC_GNUUSAGE) ? 'c' : 'v'; } diff --git a/src/Makefile.am b/src/Makefile.am index abae68b7d..c5fae3a9c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -41,10 +41,10 @@ tcpreplay.1: tcpreplay_opts.def tcpbridge.1: tcpbridge_opts.def @AUTOGEN@ -T agman-cmd.tpl $(opts_list) $< -tcpliveplay.1: tcpliveplay_opts.def +tcpliveplay.1: tcpliveplay_opts.def @AUTOGEN@ -T agman-cmd.tpl $(opts_list) $< -tcpcapinfo.1: tcpcapinfo_opts.def +tcpcapinfo.1: tcpcapinfo_opts.def @AUTOGEN@ -T agman-cmd.tpl $(opts_list) $< man_MANS = tcpreplay.1 tcpprep.1 tcprewrite.1 tcpreplay-edit.1 tcpcapinfo.1 @@ -58,7 +58,7 @@ man_MANS += tcpbridge.1 endif if COMPILE_TCPLIVEPLAY -bin_PROGRAMS += tcpliveplay +bin_PROGRAMS += tcpliveplay man_MANS += tcpliveplay.1 endif diff --git a/src/bridge.c b/src/bridge.c index d6d20e40a..970b753df 100644 --- a/src/bridge.c +++ b/src/bridge.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,27 +18,17 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "bridge.h" #include "config.h" -#include "defines.h" #include "common.h" - -#include -#include -#include -#include -#include +#include "tcpbridge.h" #include +#include #include +#include +#include -#include "tcpbridge.h" -#include "bridge.h" -#include "tcpedit/tcpedit.h" - -extern tcpbridge_opt_t options; extern tcpreplay_stats_t stats; -#ifdef DEBUG -extern int debug; -#endif volatile bool didsig; static void live_callback(u_char *, const struct pcap_pkthdr *, const u_char *); @@ -63,15 +53,6 @@ rbmacsrc_comp(struct macsrc_t *a, struct macsrc_t *b) RB_PROTOTYPE(macsrc_tree, macsrc_t, node, rbmacsrc_comp) RB_GENERATE(macsrc_tree, macsrc_t, node, rbmacsrc_comp) -/** - * redblack init - */ -void -rbinit(void) -{ - RB_INIT(&macsrc_root); -} - /** * create a new node... Malloc's memory */ @@ -86,7 +67,6 @@ new_node(void) return (node); } - /** * main loop for bridging in only one direction * optimized to not use poll(), but rather libpcap's builtin pcap_loop() @@ -105,9 +85,8 @@ do_bridge_unidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) livedata.pcap = options->pcap1; livedata.options = options; - if ((retcode = pcap_loop(options->pcap1, options->limit_send, - live_callback, (u_char*)&livedata)) < 0) { - warnx("Error in pcap_loop(): %s", pcap_geterr(options->pcap1)); + if ((retcode = pcap_loop(options->pcap1, (int)options->limit_send, live_callback, (u_char *)&livedata)) < 0) { + warnx("Error in %d pcap_loop(): %s", retcode, pcap_geterr(options->pcap1)); } } @@ -118,7 +97,7 @@ do_bridge_unidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) static void do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) { - struct pollfd polls[2]; /* one for left & right pcap */ + struct pollfd polls[2]; /* one for left & right pcap */ int pollresult, pollcount, timeout; struct live_data_t livedata; @@ -128,8 +107,7 @@ do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) livedata.tcpedit = tcpedit; livedata.options = options; - - /* + /* * loop until ctrl-C or we've sent enough packets * note that if -L wasn't specified, limit_send is * set to 0 so this will loop infinately @@ -138,8 +116,7 @@ do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) if (didsig) break; - dbgx(3, "limit_send: " COUNTER_SPEC " \t pkts_sent: " COUNTER_SPEC, - options->limit_send, stats.pkts_sent); + dbgx(3, "limit_send: " COUNTER_SPEC " \t pkts_sent: " COUNTER_SPEC, options->limit_send, stats.pkts_sent); /* reset the result codes */ polls[PCAP_INT1].revents = 0; @@ -165,8 +142,7 @@ do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) dbg(5, "Processing first interface"); livedata.source = PCAP_INT1; livedata.pcap = options->pcap1; - pcap_dispatch(options->pcap1, -1, (pcap_handler) live_callback, - (u_char *) &livedata); + pcap_dispatch(options->pcap1, -1, (pcap_handler)live_callback, (u_char *)&livedata); } /* check the other interface?? */ @@ -174,16 +150,13 @@ do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) dbg(5, "Processing second interface"); livedata.source = PCAP_INT2; livedata.pcap = options->pcap2; - pcap_dispatch(options->pcap2, -1, (pcap_handler) live_callback, - (u_char *) &livedata); + pcap_dispatch(options->pcap2, -1, (pcap_handler)live_callback, (u_char *)&livedata); } - } - else if (pollresult == 0) { + } else if (pollresult == 0) { dbg(3, "poll timeout exceeded..."); /* do something here? */ - } - else { + } else { /* poll error, probably a Ctrl-C */ warnx("poll() error: %s", strerror(errno)); } @@ -193,9 +166,8 @@ do_bridge_bidirectional(tcpbridge_opt_t *options, tcpedit_t *tcpedit) } /* do_bridge_bidirectional() */ - /** - * Main entry point to bridging. Does some initial setup and then calls the + * Main entry point to bridging. Does some initial setup and then calls the * correct loop (unidirectional or bidirectional) */ void @@ -217,7 +189,8 @@ do_bridge(tcpbridge_opt_t *options, tcpedit_t *tcpedit) if (options->unidir == 0) { /* compile filter */ dbgx(2, "Try to compile pcap bpf filter: %s", options->bpf.filter); - if (pcap_compile(options->pcap2, &options->bpf.program, options->bpf.filter, options->bpf.optimize, 0) != 0) { + if (pcap_compile(options->pcap2, &options->bpf.program, options->bpf.filter, options->bpf.optimize, 0) != + 0) { errx(-1, "Error compiling BPF filter: %s", pcap_geterr(options->pcap2)); } @@ -231,7 +204,6 @@ do_bridge(tcpbridge_opt_t *options, tcpedit_t *tcpedit) didsig = 0; (void)signal(SIGINT, signal_catcher); - if (options->unidir == 1) { do_bridge_unidirectional(options, tcpedit); } else { @@ -239,30 +211,28 @@ do_bridge(tcpbridge_opt_t *options, tcpedit_t *tcpedit) } if (gettimeofday(&stats.end_time, NULL) < 0) - errx(-1, "gettimeofday() failed: %s", strerror(errno)); + errx(-1, "gettimeofday() failed: %s", strerror(errno)); packet_stats(&stats); } - /** * This is the callback we use with pcap_dispatch to process * each packet received by libpcap on the two interfaces. * Need to return > 0 to denote success */ static void -live_callback(u_char *usr_data, const struct pcap_pkthdr *const_pkthdr, - const u_char * nextpkt) +live_callback(u_char *usr_data, const struct pcap_pkthdr *const_pkthdr, const u_char *nextpkt) { - struct live_data_t *livedata = (struct live_data_t*)usr_data; + struct live_data_t *livedata = (struct live_data_t *)usr_data; struct pcap_pkthdr pkthdr_buf = *const_pkthdr; struct pcap_pkthdr *pkthdr = &pkthdr_buf; ipv4_hdr_t *ip_hdr = NULL; ipv6_hdr_t *ip6_hdr = NULL; pcap_t *send = NULL; - static u_char *pktdata = NULL; /* full packet buffer */ - int cache_mode, retcode; + static u_char *pktdata = NULL; /* full packet buffer */ + int cache_mode; static unsigned long packetnum = 0; - struct macsrc_t *node, finder; /* rb tree nodes */ + struct macsrc_t *node, finder; /* rb tree nodes */ #ifdef DEBUG u_char dstmac[ETHER_ADDR_LEN]; #endif @@ -283,28 +253,24 @@ live_callback(u_char *usr_data, const struct pcap_pkthdr *const_pkthdr, /* copy the packet to our buffer */ memcpy(pktdata, nextpkt, pkthdr->caplen); - #ifdef ENABLE_VERBOSE /* decode packet? */ if (livedata->options->verbose) tcpdump_print(livedata->options->tcpdump, pkthdr, nextpkt); #endif - /* lookup our source MAC in the tree */ memcpy(&finder.key, &pktdata[ETHER_ADDR_LEN], ETHER_ADDR_LEN); #ifdef DEBUG memcpy(&dstmac, pktdata, ETHER_ADDR_LEN); - dbgx(1, "SRC MAC: " MAC_FORMAT "\tDST MAC: " MAC_FORMAT, - MAC_STR(finder.key), MAC_STR(dstmac)); + dbgx(1, "SRC MAC: " MAC_FORMAT "\tDST MAC: " MAC_FORMAT, MAC_STR(finder.key), MAC_STR(dstmac)); #endif /* first, is this a packet sent locally? If so, ignore it */ if ((memcmp(livedata->options->intf1_mac, &finder.key, ETHER_ADDR_LEN)) == 0) { dbgx(1, "Packet matches the MAC of %s, skipping.", livedata->options->intf1); return; - } - else if ((memcmp(livedata->options->intf2_mac, &finder.key, ETHER_ADDR_LEN)) == 0) { + } else if ((memcmp(livedata->options->intf2_mac, &finder.key, ETHER_ADDR_LEN)) == 0) { dbgx(1, "Packet matches the MAC of %s, skipping.", livedata->options->intf2); return; } @@ -333,27 +299,25 @@ live_callback(u_char *usr_data, const struct pcap_pkthdr *const_pkthdr, /* what is our cache mode? */ cache_mode = livedata->source == PCAP_INT1 ? TCPR_DIR_C2S : TCPR_DIR_S2C; - l2proto = tcpedit_l3proto(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len); + l2proto = tcpedit_l3proto(livedata->tcpedit, BEFORE_PROCESS, pktdata, (int)pkthdr->len); dbgx(2, "Packet protocol: %04hx", l2proto); /* should we skip this packet based on CIDR match? */ if (l2proto == ETHERTYPE_IP) { dbg(3, "Packet is IPv4"); - ip_hdr = (ipv4_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len); + ip_hdr = (ipv4_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, (int)pkthdr->len); /* look for include or exclude CIDR match */ if (livedata->options->xX.cidr != NULL) { - if (!ip_hdr || - !process_xX_by_cidr_ipv4(livedata->options->xX.mode, livedata->options->xX.cidr, ip_hdr)) { + if (!ip_hdr || !process_xX_by_cidr_ipv4(livedata->options->xX.mode, livedata->options->xX.cidr, ip_hdr)) { dbg(2, "Skipping IPv4 packet due to CIDR match"); return; } } - } - else if (l2proto == ETHERTYPE_IP6) { + } else if (l2proto == ETHERTYPE_IP6) { dbg(3, "Packet is IPv6"); - ip6_hdr = (ipv6_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len); + ip6_hdr = (ipv6_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, (int)pkthdr->len); /* look for include or exclude CIDR match */ if (livedata->options->xX.cidr != NULL) { @@ -362,40 +326,38 @@ live_callback(u_char *usr_data, const struct pcap_pkthdr *const_pkthdr, return; } } - } - if ((retcode = tcpedit_packet(livedata->tcpedit, &pkthdr, &pktdata, cache_mode)) < 0) + if (tcpedit_packet(livedata->tcpedit, &pkthdr, &pktdata, cache_mode) < 0) return; - /* + /* * send packets out the OTHER interface * and update the dst mac if necessary */ - switch(node->source) { - case PCAP_INT1: - dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf1, - livedata->options->intf2); - send = livedata->options->pcap2; - break; - - case PCAP_INT2: - dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf2, - livedata->options->intf1); - send = livedata->options->pcap1; - break; - - default: - errx(-1, "wtf? our node->source != PCAP_INT1 and != PCAP_INT2: %c", - node->source); + switch (node->source) { + case PCAP_INT1: + dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf1, livedata->options->intf2); + send = livedata->options->pcap2; + break; + + case PCAP_INT2: + dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf2, livedata->options->intf1); + send = livedata->options->pcap1; + break; + + default: + errx(-1, "wtf? our node->source != PCAP_INT1 and != PCAP_INT2: %c", node->source); } /* - * write packet out on the network + * write packet out on the network */ - if (pcap_sendpacket(send, pktdata, pkthdr->caplen) < 0) - errx(-1, "Unable to send packet out %s: %s", - send == livedata->options->pcap1 ? livedata->options->intf1 : livedata->options->intf2, pcap_geterr(send)); + if (pcap_sendpacket(send, pktdata, (int)pkthdr->caplen) < 0) + errx(-1, + "Unable to send packet out %s: %s", + send == livedata->options->pcap1 ? livedata->options->intf1 : livedata->options->intf2, + pcap_geterr(send)); stats.bytes_sent += pkthdr->caplen; stats.pkts_sent++; @@ -409,5 +371,4 @@ signal_catcher(int signo) /* stdio in signal handlers causes a race condition, instead set a flag */ if (signo == SIGINT) didsig = true; - } diff --git a/src/bridge.h b/src/bridge.h index 4f4dff55e..bb7783682 100644 --- a/src/bridge.h +++ b/src/bridge.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,23 +18,22 @@ * along with the Tcpreplay Suite. If not, see . */ - -#ifndef __BRIDGE_H__ -#define __BRIDGE_H__ +#pragma once #include "config.h" -#include "lib/tree.h" -#include "tcpedit/tcpedit.h" +#include "tcpbridge.h" +#include +#include /* - * RBTree node object for tracking which side of tcpreplay where + * RBTree node object for tracking which side of tcpreplay where * each source MAC address lives */ struct macsrc_t { RB_ENTRY(macsrc_t) node; u_char key[ETHER_ADDR_LEN]; - u_char source; /* interface device name we first saw the source MAC */ - sendpacket_t *sp; /* sendpacket handle to send packets out */ + u_char source; /* interface device name we first saw the source MAC */ + sendpacket_t *sp; /* sendpacket handle to send packets out */ }; /* pri and secondary pcap interfaces */ @@ -55,6 +54,3 @@ struct live_data_t { void rbinit(void); void do_bridge(tcpbridge_opt_t *, tcpedit_t *); - - -#endif diff --git a/src/common.h b/src/common.h index aee2b3c88..dd57f08df 100644 --- a/src/common.h +++ b/src/common.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,40 +18,36 @@ * along with the Tcpreplay Suite. If not, see . */ +#pragma once -#ifndef __COMMON_H__ -#define __COMMON_H__ -#include #include "config.h" +#include #ifdef __cplusplus extern "C" { #endif -#include "common/pcap_dlt.h" -#include "common/cache.h" -#include "common/cidr.h" -#include "common/err.h" -#include "common/get.h" -#include "common/fakepcap.h" -#include "common/fakepcapnav.h" -#include "common/fakepoll.h" -#include "common/list.h" -#include "common/mac.h" -#include "common/services.h" -#include "common/utils.h" -#include "common/xX.h" -#include "common/tcpdump.h" -#include "common/timer.h" -#include "common/sendpacket.h" -#include "common/interface.h" -#include "common/flows.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include const char *git_version(void); /* git_version.c */ #ifdef __cplusplus } #endif - -#endif - diff --git a/src/common/cache.c b/src/common/cache.c index 378f5b0d4..d268463d9 100644 --- a/src/common/cache.c +++ b/src/common/cache.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,23 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - - +#include #include -#include #include +#include #include #include -#include #include -#include - -#ifdef DEBUG -extern int debug; -#endif static tcpr_cache_t *new_cache(void); @@ -44,8 +37,9 @@ static tcpr_cache_t *new_cache(void); */ #ifdef DEBUG static char * -byte2bits(char byte, char *bitstring) { - int i = 1, j = 7; +byte2bits(char byte, char *bitstring) +{ + int i, j = 7; for (i = 1; i <= 255; i = i << 1) { if (byte & i) @@ -61,7 +55,7 @@ byte2bits(char byte, char *bitstring) { * simple function to read in a cache file created with tcpprep this let's us * be really damn fast in picking an interface to send the packet out returns * number of cache entries read - * + * * now also checks for the cache magic and version */ @@ -70,8 +64,8 @@ read_cache(char **cachedata, const char *cachefile, char **comment) { int cachefd; tcpr_cache_file_hdr_t header; - ssize_t read_size = 0; - COUNTER cache_size = 0; + ssize_t read_size; + COUNTER cache_size; assert(cachedata); assert(comment); @@ -92,50 +86,48 @@ read_cache(char **cachedata, const char *cachefile, char **comment) errx(-1, "Unable to process %s: not a tcpprep cache file", cachefile); /* verify version */ - if (atoi(header.version) != atoi(CACHEVERSION)) - errx(-1, "Unable to process %s: cache file version mismatch", - cachefile); + if (strtol(header.version, NULL, 10) != strtol(CACHEVERSION, NULL, 10)) + errx(-1, "Unable to process %s: cache file version mismatch", cachefile); /* read the comment */ header.comment_len = ntohs(header.comment_len); if (header.comment_len > 65534) - errx(-1, "Unable to process %s: invalid comment length %u", - cachefile, header.comment_len); + errx(-1, "Unable to process %s: invalid comment length %u", cachefile, header.comment_len); *comment = (char *)safe_malloc(header.comment_len + 1); dbgx(1, "Comment length: %d", header.comment_len); - + if ((read_size = read(cachefd, *comment, header.comment_len)) < 0) errx(-1, "Error reading comment: %s", strerror(errno)); if (read_size != (ssize_t)header.comment_len) - errx(-1, "Invalid comment read: expected=%u actual=%zd bytes", - header.comment_len, read_size); + errx(-1, "Invalid comment read: expected=%u actual=%zd bytes", header.comment_len, read_size); dbgx(1, "Cache file comment: %s", *comment); /* malloc our cache block */ header.num_packets = ntohll(header.num_packets); - header.packets_per_byte = ntohs(header.packets_per_byte); + header.packets_per_byte = ntohs(header.packets_per_byte); cache_size = header.num_packets / header.packets_per_byte; - + /* deal with any remainder, because above division is integer */ if (header.num_packets % header.packets_per_byte) - cache_size ++; + cache_size++; - dbgx(1, "Cache file contains %" PRIu64 " packets in " COUNTER_SPEC " bytes", - header.num_packets, cache_size); + dbgx(1, "Cache file contains %" PRIu64 " packets in " COUNTER_SPEC " bytes", header.num_packets, cache_size); dbgx(1, "Cache uses %d packets per byte", header.packets_per_byte); *cachedata = (char *)safe_malloc(cache_size); /* read in the cache */ - if ((COUNTER)(read_size = read(cachefd, *cachedata, cache_size)) - != cache_size) - errx(-1, "Cache data length (%zu bytes) doesn't match " - "cache header (" COUNTER_SPEC " bytes)", read_size, cache_size); + if ((COUNTER)(read_size = read(cachefd, *cachedata, cache_size)) != cache_size) + errx(-1, + "Cache data length (%zu bytes) doesn't match " + "cache header (" COUNTER_SPEC " bytes)", + read_size, + cache_size); dbgx(1, "Loaded in %" PRIu64 " packets from cache.", header.num_packets); @@ -143,29 +135,26 @@ read_cache(char **cachedata, const char *cachefile, char **comment) return (header.num_packets); } - /** * writes out the cache file header, comment and then the - * contents of *cachedata to out_file and then returns the number + * contents of *cachedata to out_file and then returns the number * of cache entries written */ COUNTER -write_cache(tcpr_cache_t * cachedata, const int out_file, COUNTER numpackets, - char *comment) +write_cache(tcpr_cache_t *cachedata, const int out_file, COUNTER numpackets, char *comment) { tcpr_cache_t *mycache = NULL; tcpr_cache_file_hdr_t *cache_header = NULL; uint32_t chars, last = 0; COUNTER packets = 0; - ssize_t written = 0; + ssize_t written; assert(out_file); /* write a header to our file */ - cache_header = (tcpr_cache_file_hdr_t *) - safe_malloc(sizeof(tcpr_cache_file_hdr_t)); - strncpy(cache_header->magic, CACHEMAGIC, strlen(CACHEMAGIC)+1); - strncpy(cache_header->version, CACHEVERSION, strlen(CACHEVERSION)+1); + cache_header = (tcpr_cache_file_hdr_t *)safe_malloc(sizeof(tcpr_cache_file_hdr_t)); + strncpy(cache_header->magic, CACHEMAGIC, strlen(CACHEMAGIC) + 1); + strncpy(cache_header->version, CACHEVERSION, strlen(CACHEVERSION) + 1); cache_header->packets_per_byte = htons(CACHE_PACKETS_PER_BYTE); cache_header->num_packets = htonll((u_int64_t)numpackets); @@ -180,18 +169,22 @@ write_cache(tcpr_cache_t * cachedata, const int out_file, COUNTER numpackets, dbgx(1, "Wrote %zu bytes of cache file header", written); if (written != sizeof(tcpr_cache_file_hdr_t)) - errx(-1, "Only wrote %zu of %zu bytes of the cache file header!\n%s", - written, sizeof(tcpr_cache_file_hdr_t), + errx(-1, + "Only wrote %zu of %zu bytes of the cache file header!\n%s", + written, + sizeof(tcpr_cache_file_hdr_t), written == -1 ? strerror(errno) : ""); /* don't write comment if there is none */ if (comment != NULL) { written = write(out_file, comment, strlen(comment)); dbgx(1, "Wrote %zu bytes of comment", written); - + if (written != (ssize_t)strlen(comment)) - errx(-1, "Only wrote %zu of %zu bytes of the comment!\n%s", - written, strlen(comment), + errx(-1, + "Only wrote %zu of %zu bytes of the comment!\n%s", + written, + strlen(comment), written == -1 ? strerror(errno) : ""); } @@ -206,8 +199,7 @@ write_cache(tcpr_cache_t * cachedata, const int out_file, COUNTER numpackets, chars = mycache->packets / CACHE_PACKETS_PER_BYTE; if (mycache->packets % CACHE_PACKETS_PER_BYTE) { chars++; - dbgx(1, "Bumping up to the next byte: %d %% %d", mycache->packets, - CACHE_PACKETS_PER_BYTE); + dbgx(1, "Bumping up to the next byte: %d %% %d", mycache->packets, CACHE_PACKETS_PER_BYTE); } /* write to file, and verify it wrote properly */ @@ -222,8 +214,7 @@ write_cache(tcpr_cache_t * cachedata, const int out_file, COUNTER numpackets, */ if (mycache->next != NULL) { mycache = mycache->next; - } - else { + } else { last = 1; } } @@ -252,10 +243,10 @@ new_cache(void) */ tcpr_dir_t -add_cache(tcpr_cache_t ** cachedata, const int send, const tcpr_dir_t interface) +add_cache(tcpr_cache_t **cachedata, const int send, const tcpr_dir_t interface) { static tcpr_cache_t *lastcache = NULL; - tcpr_dir_t result = TCPR_DIR_ERROR; + tcpr_dir_t result; #ifdef DEBUG char bitstring[9] = EIGHT_ZEROS; #endif @@ -266,8 +257,7 @@ add_cache(tcpr_cache_t ** cachedata, const int send, const tcpr_dir_t interface) if (*cachedata == NULL || lastcache == NULL) { *cachedata = new_cache(); lastcache = *cachedata; - } - else { + } else { /* check to see if this is the last bit in this struct */ if ((lastcache->packets + 1) > (CACHEDATASIZE * CACHE_PACKETS_PER_BYTE)) { /* @@ -290,12 +280,11 @@ add_cache(tcpr_cache_t ** cachedata, const int send, const tcpr_dir_t interface) u_char *byte; index = (lastcache->packets - 1) / (COUNTER)CACHE_PACKETS_PER_BYTE; - bit = (((lastcache->packets - 1) % (COUNTER)CACHE_PACKETS_PER_BYTE) * - (COUNTER)CACHE_BITS_PER_PACKET) + 1; + bit = (((lastcache->packets - 1) % (COUNTER)CACHE_PACKETS_PER_BYTE) * (COUNTER)CACHE_BITS_PER_PACKET) + 1; dbgx(3, "Bit: %d", bit); - byte = (u_char *) & lastcache->data[index]; - *byte += (u_char) (1 << bit); + byte = (u_char *)&lastcache->data[index]; + *byte += (u_char)(1 << bit); dbgx(2, "set send bit: byte " COUNTER_SPEC " = 0x%x", index, *byte); @@ -305,19 +294,17 @@ add_cache(tcpr_cache_t ** cachedata, const int send, const tcpr_dir_t interface) dbgx(2, "set interface bit: byte " COUNTER_SPEC " = 0x%x", index, *byte); result = TCPR_DIR_C2S; - } - else { + } else { dbgx(2, "don't set interface bit: byte " COUNTER_SPEC " = 0x%x", index, *byte); result = TCPR_DIR_S2C; } #ifdef DEBUG - /* + /* * only build the byte string when not in debug mode since * the calculation is a bit expensive */ - dbgx(3, "Current cache byte: %c%c%c%c%c%c%c%c", - BIT_STR(byte2bits(*byte, bitstring))); + dbgx(3, "Current cache byte: %c%c%c%c%c%c%c%c", BIT_STR(byte2bits(*byte, bitstring))); #endif } else { dbg(1, "not setting send bit"); @@ -327,14 +314,13 @@ add_cache(tcpr_cache_t ** cachedata, const int send, const tcpr_dir_t interface) return result; } - /** * returns the action for a given packet based on the CACHE */ tcpr_dir_t check_cache(char *cachedata, COUNTER packetid) { - COUNTER index = 0; + COUNTER index; uint32_t bit; assert(cachedata); @@ -343,12 +329,15 @@ check_cache(char *cachedata, COUNTER packetid) err(-1, "packetid must be > 0"); index = (packetid - 1) / (COUNTER)CACHE_PACKETS_PER_BYTE; - bit = (uint32_t)(((packetid - 1) % (COUNTER)CACHE_PACKETS_PER_BYTE) * - (COUNTER)CACHE_BITS_PER_PACKET) + 1; + bit = (uint32_t)(((packetid - 1) % (COUNTER)CACHE_PACKETS_PER_BYTE) * (COUNTER)CACHE_BITS_PER_PACKET) + 1; #ifdef DEBUG - dbgx(3, "Index: " COUNTER_SPEC "\tBit: %d\tByte: %hhu\tMask: %hhu", index, bit, - cachedata[index], (uint8_t)(cachedata[index] & (char)(1 << bit))); + dbgx(3, + "Index: " COUNTER_SPEC "\tBit: %d\tByte: %hhu\tMask: %hhu", + index, + bit, + cachedata[index], + (uint8_t)(cachedata[index] & (char)(1 << bit))); #endif if (!(cachedata[index] & (char)(1 << bit))) { @@ -359,10 +348,7 @@ check_cache(char *cachedata, COUNTER packetid) bit--; if (cachedata[index] & (char)(1 << bit)) { return TCPR_DIR_C2S; - } - else { + } else { return TCPR_DIR_S2C; } - - return TCPR_DIR_ERROR; } diff --git a/src/common/cache.h b/src/common/cache.h index a7622c3b9..f064ebdcf 100644 --- a/src/common/cache.h +++ b/src/common/cache.h @@ -18,8 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __CACHE_H__ -#define __CACHE_H__ +#pragma once + +#include "defines.h" #define CACHEMAGIC "tcpprep" #define CACHEVERSION "04" @@ -99,5 +100,3 @@ tcpr_dir_t check_cache(char *, COUNTER); /* string of 8 zeros */ #define EIGHT_ZEROS "\060\060\060\060\060\060\060\060" - -#endif diff --git a/src/common/cidr.c b/src/common/cidr.c index 59aaf8728..687fd04b7 100644 --- a/src/common/cidr.c +++ b/src/common/cidr.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,22 +18,15 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include +#include #include #include #include -/* required for inet_aton() */ #include -#include -#include - - -#ifdef DEBUG -extern int debug; -#endif static tcpr_cidr_t *cidr2cidr(char *); @@ -41,7 +34,7 @@ static tcpr_cidr_t *cidr2cidr(char *); * prints to the given fd all the entries in mycidr */ void -print_cidr(tcpr_cidr_t * mycidr) +print_cidr(tcpr_cidr_t *mycidr) { tcpr_cidr_t *cidr_ptr; @@ -50,14 +43,12 @@ print_cidr(tcpr_cidr_t * mycidr) cidr_ptr = mycidr; while (cidr_ptr != NULL) { /* print it */ - fprintf(stderr, "%s/%d, ", get_cidr2name(cidr_ptr, RESOLVE), - cidr_ptr->masklen); + fprintf(stderr, "%s/%d, ", get_cidr2name(cidr_ptr, RESOLVE), cidr_ptr->masklen); /* go to the next */ if (cidr_ptr->next != NULL) { cidr_ptr = cidr_ptr->next; - } - else { + } else { break; } } @@ -68,24 +59,21 @@ print_cidr(tcpr_cidr_t * mycidr) * deletes all entries in a cidr and destroys the datastructure */ void -destroy_cidr(tcpr_cidr_t * cidr) +destroy_cidr(tcpr_cidr_t *cidr) { - if (cidr != NULL) { if (cidr->next != NULL) destroy_cidr(cidr->next); safe_free(cidr); } - return; - } /** * adds a new tcpr_cidr_t entry to cidrdata */ void -add_cidr(tcpr_cidr_t ** cidrdata, tcpr_cidr_t ** newcidr) +add_cidr(tcpr_cidr_t **cidrdata, tcpr_cidr_t **newcidr) { tcpr_cidr_t *cidr_ptr; dbg(1, "Running new_cidr()"); @@ -102,30 +90,6 @@ add_cidr(tcpr_cidr_t ** cidrdata, tcpr_cidr_t ** newcidr) } } -/** - * takes in an IP and masklen, and returns a string in - * cidr format: x.x.x.x/y. This malloc's memory. - */ -u_char * -ip2cidr(const unsigned long ip, const int masklen) -{ - u_char *network; - char mask[32]; - - network = (u_char *)safe_malloc(20); - - strlcpy((char *)network, (char *)get_addr2name4(ip, RESOLVE), 20); - - strcat((char *)network, "/"); - snprintf(mask, sizeof(mask), "%d", masklen); - if (masklen < 10) - strncat((char *)network, mask, 1); - else - strncat((char *)network, mask, 2); - - return (network); -} - /** * Mallocs and sets to sane defaults a tcpr_cidr_t structure */ @@ -136,7 +100,7 @@ new_cidr(void) tcpr_cidr_t *newcidr; newcidr = (tcpr_cidr_t *)safe_malloc(sizeof(tcpr_cidr_t)); - + memset(newcidr, '\0', sizeof(tcpr_cidr_t)); newcidr->masklen = 99; newcidr->next = NULL; @@ -153,14 +117,13 @@ new_cidr_map(void) tcpr_cidrmap_t *new; new = (tcpr_cidrmap_t *)safe_malloc(sizeof(tcpr_cidrmap_t)); - + memset(new, '\0', sizeof(tcpr_cidrmap_t)); new->next = NULL; return (new); } - /** * Converts a single cidr (string) in the form of x.x.x.x/y into a * tcpr_cidr_t structure. Will malloc the tcpr_cidr_t structure. @@ -168,12 +131,12 @@ new_cidr_map(void) static tcpr_cidr_t * cidr2cidr(char *cidr) { - int count = 0; - unsigned int octets[4]; /* used in sscanf */ + int count; + unsigned int octets[4]; /* used in sscanf */ tcpr_cidr_t *newcidr; char networkip[16], tempoctet[4]; int family; - char* p; + char *p; assert(cidr); @@ -192,8 +155,7 @@ cidr2cidr(char *cidr) * scan it, and make sure it scanned correctly, also copy over the * masklen */ - count = sscanf(cidr, "%u.%u.%u.%u/%d", &octets[0], &octets[1], - &octets[2], &octets[3], &newcidr->masklen); + count = sscanf(cidr, "%u.%u.%u.%u/%d", &octets[0], &octets[1], &octets[2], &octets[3], &newcidr->masklen); if (count == 4) { newcidr->masklen = 32; @@ -215,7 +177,7 @@ cidr2cidr(char *cidr) /* skip past the opening [ */ if (*cidr == '[') - cidr ++; + cidr++; if (get_name2addr6(cidr, RESOLVE, &newcidr->u.network6) > 0) { family = AF_INET6; @@ -248,10 +210,8 @@ cidr2cidr(char *cidr) #elif HAVE_INET_ADDR newcidr->network = inet_addr(networkip); #endif - } else if (family == AF_INET6) { - /* Everything's done */ } else { - goto error; + /* Everything's done */ } newcidr->family = family; @@ -260,20 +220,18 @@ cidr2cidr(char *cidr) /* we only get here on error parsing input */ error: errx(-1, "%s: %s", "Unable to parse as a valid CIDR", cidr); - return NULL; } -static void -mask_cidr6(char **cidrin, char* delim) +static void +mask_cidr6(char **cidrin, const char *delim) { if (**cidrin == '[' && *delim == ':') { char *p; ++*cidrin; /* make strtok happy */ for (p = *cidrin; *p && *p != ']'; ++p) { - if (*p == ':') { + if (*p == ':') *p = '#'; - } } } } @@ -285,9 +243,9 @@ mask_cidr6(char **cidrin, char* delim) * since we use strtok to process cidr, it gets zeroed out. */ int -parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim) +parse_cidr(tcpr_cidr_t **cidrdata, char *cidrin, char *delim) { - tcpr_cidr_t *cidr_ptr; /* ptr to current cidr record */ + tcpr_cidr_t *cidr_ptr; /* ptr to current cidr record */ char *network; char *token = NULL; @@ -295,6 +253,8 @@ parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim) /* first iteration of input using strtok */ network = strtok_r(cidrin, delim, &token); + if (network == NULL) + return 0; *cidrdata = cidr2cidr(network); cidr_ptr = *cidrdata; @@ -313,8 +273,8 @@ parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim) cidr_ptr->next = cidr2cidr(network); cidr_ptr = cidr_ptr->next; } - return 1; + return 1; } /** @@ -324,7 +284,7 @@ parse_cidr(tcpr_cidr_t ** cidrdata, char *cidrin, char *delim) * since we use strtok to process optarg, it gets zeroed out */ int -parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const char *optarg) +parse_endpoints(tcpr_cidrmap_t **cidrmap1, tcpr_cidrmap_t **cidrmap2, const char *optarg) { #define NEWMAP_LEN (INET6_ADDRSTRLEN * 2) char *map = NULL, newmap[NEWMAP_LEN]; @@ -341,13 +301,13 @@ parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const ch p = strstr(string, "]:["); if (!p) goto done; - + *p = 0; strlcpy(newmap, "[::/0]:", NEWMAP_LEN); strlcat(newmap, string, NEWMAP_LEN); strlcat(newmap, "]", NEWMAP_LEN); - - if (! parse_cidr_map(cidrmap1, newmap)) + + if (!parse_cidr_map(cidrmap1, newmap)) goto done; /* do again with the second IP */ @@ -355,29 +315,31 @@ parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const ch strlcpy(newmap, "[::/0]:", NEWMAP_LEN); strlcat(newmap, p + 2, NEWMAP_LEN); - if (! parse_cidr_map(cidrmap2, newmap)) + if (!parse_cidr_map(cidrmap2, newmap)) goto done; } else { /* ipv4 mode */ memset(newmap, '\0', NEWMAP_LEN); map = strtok_r(string, ":", &token); + if (map == NULL) + goto done; strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN); strlcat(newmap, map, NEWMAP_LEN); - if (! parse_cidr_map(cidrmap1, newmap)) + if (!parse_cidr_map(cidrmap1, newmap)) goto done; - + /* do again with the second IP */ memset(newmap, '\0', NEWMAP_LEN); map = strtok_r(NULL, ":", &token); - + strlcpy(newmap, "0.0.0.0/0:", NEWMAP_LEN); strlcat(newmap, map, NEWMAP_LEN); - if (! parse_cidr_map(cidrmap2, newmap)) + if (!parse_cidr_map(cidrmap2, newmap)) goto done; } - + /* success */ res = 1; @@ -386,7 +348,6 @@ parse_endpoints(tcpr_cidrmap_t ** cidrmap1, tcpr_cidrmap_t ** cidrmap2, const ch return res; } - /** * parses a list of tcpr_cidrmap_t's input from the user which should be in the form * of x.x.x.x/y:x.x.x.x/y,... @@ -402,12 +363,12 @@ parse_cidr_map(tcpr_cidrmap_t **cidrmap, const char *optarg) char *token = NULL, *string; tcpr_cidrmap_t *ptr; int res = 0; - + string = safe_strdup(optarg); /* first iteration */ map = strtok_r(string, ",", &token); - if (! parse_cidr(&cidr, map, ":")) + if (!parse_cidr(&cidr, map, ":")) goto done; /* must return a linked list of two */ @@ -423,12 +384,12 @@ parse_cidr_map(tcpr_cidrmap_t **cidrmap, const char *optarg) ptr->from->next = NULL; /* do the same with the reset of the input */ - while(1) { + while (1) { map = strtok_r(NULL, ",", &token); if (map == NULL) break; - if (! parse_cidr(&cidr, map, ":")) + if (!parse_cidr(&cidr, map, ":")) goto done; /* must return a linked list of two */ @@ -456,14 +417,14 @@ parse_cidr_map(tcpr_cidrmap_t **cidrmap, const char *optarg) * returns 1 for true, 0 for false */ int -ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip) +ip_in_cidr(const tcpr_cidr_t *mycidr, const unsigned long ip) { - unsigned long ipaddr = 0, network = 0, mask = 0; - int ret = 0; + unsigned long ipaddr, network, mask; + int ret; #ifdef DEBUG char netstr[20]; #endif - + if (mycidr->family != AF_INET) return 0; @@ -471,7 +432,7 @@ ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip) if (mycidr->masklen == 0 && mycidr->u.network == 0) return 1; - mask = ~0; /* turn on all the bits */ + mask = ~0; /* turn on all the bits */ /* shift over by the correct number of bits */ mask = mask << (32 - mycidr->masklen); @@ -481,7 +442,6 @@ ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip) network = htonl(mycidr->u.network) & mask; - #ifdef DEBUG /* copy this for debug purposes, since it's not re-entrant */ strlcpy(netstr, get_addr2name4(mycidr->u.network, RESOLVE), 20); @@ -490,32 +450,29 @@ ip_in_cidr(const tcpr_cidr_t * mycidr, const unsigned long ip) /* if they're the same, then ip is in network */ if (network == ipaddr) { #ifdef DEBUG - dbgx(1, "The ip %s is inside of %s/%d", - get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen); + dbgx(1, "The ip %s is inside of %s/%d", get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen); #endif ret = 1; } else { #ifdef DEBUG - dbgx(1, "The ip %s is not inside of %s/%d", - get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen); + dbgx(1, "The ip %s is not inside of %s/%d", get_addr2name4(ip, RESOLVE), netstr, mycidr->masklen); #endif ret = 0; } return ret; - } static int ip6_addr_is_unspec(const struct tcpr_in6_addr *addr) { - return addr->tcpr_s6_addr32[0] == 0 && addr->tcpr_s6_addr32[1] == 0 && - addr->tcpr_s6_addr32[2] == 0 && addr->tcpr_s6_addr32[3] == 0; + return addr->tcpr_s6_addr32[0] == 0 && addr->tcpr_s6_addr32[1] == 0 && addr->tcpr_s6_addr32[2] == 0 && + addr->tcpr_s6_addr32[3] == 0; } int -ip6_in_cidr(const tcpr_cidr_t * mycidr, const struct tcpr_in6_addr *addr) +ip6_in_cidr(const tcpr_cidr_t *mycidr, const struct tcpr_in6_addr *addr) { - int ret = 0; + int ret; #ifdef DEBUG char netstr[INET6_ADDRSTRLEN]; #endif @@ -536,7 +493,7 @@ ip6_in_cidr(const tcpr_cidr_t * mycidr, const struct tcpr_in6_addr *addr) goto out; } } - + if ((k = mycidr->masklen % 8) == 0) { ret = 1; goto out; @@ -556,47 +513,42 @@ ip6_in_cidr(const tcpr_cidr_t * mycidr, const struct tcpr_in6_addr *addr) /* if they're the same, then ip is in network */ if (ret) { #ifdef DEBUG - dbgx(1, "The ip %s is inside of %s/%d", - get_addr2name6(addr, RESOLVE), netstr, mycidr->masklen); + dbgx(1, "The ip %s is inside of %s/%d", get_addr2name6(addr, RESOLVE), netstr, mycidr->masklen); #endif } else { #ifdef DEBUG - dbgx(1, "The ip %s is not inside of %s/%d", - get_addr2name6(addr, RESOLVE), netstr, mycidr->masklen); + dbgx(1, "The ip %s is not inside of %s/%d", get_addr2name6(addr, RESOLVE), netstr, mycidr->masklen); #endif } return ret; - } - /** * iterates over cidrdata to find if a given ip matches * returns 1 for true, 0 for false */ int -check_ip_cidr(tcpr_cidr_t * cidrdata, const unsigned long ip) +check_ip_cidr(tcpr_cidr_t *cidrdata, const unsigned long ip) { tcpr_cidr_t *mycidr; - /* if we have no cidrdata, of course it isn't in there + /* if we have no cidrdata, of course it isn't in there * this actually should happen occasionally, so don't put an assert here */ if (cidrdata == NULL) return 1; - + mycidr = cidrdata; /* loop through cidr */ while (1) { - /* if match, return 1 */ if (ip_in_cidr(mycidr, ip)) { dbgx(3, "Found %s in cidr", get_addr2name4(ip, RESOLVE)); return 1; } - + /* check for next record */ if (mycidr->next != NULL) { mycidr = mycidr->next; @@ -611,7 +563,7 @@ check_ip_cidr(tcpr_cidr_t * cidrdata, const unsigned long ip) } int -check_ip6_cidr(tcpr_cidr_t * cidrdata, const struct tcpr_in6_addr *addr) +check_ip6_cidr(tcpr_cidr_t *cidrdata, const struct tcpr_in6_addr *addr) { tcpr_cidr_t *mycidr; @@ -626,13 +578,12 @@ check_ip6_cidr(tcpr_cidr_t * cidrdata, const struct tcpr_in6_addr *addr) /* loop through cidr */ while (1) { - /* if match, return 1 */ if (ip6_in_cidr(mycidr, addr)) { dbgx(3, "Found %s in cidr", get_addr2name6(addr, RESOLVE)); return 1; } - + /* check for next record */ if (mycidr->next != NULL) { mycidr = mycidr->next; @@ -645,55 +596,3 @@ check_ip6_cidr(tcpr_cidr_t * cidrdata, const struct tcpr_in6_addr *addr) dbgx(3, "Didn't find %s in cidr", get_addr2name6(addr, RESOLVE)); return 0; } - - -/** - * cidr2ip takes a tcpr_cidr_t and a delimiter - * and returns a string which lists all the IP addresses in the cidr - * deliminated by the given char - */ -char * -cidr2iplist(tcpr_cidr_t * cidr, char delim) -{ - char *list = NULL; - char ipaddr[18], tempbuff[20]; - u_int32_t size, addr, first, last, numips; - struct in_addr in; - int i; - - /* - * 16 bytes per IP + delim - * # of IP's = 2^(32-masklen) - */ - numips = 2; - for (i = 2; i <= (32 - cidr->masklen); i++) - numips *= 2; - - size = 17 * numips - 1; - - list = (char *)safe_malloc(size); - - memset(list, 0, size); - - /* first and last should not include network or broadcast */ - first = ntohl(cidr->u.network) + 1; - last = first + numips - 3; - - dbgx(1, "First: %u\t\tLast: %u", first, last); - - /* loop through all but the last one */ - for (addr = first; addr < last; addr++) { - in.s_addr = htonl(addr); - snprintf(tempbuff, 17, "%s%c", inet_ntoa(in), delim); - memcpy(ipaddr, tempbuff, 16); - dbgx(2, "%s", ipaddr); - strlcat(list, ipaddr, size); - } - - /* last is a special case, end in \0 */ - in.s_addr = htonl(addr); - snprintf(ipaddr, 17, "%s", inet_ntoa(in)); - strlcat(list, ipaddr, size); - - return list; -} diff --git a/src/common/cidr.h b/src/common/cidr.h index 359dc70a1..e2fb475c4 100644 --- a/src/common/cidr.h +++ b/src/common/cidr.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,13 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "cache.h" +#pragma once -#ifndef __CIDR_H__ -#define __CIDR_H__ +#include "cache.h" struct tcpr_cidr_s { - int family; /* AF_INET or AF_INET6 */ + int family; /* AF_INET or AF_INET6 */ union { u_int32_t network; struct tcpr_in6_addr network6; @@ -48,15 +47,11 @@ int check_ip6_cidr(tcpr_cidr_t *, const struct tcpr_in6_addr *addr); int parse_cidr(tcpr_cidr_t **, char *, char *delim); int parse_cidr_map(tcpr_cidrmap_t **, const char *); int parse_endpoints(tcpr_cidrmap_t **, tcpr_cidrmap_t **, const char *); -u_char *ip2cidr(const unsigned long, const int); void add_cidr(tcpr_cidr_t **, tcpr_cidr_t **); tcpr_cidr_t *new_cidr(void); tcpr_cidrmap_t *new_cidr_map(void); void destroy_cidr(tcpr_cidr_t *); void print_cidr(tcpr_cidr_t *); -char *cidr2iplist(tcpr_cidr_t *, char); -int ip6_in_cidr(const tcpr_cidr_t * mycidr, const struct tcpr_in6_addr *addr); +int ip6_in_cidr(const tcpr_cidr_t *mycidr, const struct tcpr_in6_addr *addr); int check_ip6_cidr(tcpr_cidr_t *, const struct tcpr_in6_addr *addr); - -#endif diff --git a/src/common/err.c b/src/common/err.c index 240affc7b..6f16ff7e3 100644 --- a/src/common/err.c +++ b/src/common/err.c @@ -44,18 +44,11 @@ */ #include "config.h" -#include "defines.h" #include "common.h" - +#include #include #include -#include #include -#include - -#ifdef DEBUG -extern int debug; -#endif /** * writes a notice message to stderr. Always forces a newline @@ -76,21 +69,19 @@ notice(const char *fmt, ...) /** * Inner call to dbgx() which prints the function, line & function along * with the message to stderr. Always forces a newline. - * + * * You don't actually want to call this! use dbgx() instead! */ #ifdef DEBUG void -_our_verbose_dbgx(int dbg_level, const char *fmt, const char *function, - const int line, const char *file, ...) +our_verbose_dbgx(int dbg_level, const char *fmt, const char *function, const int line, const char *file, ...) { va_list ap; if (debug < dbg_level) return; - fprintf(stderr, "DEBUG%d in %s:%s() line %d: ", dbg_level, file, - function, line); + fprintf(stderr, "DEBUG%d in %s:%s() line %d: ", dbg_level, file, function, line); va_start(ap, file); @@ -108,10 +99,12 @@ _our_verbose_dbgx(int dbg_level, const char *fmt, const char *function, */ #ifdef DEBUG void -_our_verbose_errx(int eval, const char *fmt, const char *function, const int line, const char *file, ...) { +our_verbose_errx(int eval, const char *fmt, const char *function, const int line, const char *file, ...) +{ #else void -_our_verbose_errx(int eval, const char *fmt, ...) { +our_verbose_errx(int eval, const char *fmt, ...) +{ #endif va_list ap; @@ -125,7 +118,7 @@ _our_verbose_errx(int eval, const char *fmt, ...) { #endif if (fmt != NULL) - (void)vfprintf(stderr, fmt, ap); + (void)vfprintf(stderr, fmt, ap); (void)fprintf(stderr, "\n"); va_end(ap); exit(eval); @@ -137,10 +130,12 @@ _our_verbose_errx(int eval, const char *fmt, ...) { */ #ifdef DEBUG void -_our_verbose_warnx(const char *fmt, const char *function, const int line, const char *file, ...) { +our_verbose_warnx(const char *fmt, const char *function, const int line, const char *file, ...) +{ #else -void -_our_verbose_warnx(const char *fmt, ...) { +void +our_verbose_warnx(const char *fmt, ...) +{ #endif va_list ap; diff --git a/src/common/err.h b/src/common/err.h index fde7aa341..57afb8358 100644 --- a/src/common/err.h +++ b/src/common/err.h @@ -45,9 +45,9 @@ * @(#)err.h 8.1 (Berkeley) 6/2/93 */ -#ifndef _ERR_H_ -#define _ERR_H_ +#pragma once +#include "defines.h" #include #ifdef DEBUG @@ -145,6 +145,3 @@ void notice(const char *fmt, ...); fflush(NULL); \ } while (0) #endif /* DEBUG */ - - -#endif /* !_ERR_H_ */ diff --git a/src/common/fakepcap.c b/src/common/fakepcap.c index 994b19203..cf69b4500 100644 --- a/src/common/fakepcap.c +++ b/src/common/fakepcap.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -21,14 +21,13 @@ /* * This file implements missing libpcap functions which only exist in really * recent versions of libpcap. We assume the user has at least 0.6, so anything - * after that needs to be re-implimented here unless we want to start + * after that needs to be re-implimented here unless we want to start * requiring a newer version */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - #include #ifndef HAVE_DLT_VAL_TO_DESC @@ -44,7 +43,6 @@ pcap_datalink_val_to_description(int dlt) return "Unknown"; return dlt2desc[dlt]; - } /** @@ -56,9 +54,8 @@ pcap_datalink_val_to_name(int dlt) { if (dlt > DLT2NAME_LEN) return "Unknown"; - + return dlt2name[dlt]; - } #endif diff --git a/src/common/fakepcap.h b/src/common/fakepcap.h index 5d4191e6d..fd0efd905 100644 --- a/src/common/fakepcap.h +++ b/src/common/fakepcap.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _FAKEPCAP_H_ -#define _FAKEPCAP_H_ +#pragma once #include "config.h" @@ -44,5 +43,3 @@ const char *pcap_datalink_val_to_description(int dlt); const char *pcap_datalink_val_to_name(int dlt); #endif - -#endif /* end of _FAKEPCAP_H_ */ diff --git a/src/common/fakepcapnav.c b/src/common/fakepcapnav.c index e73d4f9d0..057c97109 100644 --- a/src/common/fakepcapnav.c +++ b/src/common/fakepcapnav.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,30 +19,27 @@ */ /* This file implements a fake, non-functioning version of the libpcapnav - * API based on libpcap. It's solely here for people who don't have + * API based on libpcap. It's solely here for people who don't have * libpcapnav installed on their system, and to keep the code maintainable. */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - #include #ifndef HAVE_PCAPNAV /** - * pcapnav_init does nothing! + * pcapnav_init does nothing! */ void pcapnav_init(void) -{ - return; -} +{} /** - * pcapnav_open_offline opens a pcap file, - * and creates the struct for our use + * pcapnav_open_offline opens a pcap file, + * and creates the struct for our use */ pcapnav_t * pcapnav_open_offline(const char *filename) @@ -50,7 +47,7 @@ pcapnav_open_offline(const char *filename) pcapnav_t *pcapnav; char errbuf[PCAP_ERRBUF_SIZE]; - pcapnav = (pcapnav_t *) malloc(sizeof(pcapnav_t)); + pcapnav = (pcapnav_t *)malloc(sizeof(pcapnav_t)); if (pcapnav == NULL) { err(-1, "malloc() error: unable to malloc pcapnav_t"); } @@ -64,23 +61,22 @@ pcapnav_open_offline(const char *filename) } /** - * closes our pcap file and free's the pcapnav + * closes our pcap file and free's the pcapnav */ void -pcapnav_close(pcapnav_t * pcapnav) +pcapnav_close(pcapnav_t *pcapnav) { pcap_close(pcapnav->pcap); safe_free(pcapnav); } /** - * returns the pcap_t data struct + * returns the pcap_t data struct */ pcap_t * -pcapnav_pcap(pcapnav_t * pcapnav) +pcapnav_pcap(pcapnav_t *pcapnav) { return (pcapnav->pcap); } - #endif diff --git a/src/common/fakepcapnav.h b/src/common/fakepcapnav.h index 0cfca41d1..a1f862502 100644 --- a/src/common/fakepcapnav.h +++ b/src/common/fakepcapnav.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,16 +18,15 @@ * along with the Tcpreplay Suite. If not, see . */ +#pragma once + #ifdef HAVE_PCAPNAV #include #define _FAKEPCAPNAV_H_ #endif -#ifndef _FAKEPCAPNAV_H_ -#define _FAKEPCAPNAV_H_ - -#include "config.h" #include "defines.h" +#include "config.h" #ifndef HAVE_PCAPNAV @@ -43,5 +42,3 @@ void pcapnav_close(pcapnav_t *); pcap_t *pcapnav_pcap(pcapnav_t *); #endif - -#endif diff --git a/src/common/fakepoll.c b/src/common/fakepoll.c index e8919fc85..ddae60a7f 100644 --- a/src/common/fakepoll.c +++ b/src/common/fakepoll.c @@ -6,7 +6,7 @@ * On systems where 'poll' doesn't exist, fake it with 'select'. * * Copyright (c) 2001-2003, Nick Mathewson - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -22,7 +22,7 @@ * * Neither the names of the copyright owners nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -36,19 +36,19 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" /* prevents ISO C error */ #ifdef USE_FAKE_POLL -static void FAKEPOLL(int stop) -{ - if (! stop) - FAKEPOLL(1); +static void +FAKEPOLL(int stop) +{ + if (!stop) + FAKEPOLL(1); return; - -} +} #include #ifdef HAVE_UNISTD_H @@ -118,8 +118,7 @@ poll(struct pollfd *ufds, unsigned int nfds, int timeout) return 0; } #endif - r = select(maxfd + 1, &readfds, &writefds, &exceptfds, - timeout == -1 ? NULL : &_timeout); + r = select(maxfd + 1, &readfds, &writefds, &exceptfds, timeout == -1 ? NULL : &_timeout); if (r <= 0) return r; r = 0; diff --git a/src/common/fakepoll.h b/src/common/fakepoll.h index c25938e9f..5a3387bd1 100644 --- a/src/common/fakepoll.h +++ b/src/common/fakepoll.h @@ -6,7 +6,7 @@ * On systems where 'poll' doesn't exist, fake it with 'select'. * * Copyright (c) 2001-2003, Nick Mathewson - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: @@ -22,7 +22,7 @@ * * Neither the names of the copyright owners nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -36,13 +36,15 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#pragma once + /* don't warn on OS X that poll is emulated */ -#define POLL_NO_WARN +#define POLL_NO_WARN #define SYS_POLL_NO_WARN #ifdef HAVE_POLL_H #include -#define __FAKEPOLL_H +#define __FAKEPOLL_H #elif HAVE_SYS_POLL_H #include #define __FAKEPOLL_H @@ -63,11 +65,11 @@ struct pollfd { short revents; }; -#define POLLIN 0x0001 -#define POLLPRI 0x0002 -#define POLLOUT 0x0004 -#define POLLERR 0x0008 -#define POLLHUP 0x0010 +#define POLLIN 0x0001 +#define POLLPRI 0x0002 +#define POLLOUT 0x0004 +#define POLLERR 0x0008 +#define POLLHUP 0x0010 #define POLLNVAL 0x0020 int poll(struct pollfd *ufds, unsigned int nfds, int timeout); diff --git a/src/common/flows.c b/src/common/flows.c index 5e64d144f..28a4615a9 100644 --- a/src/common/flows.c +++ b/src/common/flows.c @@ -21,7 +21,6 @@ #include #include #include -#include "../../lib/sll.h" #define JUNIPER_FLAG_NO_L2 0x02 /* L2 header */ #define JUNIPER_FLAG_EXT 0x80 /* Juniper extensions present */ @@ -120,7 +119,7 @@ static inline flow_entry_type_t hash_put_data(flow_hash_table_t *fht, const uint { uint32_t hash_value = key & (fht->num_buckets - 1); flow_hash_entry_t *he; - flow_entry_type_t res = FLOW_ENTRY_INVALID; + flow_entry_type_t res; for (he = fht->buckets[hash_value]; he; he = he->next) { /* @@ -201,8 +200,6 @@ flow_entry_type_t flow_decode(flow_hash_table_t *fht, const struct pcap_pkthdr * return FLOW_ENTRY_INVALID; } - assert(l2len > 0); - if (ether_type == ETHERTYPE_IP) { if (pkt_len < l2len + sizeof(ipv4_hdr_t)) return FLOW_ENTRY_INVALID; @@ -265,6 +262,9 @@ flow_entry_type_t flow_decode(flow_hash_table_t *fht, const struct pcap_pkthdr * entry.src_port = icmp_hdr->icmp_type; entry.dst_port = icmp_hdr->icmp_code; break; + default: + entry.src_port = 0; + entry.dst_port = 0; } /* hash the 5-tuple */ diff --git a/src/common/flows.h b/src/common/flows.h index 66b5a6f5e..14a02f755 100644 --- a/src/common/flows.h +++ b/src/common/flows.h @@ -2,9 +2,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -15,27 +15,27 @@ * You should have received a copy of the GNU General Public License * along with the Tcpreplay Suite. If not, see . */ -#ifndef FLOWS_H_ -#define FLOWS_H_ +#pragma once #include "defines.h" #include "common.h" -#define DEFAULT_FLOW_HASH_BUCKET_SIZE (1 << 16) /* 64K - must be a power of two */ +#define DEFAULT_FLOW_HASH_BUCKET_SIZE (1 << 16) /* 64K - must be a power of two */ typedef enum flow_entry_type_e { - FLOW_ENTRY_INVALID, /* unknown packet type */ - FLOW_ENTRY_NON_IP, /* is a flow, but non-IP */ - FLOW_ENTRY_NEW, /* flow never seen before */ - FLOW_ENTRY_EXISTING, /* flow already seen */ - FLOW_ENTRY_EXPIRED, /* flow existed but was expired */ + FLOW_ENTRY_INVALID, /* unknown packet type */ + FLOW_ENTRY_NON_IP, /* is a flow, but non-IP */ + FLOW_ENTRY_NEW, /* flow never seen before */ + FLOW_ENTRY_EXISTING, /* flow already seen */ + FLOW_ENTRY_EXPIRED, /* flow existed but was expired */ } flow_entry_type_t; typedef struct flow_hash_table flow_hash_table_t; flow_hash_table_t *flow_hash_table_init(size_t n); -void flow_hash_table_release(flow_hash_table_t * table); -flow_entry_type_t flow_decode(flow_hash_table_t *fht, const struct pcap_pkthdr *pkthdr, - const u_char *pktdata, const int datalink, const int expiry); - -#endif /* FLOWS_H_ */ +void flow_hash_table_release(flow_hash_table_t *table); +flow_entry_type_t flow_decode(flow_hash_table_t *fht, + const struct pcap_pkthdr *pkthdr, + const u_char *pktdata, + const int datalink, + const int expiry); diff --git a/src/common/get.c b/src/common/get.c index f01910d3f..2d911160f 100644 --- a/src/common/get.c +++ b/src/common/get.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,39 +18,36 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" -#include "../../lib/sll.h" - -#include -#include -#include +#include #include #include -#include +#include #include +#include +#include +#include -#ifdef DEBUG -extern int debug; -#endif - -#if defined HAVE_PCAP_VERSION && ! defined HAVE_WIN32 +#if defined HAVE_PCAP_VERSION && !defined HAVE_WIN32 extern const char pcap_version[]; #endif -#define JUNIPER_FLAG_NO_L2 0x02 /* L2 header */ -#define JUNIPER_FLAG_EXT 0x80 /* Juniper extensions present */ -#define JUNIPER_PCAP_MAGIC "MGC" +#define JUNIPER_FLAG_NO_L2 0x02 /* L2 header */ +#define JUNIPER_FLAG_EXT 0x80 /* Juniper extensions present */ +#define JUNIPER_PCAP_MAGIC "MGC" + +static void *get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const u_char *end_ptr); + /** - * Depending on what version of libpcap/WinPcap there are different ways to get - * the version of the libpcap/WinPcap library. This presents a unified way to + * Depending on what version of libpcap/WinPcap there are different ways to get + * the version of the libpcap/WinPcap library. This presents a unified way to * get that information. */ const char * get_pcap_version(void) { - #if defined HAVE_WINPCAP static char ourver[255]; char *last, *version; @@ -87,14 +84,11 @@ get_pcap_version(void) * * return 0 on success, -1 on failure */ -int parse_mpls(const u_char *pktdata, - const uint32_t datalen, - uint16_t *next_protocol, - uint32_t *l2len, - uint32_t *l2offset) +int +parse_mpls(const u_char *pktdata, uint32_t datalen, uint16_t *next_protocol, uint32_t *l2len, uint32_t *l2offset) { struct tcpr_mpls_label *mpls_label; - int len_remaining = (int)datalen; + const u_char *end_ptr = pktdata + datalen; u_char first_nibble; eth_hdr_t *eth_hdr; bool bos = false; @@ -109,12 +103,11 @@ int parse_mpls(const u_char *pktdata, /* move over MPLS labels until we get to the last one */ while (!bos) { - if (len_remaining < (int)sizeof(*mpls_label)) + if (pktdata + len + sizeof(*mpls_label) > end_ptr) return -1; - mpls_label = (struct tcpr_mpls_label*)(pktdata + len); + mpls_label = (struct tcpr_mpls_label *)(pktdata + len); len += sizeof(*mpls_label); - len_remaining -= sizeof(*mpls_label); bos = (ntohl(mpls_label->entry) & MPLS_LS_S_MASK) != 0; label = ntohl(mpls_label->entry) >> MPLS_LS_LABEL_SHIFT; if (label == MPLS_LABEL_GACH) { @@ -124,11 +117,11 @@ int parse_mpls(const u_char *pktdata, } } - if (len_remaining < 4) + if ((u_char *)(mpls_label + 1) + 1 > end_ptr) return -1; first_nibble = *((u_char *)(mpls_label + 1)) >> 4; - switch(first_nibble) { + switch (first_nibble) { case 4: *next_protocol = ETHERTYPE_IP; break; @@ -139,13 +132,12 @@ int parse_mpls(const u_char *pktdata, /* EoMPLS - jump over PW Ethernet Control Word and handle * inner Ethernet header */ - len += 4; - len_remaining -= 4; - if (len_remaining < (int)sizeof(*eth_hdr)) + if (pktdata + len + 4 + sizeof(*eth_hdr) > end_ptr) return -1; + len += 4; *l2offset = len; - eth_hdr = (eth_hdr_t*)(pktdata + len); + eth_hdr = (eth_hdr_t *)(pktdata + len); len += sizeof(*eth_hdr); *next_protocol = ntohs(eth_hdr->ether_type); break; @@ -169,16 +161,14 @@ int parse_mpls(const u_char *pktdata, * * return 0 on success, -1 on failure */ -int parse_vlan(const u_char *pktdata, - const uint32_t datalen, - uint16_t *next_protocol, - uint32_t *l2len) +int +parse_vlan(const u_char *pktdata, uint32_t datalen, uint16_t *next_protocol, uint32_t *l2len) { vlan_hdr_t *vlan_hdr; if ((size_t)datalen < *l2len + sizeof(*vlan_hdr)) return -1; - vlan_hdr = (vlan_hdr_t*)(pktdata + *l2len); + vlan_hdr = (vlan_hdr_t *)(pktdata + *l2len); *next_protocol = ntohs(vlan_hdr->vlan_tpid); *l2len += sizeof(vlan_hdr_t); @@ -197,12 +187,13 @@ int parse_vlan(const u_char *pktdata, * * return 0 on success, -1 on failure */ -static int parse_metadata(const u_char *pktdata, - const uint32_t datalen, - uint16_t *next_protocol, - uint32_t *l2len, - uint32_t *l2offset, - uint32_t *vlan_offset) +static int +parse_metadata(const u_char *pktdata, + uint32_t datalen, + uint16_t *next_protocol, + uint32_t *l2len, + uint32_t *l2offset, + uint32_t *vlan_offset) { bool done = false; int res = 0; @@ -244,25 +235,22 @@ static int parse_metadata(const u_char *pktdata, * * return 0 on success, -1 on failure */ -int get_l2len_protocol(const u_char *pktdata, - const uint32_t datalen, - const int datalink, - uint16_t *protocol, - uint32_t *l2len, - uint32_t *l2offset, - uint32_t *vlan_offset) +int +get_l2len_protocol(const u_char *pktdata, + uint32_t datalen, + int datalink, + uint16_t *protocol, + uint32_t *l2len, + uint32_t *l2offset, + uint32_t *vlan_offset) { assert(protocol); assert(l2len); assert(l2offset); assert(vlan_offset); - if (!pktdata || !datalen) { - errx(-1, "get_l2len_protocol: invalid L2 parameters: pktdata=0x%p len=%d", - pktdata, - datalen); - return -1; - } + if (!pktdata || !datalen) + errx(-1, "get_l2len_protocol: invalid L2 parameters: pktdata=0x%p len=%d", pktdata, datalen); *protocol = 0; *l2len = 0; @@ -270,10 +258,8 @@ int get_l2len_protocol(const u_char *pktdata, *vlan_offset = 0; switch (datalink) { + case DLT_NULL: case DLT_RAW: - if (datalen == 0) - return -1; - if ((pktdata[0] >> 4) == 4) *protocol = ETHERTYPE_IP; else if ((pktdata[0] >> 4) == 6) @@ -283,7 +269,7 @@ int get_l2len_protocol(const u_char *pktdata, if (datalen < 4) return -1; - if (memcmp(pktdata, JUNIPER_PCAP_MAGIC, 3)) { + if (memcmp(pktdata, JUNIPER_PCAP_MAGIC, 3) != 0) { warnx("No Magic Number found during protocol lookup: %s (0x%x)", pcap_datalink_val_to_description(datalink), datalink); @@ -294,7 +280,7 @@ int get_l2len_protocol(const u_char *pktdata, if (datalen < 6) return -1; - *l2offset = ntohs(*((uint16_t*)&pktdata[4])); + *l2offset = ntohs(*((uint16_t *)&pktdata[4])); *l2offset += 6; /* MGC + flags + ext_total_len */ } else { *l2offset = 4; /* MGC + flags (no header extensions) */ @@ -315,24 +301,20 @@ int get_l2len_protocol(const u_char *pktdata, } /* fall through */ - case DLT_EN10MB: - { - eth_hdr_t *eth_hdr = (eth_hdr_t*)(pktdata + *l2offset); + case DLT_EN10MB: { + eth_hdr_t *eth_hdr; + uint16_t ether_type; uint32_t l2_net_off = sizeof(*eth_hdr) + *l2offset; - uint16_t ether_type = ntohs(eth_hdr->ether_type); if (datalen <= l2_net_off) return -1; - if (parse_metadata(pktdata, - datalen, - ðer_type, - &l2_net_off, - l2offset, - vlan_offset)) + eth_hdr = (eth_hdr_t *)(pktdata + *l2offset); + ether_type = ntohs(eth_hdr->ether_type); + if (parse_metadata(pktdata, datalen, ðer_type, &l2_net_off, l2offset, vlan_offset)) return -1; - if (datalen < l2_net_off) + if (datalen <= l2_net_off) return -1; *l2len = l2_net_off; @@ -355,7 +337,7 @@ int get_l2len_protocol(const u_char *pktdata, if ((size_t)datalen < sizeof(struct tcpr_pppserial_hdr)) return -1; - struct tcpr_pppserial_hdr *ppp = (struct tcpr_pppserial_hdr*)pktdata; + struct tcpr_pppserial_hdr *ppp = (struct tcpr_pppserial_hdr *)pktdata; *l2len = sizeof(*ppp); if (ntohs(ppp->protocol) == 0x0021) *protocol = ETHERTYPE_IP; @@ -367,7 +349,7 @@ int get_l2len_protocol(const u_char *pktdata, if (datalen < CISCO_HDLC_LEN) return -1; - hdlc_hdr_t *hdlc_hdr = (hdlc_hdr_t*)pktdata; + hdlc_hdr_t *hdlc_hdr = (hdlc_hdr_t *)pktdata; *l2len = sizeof(*hdlc_hdr); *protocol = ntohs(hdlc_hdr->protocol); break; @@ -375,12 +357,13 @@ int get_l2len_protocol(const u_char *pktdata, if (datalen < SLL_HDR_LEN) return -1; - sll_hdr_t *sll_hdr = (sll_hdr_t*)pktdata; + sll_hdr_t *sll_hdr = (sll_hdr_t *)pktdata; *l2len = sizeof(*sll_hdr); *protocol = ntohs(sll_hdr->sll_protocol); break; default: - errx(-1, "Unable to process unsupported DLT type: %s (0x%x)", + errx(-1, + "Unable to process unsupported DLT type: %s (0x%x)", pcap_datalink_val_to_description(datalink), datalink); } @@ -392,25 +375,19 @@ int get_l2len_protocol(const u_char *pktdata, * returns the length in number of bytes of the L2 header, or -1 on error */ int -get_l2len(const u_char *pktdata, const int datalen, const int datalink) +get_l2len(const u_char *pktdata, int datalen, int datalink) { uint16_t _U_ protocol; uint32_t _U_ l2offset; uint32_t _U_ vlan_offset; uint32_t l2len = 0; - int res = get_l2len_protocol(pktdata, - datalen, - datalink, - &protocol, - &l2len, - &l2offset, - &vlan_offset); + int res = get_l2len_protocol(pktdata, datalen, datalink, &protocol, &l2len, &l2offset, &vlan_offset); if (res == -1) return 0; - return l2len; + return (int)l2len; } /** @@ -420,7 +397,7 @@ get_l2len(const u_char *pktdata, const int datalen, const int datalink) * on strictly aligned systems where the layer 2 header doesn't * fall on a 4 byte boundary (like a standard Ethernet header) * - * Note: you can cast the result as an ip_hdr_t, but you'll be able + * Note: you can cast the result as an ip_hdr_t, but you'll be able * to access data above the header minus any stripped L2 data */ const u_char * @@ -439,13 +416,7 @@ get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) assert(pkt_len); assert(*newbuff); - res = get_l2len_protocol(packet, - pkt_len, - datalink, - &proto, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(packet, pkt_len, datalink, &proto, &l2len, &l2offset, &vlan_offset); /* sanity... pkt_len must be > l2len + IP header len*/ if (res == -1 || l2len + TCPR_IPV4_H > pkt_len) { @@ -458,13 +429,13 @@ get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) packet += l2offset; l2len -= l2offset; +#ifdef FORCE_ALIGN pkt_len -= l2offset; -#ifdef FORCE_ALIGN /* * copy layer 3 and up to our temp packet buffer * for now on, we have to edit the packetbuff because - * just before we send the packet, we copy the packetbuff + * just before we send the packet, we copy the packetbuff * back onto the pkt.data + l2len buffer * we do all this work to prevent byte alignment issues */ @@ -472,13 +443,12 @@ get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) memcpy(*newbuff, (packet + l2len), (pkt_len - l2len)); ip_hdr = *newbuff; } else { - /* we don't have to do a memcpy if l2len lands on a boundary */ ip_hdr = (packet + l2len); } #else /* - * on non-strict byte align systems, don't need to memcpy(), + * on non-strict byte align systems, don't need to memcpy(), * just point to l2len bytes into the existing buffer */ ip_hdr = (packet + l2len); @@ -487,7 +457,6 @@ get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) return ip_hdr; } - /** * \brief returns a ptr to the ipv6 header + data or NULL if it's not IP * @@ -495,7 +464,7 @@ get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) * on strictly aligned systems where the layer 2 header doesn't * fall on a 4 byte boundary (like a standard Ethernet header) * - * Note: you can cast the result as an ip_hdr_t, but you'll be able + * Note: you can cast the result as an ip_hdr_t, but you'll be able * to access data above the header minus any stripped L2 data */ const u_char * @@ -514,13 +483,7 @@ get_ipv6(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) assert(pkt_len); assert(*newbuff); - res = get_l2len_protocol(packet, - pkt_len, - datalink, - &proto, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(packet, pkt_len, datalink, &proto, &l2len, &l2offset, &vlan_offset); /* sanity... pkt_len must be > l2len + IP header len*/ if (res == -1 || l2len + TCPR_IPV6_H > pkt_len) { @@ -533,9 +496,9 @@ get_ipv6(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) packet += l2offset; l2len -= l2offset; +#ifdef FORCE_ALIGN pkt_len -= l2offset; -#ifdef FORCE_ALIGN /* * copy layer 3 and up to our temp packet buffer * for now on, we have to edit the packetbuff because @@ -547,7 +510,6 @@ get_ipv6(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) memcpy(*newbuff, (packet + l2len), (pkt_len - l2len)); ip6_hdr = *newbuff; } else { - /* we don't have to do a memcpy if l2len lands on a boundary */ ip6_hdr = (packet + l2len); } @@ -568,15 +530,16 @@ get_ipv6(const u_char *pktdata, int datalen, int datalink, u_char **newbuff) * If the packet is to short, returns NULL */ void * -get_layer4_v4(const ipv4_hdr_t *ip_hdr, const int l3len) +get_layer4_v4(const ipv4_hdr_t *ip_hdr, const u_char *end_ptr) { void *ptr; assert(ip_hdr); + assert(end_ptr); ptr = (u_char *)ip_hdr + (ip_hdr->ip_hl << 2); /* make sure we don't jump over the end of the buffer */ - if ((u_char *)ptr > ((u_char *)ip_hdr + l3len)) + if ((u_char *)ptr > end_ptr) return NULL; return ((void *)ptr); @@ -588,24 +551,21 @@ get_layer4_v4(const ipv4_hdr_t *ip_hdr, const int l3len) * v6 Frag or ESP header. Function is recursive. */ void * -get_layer4_v6(const ipv6_hdr_t *ip6_hdr, const int l3len) +get_layer4_v6(const ipv6_hdr_t *ip6_hdr, const u_char *end_ptr) { struct tcpr_ipv6_ext_hdr_base *next, *exthdr; bool done = false; - uint32_t maxlen; uint8_t proto; - int min_len; assert(ip6_hdr); - - min_len = TCPR_IPV6_H + sizeof(struct tcpr_ipv6_ext_hdr_base); - if (l3len < min_len) - return NULL; + assert(end_ptr); /* jump to the end of the IPv6 header */ next = (struct tcpr_ipv6_ext_hdr_base *)((u_char *)ip6_hdr + TCPR_IPV6_H); - proto = ip6_hdr->ip_nh; + if ((u_char *)next > end_ptr) + return NULL; + proto = ip6_hdr->ip_nh; while (!done) { dbgx(3, "Processing proto: 0x%hx", (uint16_t)proto); @@ -613,7 +573,7 @@ get_layer4_v6(const ipv6_hdr_t *ip6_hdr, const int l3len) /* recurse due to v6-in-v6, need to recast next as an IPv6 Header */ case TCPR_IPV6_NH_IPV6: dbg(3, "recursing due to v6-in-v6"); - next = get_layer4_v6((ipv6_hdr_t *)next, l3len - min_len); + next = get_layer4_v6((ipv6_hdr_t *)next, end_ptr); break; /* loop again */ @@ -622,9 +582,9 @@ get_layer4_v6(const ipv6_hdr_t *ip6_hdr, const int l3len) case TCPR_IPV6_NH_DESTOPTS: case TCPR_IPV6_NH_HBH: dbgx(3, "Going deeper due to extension header 0x%02X", proto); - maxlen = l3len - (int)((u_char *)ip6_hdr - (u_char *)next); - exthdr = get_ipv6_next(next, maxlen); + exthdr = get_ipv6_next(next, end_ptr); if (exthdr == NULL) { + next = NULL; done = true; break; } @@ -646,37 +606,35 @@ get_layer4_v6(const ipv6_hdr_t *ip6_hdr, const int l3len) */ default: if (proto != ip6_hdr->ip_nh) { - dbgx(3, "Returning byte offset of this ext header: %u", - IPV6_EXTLEN_TO_BYTES(next->ip_len)); - next = (void *)((u_char *)next + IPV6_EXTLEN_TO_BYTES(next->ip_len)); + dbgx(3, "Returning byte offset of this ext header: %u", IPV6_EXTLEN_TO_BYTES(next->ip_len)); + next = (void *)((u_char *)next + IPV6_EXTLEN_TO_BYTES(next->ip_len)); } else { dbgx(3, "%s", "Returning end of IPv6 Header"); } done = true; } /* switch */ - } /* while */ - if (!next || (u_char*)next > (u_char*)ip6_hdr + l3len) - return NULL; + if (next == NULL) + done = true; + } /* while */ return next; } - /** * returns the next payload or header of the current extension header * returns NULL for none/ESP. */ -void * -get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const int len) +static void * +get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const u_char *end_ptr) { - int extlen = 0; - int maxlen; - void *ptr; + uint8_t extlen; + u_char *ptr; assert(exthdr); - maxlen = *((int*)((u_char *)exthdr + len)); + if ((u_char *)exthdr + sizeof(*exthdr) > end_ptr) + return NULL; dbgx(3, "Jumping to next IPv6 header. Processing 0x%02x", exthdr->ip_nh); switch (exthdr->ip_nh) { @@ -685,20 +643,18 @@ get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const int len) case TCPR_IPV6_NH_ESP: dbg(3, "No-Next or ESP... can't go any further..."); return NULL; - break; /* - * fragment header is fixed size + * fragment header is fixed size * FIXME: Frag header has further ext headers (has a ip_nh field) * but I don't support it because there's never a full L4 + payload beyond. */ case TCPR_IPV6_NH_FRAGMENT: dbg(3, "Looks like were a fragment header. Returning some frag'd data."); ptr = (void *)((u_char *)exthdr + sizeof(struct tcpr_ipv6_frag_hdr)); - if (*(int*)ptr > maxlen) + if (ptr > end_ptr) return NULL; - return ptr; - break; + return (void *)ptr; /* all the rest require us to go deeper using the ip_len field */ case TCPR_IPV6_NH_IPV6: @@ -707,18 +663,19 @@ get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const int len) case TCPR_IPV6_NH_HBH: case TCPR_IPV6_NH_AH: extlen = IPV6_EXTLEN_TO_BYTES(exthdr->ip_len); - dbgx(3, "Looks like we're an ext header (0x%hhx). Jumping %u bytes" - " to the next", exthdr->ip_nh, extlen); - ptr = (void *)((u_char *)exthdr + extlen); - if (*(int*)ptr > maxlen) + dbgx(3, + "Looks like we're an ext header (0x%hhx). Jumping %u bytes" + " to the next", + exthdr->ip_nh, + extlen); + ptr = (u_char *)exthdr + extlen; + if (ptr > end_ptr) return NULL; - return ptr; - break; + return (void *)ptr; default: dbg(3, "Must not be a v6 extension header... returning self"); return (void *)exthdr; - break; } } @@ -726,8 +683,8 @@ get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const int len) * returns the protocol of the actual layer4 header by processing through * the extension headers */ -uint8_t -get_ipv6_l4proto(const ipv6_hdr_t *ip6_hdr, const int l3len) +uint8_t +get_ipv6_l4proto(const ipv6_hdr_t *ip6_hdr, const u_char *end_ptr) { u_char *ptr = (u_char *)ip6_hdr + TCPR_IPV6_H; /* jump to the end of the IPv6 header */ uint8_t proto; @@ -735,54 +692,50 @@ get_ipv6_l4proto(const ipv6_hdr_t *ip6_hdr, const int l3len) assert(ip6_hdr); - proto = ip6_hdr->ip_nh; - int l4len = l3len - TCPR_IPV6_H; - if (l4len < 0) - return proto; + if (ptr > end_ptr) + return TCPR_IPV6_NH_NO_NEXT; + proto = ip6_hdr->ip_nh; while (TRUE) { dbgx(3, "Processing next proto 0x%02X", proto); switch (proto) { - /* no further processing for IPV6 types with nothing beyond them */ - case TCPR_IPV6_NH_FRAGMENT: - case TCPR_IPV6_NH_ESP: - dbg(3, "No-Next or ESP... can't go any further..."); - return proto; - break; + /* no further processing for IPV6 types with nothing beyond them */ + case TCPR_IPV6_NH_NO_NEXT: + case TCPR_IPV6_NH_FRAGMENT: + case TCPR_IPV6_NH_ESP: + dbg(3, "No-Next or ESP... can't go any further..."); + return proto; - /* recurse */ - case TCPR_IPV6_NH_IPV6: - dbg(3, "Recursing due to v6 in v6"); - return get_ipv6_l4proto((ipv6_hdr_t *)ptr, l4len); - break; + /* recurse */ + case TCPR_IPV6_NH_IPV6: + dbg(3, "Recursing due to v6 in v6"); + return get_ipv6_l4proto((ipv6_hdr_t *)ptr, end_ptr); - /* loop again */ - case TCPR_IPV6_NH_AH: - case TCPR_IPV6_NH_ROUTING: - case TCPR_IPV6_NH_DESTOPTS: - case TCPR_IPV6_NH_HBH: - dbgx(3, "Jumping to next extension header (0x%hhx)", proto); - exthdr = get_ipv6_next((struct tcpr_ipv6_ext_hdr_base *)ptr, - l4len); - if (exthdr == NULL) - return proto; - proto = exthdr->ip_nh; - l4len -= (u_char *)exthdr - ptr; - ptr = (u_char *)exthdr; - break; + /* loop again */ + case TCPR_IPV6_NH_AH: + case TCPR_IPV6_NH_ROUTING: + case TCPR_IPV6_NH_DESTOPTS: + case TCPR_IPV6_NH_HBH: + dbgx(3, "Jumping to next extension header (0x%hhx)", proto); + exthdr = get_ipv6_next((struct tcpr_ipv6_ext_hdr_base *)ptr, end_ptr); + if (exthdr == NULL || (u_char *)exthdr + sizeof(*exthdr) > end_ptr) + return TCPR_IPV6_NH_NO_NEXT; + proto = exthdr->ip_nh; + ptr = (u_char *)exthdr; + break; - /* should be TCP, UDP or the like */ - default: - dbgx(3, "Selecting next L4 Proto as: 0x%02x", proto); - return proto; + /* should be TCP, UDP or the like */ + default: + dbgx(3, "Selecting next L4 Proto as: 0x%02x", proto); + return proto; } /* switch */ - } /* while */ + } /* while */ } /** * \brief Converts a human readable IPv4 address to a binary one * - * stolen from LIBNET since I didn't want to have to deal with + * stolen from LIBNET since I didn't want to have to deal with * passing a libnet_t around. Returns 0xFFFFFFFF (255.255.255.255) * on error */ @@ -790,14 +743,14 @@ uint32_t get_name2addr4(const char *hostname, bool dnslookup) { struct in_addr addr; -#if ! defined HAVE_INET_ATON && defined HAVE_INET_ADDR - struct hostent *host_ent; +#if !defined HAVE_INET_ATON && defined HAVE_INET_ADDR + struct hostent *host_ent; #endif if (dnslookup) { #ifdef HAVE_INET_ATON if (inet_aton(hostname, &addr) != 1) { - return(0xffffffff); + return (0xffffffff); } #elif defined HAVE_INET_ADDR @@ -809,12 +762,12 @@ get_name2addr4(const char *hostname, bool dnslookup) } /* was: host_ent->h_length); */ - memcpy(&addr.s_addr, host_ent->h_addr, sizeof(addr.s_addr)); + memcpy(&addr.s_addr, host_ent->h_addr, sizeof(addr.s_addr)); } #else warn("Unable to support get_name2addr4 w/ resolve"); /* call ourselves recursively once w/o resolving the hostname */ - return get_name2addr4(hostname, DNS_DONT_RESOLVE); + return get_name2addr4(hostname, DNS_DONT_RESOLVE); #endif /* return in network byte order */ return (addr.s_addr); @@ -826,13 +779,11 @@ get_name2addr4(const char *hostname, bool dnslookup) uint32_t m; if (!isdigit(hostname[0])) { - warnx("Expected dotted-quad notation (%s) when DNS lookups are disabled", - hostname); + warnx("Expected dotted-quad notation (%s) when DNS lookups are disabled", hostname); /* XXX - this is actually 255.255.255.255 */ return (-1); } - m = 0; for (i = 0; i < 4; i++) { u_int val; @@ -857,7 +808,7 @@ get_name2addr4(const char *hostname, bool dnslookup) } } /* host byte order */ - return (ntohl(m)); + return (ntohl(m)); } } @@ -878,7 +829,6 @@ get_name2addr6(const char *hostname, bool dnslookup, struct tcpr_in6_addr *addr) #else #error "Unable to support get_name2addr6: Missing inet_pton() support." #endif - return -1; } /** @@ -888,7 +838,7 @@ get_name2addr6(const char *hostname, bool dnslookup, struct tcpr_in6_addr *addr) * is available on your system. Does not support DNS. */ const char * -get_addr2name4(const uint32_t ip, bool _U_ dnslookup) +get_addr2name4(uint32_t ip, bool _U_ dnslookup) { struct in_addr addr; static char *new_string = NULL; @@ -952,4 +902,3 @@ get_cidr2name(const tcpr_cidr_t *cidr_ptr, bool dnslookup) return NULL; } } - diff --git a/src/common/get.h b/src/common/get.h index 474f5cba0..181abd46b 100644 --- a/src/common/get.h +++ b/src/common/get.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __GET_H__ -#define __GET_H__ +#pragma once #include "config.h" #include "defines.h" @@ -27,37 +26,36 @@ int parse_mpls(const u_char *pktdata, - const uint32_t datalen, + uint32_t datalen, uint16_t *protocol, uint32_t *l2len, uint32_t *l2offset); int parse_vlan(const u_char *pktdata, - const uint32_t datalen, + uint32_t datalen, uint16_t *next_protocol, uint32_t *l2len); -int get_l2len(const u_char *pktdata, const int datalen, const int datalink); +int get_l2len(const u_char *pktdata, int datalen, int datalink); int get_l2len_protocol(const u_char *pktdata, - const uint32_t datalen, - const int datalink, + uint32_t datalen, + int datalink, uint16_t *protocol, uint32_t *l2len, uint32_t *l2offset, uint32_t *vlan_offset); -void *get_layer4_v4(const ipv4_hdr_t *ip_hdr, const int l3len); -void *get_layer4_v6(const ipv6_hdr_t *ip_hdr, const int l3len); +void *get_layer4_v4(const ipv4_hdr_t *ip_hdr, const u_char *end_ptr); +void *get_layer4_v6(const ipv6_hdr_t *ip_hdr, const u_char *end_ptr); -u_int8_t get_ipv6_l4proto(const ipv6_hdr_t *ip6_hdr, const int l3len); -void *get_ipv6_next(struct tcpr_ipv6_ext_hdr_base *exthdr, const int l3len); +u_int8_t get_ipv6_l4proto(const ipv6_hdr_t *ip6_hdr, const u_char *end_ptr); const u_char *get_ipv4(const u_char *pktdata, int datalen, int datalink, u_char **newbuff); const u_char *get_ipv6(const u_char *pktdata, int datalen, int datalink, u_char **newbuff); u_int32_t get_name2addr4(const char *hostname, bool dnslookup); -const char *get_addr2name4(const u_int32_t ip, bool dnslookup); +const char *get_addr2name4(u_int32_t ip, bool dnslookup); const char *get_addr2name6(const struct tcpr_in6_addr *addr, bool dnslookup); const char *get_pcap_version(void); @@ -65,6 +63,3 @@ int get_name2addr6(const char *hostname, bool dnslookup, struct tcpr_in6_addr *a const char *get_cidr2name(const tcpr_cidr_t *cidr_ptr, bool dnslookup); - - -#endif diff --git a/src/common/interface.c b/src/common/interface.c index 5f2df4ab6..006f7133d 100644 --- a/src/common/interface.c +++ b/src/common/interface.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,33 +18,21 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include -#include -#include -#include -#include -#include -#include - +#include "interface.h" #include "config.h" -#include "defines.h" #include "common.h" -#include "interface.h" -#ifdef HAVE_NETMAP -#include "common/netmap.h" -#endif - -#ifdef DEBUG -extern int debug; -#endif +#include +#include +#include +#include +#include /** * Method takes a user specified device name and returns - * the canonical name for that device. This allows me to + * the canonical name for that device. This allows me to * create named interface aliases on platforms like Windows * which use horrifically long interface names - * + * * Returns NULL on error */ char * @@ -58,17 +46,16 @@ get_interface(interface_list_t *list, const char *alias) while (ptr) { /* check both the alias & name fields */ - if (strcmp(alias, ptr->alias) == 0 || - strcmp(alias, ptr->name) == 0) - return(ptr->name); + if (strcmp(alias, ptr->alias) == 0 || strcmp(alias, ptr->name) == 0) + return (ptr->name); ptr = ptr->next; } - return(NULL); + return (NULL); } -/** +/** * Get all available interfaces as an interface_list * */ interface_list_t * @@ -124,13 +111,12 @@ get_interface_list(void) * * available at http://code.google.com/p/netmap-libpcap/ */ - if (!(pcap_if_ptr->flags & PCAP_IF_LOOPBACK) - && strcmp("any", pcap_if_ptr->name)) { + if (!(pcap_if_ptr->flags & PCAP_IF_LOOPBACK) && strcmp("any", pcap_if_ptr->name)) { #endif #ifdef HAVE_NETMAP int fd = -1; - if (netmap_version != -1 && (fd = open ("/dev/netmap", O_RDWR)) < 0) + if (netmap_version != -1 && (fd = open("/dev/netmap", O_RDWR)) < 0) continue; bzero(&nmr, sizeof(nmr)); @@ -218,7 +204,7 @@ get_interface_list(void) } dbg(1, "xxx get_interface_list end"); - return(list_head); + return (list_head); } /** @@ -235,12 +221,11 @@ list_interfaces(interface_list_t *list) } printf("Available network interfaces:\n"); - -#ifdef HAVE_WIN32 /* Win32 has alias/name/description */ + +#ifdef HAVE_WIN32 /* Win32 has alias/name/description */ printf("Alias\tName\tDescription\n"); #endif - - + ptr = list; do { diff --git a/src/common/interface.h b/src/common/interface.h index 2fa1b3093..446b51a33 100644 --- a/src/common/interface.h +++ b/src/common/interface.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _INTERFACE_H_ -#define _INTERFACE_H_ +#pragma once + +#include "defines.h" typedef struct interface_list_s { char name[255]; @@ -34,5 +35,3 @@ typedef struct interface_list_s { char *get_interface(interface_list_t *, const char *); interface_list_t *get_interface_list(void); void list_interfaces(interface_list_t *); - -#endif diff --git a/src/common/list.c b/src/common/list.c index 303e5a5b9..ec41dd12b 100644 --- a/src/common/list.c +++ b/src/common/list.c @@ -2,9 +2,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -24,16 +24,13 @@ * if an integer exists in the list. */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include #include #include #include -#include -#include - /** * Creates a new tcpr_list entry. Malloc's memory. @@ -49,11 +46,11 @@ new_list() /** * Processes a string (ourstr) containing the list in human readable - * format and places the data in **list and finally returns 1 for + * format and places the data in **list and finally returns 1 for * success, 0 for fail. */ int -parse_list(tcpr_list_t ** listdata, char *ourstr) +parse_list(tcpr_list_t **listdata, char *ourstr) { tcpr_list_t *listcur, *list_ptr; char *this = NULL; @@ -64,7 +61,6 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) char *token = NULL; u_int i; - /* compile the regex first */ if ((rcode = regcomp(&preg, regex, REG_EXTENDED | REG_NOSUB)) != 0) { char ebuf[EBUF_SIZE]; @@ -78,7 +74,7 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) second = NULL; /* regex test */ - if (regexec(&preg, this, 0, NULL, 0) != 0) { + if (this == NULL || regexec(&preg, this, 0, NULL, 0) != 0) { warnx("Unable to parse: %s", this); regfree(&preg); return 0; @@ -98,8 +94,7 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) list_ptr->min = strtoull(first, NULL, 0); if (second != NULL) { list_ptr->max = strtoull(second, NULL, 0); - } - else { + } else { list_ptr->max = list_ptr->min; } @@ -111,7 +106,6 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) first = this; second = NULL; - /* regex test */ if (regexec(&preg, this, 0, NULL, 0) != 0) { warnx("Unable to parse: %s", this); @@ -132,11 +126,9 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) listcur->min = strtoull(first, NULL, 0); if (second != NULL) { listcur->max = strtoull(second, NULL, 0); - } - else { + } else { listcur->max = listcur->min; } - } regfree(&preg); @@ -144,14 +136,12 @@ parse_list(tcpr_list_t ** listdata, char *ourstr) return 1; } - - /** * Checks to see if the given integer exists in the LIST. * Return 1 if in the list, otherwise 0 */ tcpr_dir_t -check_list(tcpr_list_t * list, COUNTER value) +check_list(tcpr_list_t *list, COUNTER value) { tcpr_list_t *current; current = list; @@ -177,14 +167,12 @@ check_list(tcpr_list_t * list, COUNTER value) return 0; } - /** * Free's all the memory associated with the given LIST */ void -free_list(tcpr_list_t * list) +free_list(tcpr_list_t *list) { - /* recursively go down the list */ if (list->next != NULL) free_list(list->next); diff --git a/src/common/list.h b/src/common/list.h index 8a6a70542..9eaa425fa 100644 --- a/src/common/list.h +++ b/src/common/list.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __LIST_H__ -#define __LIST_H__ +#pragma once struct list_s { COUNTER max; @@ -32,5 +31,3 @@ typedef struct list_s tcpr_list_t; int parse_list(tcpr_list_t **, char *); int check_list(tcpr_list_t *, COUNTER); void free_list(tcpr_list_t *); - -#endif diff --git a/src/common/mac.c b/src/common/mac.c index 3747a174e..45e45facd 100644 --- a/src/common/mac.c +++ b/src/common/mac.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,19 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "mac.h" #include "config.h" -#include "defines.h" #include "common.h" -#include -#include -#include #include - -#include "mac.h" +#include +#include /** - * converts a string representation of a MAC address, based on - * non-portable ether_aton() + * converts a string representation of a MAC address, based on + * non-portable ether_aton() */ void mac2hex(const char *mac, u_char *dst, int len) @@ -51,14 +48,14 @@ mac2hex(const char *mac, u_char *dst, int len) return; if (!(*pp == ':' || (i == 5 && (isspace(*pp) || *pp == '\0')))) return; - dst[i] = (u_char) l; + dst[i] = (u_char)l; mac = pp + 1; } } /** * converts a string representation of TWO MAC addresses, which - * are comma deliminated into two hex values. Either *first or *second + * are comma deliminated into two hex values. Either *first or *second * can be NULL if there is nothing before or after the comma. * returns: * 1 = first mac @@ -75,10 +72,8 @@ dualmac2hex(const char *dualmac, u_char *first, u_char *second, int len) string = safe_strdup(dualmac); /* if we've only got a comma, then return NULL's */ - if (len <= 1) { - second = first = NULL; + if (len <= 1) goto done; - } temp = strtok_r(string, ",", &tok); if (strlen(temp)) { @@ -88,12 +83,12 @@ dualmac2hex(const char *dualmac, u_char *first, u_char *second, int len) temp = strtok_r(NULL, ",", &tok); /* temp is null if no comma */ - if (temp != NULL) { + if (temp != NULL) { if (strlen(temp)) { mac2hex(temp, second, len); ret += 2; } - } + } done: safe_free(string); @@ -112,36 +107,36 @@ macinstring(const char *macstring, const u_char *mac) char *tok = NULL, *tempstr, *ourstring; u_char tempmac[6]; int len = 6, ret = TCPR_DIR_S2C; - + ourstring = safe_strdup(macstring); memset(&tempmac[0], 0, sizeof(tempmac)); - + tempstr = strtok_r(ourstring, ",", &tok); - if (strlen(tempstr)) { - mac2hex(tempstr, tempmac, len); - if (memcmp(mac, tempmac, len) == 0) { - dbgx(3, "Packet matches: " MAC_FORMAT " sending out primary.\n", MAC_STR(tempmac)); - ret = TCPR_DIR_C2S; - goto EXIT_MACINSTRING; - } + if (tempstr != NULL && strlen(tempstr)) { + mac2hex(tempstr, tempmac, len); + if (memcmp(mac, tempmac, len) == 0) { + dbgx(3, "Packet matches: " MAC_FORMAT " sending out primary.\n", MAC_STR(tempmac)); + ret = TCPR_DIR_C2S; + goto EXIT_MACINSTRING; + } } else { goto EXIT_MACINSTRING; } while ((tempstr = strtok_r(NULL, ",", &tok)) != NULL) { - mac2hex(tempstr, tempmac, len); - if (memcmp(mac, tempmac, len) == 0) { - ret = TCPR_DIR_C2S; - dbgx(3, "Packet matches: " MAC_FORMAT " sending out primary.\n", MAC_STR(tempmac)); - goto EXIT_MACINSTRING; - } + mac2hex(tempstr, tempmac, len); + if (memcmp(mac, tempmac, len) == 0) { + ret = TCPR_DIR_C2S; + dbgx(3, "Packet matches: " MAC_FORMAT " sending out primary.\n", MAC_STR(tempmac)); + goto EXIT_MACINSTRING; + } } EXIT_MACINSTRING: safe_free(ourstring); #ifdef DEBUG if (ret == TCPR_DIR_S2C) - dbg(3, "Packet doesn't match any MAC addresses sending out secondary.\n"); + dbg(3, "Packet doesn't match any MAC addresses sending out secondary.\n"); #endif return ret; } diff --git a/src/common/mac.h b/src/common/mac.h index a8f1e47ce..50116a8e9 100644 --- a/src/common/mac.h +++ b/src/common/mac.h @@ -18,11 +18,11 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __MAC_H__ -#define __MAC_H__ +#pragma once + +#include "cache.h" +#include "defines.h" void mac2hex(const char *mac, u_char *dst, int len); int dualmac2hex(const char *dualmac, u_char *first, u_char *second, int len); tcpr_dir_t macinstring(const char *macstring, const u_char *mac); - -#endif /* __MAC_H__ */ diff --git a/src/common/netmap.c b/src/common/netmap.c index ca0310497..7a5ccef26 100644 --- a/src/common/netmap.c +++ b/src/common/netmap.c @@ -1,9 +1,9 @@ /* * Copyright (c) 2013 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -15,28 +15,20 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - +#include "netmap.h" #include "config.h" -#include "defines.h" #include "common.h" #include "tcpreplay_api.h" -#include "netmap.h" - -#ifdef DEBUG -extern int debug; -#endif - +#include +#include +#include +#include #include -static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd); +#include +#include +#include + +static int nm_do_ioctl(sendpacket_t *sp, u_long what, int subcmd); /** * Method takes an open "/dev/netmap" file descriptor and returns @@ -51,18 +43,17 @@ get_netmap_version() nmreq_t nmr; int fd; - if ((fd = open ("/dev/netmap", O_RDWR)) < 0) + if ((fd = open("/dev/netmap", O_RDWR)) < 0) return -1; /* netmap version discovery */ - bzero (&nmr, sizeof(nmr)); + bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; /* attempt using the netmap API version that this was compiled under */ - if(ioctl(fd, NIOCGINFO, &nmr) == 0) { + if (ioctl(fd, NIOCGINFO, &nmr) == 0) { netmap_version = nmr.nr_version; - dbgx(1, "netmap detected API version %d which matches compiled version\n", - netmap_version); + dbgx(1, "netmap detected API version %d which matches compiled version\n", netmap_version); } else { /* failed. * @@ -71,12 +62,14 @@ get_netmap_version() */ int x; for (x = 0; x < 50; ++x) { - bzero (&nmr, sizeof(nmr)); + bzero(&nmr, sizeof(nmr)); nmr.nr_version = x; - if(ioctl(fd, NIOCGINFO, &nmr) == 0) { + if (ioctl(fd, NIOCGINFO, &nmr) == 0) { netmap_version = nmr.nr_version; - dbgx(1, "netmap detected API version %d which doesn't match compiled version %d\n", - netmap_version, NETMAP_API); + dbgx(1, + "netmap detected API version %d which doesn't match compiled version %d\n", + netmap_version, + NETMAP_API); break; } } @@ -84,13 +77,15 @@ get_netmap_version() close(fd); - return netmap_version; + return (int)netmap_version; } /** * ioctl support for netmap */ -static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd) { +static int +nm_do_ioctl(sendpacket_t *sp, u_long what, int subcmd) +{ struct ifreq ifr; int error; int fd; @@ -100,14 +95,14 @@ static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd) { assert(sp); - fd = socket (AF_INET, SOCK_DGRAM, 0); + fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { dbg(1, "ioctl error: cannot get device control socket.\n"); return -1; } - bzero (&ifr, sizeof(ifr)); - strncpy (ifr.ifr_name, sp->device, sizeof(ifr.ifr_name)); + bzero(&ifr, sizeof(ifr)); + strncpy(ifr.ifr_name, sp->device, sizeof(ifr.ifr_name)); switch (what) { case SIOCSIFFLAGS: @@ -125,7 +120,7 @@ static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd) { #endif } - error = ioctl (fd, what, &ifr); + error = ioctl(fd, what, &ifr); if (error) goto done; @@ -157,14 +152,17 @@ static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd) { sp->txcsum = eval.data; dbgx(1, "ioctl SIOCETHTOOL ETHTOOL_GTXCSUM=%u", eval.data); break; + default: + return -1; } break; #endif - + default: + return -1; } done: - close (fd); + close(fd); if (error) warnx("ioctl error %d %lu:%d", error, what, subcmd); @@ -175,8 +173,9 @@ static int nm_do_ioctl (sendpacket_t *sp, u_long what, int subcmd) { * Inner sendpacket_open() method for using netmap */ void * -sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { - tcpreplay_t *ctx = (tcpreplay_t*)arg; +sendpacket_open_netmap(const char *device, char *errbuf, void *arg) +{ + tcpreplay_t *ctx = (tcpreplay_t *)arg; sendpacket_t *sp = NULL; nmreq_t nmr; char ifname_buf[MAX_IFNAMELEN]; @@ -205,8 +204,10 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { /* get the version of the netmap driver. If < 0, driver is not installed */ sp->netmap_version = get_netmap_version(); if (sp->netmap_version < 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to determine the running netmap version.\n" - "See INSTALL document for details on installing or upgrading netmap."); + snprintf(errbuf, + SENDPACKET_ERRBUF_SIZE, + "Unable to determine the running netmap version.\n" + "See INSTALL document for details on installing or upgrading netmap."); goto NETMAP_NOT_INSTALLED; } @@ -259,9 +260,11 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { */ if ((sp->handle.fd = open("/dev/netmap", O_RDWR)) < 0) { dbg(1, "sendpacket_open_netmap: Unable to access netmap"); - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to access netmap.\n" - "See INSTALL to learn which NICs are supported and\n" - "how to set up netmap-capable network drivers."); + snprintf(errbuf, + SENDPACKET_ERRBUF_SIZE, + "Unable to access netmap.\n" + "See INSTALL to learn which NICs are supported and\n" + "how to set up netmap-capable network drivers."); goto OPEN_FAILED; } @@ -275,7 +278,7 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { switch (*port) { case '-': /* one NIC */ nr_flags = NR_REG_ONE_NIC; - nr_ringid = atoi(port + 1); + nr_ringid = strtol(port + 1, NULL, 10); break; case '*': /* NIC and SW, ignore port */ @@ -296,19 +299,19 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { case '{': nr_flags = NR_REG_PIPE_MASTER; - nr_ringid = atoi(port + 1); + nr_ringid = strtol(port + 1, NULL, 10); break; case '}': nr_flags = NR_REG_PIPE_SLAVE; - nr_ringid = atoi(port + 1); + nr_ringid = strtol(port + 1, NULL, 10); break; case '!': nr_flags = NR_REG_ALL_NIC; break; - default: /* '\0', no suffix */ + default: /* '\0', no suffix */ nr_flags = NR_REG_ALL_NIC; is_default = 1; break; @@ -335,35 +338,35 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { * * Cards take a long time to reset the PHY. */ - fprintf(stderr, "Switching network driver for %s to netmap bypass mode... ", - sp->device); + fprintf(stderr, "Switching network driver for %s to netmap bypass mode... ", sp->device); fflush(NULL); - sleep(1); /* ensure message prints when user is connected via ssh */ - - if (ioctl (sp->handle.fd, NIOCREGIF, &nmr)) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Failure accessing netmap.\n" - "\tRequest for netmap version %d failed.\n\tCompiled netmap driver is version %d.\n\tError=%s\n", - sp->netmap_version, NETMAP_API, strerror(errno)); + sleep(1); /* ensure message prints when user is connected via ssh */ + + if (ioctl(sp->handle.fd, NIOCREGIF, &nmr)) { + snprintf(errbuf, + SENDPACKET_ERRBUF_SIZE, + "Failure accessing netmap.\n" + "\tRequest for netmap version %d failed.\n\tCompiled netmap driver is version %d.\n\tError=%s\n", + sp->netmap_version, + NETMAP_API, + strerror(errno)); goto NETMAP_IF_FAILED; } if (!nmr.nr_memsize) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Netmap interface '%s' not configured.\n", - device); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Netmap interface '%s' not configured.\n", device); goto NETMAP_IF_FAILED; } sp->mmap_size = nmr.nr_memsize; - sp->mmap_addr = (struct netmap_d *)mmap (0, sp->mmap_size, - PROT_WRITE | PROT_READ, MAP_SHARED, sp->handle.fd, 0); + sp->mmap_addr = (struct netmap_d *)mmap(0, sp->mmap_size, PROT_WRITE | PROT_READ, MAP_SHARED, sp->handle.fd, 0); if (!sp->mmap_addr || sp->mmap_addr == MAP_FAILED) { - snprintf (errbuf, SENDPACKET_ERRBUF_SIZE, "mmap: %s", strerror (errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "mmap: %s", strerror(errno)); goto MMAP_FAILED; } - dbgx(1, "sendpacket_open_netmap: mapping %d Kbytes queues=%d", - sp->mmap_size >> 10, nmr.nr_tx_rings); + dbgx(1, "sendpacket_open_netmap: mapping %d Kbytes queues=%d", sp->mmap_size >> 10, nmr.nr_tx_rings); sp->nm_if = NETMAP_IF(sp->mmap_addr, nmr.nr_offset); sp->nmr = nmr; @@ -371,8 +374,8 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { /* set up ring IDs */ sp->cur_tx_ring = 0; - switch(nr_flags) { - case NR_REG_DEFAULT: /* only use one queue to prevent TX reordering */ + switch (nr_flags) { + case NR_REG_DEFAULT: /* only use one queue to prevent TX reordering */ sp->first_tx_ring = sp->last_tx_ring = sp->cur_tx_ring = 0; break; @@ -405,16 +408,23 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { /* debugging code */ int i; - dbgx(1, "%s tx first=%d last=%d num=%d", ifname, - sp->first_tx_ring, sp->last_tx_ring, sp->nmr.nr_tx_rings); + dbgx(1, "%s tx first=%d last=%d num=%d", ifname, sp->first_tx_ring, sp->last_tx_ring, sp->nmr.nr_tx_rings); for (i = 0; i <= sp->nmr.nr_tx_rings; i++) { #ifdef HAVE_NETMAP_RING_HEAD_TAIL - dbgx(1, "TX%d 0x%p head=%d cur=%d tail=%d", i, NETMAP_TXRING(sp->nm_if, i), - (NETMAP_TXRING(sp->nm_if, i))->head, - (NETMAP_TXRING(sp->nm_if, i))->cur, (NETMAP_TXRING(sp->nm_if, i))->tail); + dbgx(1, + "TX%d 0x%p head=%d cur=%d tail=%d", + i, + NETMAP_TXRING(sp->nm_if, i), + (NETMAP_TXRING(sp->nm_if, i))->head, + (NETMAP_TXRING(sp->nm_if, i))->cur, + (NETMAP_TXRING(sp->nm_if, i))->tail); #else - dbgx(1, "TX%d 0x%p cur=%d avail=%d", i, NETMAP_TXRING(sp->nm_if, i), - (NETMAP_TXRING(sp->nm_if, i))->cur, (NETMAP_TXRING(sp->nm_if, i))->avail); + dbgx(1, + "TX%d 0x%p cur=%d avail=%d", + i, + NETMAP_TXRING(sp->nm_if, i), + (NETMAP_TXRING(sp->nm_if, i))->cur, + (NETMAP_TXRING(sp->nm_if, i))->avail); #endif } } @@ -429,7 +439,7 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { if ((sp->if_flags & IFF_RUNNING) == 0) { dbgx(1, "sendpacket_open_netmap: %s is not running", sp->device); - snprintf (errbuf, SENDPACKET_ERRBUF_SIZE, "interface %s is not running - check cables\n", sp->device); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "interface %s is not running - check cables\n", sp->device); goto NETMAP_IF_NOT_RUNNING; } @@ -450,22 +460,18 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { * - rx-checksumming * - tx-checksumming */ - if (nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GGSO) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GTSO) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GRXCSUM) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GTXCSUM) < 0) + if (nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GGSO) < 0 || nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GTSO) < 0 || + nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GRXCSUM) < 0 || nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_GTXCSUM) < 0) goto NM_DO_IOCTL_FAILED; sp->data = 0; - if (nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_SGSO) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_STSO) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_SRXCSUM) < 0 || - nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_STXCSUM)) + if (nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_SGSO) < 0 || nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_STSO) < 0 || + nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_SRXCSUM) < 0 || nm_do_ioctl(sp, SIOCETHTOOL, ETHTOOL_STXCSUM)) goto NM_DO_IOCTL_FAILED; #endif } - if(sp->abort) + if (sp->abort) goto NETMAP_ABORT; notice("done!"); @@ -473,12 +479,11 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { return sp; NM_DO_IOCTL_FAILED: - snprintf (errbuf, SENDPACKET_ERRBUF_SIZE, "nm_do_ioctl: %s", strerror (errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "nm_do_ioctl: %s", strerror(errno)); NETMAP_IF_NOT_RUNNING: notice("failed!"); NETMAP_ABORT: - fprintf(stderr, " Switching network driver for %s to normal mode... ", - sp->device); + fprintf(stderr, " Switching network driver for %s to normal mode... ", sp->device); fflush(NULL); munmap(sp->mmap_addr, sp->mmap_size); MMAP_FAILED: @@ -487,7 +492,7 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { #endif NETMAP_IF_FAILED: NETMAP_IF_PARSE_FAIL: - close (sp->handle.fd); + close(sp->handle.fd); OPEN_FAILED: safe_free(sp); IFACENAME_INVALID: @@ -496,11 +501,11 @@ sendpacket_open_netmap(const char *device, char *errbuf, void *arg) { return NULL; } -void sendpacket_close_netmap(void *p) +void +sendpacket_close_netmap(void *p) { sendpacket_t *sp = p; - fprintf(stderr, "Switching network driver for %s to normal mode... ", - sp->device); + fprintf(stderr, "Switching network driver for %s to normal mode... ", sp->device); fflush(NULL); /* flush any remaining packets */ @@ -511,7 +516,6 @@ void sendpacket_close_netmap(void *p) sleep(sp->netmap_delay); dbg(2, "Ready!"); - #ifdef linux if (!sp->is_vale) { /* restore original settings: @@ -541,7 +545,8 @@ void sendpacket_close_netmap(void *p) notice("done!"); } -bool netmap_tx_queues_empty(void *p) +bool +netmap_tx_queues_empty(void *p) { sendpacket_t *sp = p; struct netmap_ring *txring; @@ -570,7 +575,8 @@ bool netmap_tx_queues_empty(void *p) return false; } -int sendpacket_send_netmap(void *p, const u_char *data, size_t len) +int +sendpacket_send_netmap(void *p, const u_char *data, size_t len) { sendpacket_t *sp = p; struct netmap_ring *txring; @@ -625,9 +631,14 @@ int sendpacket_send_netmap(void *p, const u_char *data, size_t len) if (avail <= 1) slot->flags = NS_REPORT; - dbgx(3, "netmap cur=%d slot index=%d flags=0x%x empty=%d avail=%u bufsize=%d\n", - cur, slot->buf_idx, slot->flags, NETMAP_TX_RING_EMPTY(txring), - nm_ring_space(txring), txring->nr_buf_size); + dbgx(3, + "netmap cur=%d slot index=%d flags=0x%x empty=%d avail=%u bufsize=%d\n", + cur, + slot->buf_idx, + slot->flags, + NETMAP_TX_RING_EMPTY(txring), + nm_ring_space(txring), + txring->nr_buf_size); /* let kernel know that packet is available */ cur = NETMAP_RING_NEXT(txring, cur); diff --git a/src/common/netmap.h b/src/common/netmap.h index a64824a11..02bc34ff3 100644 --- a/src/common/netmap.h +++ b/src/common/netmap.h @@ -1,9 +1,9 @@ /* * Copyright (c) 2013 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -14,11 +14,10 @@ * You should have received a copy of the GNU General Public License * along with the Tcpreplay Suite. If not, see . */ -#ifndef NETMAP_H_ -#define NETMAP_H_ +#pragma once -#include "config.h" #include "defines.h" +#include "config.h" #include #ifdef __NetBSD__ #include @@ -31,8 +30,8 @@ #include #ifdef linux -# include -# include +#include +#include #endif /* linux */ #ifndef NETMAP_API @@ -50,9 +49,10 @@ #endif #ifndef HAVE_NETMAP_NR_REG -#define NR_REG_MASK 0xf /* values for nr_flags */ +#define NR_REG_MASK 0xf /* values for nr_flags */ #if NETMAP_API < 11 -enum { NR_REG_DEFAULT = 0, /* backward compat, used in older versions. */ +enum { + NR_REG_DEFAULT = 0, /* backward compat, used in older versions. */ NR_REG_ALL_NIC, NR_REG_SW, NR_REG_NIC_SW, @@ -64,72 +64,69 @@ enum { NR_REG_DEFAULT = 0, /* backward compat, used in older versions. */ #endif #ifndef NETMAP_HW_RING -#define NETMAP_HW_RING 0x4000 /* single NIC ring pair */ +#define NETMAP_HW_RING 0x4000 /* single NIC ring pair */ #endif #ifndef NETMAP_SW_RING -#define NETMAP_SW_RING 0x2000 /* only host ring pair */ +#define NETMAP_SW_RING 0x2000 /* only host ring pair */ #endif #ifndef NETMAP_RING_MASK -#define NETMAP_RING_MASK 0x0fff /* the ring number */ +#define NETMAP_RING_MASK 0x0fff /* the ring number */ #endif #ifndef NETMAP_NO_TX_POLL -#define NETMAP_NO_TX_POLL 0x1000 /* no automatic txsync on poll */ +#define NETMAP_NO_TX_POLL 0x1000 /* no automatic txsync on poll */ #endif #ifndef NETMAP_DO_RX_POLL -#define NETMAP_DO_RX_POLL 0x8000 /* DO automatic rxsync on poll */ +#define NETMAP_DO_RX_POLL 0x8000 /* DO automatic rxsync on poll */ #endif #ifndef NETMAP_BDG_ATTACH -#define NETMAP_BDG_ATTACH 1 /* attach the NIC */ +#define NETMAP_BDG_ATTACH 1 /* attach the NIC */ #endif #ifndef NETMAP_BDG_DETACH -#define NETMAP_BDG_DETACH 2 /* detach the NIC */ +#define NETMAP_BDG_DETACH 2 /* detach the NIC */ #endif #ifndef NETMAP_BDG_LOOKUP_REG -#define NETMAP_BDG_LOOKUP_REG 3 /* register lookup function */ +#define NETMAP_BDG_LOOKUP_REG 3 /* register lookup function */ #endif #ifndef NETMAP_BDG_LIST -#define NETMAP_BDG_LIST 4 /* get bridge's info */ +#define NETMAP_BDG_LIST 4 /* get bridge's info */ #endif #ifndef NETMAP_BDG_VNET_HDR -#define NETMAP_BDG_VNET_HDR 5 /* set the port virtio-net-hdr length */ +#define NETMAP_BDG_VNET_HDR 5 /* set the port virtio-net-hdr length */ #endif #ifndef NETMAP_BDG_OFFSET -#define NETMAP_BDG_OFFSET NETMAP_BDG_VNET_HDR /* deprecated alias */ +#define NETMAP_BDG_OFFSET NETMAP_BDG_VNET_HDR /* deprecated alias */ #endif #ifndef NETMAP_BDG_HOST -#define NETMAP_BDG_HOST 1 /* attach the host stack on ATTACH */ +#define NETMAP_BDG_HOST 1 /* attach the host stack on ATTACH */ #endif #ifdef HAVE_NETMAP_NR_FLAGS typedef struct nmreq nmreq_t; #else struct tcpr_nmreq { - char nr_name[IFNAMSIZ]; - uint32_t nr_version; /* API version */ - uint32_t nr_offset; /* nifp offset in the shared region */ - uint32_t nr_memsize; /* size of the shared region */ - uint32_t nr_tx_slots; /* slots in tx rings */ - uint32_t nr_rx_slots; /* slots in rx rings */ - uint16_t nr_tx_rings; /* number of tx rings */ - uint16_t nr_rx_rings; /* number of rx rings */ - uint16_t nr_ringid; /* ring(s) we care about */ - uint16_t nr_cmd; - uint16_t nr_arg1; /* reserve extra rings in NIOCREGIF */ - uint16_t nr_arg2; - uint32_t nr_arg3; /* req. extra buffers in NIOCREGIF */ - uint32_t nr_flags; + char nr_name[IFNAMSIZ]; + uint32_t nr_version; /* API version */ + uint32_t nr_offset; /* nifp offset in the shared region */ + uint32_t nr_memsize; /* size of the shared region */ + uint32_t nr_tx_slots; /* slots in tx rings */ + uint32_t nr_rx_slots; /* slots in rx rings */ + uint16_t nr_tx_rings; /* number of tx rings */ + uint16_t nr_rx_rings; /* number of rx rings */ + uint16_t nr_ringid; /* ring(s) we care about */ + uint16_t nr_cmd; + uint16_t nr_arg1; /* reserve extra rings in NIOCREGIF */ + uint16_t nr_arg2; + uint32_t nr_arg3; /* req. extra buffers in NIOCREGIF */ + uint32_t nr_flags; /* various modes, extends nr_ringid */ - uint32_t spare2[1]; + uint32_t spare2[1]; }; typedef struct tcpr_nmreq nmreq_t; #endif /* HAVE_NETMAP_NR_FLAGS */ -#define NETMAP_TX_TIMEOUT_SEC 10 int get_netmap_version(void); void *sendpacket_open_netmap(const char *device, char *errbuf, void *arg); void sendpacket_close_netmap(void *p); bool netmap_tx_queues_empty(void *p); int sendpacket_send_netmap(void *p, const u_char *data, size_t len); - -#endif /* NETMAP_H_ */ diff --git a/src/common/pcap_dlt.h b/src/common/pcap_dlt.h index 84f8fa57b..2d5827821 100644 --- a/src/common/pcap_dlt.h +++ b/src/common/pcap_dlt.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,11 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _PCAP_DLT_H_ -#define _PCAP_DLT_H_ +#pragma once /* - * Cisco HDLC. Used by Dag interfaces for SONET + * Cisco HDLC. Used by Dag interfaces for SONET * and possibly others */ @@ -33,8 +32,3 @@ struct hdlc_hdr_s { u_int16_t protocol; }; typedef struct hdlc_hdr_s hdlc_hdr_t; - - -#endif /* _PCAP_DLT_H_ */ - - diff --git a/src/common/sendpacket.c b/src/common/sendpacket.c index e0e0dc432..9dc378f6d 100644 --- a/src/common/sendpacket.c +++ b/src/common/sendpacket.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,46 +18,45 @@ * along with the Tcpreplay Suite. If not, see . */ - /* sendpacket.[ch] is my attempt to write a universal packet injection - * API for BPF, libpcap, libdnet, and Linux's PF_PACKET. I got sick - * and tired dealing with libnet bugs and its lack of active maintenance, - * but unfortunately, libpcap frame injection support is relatively new - * and not everyone uses Linux, so I decided to support all four as - * best as possible. If your platform/OS/hardware supports an additional - * injection method, then by all means add it here (and send me a patch). - * - * Anyways, long story short, for now the order of preference is: - * 1. TX_RING - * 2. PF_PACKET - * 3. BPF - * 4. libdnet - * 5. pcap_inject() - * 6. pcap_sendpacket() - * - * Right now, one big problem with the pcap_* methods is that libpcap - * doesn't provide a reliable method of getting the MAC address of - * an interface (required for tcpbridge). - * You can use PF_PACKET or BPF to get that, but if your system supports - * those, might as well inject directly without going through another - * level of indirection. - * - * Please note that some of this code was copied from Libnet 1.1.3 - */ +/* sendpacket.[ch] is my attempt to write a universal packet injection + * API for BPF, libpcap, libdnet, and Linux's PF_PACKET. I got sick + * and tired dealing with libnet bugs and its lack of active maintenance, + * but unfortunately, libpcap frame injection support is relatively new + * and not everyone uses Linux, so I decided to support all four as + * best as possible. If your platform/OS/hardware supports an additional + * injection method, then by all means add it here (and send me a patch). + * + * Anyways, long story short, for now the order of preference is: + * 1. TX_RING + * 2. PF_PACKET + * 3. BPF + * 4. libdnet + * 5. pcap_inject() + * 6. pcap_sendpacket() + * + * Right now, one big problem with the pcap_* methods is that libpcap + * doesn't provide a reliable method of getting the MAC address of + * an interface (required for tcpbridge). + * You can use PF_PACKET or BPF to get that, but if your system supports + * those, might as well inject directly without going through another + * level of indirection. + * + * Please note that some of this code was copied from Libnet 1.1.3 + */ -#include +#include "sendpacket.h" +#include "defines.h" +#include "config.h" +#include "common.h" #include #include #include -#include -#include -#include +#include #include +#include #include - -#include "config.h" -#include "defines.h" -#include "common.h" -#include "sendpacket.h" +#include +#include #ifdef FORCE_INJECT_TX_RING /* TX_RING uses PF_PACKET API so don't undef it here */ #undef HAVE_LIBDNET @@ -110,11 +109,11 @@ #undef HAVE_PCAP_INJECT /* configure returns true for some odd reason */ #endif -#if !defined HAVE_PCAP_INJECT && !defined HAVE_PCAP_SENDPACKET && !defined HAVE_LIBDNET && !defined HAVE_PF_PACKET && !defined HAVE_BPF && !defined TX_RING +#if !defined HAVE_PCAP_INJECT && !defined HAVE_PCAP_SENDPACKET && !defined HAVE_LIBDNET && !defined HAVE_PF_PACKET && \ + !defined HAVE_BPF && !defined TX_RING #error You need pcap_inject() or pcap_sendpacket() from libpcap, libdnet, Linux's PF_PACKET/TX_RING or *BSD's BPF #endif - #ifdef HAVE_SYS_PARAM_H #include #endif @@ -138,11 +137,11 @@ #endif #include -#include #include -#include #include +#include #include +#include #ifdef HAVE_TX_RING #include "txring.h" @@ -156,31 +155,31 @@ static int get_iface_index(int fd, const char *device, char *); #ifdef HAVE_TUNTAP #ifdef HAVE_LINUX -#include #include +#include #elif defined(HAVE_FREEBSD) #define TUNTAP_DEVICE_PREFIX "/dev/" #endif static sendpacket_t *sendpacket_open_tuntap(const char *, char *); #endif -#if defined HAVE_BPF && ! defined INJECT_METHOD +#if defined HAVE_BPF && !defined INJECT_METHOD #undef INJECT_METHOD #define INJECT_METHOD "bpf send()" #include -#include -#include #include -#include #include // used for get_hwaddr_bpf() +#include +#include +#include static sendpacket_t *sendpacket_open_bpf(const char *, char *) _U_; static struct tcpr_ether_addr *sendpacket_get_hwaddr_bpf(sendpacket_t *) _U_; #endif /* HAVE_BPF */ -#if defined HAVE_LIBDNET && ! defined INJECT_METHOD +#if defined HAVE_LIBDNET && !defined INJECT_METHOD #undef INJECT_METHOD #define INJECT_METHOD "libdnet eth_send()" /* need to undef these which are pulled in via defines.h, prior to importing dnet.h */ @@ -199,22 +198,23 @@ static sendpacket_t *sendpacket_open_libdnet(const char *, char *) _U_; static struct tcpr_ether_addr *sendpacket_get_hwaddr_libdnet(sendpacket_t *) _U_; #endif /* HAVE_LIBDNET */ -#if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) && !(defined HAVE_PF_PACKET || defined BPF || defined HAVE_LIBDNET) +#if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) && \ + !(defined HAVE_PF_PACKET || defined BPF || defined HAVE_LIBDNET) static sendpacket_t *sendpacket_open_pcap(const char *, char *) _U_; static struct tcpr_ether_addr *sendpacket_get_hwaddr_pcap(sendpacket_t *) _U_; #endif /* HAVE_PCAP_INJECT || HAVE_PACKET_SENDPACKET */ -#if defined HAVE_PCAP_INJECT && ! defined INJECT_METHOD +#if defined HAVE_PCAP_INJECT && !defined INJECT_METHOD #undef INJECT_METHOD #define INJECT_METHOD "pcap_inject()" -#elif defined HAVE_PCAP_SENDPACKET && ! defined INJECT_METHOD +#elif defined HAVE_PCAP_SENDPACKET && !defined INJECT_METHOD #undef INJECT_METHOD #define INJECT_METHOD "pcap_sendpacket()" #endif static void sendpacket_seterr(sendpacket_t *sp, const char *fmt, ...); -static sendpacket_t * sendpacket_open_khial(const char *, char *) _U_; -static struct tcpr_ether_addr * sendpacket_get_hwaddr_khial(sendpacket_t *) _U_; +static sendpacket_t *sendpacket_open_khial(const char *, char *) _U_; +static struct tcpr_ether_addr *sendpacket_get_hwaddr_khial(sendpacket_t *) _U_; /** * returns number of bytes sent on success or -1 on error @@ -243,223 +243,230 @@ sendpacket(sendpacket_t *sp, const u_char *data, size_t len, struct pcap_pkthdr return -1; TRY_SEND_AGAIN: - sp->attempt ++; + sp->attempt++; switch (sp->handle_type) { - case SP_TYPE_KHIAL: - - memcpy(buffer, pkthdr, sizeof(struct pcap_pkthdr)); - memcpy(buffer + sizeof(struct pcap_pkthdr), data, min(len, buffer_payload_size)); - - /* tell the kernel module which direction the traffic is going */ - if (sp->cache_dir == TCPR_DIR_C2S) { /* aka PRIMARY */ - val = KHIAL_DIRECTION_RX; - if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { - sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", - sp->device, strerror(errno), errno); - return -1; - } - } else if (sp->cache_dir == TCPR_DIR_S2C) { - val = KHIAL_DIRECTION_TX; - if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { - sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", - sp->device, strerror(errno), errno); - return -1; - } - } + case SP_TYPE_KHIAL: - /* write the pkthdr + packet data all at once */ - retcode = write(sp->handle.fd, (void *)buffer, sizeof(struct pcap_pkthdr) + len); - retcode -= sizeof(struct pcap_pkthdr); /* only record packet bytes we sent, not pcap data too */ - - if (retcode < 0 && !sp->abort) { - switch(errno) { - case EAGAIN: - sp->retry_eagain ++; - goto TRY_SEND_AGAIN; - break; - case ENOBUFS: - sp->retry_enobufs ++; - goto TRY_SEND_AGAIN; - break; - default: - sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", - "khial", sp->sent + sp->failed + 1, strerror(errno), errno); - } - break; + memcpy(buffer, pkthdr, sizeof(struct pcap_pkthdr)); + memcpy(buffer + sizeof(struct pcap_pkthdr), data, min(len, buffer_payload_size)); + + /* tell the kernel module which direction the traffic is going */ + if (sp->cache_dir == TCPR_DIR_C2S) { /* aka PRIMARY */ + val = KHIAL_DIRECTION_RX; + if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { + sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", sp->device, strerror(errno), errno); + return -1; + } + } else if (sp->cache_dir == TCPR_DIR_S2C) { + val = KHIAL_DIRECTION_TX; + if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { + sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", sp->device, strerror(errno), errno); + return -1; } + } - break; + /* write the pkthdr + packet data all at once */ + retcode = (int)write(sp->handle.fd, (void *)buffer, sizeof(struct pcap_pkthdr) + len); + retcode -= sizeof(struct pcap_pkthdr); /* only record packet bytes we sent, not pcap data too */ - case SP_TYPE_TUNTAP: - retcode = write(sp->handle.fd, (void *)data, len); + if (retcode < 0 && !sp->abort) { + switch (errno) { + case EAGAIN: + sp->retry_eagain++; + goto TRY_SEND_AGAIN; + case ENOBUFS: + sp->retry_enobufs++; + goto TRY_SEND_AGAIN; + default: + sendpacket_seterr(sp, + "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", + "khial", + sp->sent + sp->failed + 1, + strerror(errno), + errno); + } break; + } + + break; + + case SP_TYPE_TUNTAP: + retcode = (int)write(sp->handle.fd, (void *)data, len); + break; - /* Linux PF_PACKET and TX_RING */ - case SP_TYPE_PF_PACKET: - case SP_TYPE_TX_RING: + /* Linux PF_PACKET and TX_RING */ + case SP_TYPE_PF_PACKET: + case SP_TYPE_TX_RING: #if defined HAVE_PF_PACKET #ifdef HAVE_TX_RING - retcode = (int)txring_put(sp->tx_ring, data, len); + retcode = (int)txring_put(sp->tx_ring, data, len); #else - retcode = (int)send(sp->handle.fd, (void *)data, len, 0); + retcode = (int)send(sp->handle.fd, (void *)data, len, 0); #endif - /* out of buffers, or hit max PHY speed, silently retry - * as long as we're not told to abort - */ - if (retcode < 0 && !sp->abort) { - switch (errno) { - case EAGAIN: - sp->retry_eagain ++; - goto TRY_SEND_AGAIN; - break; - case ENOBUFS: - sp->retry_enobufs ++; - goto TRY_SEND_AGAIN; - break; - - default: - sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", - INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); - } + /* out of buffers, or hit max PHY speed, silently retry + * as long as we're not told to abort + */ + if (retcode < 0 && !sp->abort) { + switch (errno) { + case EAGAIN: + sp->retry_eagain++; + goto TRY_SEND_AGAIN; + case ENOBUFS: + sp->retry_enobufs++; + goto TRY_SEND_AGAIN; + default: + sendpacket_seterr(sp, + "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", + INJECT_METHOD, + sp->sent + sp->failed + 1, + strerror(errno), + errno); } + } #endif /* HAVE_PF_PACKET */ - break; - + break; - /* BPF */ - case SP_TYPE_BPF: + /* BPF */ + case SP_TYPE_BPF: #if defined HAVE_BPF - retcode = write(sp->handle.fd, (void *)data, len); - - /* out of buffers, or hit max PHY speed, silently retry */ - if (retcode < 0 && !sp->abort) { - switch (errno) { - case EAGAIN: - sp->retry_eagain ++; - goto TRY_SEND_AGAIN; - break; - - case ENOBUFS: - sp->retry_enobufs ++; - goto TRY_SEND_AGAIN; - break; - - default: - sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", - INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); - } + retcode = write(sp->handle.fd, (void *)data, len); + + /* out of buffers, or hit max PHY speed, silently retry */ + if (retcode < 0 && !sp->abort) { + switch (errno) { + case EAGAIN: + sp->retry_eagain++; + goto TRY_SEND_AGAIN; + break; + + case ENOBUFS: + sp->retry_enobufs++; + goto TRY_SEND_AGAIN; + break; + + default: + sendpacket_seterr(sp, + "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", + INJECT_METHOD, + sp->sent + sp->failed + 1, + strerror(errno), + errno); } + } #endif - break; + break; - /* Libdnet */ - case SP_TYPE_LIBDNET: + /* Libdnet */ + case SP_TYPE_LIBDNET: #if defined HAVE_LIBDNET - retcode = eth_send(sp->handle.ldnet, (void*)data, (size_t)len); - - /* out of buffers, or hit max PHY speed, silently retry */ - if (retcode < 0 && !sp->abort) { - switch (errno) { - case EAGAIN: - sp->retry_eagain ++; - goto TRY_SEND_AGAIN; - break; - - case ENOBUFS: - sp->retry_enobufs ++; - goto TRY_SEND_AGAIN; - break; - - default: - sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", - INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); - } + retcode = eth_send(sp->handle.ldnet, (void *)data, (size_t)len); + + /* out of buffers, or hit max PHY speed, silently retry */ + if (retcode < 0 && !sp->abort) { + switch (errno) { + case EAGAIN: + sp->retry_eagain++; + goto TRY_SEND_AGAIN; + break; + + case ENOBUFS: + sp->retry_enobufs++; + goto TRY_SEND_AGAIN; + break; + + default: + sendpacket_seterr(sp, + "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", + INJECT_METHOD, + sp->sent + sp->failed + 1, + strerror(errno), + errno); } + } #endif - break; + break; - case SP_TYPE_LIBPCAP: + case SP_TYPE_LIBPCAP: #if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) #if defined HAVE_PCAP_INJECT - /* - * pcap methods don't seem to support ENOBUFS, so we just straight fail - * is there a better way??? - */ - retcode = pcap_inject(sp->handle.pcap, (void*)data, len); + /* + * pcap methods don't seem to support ENOBUFS, so we just straight fail + * is there a better way??? + */ + retcode = pcap_inject(sp->handle.pcap, (void *)data, len); #elif defined HAVE_PCAP_SENDPACKET - retcode = pcap_sendpacket(sp->handle.pcap, data, (int)len); + retcode = pcap_sendpacket(sp->handle.pcap, data, (int)len); #endif - /* out of buffers, or hit max PHY speed, silently retry */ - if (retcode < 0 && !sp->abort) { - switch (errno) { - case EAGAIN: - sp->retry_eagain ++; - goto TRY_SEND_AGAIN; - break; - - case ENOBUFS: - sp->retry_enobufs ++; - goto TRY_SEND_AGAIN; - break; - - default: - sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", - INJECT_METHOD, sp->sent + sp->failed + 1, pcap_geterr(sp->handle.pcap), errno); - } + /* out of buffers, or hit max PHY speed, silently retry */ + if (retcode < 0 && !sp->abort) { + switch (errno) { + case EAGAIN: + sp->retry_eagain++; + goto TRY_SEND_AGAIN; + case ENOBUFS: + sp->retry_enobufs++; + goto TRY_SEND_AGAIN; + default: + sendpacket_seterr(sp, + "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", + INJECT_METHOD, + sp->sent + sp->failed + 1, + pcap_geterr(sp->handle.pcap), + errno); } + } #if defined HAVE_PCAP_SENDPACKET - /* - * pcap_sendpacket returns 0 on success, not the packet length! - * hence, we have to fix retcode to be more standard on success - */ - if (retcode == 0) - retcode = len; + /* + * pcap_sendpacket returns 0 on success, not the packet length! + * hence, we have to fix retcode to be more standard on success + */ + if (retcode == 0) + retcode = (int)len; #endif /* HAVE_PCAP_SENDPACKET */ #endif /* HAVE_PCAP_INJECT || HAVE_PCAP_SENDPACKET */ - break; + break; - case SP_TYPE_NETMAP: + case SP_TYPE_NETMAP: #ifdef HAVE_NETMAP - retcode = sendpacket_send_netmap(sp, data, len); - - if (retcode == -1) { - sendpacket_seterr(sp, "interface hung!!"); - } else if (retcode == -2) { - /* this indicates that a retry was requested - this is not a failure */ - sp->retry_eagain ++; - retcode = 0; + retcode = sendpacket_send_netmap(sp, data, len); + + if (retcode == -1) { + sendpacket_seterr(sp, "interface hung!!"); + } else if (retcode == -2) { + /* this indicates that a retry was requested - this is not a failure */ + sp->retry_eagain++; + retcode = 0; #ifdef HAVE_SCHED_H - /* yield the CPU so other apps remain responsive */ - sched_yield(); + /* yield the CPU so other apps remain responsive */ + sched_yield(); #endif - goto TRY_SEND_AGAIN; - } + goto TRY_SEND_AGAIN; + } #endif /* HAVE_NETMAP */ - break; + break; - default: - errx(-1, "Unsupported sp->handle_type = %d", sp->handle_type); + default: + errx(-1, "Unsupported sp->handle_type = %d", sp->handle_type); } /* end case */ if (retcode < 0) { - sp->failed ++; + sp->failed++; } else if (sp->abort) { sendpacket_seterr(sp, "User abort"); } else if (retcode != (int)len) { - sendpacket_seterr(sp, "Only able to write %d bytes out of %u bytes total", - retcode, len); - sp->trunc_packets ++; + sendpacket_seterr(sp, "Only able to write %d bytes out of %lu bytes total", retcode, len); + sp->trunc_packets++; } else { sp->bytes_sent += len; - sp->sent ++; + sp->sent++; } return retcode; } @@ -470,8 +477,11 @@ sendpacket(sendpacket_t *sp, const u_char *data, size_t len, struct pcap_pkthdr * that this interface represents */ sendpacket_t * -sendpacket_open(const char *device, char *errbuf, tcpr_dir_t direction, - sendpacket_type_t sendpacket_type _U_, void *arg _U_) +sendpacket_open(const char *device, + char *errbuf, + tcpr_dir_t direction, + sendpacket_type_t sendpacket_type _U_, + void *arg _U_) { #ifdef HAVE_TUNTAP char sys_dev_dir[128]; @@ -492,37 +502,24 @@ sendpacket_open(const char *device, char *errbuf, tcpr_dir_t direction, /* khial is universal */ if (stat(device, &sdata) == 0) { - if (((sdata.st_mode & S_IFMT) == S_IFCHR)) { - + if (((sdata.st_mode & S_IFMT) == S_IFCHR)) { sp = sendpacket_open_khial(device, errbuf); } else { switch (sdata.st_mode & S_IFMT) { - case S_IFBLK: - errx(-1, "\"%s\" is a block device and is not a valid Tcpreplay device", - device); - break; - case S_IFDIR: - errx(-1, "\"%s\" is a directory and is not a valid Tcpreplay device", - device); - break; - case S_IFIFO: - errx(-1, "\"%s\" is a FIFO and is not a valid Tcpreplay device", - device); - break; - case S_IFLNK: - errx(-1, "\"%s\" is a symbolic link and is not a valid Tcpreplay device", - device); - break; - case S_IFREG: - errx(-1, "\"%s\" is a file and is not a valid Tcpreplay device", - device); - break; - default: - errx(-1, "\"%s\" is not a valid Tcpreplay device", - device); - break; - } + case S_IFBLK: + errx(-1, "\"%s\" is a block device and is not a valid Tcpreplay device", device); + case S_IFDIR: + errx(-1, "\"%s\" is a directory and is not a valid Tcpreplay device", device); + case S_IFIFO: + errx(-1, "\"%s\" is a FIFO and is not a valid Tcpreplay device", device); + case S_IFLNK: + errx(-1, "\"%s\" is a symbolic link and is not a valid Tcpreplay device", device); + case S_IFREG: + errx(-1, "\"%s\" is a file and is not a valid Tcpreplay device", device); + default: + errx(-1, "\"%s\" is not a valid Tcpreplay device", device); + } } #ifdef HAVE_TUNTAP } else if (strncmp(device, "tap", 3) == 0 && !device_exists) { @@ -531,17 +528,17 @@ sendpacket_open(const char *device, char *errbuf, tcpr_dir_t direction, } else { #ifdef HAVE_NETMAP if (sendpacket_type == SP_TYPE_NETMAP) - sp = (sendpacket_t*)sendpacket_open_netmap(device, errbuf, arg); + sp = (sendpacket_t *)sendpacket_open_netmap(device, errbuf, arg); else #endif #if defined HAVE_PF_PACKET sp = sendpacket_open_pf(device, errbuf); #elif defined HAVE_BPF - sp = sendpacket_open_bpf(device, errbuf); + sp = sendpacket_open_bpf(device, errbuf); #elif defined HAVE_LIBDNET - sp = sendpacket_open_libdnet(device, errbuf); + sp = sendpacket_open_libdnet(device, errbuf); #elif (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) - sp = sendpacket_open_pcap(device, errbuf); + sp = sendpacket_open_pcap(device, errbuf); #else #error "No defined packet injection method for sendpacket_open()" #endif @@ -568,25 +565,36 @@ sendpacket_getstat(sendpacket_t *sp, char *buf, size_t buf_size) assert(buf); memset(buf, 0, buf_size); - offset = snprintf(buf, buf_size, "Statistics for network device: %s\n" - "\tSuccessful packets: " COUNTER_SPEC "\n" - "\tFailed packets: " COUNTER_SPEC "\n" - "\tTruncated packets: " COUNTER_SPEC "\n" - "\tRetried packets (ENOBUFS): " COUNTER_SPEC "\n" - "\tRetried packets (EAGAIN): " COUNTER_SPEC "\n", - sp->device, sp->sent, sp->failed, sp->trunc_packets, - sp->retry_enobufs, sp->retry_eagain); + offset = snprintf(buf, + buf_size, + "Statistics for network device: %s\n" + "\tSuccessful packets: " COUNTER_SPEC "\n" + "\tFailed packets: " COUNTER_SPEC "\n" + "\tTruncated packets: " COUNTER_SPEC "\n" + "\tRetried packets (ENOBUFS): " COUNTER_SPEC "\n" + "\tRetried packets (EAGAIN): " COUNTER_SPEC "\n", + sp->device, + sp->sent, + sp->failed, + sp->trunc_packets, + sp->retry_enobufs, + sp->retry_eagain); if (sp->flow_packets && offset > 0) { - offset += snprintf(&buf[offset], buf_size - offset, - "\tFlows total: " COUNTER_SPEC "\n" - "\tFlows unique: " COUNTER_SPEC "\n" - "\tFlows expired: " COUNTER_SPEC "\n" - "\tFlow packets: " COUNTER_SPEC "\n" - "\tNon-flow packets: " COUNTER_SPEC "\n" - "\tInvalid flow packets: " COUNTER_SPEC "\n", - sp->flows, sp->flows_expired, sp->flows_expired, sp->flow_packets, - sp->flow_non_flow_packets, sp->flows_invalid_packets); + offset += snprintf(&buf[offset], + buf_size - offset, + "\tFlows total: " COUNTER_SPEC "\n" + "\tFlows unique: " COUNTER_SPEC "\n" + "\tFlows expired: " COUNTER_SPEC "\n" + "\tFlow packets: " COUNTER_SPEC "\n" + "\tNon-flow packets: " COUNTER_SPEC "\n" + "\tInvalid flow packets: " COUNTER_SPEC "\n", + sp->flows, + sp->flows_expired, + sp->flows_expired, + sp->flow_packets, + sp->flow_non_flow_packets, + sp->flows_invalid_packets); } return offset; @@ -599,54 +607,50 @@ void sendpacket_close(sendpacket_t *sp) { assert(sp); - switch(sp->handle_type) { - case SP_TYPE_KHIAL: - close(sp->handle.fd); - break; + switch (sp->handle_type) { + case SP_TYPE_KHIAL: + close(sp->handle.fd); + break; - case SP_TYPE_BPF: + case SP_TYPE_BPF: #if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) - close(sp->handle.fd); + close(sp->handle.fd); #endif - break; + break; - case SP_TYPE_PF_PACKET: - case SP_TYPE_TX_RING: + case SP_TYPE_PF_PACKET: + case SP_TYPE_TX_RING: #ifdef HAVE_PF_PACKET - close(sp->handle.fd); + close(sp->handle.fd); #endif - break; + break; - case SP_TYPE_LIBPCAP: + case SP_TYPE_LIBPCAP: #ifdef HAVE_LIBPCAP - pcap_close(sp->handle.pcap); + pcap_close(sp->handle.pcap); #endif - break; + break; - case SP_TYPE_LIBDNET: -#ifdef HAVE_LIBDNET - eth_close(sp->handle.ldnet); + case SP_TYPE_LIBDNET: +#ifdef HAVE_LIBDNET + eth_close(sp->handle.ldnet); #endif - break; - - case SP_TYPE_LIBNET: - err(-1, "Libnet is no longer supported!"); - break; + break; - case SP_TYPE_NETMAP: + case SP_TYPE_LIBNET: + err(-1, "Libnet is no longer supported!"); + case SP_TYPE_NETMAP: #ifdef HAVE_NETMAP - sendpacket_close_netmap(sp); + sendpacket_close_netmap(sp); #endif /* HAVE_NETMAP */ - break; - - case SP_TYPE_TUNTAP: + break; + case SP_TYPE_TUNTAP: #ifdef HAVE_TUNTAP - close(sp->handle.fd); + close(sp->handle.fd); #endif - break; - case SP_TYPE_NONE: - err(-1, "no injector selected!"); - break; + break; + case SP_TYPE_NONE: + err(-1, "no injector selected!"); } safe_free(sp); } @@ -667,7 +671,7 @@ sendpacket_get_hwaddr(sendpacket_t *sp) if (sp->handle_type == SP_TYPE_KHIAL) { addr = sendpacket_get_hwaddr_khial(sp); - } else { + } else { #if defined HAVE_PF_PACKET addr = sendpacket_get_hwaddr_pf(sp); #elif defined HAVE_BPF @@ -706,11 +710,11 @@ sendpacket_seterr(sendpacket_t *sp, const char *fmt, ...) (void)vsnprintf(sp->errbuf, SENDPACKET_ERRBUF_SIZE, fmt, ap); va_end(ap); - sp->errbuf[(SENDPACKET_ERRBUF_SIZE-1)] = '\0'; // be safe + sp->errbuf[(SENDPACKET_ERRBUF_SIZE - 1)] = '\0'; // be safe } - -#if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) && !(defined HAVE_PF_PACKET || defined BPF || defined HAVE_LIBDNET) +#if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) && \ + !(defined HAVE_PF_PACKET || defined BPF || defined HAVE_LIBDNET) /** * Inner sendpacket_open() method for using libpcap */ @@ -738,8 +742,8 @@ sendpacket_open_pcap(const char *device, char *errbuf) sp->handle.pcap = pcap; #ifdef BIOCSHDRCMPLT - /* - * Only systems using BPF on the backend need this... + /* + * Only systems using BPF on the backend need this... * other systems don't have ioctl and will get compile errors. */ fd = pcap_get_selectable_fd(pcap); @@ -767,7 +771,7 @@ sendpacket_get_hwaddr_pcap(sendpacket_t *sp) /** * Inner sendpacket_open() method for using libdnet */ -static sendpacket_t * +static sendpacket_t * sendpacket_open_libdnet(const char *device, char *errbuf) { eth_t *ldnet; @@ -784,8 +788,8 @@ sendpacket_open_libdnet(const char *device, char *errbuf) sp = (sendpacket_t *)safe_malloc(sizeof(sendpacket_t)); strlcpy(sp->device, device, sizeof(sp->device)); sp->handle.ldnet = ldnet; - sp->handle_type = SP_TYPE_LIBDNET; - return sp; + sp->handle_type = SP_TYPE_LIBDNET; + return sp; } /** @@ -806,7 +810,7 @@ sendpacket_get_hwaddr_libdnet(sendpacket_t *sp) } memcpy(&sp->ether, addr, sizeof(struct tcpr_ether_addr)); - return(&sp->ether); + return (&sp->ether); } #endif /* HAVE_LIBDNET */ @@ -831,9 +835,9 @@ sendpacket_open_tuntap(const char *device, char *errbuf) } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = (IFF_TAP | IFF_NO_PI); - strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name)-1); + strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name) - 1); - if (ioctl(tapfd, TUNSETIFF, (void *) &ifr) < 0) { + if (ioctl(tapfd, TUNSETIFF, (void *)&ifr) < 0) { snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to create tuntap interface: %s", device); close(tapfd); return NULL; @@ -923,15 +927,13 @@ sendpacket_open_pf(const char *device, char *errbuf) /* check for errors, network down, etc... */ if (getsockopt(mysocket, SOL_SOCKET, SO_ERROR, &err, &errlen) < 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "error opening %s: %s", device, - strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "error opening %s: %s", device, strerror(errno)); close(mysocket); return NULL; } if (err > 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "error opening %s: %s", device, - strerror(err)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "error opening %s: %s", device, strerror(err)); close(mysocket); return NULL; } @@ -942,15 +944,16 @@ sendpacket_open_pf(const char *device, char *errbuf) if (ioctl(mysocket, SIOCGIFHWADDR, &ifr) < 0) { close(mysocket); - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Error getting hardware type: %s", - strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Error getting hardware type: %s", strerror(errno)); return NULL; } /* make sure it's not loopback (PF_PACKET doesn't support it) */ if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) warnx("Unsupported physical layer type 0x%04x on %s. Maybe it works, maybe it won't." - " See tickets #123/318", ifr.ifr_hwaddr.sa_family, device); + " See tickets #123/318", + ifr.ifr_hwaddr.sa_family, + device); #ifdef SO_BROADCAST /* @@ -962,12 +965,11 @@ sendpacket_open_pf(const char *device, char *errbuf) * effect on stream-oriented sockets. */ if (setsockopt(mysocket, SOL_SOCKET, SO_BROADCAST, &n, sizeof(n)) == -1) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, - "SO_BROADCAST: %s", strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "SO_BROADCAST: %s", strerror(errno)); close(mysocket); return NULL; } -#endif /* SO_BROADCAST */ +#endif /* SO_BROADCAST */ /* prep & return our sp handle */ sp = (sendpacket_t *)safe_malloc(sizeof(sendpacket_t)); @@ -987,7 +989,7 @@ sendpacket_open_pf(const char *device, char *errbuf) mtu = ifr.ifr_ifru.ifru_mtu; /* Init TX ring for sp->handle.fd socket */ - if ((sp->tx_ring = txring_init(sp->handle.fd, mtu)) == 0) { + if ((sp->tx_ring = txring_init(sp->handle.fd, mtu)) == 0) { snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "txring_init: %s", strerror(errno)); close(mysocket); return NULL; @@ -1003,7 +1005,8 @@ sendpacket_open_pf(const char *device, char *errbuf) * get the interface index (necessary for sending packets w/ PF_PACKET) */ static int -get_iface_index(int fd, const char *device, char *errbuf) { +get_iface_index(int fd, const char *device, char *errbuf) +{ struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); @@ -1033,7 +1036,6 @@ sendpacket_get_hwaddr_pf(sendpacket_t *sp) return NULL; } - /* create dummy socket for ioctl */ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { sendpacket_seterr(sp, "Unable to open dummy socket for get_hwaddr: %s", strerror(errno)); @@ -1051,7 +1053,7 @@ sendpacket_get_hwaddr_pf(sendpacket_t *sp) memcpy(&sp->ether, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN); close(fd); - return(&sp->ether); + return (&sp->ether); } #endif /* HAVE_PF_PACKET */ @@ -1079,7 +1081,7 @@ sendpacket_open_bpf(const char *device, char *errbuf) dbg(1, "sendpacket_open_bpf: using BPF"); /* open socket */ mysocket = -1; - for (dev = 0; dev < 512; dev ++) { + for (dev = 0; dev < 512; dev++) { memset(bpf_dev, '\0', sizeof(bpf_dev)); snprintf(bpf_dev, sizeof(bpf_dev), "/dev/bpf%d", dev); dbgx(3, "sendpacket_open_bpf: attempting to open %s", bpf_dev); @@ -1092,9 +1094,8 @@ sendpacket_open_bpf(const char *device, char *errbuf) /* error?? */ if (mysocket < 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, - "Unable to open /dev/bpfX: %s", strerror(errno)); - errbuf[SENDPACKET_ERRBUF_SIZE -1] = '\0'; + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to open /dev/bpfX: %s", strerror(errno)); + errbuf[SENDPACKET_ERRBUF_SIZE - 1] = '\0'; return NULL; } @@ -1112,15 +1113,13 @@ sendpacket_open_bpf(const char *device, char *errbuf) /* attach to device */ strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name)); if (ioctl(mysocket, BIOCSETIF, (caddr_t)&ifr) < 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to bind %s to %s: %s", - bpf_dev, device, strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to bind %s to %s: %s", bpf_dev, device, strerror(errno)); return NULL; } /* get datalink type */ if (ioctl(mysocket, BIOCGDLT, (caddr_t)&v) < 0) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to get datalink type: %s", - strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to get datalink type: %s", strerror(errno)); return NULL; } @@ -1130,8 +1129,7 @@ sendpacket_open_bpf(const char *device, char *errbuf) */ #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT) if (ioctl(mysocket, BIOCSHDRCMPLT, &spoof_eth_src) == -1) { - snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, - "Unable to enable spoofing src MAC: %s", strerror(errno)); + snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "Unable to enable spoofing src MAC: %s", strerror(errno)); return NULL; } #endif @@ -1171,8 +1169,8 @@ sendpacket_open_bpf(const char *device, char *errbuf) sp = (sendpacket_t *)safe_malloc(sizeof(sendpacket_t)); strlcpy(sp->device, device, sizeof(sp->device)); sp->handle.fd = mysocket; - //sp->link_type = link_type; - //sp->link_offset = link_offset; + // sp->link_type = link_type; + // sp->link_offset = link_offset; sp->handle_type = SP_TYPE_BPF; return sp; @@ -1224,7 +1222,7 @@ sendpacket_get_hwaddr_bpf(sendpacket_t *sp) } } safe_free(buf); - return(&sp->ether); + return (&sp->ether); } #endif /* HAVE_BPF */ @@ -1238,31 +1236,28 @@ sendpacket_get_dlt(sendpacket_t *sp) { int dlt = DLT_EN10MB; - if (sp->handle_type == SP_TYPE_KHIAL || - sp->handle_type == SP_TYPE_NETMAP || - sp->handle_type == SP_TYPE_TUNTAP) { + if (sp->handle_type == SP_TYPE_KHIAL || sp->handle_type == SP_TYPE_NETMAP || sp->handle_type == SP_TYPE_TUNTAP) { /* always EN10MB */ - ; } else { #if defined HAVE_BPF - int rcode; + int rcode; - if ((rcode = ioctl(sp->handle.fd, BIOCGDLT, &dlt)) < 0) { - warnx("Unable to get DLT value for BPF device (%s): %s", sp->device, strerror(errno)); - return(-1); - } + if ((rcode = ioctl(sp->handle.fd, BIOCGDLT, &dlt)) < 0) { + warnx("Unable to get DLT value for BPF device (%s): %s", sp->device, strerror(errno)); + return (-1); + } #elif defined HAVE_PF_PACKET || defined HAVE_LIBDNET - /* use libpcap to get dlt */ - pcap_t *pcap; - char errbuf[PCAP_ERRBUF_SIZE]; - if ((pcap = pcap_open_live(sp->device, 65535, 0, 0, errbuf)) == NULL) { - warnx("Unable to get DLT value for %s: %s", sp->device, errbuf); - return(-1); - } - dlt = pcap_datalink(pcap); - pcap_close(pcap); + /* use libpcap to get dlt */ + pcap_t *pcap; + char errbuf[PCAP_ERRBUF_SIZE]; + if ((pcap = pcap_open_live(sp->device, 65535, 0, 0, errbuf)) == NULL) { + warnx("Unable to get DLT value for %s: %s", sp->device, errbuf); + return (-1); + } + dlt = pcap_datalink(pcap); + pcap_close(pcap); #elif defined HAVE_PCAP_SENDPACKET || defined HAVE_PCAP_INJECT - dlt = pcap_datalink(sp->handle.pcap); + dlt = pcap_datalink(sp->handle.pcap); #endif } return dlt; @@ -1286,7 +1281,7 @@ sendpacket_get_method(sendpacket_t *sp) } /** - * Opens a character device for injecting packets directly into + * Opens a character device for injecting packets directly into * your kernel via a custom driver */ static sendpacket_t * @@ -1298,7 +1293,7 @@ sendpacket_open_khial(const char *device, char *errbuf) assert(device); assert(errbuf); - if ((mysocket = open(device, O_WRONLY|O_EXCL)) < 0) { + if ((mysocket = open(device, O_WRONLY | O_EXCL)) < 0) { snprintf(errbuf, SENDPACKET_ERRBUF_SIZE, "error opening khial device: %s", strerror(errno)); return NULL; } @@ -1308,7 +1303,6 @@ sendpacket_open_khial(const char *device, char *errbuf) sp->handle.fd = mysocket; sp->handle_type = SP_TYPE_KHIAL; - return sp; } diff --git a/src/common/sendpacket.h b/src/common/sendpacket.h index 248b87f2e..e1dd6a424 100644 --- a/src/common/sendpacket.h +++ b/src/common/sendpacket.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" -#include "defines.h" +#pragma once +#include "defines.h" +#include "config.h" #include #ifdef __NetBSD__ @@ -56,9 +57,6 @@ #endif #endif -#ifndef _SENDPACKET_H_ -#define _SENDPACKET_H_ - typedef enum sendpacket_type_e { SP_TYPE_NONE, SP_TYPE_LIBNET, @@ -73,8 +71,8 @@ typedef enum sendpacket_type_e { } sendpacket_type_t; /* these are the file_operations ioctls */ -#define KHIAL_SET_DIRECTION (0x1) -#define KHIAL_GET_DIRECTION (0x2) +#define KHIAL_SET_DIRECTION (0x1) +#define KHIAL_GET_DIRECTION (0x2) /* these are the directions */ typedef enum khial_direction_e { @@ -82,7 +80,6 @@ typedef enum khial_direction_e { KHIAL_DIRECTION_TX, } khial_direction_t; - union sendpacket_handle { pcap_t *pcap; int fd; @@ -92,7 +89,7 @@ union sendpacket_handle { }; #define SENDPACKET_ERRBUF_SIZE 1024 -#define MAX_IFNAMELEN 64 +#define MAX_IFNAMELEN 64 struct sendpacket_s { tcpr_dir_t cache_dir; @@ -128,7 +125,6 @@ struct sendpacket_s { uint32_t if_flags; uint32_t is_vale; int netmap_version; - int tx_timeouts; uint16_t first_tx_ring, last_tx_ring, cur_tx_ring; #ifdef linux uint32_t data; @@ -142,7 +138,7 @@ struct sendpacket_s { #ifdef HAVE_PF_PACKET struct sockaddr_ll sa; #ifdef HAVE_TX_RING - txring_t * tx_ring; + txring_t *tx_ring; #endif #endif bool abort; @@ -159,7 +155,3 @@ struct tcpr_ether_addr *sendpacket_get_hwaddr(sendpacket_t *); int sendpacket_get_dlt(sendpacket_t *); const char *sendpacket_get_method(sendpacket_t *); void sendpacket_abort(sendpacket_t *); - -#endif /* _SENDPACKET_H_ */ - - diff --git a/src/common/services.c b/src/common/services.c index 1eb3babad..76b92599f 100644 --- a/src/common/services.c +++ b/src/common/services.c @@ -22,7 +22,6 @@ #include "defines.h" #include "common.h" -#include #include #include #include @@ -76,7 +75,7 @@ parse_services(const char *file, tcpr_services_t *services) strncpy(proto, &service_line[pmatch[2].rm_so], (pmatch[2].rm_eo - pmatch[2].rm_so)); /* convert port[] into an integer */ - portc = (uint16_t)atoi(port); + portc = (uint16_t)strtol(port, NULL, 10); /* update appropriate service array with the server port */ if (strcmp(proto, "tcp") == 0) { diff --git a/src/common/services.h b/src/common/services.h index 760f7d39b..a632df23a 100644 --- a/src/common/services.h +++ b/src/common/services.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __SERVICES_H__ -#define __SERVICES_H__ +#pragma once void parse_services(const char *file, tcpr_services_t *services); /* max width of a line in /etc/services */ #define MAXLINE 1024 - -#endif diff --git a/src/common/tcpdump.c b/src/common/tcpdump.c index 5b914e24c..637af8399 100644 --- a/src/common/tcpdump.c +++ b/src/common/tcpdump.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -32,27 +32,21 @@ * Lawrence Berkeley Laboratory and its contributors */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include #include +#include #include -#include -#include #include -#include -#include +#include #ifdef HAVE_SIGNAL_H #include #endif #include "tcpdump.h" -#ifdef DEBUG -extern int debug; -#endif - char *options_vec[OPTIONS_VEC_SIZE]; static int tcpdump_fill_in_options(char *opt); static int can_exec(const char *filename); @@ -71,8 +65,8 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data uint32_t ts_sec; uint32_t ts_usec; } ts; - uint32_t caplen; /* length of portion present */ - uint32_t len; /* length this packet (off wire) */ + uint32_t caplen; /* length of portion present */ + uint32_t len; /* length this packet (off wire) */ } actual_pkthdr; assert(tcpdump); @@ -94,30 +88,30 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data /* wait until we can write the header to the tcpdump pipe */ res = poll(&poller, 1, TCPDUMP_POLL_TIMEOUT); if (res < 0) - errx(-1, "Error writing header to fd %d during poll() to write to tcpdump\n%s", - PARENT_WRITE_FD, strerror(errno)); + errx(-1, + "Error writing header to fd %d during poll() to write to tcpdump\n%s", + PARENT_WRITE_FD, + strerror(errno)); if (res == 0) - err(-1, "poll() timeout... tcpdump seems to be having a problem keeping up\n" + err(-1, + "poll() timeout... tcpdump seems to be having a problem keeping up\n" "Try increasing TCPDUMP_POLL_TIMEOUT"); #ifdef DEBUG if (debug >= 5) { - if (write(tcpdump->debugfd, (char *)&actual_pkthdr, sizeof(actual_pkthdr)) - != sizeof(actual_pkthdr)) + if (write(tcpdump->debugfd, (char *)&actual_pkthdr, sizeof(actual_pkthdr)) != sizeof(actual_pkthdr)) errx(-1, "Error writing pcap file header to tcpdump debug\n%s", strerror(errno)); } #endif /* res > 0 if we get here */ while (total != sizeof(actual_pkthdr) && - (res = write(PARENT_WRITE_FD, &actual_pkthdr + total, - sizeof(actual_pkthdr) - total))) { + (res = (int)write(PARENT_WRITE_FD, &actual_pkthdr + total, sizeof(actual_pkthdr) - total))) { if (res < 0) { if (errno == EAGAIN) goto header_again; - errx(-1, "Error writing pcap file header to tcpdump\n%s", - strerror(errno)); + errx(-1, "Error writing pcap file header to tcpdump\n%s", strerror(errno)); } total += res; @@ -132,11 +126,11 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data res = poll(&poller, 1, TCPDUMP_POLL_TIMEOUT); if (res < 0) - errx(-1, "Error writing to fd %d during poll() to write to tcpdump\n%s", - PARENT_WRITE_FD, strerror(errno)); + errx(-1, "Error writing to fd %d during poll() to write to tcpdump\n%s", PARENT_WRITE_FD, strerror(errno)); if (res == 0) - err(-1, "poll() timeout... tcpdump seems to be having a problem keeping up\n" + err(-1, + "poll() timeout... tcpdump seems to be having a problem keeping up\n" "Try increasing TCPDUMP_POLL_TIMEOUT"); #ifdef DEBUG @@ -147,7 +141,7 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data #endif while (total != (ssize_t)pkthdr->caplen && - (res = write(PARENT_WRITE_FD, data + total, pkthdr->caplen - total))) { + (res = (int)write(PARENT_WRITE_FD, data + total, pkthdr->caplen - total))) { if (res < 0) { if (errno == EAGAIN) goto data_again; @@ -165,14 +159,14 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data res = poll(&poller, 1, TCPDUMP_POLL_TIMEOUT); if (res < 0) - errx(-1, "Error out to fd %d during poll() to read from tcpdump\n%s", - PARENT_READ_FD, strerror(errno)); + errx(-1, "Error out to fd %d during poll() to read from tcpdump\n%s", PARENT_READ_FD, strerror(errno)); if (res == 0) - err(-1, "poll() timeout... tcpdump seems to be having a problem keeping up\n" + err(-1, + "poll() timeout... tcpdump seems to be having a problem keeping up\n" "Try increasing TCPDUMP_POLL_TIMEOUT"); - while ((res = read(PARENT_READ_FD, decode, TCPDUMP_DECODE_LEN))) { + while ((res = (int)read(PARENT_READ_FD, decode, TCPDUMP_DECODE_LEN))) { if (res < 0) { if (errno == EAGAIN) break; @@ -180,7 +174,7 @@ tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data errx(-1, "Error reading tcpdump decode: %s", strerror(errno)); } - decode[min(res, TCPDUMP_DECODE_LEN-1)] = 0; + decode[min(res, TCPDUMP_DECODE_LEN - 1)] = 0; dbgx(4, "read %d byte from tcpdump", res); printf("%s", decode); } @@ -205,17 +199,18 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) } /* is tcpdump executable? */ - if (! can_exec(TCPDUMP_BINARY)) { + if (!can_exec(TCPDUMP_BINARY)) { errx(-1, "Unable to execute tcpdump binary: %s", TCPDUMP_BINARY); } #ifdef DEBUG - strlcpy(tcpdump->debugfile, TCPDUMP_DEBUG, sizeof(tcpdump->debugfile)); - if (debug >= 5) { - dbgx(5, "Opening tcpdump debug file: %s", tcpdump->debugfile); + strlcpy(tcpdump->debugfile, TCPDUMP_DEBUG, sizeof(tcpdump->debugfile)); + if (debug >= 5) { + dbgx(5, "Opening tcpdump debug file: %s", tcpdump->debugfile); - if ((tcpdump->debugfd = open(tcpdump->debugfile, O_WRONLY|O_CREAT|O_TRUNC, - S_IREAD|S_IWRITE|S_IRGRP|S_IROTH)) == -1) { + if ((tcpdump->debugfd = + open(tcpdump->debugfile, O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE | S_IRGRP | S_IROTH)) == + -1) { errx(-1, "Error opening tcpdump debug file: %s\n%s", tcpdump->debugfile, strerror(errno)); } } @@ -228,11 +223,10 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) dbg(2, "Starting tcpdump..."); /* create our pipe to send packet data to tcpdump via */ - if (pipe(tcpdump->pipes[PARENT_READ_PIPE]) < 0 || - pipe(tcpdump->pipes[PARENT_WRITE_PIPE]) < 0) + if (pipe(tcpdump->pipes[PARENT_READ_PIPE]) < 0 || pipe(tcpdump->pipes[PARENT_WRITE_PIPE]) < 0) errx(-1, "Unable to create pipe: %s", strerror(errno)); - if ((tcpdump->pid = fork() ) < 0) + if ((tcpdump->pid = fork()) < 0) errx(-1, "Fork failed: %s", strerror(errno)); dbgx(2, "tcpdump pid: %d", tcpdump->pid); @@ -241,8 +235,7 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) /* parent - we're still in tcpreplay */ /* close fds not required by parent */ - dbgx(2, "[parent] closing child read/write fd %d/%d", CHILD_READ_FD, - CHILD_WRITE_FD); + dbgx(2, "[parent] closing child read/write fd %d/%d", CHILD_READ_FD, CHILD_WRITE_FD); close(CHILD_READ_FD); close(CHILD_WRITE_FD); CHILD_READ_FD = 0; @@ -255,7 +248,7 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) return FALSE; } - pcap_dump_flush((pcap_dumper_t*)writer); + pcap_dump_flush((pcap_dumper_t *)writer); if (fcntl(PARENT_WRITE_FD, F_SETFL, O_NONBLOCK) < 0) warnx("[parent] Unable to fcntl write pipe:\n%s", strerror(errno)); @@ -267,21 +260,18 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) /* we're in the child process - run "tcpdump -r -" */ if (dup2(CHILD_READ_FD, STDIN_FILENO) != STDIN_FILENO) { - errx(-1, "[child] Unable to duplicate socket to stdin: %s", - strerror(errno)); + errx(-1, "[child] Unable to duplicate socket to stdin: %s", strerror(errno)); } if (dup2(CHILD_WRITE_FD, STDOUT_FILENO) != STDOUT_FILENO) { - errx(-1, "[child] Unable to duplicate socket to stdout: %s", - strerror(errno)); + errx(-1, "[child] Unable to duplicate socket to stdout: %s", strerror(errno)); } /* * Close sockets not required by child. The exec'ed program must * not know that they ever existed. */ - dbgx(2, "[child] closing in fds %d/%d/%d/%d", CHILD_READ_FD, - CHILD_WRITE_FD, PARENT_READ_FD, PARENT_WRITE_FD); + dbgx(2, "[child] closing in fds %d/%d/%d/%d", CHILD_READ_FD, CHILD_WRITE_FD, PARENT_READ_FD, PARENT_WRITE_FD); close(CHILD_READ_FD); close(CHILD_WRITE_FD); close(PARENT_READ_FD); @@ -299,12 +289,12 @@ tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap) } /** - * shutdown tcpdump + * shutdown tcpdump */ void tcpdump_close(tcpdump_t *tcpdump) { - if (! tcpdump) + if (!tcpdump) return; if (tcpdump->pid <= 0) @@ -324,21 +314,6 @@ tcpdump_close(tcpdump_t *tcpdump) PARENT_WRITE_FD = 0; } -/** - * forcefully kill tcpdump - */ -void -tcpdump_kill(tcpdump_t *tcpdump) -{ - if (tcpdump->pid) { - if (kill(tcpdump->pid, SIGTERM) != 0) - kill(tcpdump->pid, SIGKILL); - } - - tcpdump->pid = 0; -} - - /** * copy the string of args (*opt) to the vector (**opt_vec) * for a max of opt_len. Returns the number of options @@ -354,10 +329,9 @@ tcpdump_fill_in_options(char *opt) /* zero out our options_vec for execv() */ memset(options_vec, '\0', sizeof(options_vec)); - + /* first arg should be the binary (by convention) */ options_vec[0] = TCPDUMP_BINARY; - /* prep args */ memset(options, '\0', 256); @@ -367,31 +341,27 @@ tcpdump_fill_in_options(char *opt) strlcat(options, TCPDUMP_ARGS, sizeof(options)); dbgx(2, "[child] Will execute: tcpdump %s", options); - /* process args */ - + /* process the first argument */ arg = strtok_r(options, OPT_DELIM, &token); - arglen = strlen(arg) + 2; /* -{arg}\0 */ + arglen = (int)strlen(arg) + 2; /* -{arg}\0 */ newarg = (char *)safe_malloc(arglen); - strlcat(newarg, "-", arglen); + strlcat(newarg, "-", arglen); strlcat(newarg, arg, arglen); options_vec[i++] = newarg; - /* process the remaining args + /* process the remaining args * note that i < OPTIONS_VEC_SIZE - 1 * because: a) we need to add '-' as an option to the end * b) because the array has to be null terminated */ - while (((arg = strtok_r(NULL, OPT_DELIM, &token)) != NULL) && - (i < OPTIONS_VEC_SIZE - 1)) { - - arglen = strlen(arg) + 2; + while (((arg = strtok_r(NULL, OPT_DELIM, &token)) != NULL) && (i < OPTIONS_VEC_SIZE - 1)) { + arglen = (int)strlen(arg) + 2; newarg = (char *)safe_malloc(arglen); strlcat(newarg, "-", arglen); strlcat(newarg, arg, arglen); options_vec[i++] = newarg; - } /* tell -r to read from stdin */ @@ -400,16 +370,17 @@ tcpdump_fill_in_options(char *opt) return i; } - /** - * can we exec the given file? + * can we exec the given file? */ static int can_exec(const char *filename) { struct stat st; - if (!filename || filename[0] == '\0') + assert (filename); + + if (filename[0] == '\0') return FALSE; /* Stat the file to see if it's executable and @@ -418,9 +389,7 @@ can_exec(const char *filename) if (lstat(filename, &st) < 0) return FALSE; - if ((st.st_mode & S_IXUSR) || - (st.st_mode & S_IXGRP) || - (st.st_mode & S_IXOTH)) + if ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH)) return TRUE; return FALSE; diff --git a/src/common/tcpdump.h b/src/common/tcpdump.h index 6b064dbb2..e5dcec12b 100644 --- a/src/common/tcpdump.h +++ b/src/common/tcpdump.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TCPDUMP_H__ -#define __TCPDUMP_H__ +#pragma once /* line buffer stdout, read from stdin */ #define TCPDUMP_ARGS " -n -l -r -" @@ -56,7 +55,7 @@ * 1. data from parent to child's STDIN * 2. child's STDOUT to this program */ -#define NUM_PIPES 2 +#define NUM_PIPES 2 /* unidirectional rule for pipes: pipe[0] for read, pipe[1] for writes */ enum { @@ -69,11 +68,11 @@ enum { PARENT_WRITE_PIPE, }; -#define PARENT_READ_FD (tcpdump->pipes[PARENT_READ_PIPE][READ_FD]) +#define PARENT_READ_FD (tcpdump->pipes[PARENT_READ_PIPE][READ_FD]) #define PARENT_WRITE_FD (tcpdump->pipes[PARENT_WRITE_PIPE][WRITE_FD]) -#define CHILD_READ_FD (tcpdump->pipes[PARENT_WRITE_PIPE][READ_FD]) -#define CHILD_WRITE_FD (tcpdump->pipes[PARENT_READ_PIPE][WRITE_FD]) +#define CHILD_READ_FD (tcpdump->pipes[PARENT_WRITE_PIPE][READ_FD]) +#define CHILD_WRITE_FD (tcpdump->pipes[PARENT_READ_PIPE][WRITE_FD]) typedef struct tcpdump_s { char *filename; @@ -83,7 +82,7 @@ typedef struct tcpdump_s { int pipes[NUM_PIPES][2]; /* following vars are for figuring out exactly what we send to - * tcpdump. See TCPDUMP_DEBUG + * tcpdump. See TCPDUMP_DEBUG */ #ifdef DEBUG int debugfd; @@ -91,11 +90,8 @@ typedef struct tcpdump_s { #endif } tcpdump_t; -//int tcpdump_init(tcpdump_t *tcpdump); +// int tcpdump_init(tcpdump_t *tcpdump); int tcpdump_open(tcpdump_t *tcpdump, pcap_t *pcap); -//int tcpdump_open_live(tcpdump_t *tcpdump, pcap_t *pcap); +// int tcpdump_open_live(tcpdump_t *tcpdump, pcap_t *pcap); int tcpdump_print(tcpdump_t *tcpdump, struct pcap_pkthdr *pkthdr, const u_char *data); void tcpdump_close(tcpdump_t *tcpdump); -void tcpdump_kill(tcpdump_t *tcpdump); - -#endif diff --git a/src/common/timer.c b/src/common/timer.c index 0bd9bab8c..169ca65d2 100755 --- a/src/common/timer.c +++ b/src/common/timer.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,71 +18,24 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" -#include "defines.h" -#include "common.h" - #include "timer.h" - +#include "config.h" #include /* Miscellaneous timeval routines */ -/** - * Divide tvp by div, storing the result in tvp - */ -void -timerdiv_float(struct timeval *tvp, float div) -{ - double interval; - - if (div == 0 || div == 1) - return; - - interval = ((double)tvp->tv_sec * 1000000 + tvp->tv_usec) / (double)div; - tvp->tv_sec = interval / (int)1000000; - tvp->tv_usec = interval - (tvp->tv_sec * 1000000); -} - /* Divide tvs by div, storing the result in tvs */ -void timesdiv_float(struct timespec *tvs, float div) -{ - double interval; - - if (div == 0 || div == 1) - return; - - interval = ((double)tvs->tv_sec * 1000000000 + tvs->tv_nsec) / (double)div; - tvs->tv_sec = interval / (int)1000000000; - tvs->tv_nsec = interval - (tvs->tv_sec * 1000000000); -} - void -timerdiv(struct timeval *tvp, COUNTER div) +timesdiv_float(struct timespec *tvs, float div) { - uint64_t interval; + double interval; - if (div == 0 || div == 1) + if (div == 0.0 || div == 1.0) return; - interval = (uint64_t)tvp->tv_sec * 1000000 + tvp->tv_usec; - do_div(interval, div); - tvp->tv_sec = interval / 1000000; - tvp->tv_usec = interval - (tvp->tv_sec * 1000000); -} - -/* Divide tvs by div, storing the result in tvs */ -void timesdiv(struct timespec *tvs, COUNTER div) -{ - uint64_t interval; - - if (div == 0 || div == 1) - return; - - interval = (uint64_t)tvs->tv_sec * 1000000000 + tvs->tv_nsec; - do_div(interval, div); - tvs->tv_sec = interval / 1000000000; - tvs->tv_nsec = interval - (tvs->tv_sec * 1000000000); + interval = ((double)tvs->tv_sec * 1000000000.0 + (double)tvs->tv_nsec) / (double)div; + tvs->tv_sec = (time_t)interval / (time_t)1000000000; + tvs->tv_nsec = (time_t)interval - (tvs->tv_sec * 1000000000); } void @@ -90,4 +43,3 @@ init_timestamp(timestamp_t *ctx) { timerclear(ctx); } - diff --git a/src/common/timer.h b/src/common/timer.h index 979055735..db5bc1744 100755 --- a/src/common/timer.h +++ b/src/common/timer.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,18 +18,15 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TIMER_H_ -#define _TIMER_H_ +#pragma once -#include "config.h" #include "defines.h" -#include "tcpreplay.h" +#include "config.h" #include "common.h" - -#include -#include +#include "tcpreplay.h" #include - +#include +#include /* * 1 sec = 1,0000 millisec (ms) @@ -39,138 +36,118 @@ * 1 microsec = 1,000 nanosec */ -void timerdiv_float(struct timeval *tvp, float div); void timesdiv_float(struct timespec *tvs, float div); -void timerdiv(struct timeval *tvp, COUNTER div); -void timesdiv(struct timespec *tvs, COUNTER div); /* convert float time to struct timeval *tvp */ #ifndef float2timer -#define float2timer(time, tvp) \ - do { \ - (tvp)->tv_sec = time; \ - (tvp)->tv_usec = (time - (tvp)->tv_sec) * 100000; \ +#define float2timer(time, tvp) \ + do { \ + (tvp)->tv_sec = time; \ + (tvp)->tv_usec = (time - (tvp)->tv_sec) * 100000; \ } while (0) #endif /* timesec to float */ #ifndef timer2float -#define timer2float(tvp, time) \ - do { \ - time = (tvp)->tv_sec; \ - time += (float)((tvp)->tv_usec / 10000) * 0.01; \ +#define timer2float(tvp, time) \ + do { \ + time = (tvp)->tv_sec; \ + time += (float)((tvp)->tv_usec / 10000) * 0.01; \ } while (0) #endif #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 #ifndef TIMESPEC_TO_TIMEVAL -#define TIMESPEC_TO_TIMEVAL(tv, ts) { \ - (tv)->tv_sec = (ts)->tv_sec; \ - (tv)->tv_usec = (ts)->tv_nsec / 1000; } +#define TIMESPEC_TO_TIMEVAL(tv, ts) \ + { \ + (tv)->tv_sec = (ts)->tv_sec; \ + (tv)->tv_usec = (ts)->tv_nsec / 1000; \ + } #endif #ifndef ROUND_TIMESPEC_TO_MICROSEC -#define ROUND_TIMESPEC_TO_MICROSEC(ts) \ - do { \ - (ts)->tv_nsec = ((((ts)->tv_nsec / 1000) + ((ts)->tv_nsec % 1000 >= 500 ? 1 : 0)) * 1000); \ +#define ROUND_TIMESPEC_TO_MICROSEC(ts) \ + do { \ + (ts)->tv_nsec = ((((ts)->tv_nsec / 1000) + ((ts)->tv_nsec % 1000 >= 500 ? 1 : 0)) * 1000); \ } while (0) #endif - - /* zero out a timer */ #ifndef timerclear -#define timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0 +#define timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0 #endif /* zero out a timespec */ #ifndef timesclear -#define timesclear(tvs) (tvs)->tv_sec = (tvs)->tv_nsec = 0 +#define timesclear(tvs) (tvs)->tv_sec = (tvs)->tv_nsec = 0 #endif /* is timer non-zero? */ #ifndef timerisset -#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) +#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) #endif /* is timespec non-zero? */ #ifndef timesisset -#define timesisset(tvs) ((tvs)->tv_sec || (tvs)->tv_nsec) +#define timesisset(tvs) ((tvs)->tv_sec || (tvs)->tv_nsec) #endif - /* add tvp and uvp and store in vvp */ #ifndef timeradd -#define timeradd(tvp, uvp, vvp) \ - do { \ - (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \ - (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \ - if ((vvp)->tv_usec >= 1000000) { \ - (vvp)->tv_sec++; \ - (vvp)->tv_usec -= 1000000; \ - } \ +#define timeradd(tvp, uvp, vvp) \ + do { \ + (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \ + (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \ + if ((vvp)->tv_usec >= 1000000) { \ + (vvp)->tv_sec++; \ + (vvp)->tv_usec -= 1000000; \ + } \ } while (0) #endif /* subtract uvp from tvp and store in vvp */ #ifndef timersub -#define timersub(tvp, uvp, vvp) \ - do { \ - (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \ - (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \ - if ((vvp)->tv_usec < 0) { \ - (vvp)->tv_sec--; \ - (vvp)->tv_usec += 1000000; \ - } \ +#define timersub(tvp, uvp, vvp) \ + do { \ + (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \ + (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \ + if ((vvp)->tv_usec < 0) { \ + (vvp)->tv_sec--; \ + (vvp)->tv_usec += 1000000; \ + } \ } while (0) #endif #ifndef timessub -#define timessub(tsp, usp, vsp) \ - do { \ - (vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec; \ - (vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec; \ - if ((vsp)->tv_nsec < 0) { \ - (vsp)->tv_sec--; \ - (vsp)->tv_nsec += 1000000000; \ - } \ +#define timessub(tsp, usp, vsp) \ + do { \ + (vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec; \ + (vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec; \ + if ((vsp)->tv_nsec < 0) { \ + (vsp)->tv_sec--; \ + (vsp)->tv_nsec += 1000000000; \ + } \ } while (0) #endif /* compare tvp and uvp using cmp */ #ifndef timercmp -#define timercmp(tvp, uvp, cmp) \ - (((tvp)->tv_sec == (uvp)->tv_sec) ? \ - ((tvp)->tv_usec cmp (uvp)->tv_usec) : \ - ((tvp)->tv_sec cmp (uvp)->tv_sec)) +#define timercmp(tvp, uvp, cmp) \ + (((tvp)->tv_sec == (uvp)->tv_sec) ? ((tvp)->tv_usec cmp(uvp)->tv_usec) : ((tvp)->tv_sec cmp(uvp)->tv_sec)) #endif #ifndef timescmp -#define timescmp(tsp, usp, cmp) \ - (((tsp)->tv_sec == (usp)->tv_sec) ? \ - ((tsp)->tv_nsec cmp (usp)->tv_nsec) : \ - ((tsp)->tv_sec cmp (usp)->tv_sec)) +#define timescmp(tsp, usp, cmp) \ + (((tsp)->tv_sec == (usp)->tv_sec) ? ((tsp)->tv_nsec cmp(usp)->tv_nsec) : ((tsp)->tv_sec cmp(usp)->tv_sec)) #endif -/* multiply tvp by x and store in uvp */ -#define timermul(tvp, uvp, x) \ - do { \ - (uvp)->tv_sec = (tvp)->tv_sec * x; \ - (uvp)->tv_usec = (tvp)->tv_usec * x; \ - while((uvp)->tv_usec > 1000000) { \ - (uvp)->tv_sec++; \ - (uvp)->tv_usec -= 1000000; \ - } \ - } while(0) - - typedef struct timeval timestamp_t; +typedef struct timeval timestamp_t; void init_timestamp(timestamp_t *ctx); - - -#endif /* _TIMER_H_ */ diff --git a/src/common/txring.c b/src/common/txring.c index 28a355f2f..d5768d75f 100644 --- a/src/common/txring.c +++ b/src/common/txring.c @@ -33,18 +33,17 @@ #ifdef HAVE_TX_RING +#include "txring.h" #include "err.h" #include "utils.h" -#include "txring.h" -#include +#include #include #include -#include +#include volatile int shutdown_flag = 0; int tdata_offset = TPACKET_HDRLEN - sizeof(struct sockaddr_ll); - /** * This task will call send() procedure */ @@ -57,67 +56,65 @@ txring_send(void *arg) do { /* send all buffers with TP_STATUS_SEND_REQUEST */ - ec_send=sendto(fd_socket, NULL, 0, MSG_DONTWAIT, - (struct sockaddr *)NULL, sizeof(struct sockaddr_ll)); + ec_send = sendto(fd_socket, NULL, 0, MSG_DONTWAIT, (struct sockaddr *)NULL, sizeof(struct sockaddr_ll)); if (ec_send > 0) { total += ec_send; dbgx(2, "Sent %d bytes (+%d bytes)", total, ec_send); - } else { + } else { /* nothing to do => schedule : useful if no SMP */ usleep(100); } - } while (!shutdown_flag); - //if(blocking) printf("end of task send()\n"); - //printf("end of task send(ec=%x)\n", ec_send); + // if(blocking) printf("end of task send()\n"); + // printf("end of task send(ec=%x)\n", ec_send); - return (void*) ec_send; + return (void *)ec_send; } /** * Put data in TX ring buffer and rotate it if necessary */ int -txring_put(txring_t *txp, const void * data, size_t length) +txring_put(txring_t *txp, const void *data, size_t length) { struct tpacket_hdr *ps_header; - char * to_data; + char *to_data; int loop = 1; int first_loop = 1; unsigned int start_index = txp->tx_index; do { - ps_header = ((struct tpacket_hdr *)((void *)txp->tx_head + - (txp->treq->tp_frame_size * txp->tx_index))); - to_data = ((void*) ps_header) + tdata_offset; + ps_header = ((struct tpacket_hdr *)((void *)txp->tx_head + (txp->treq->tp_frame_size * txp->tx_index))); + to_data = ((void *)ps_header) + tdata_offset; switch ((volatile uint32_t)ps_header->tp_status) { - case TP_STATUS_WRONG_FORMAT: - warnx("TP_STATUS_WRONG_FORMAT occuries O_o. Frame %d, pkt len %d\n", - txp->tx_index, length); - break; - - case TP_STATUS_AVAILABLE: - if (length > txp->treq->tp_frame_size) { - //TODO Fragment packet - warnx("[!] %d bytes from %d packet truncated\n", - length-txp->treq->tp_frame_size, length); - length = txp->treq->tp_frame_size; - } - memcpy(to_data, data, length); - ps_header->tp_len = length; - ps_header->tp_status = TP_STATUS_SEND_REQUEST; - loop = 0; - break; - - default: - dbgx(2,"TPACKET status %u at frame %d with length %d\n", - ps_header->tp_status, txp->tx_index, ps_header->tp_len); - usleep(0); - break; + case TP_STATUS_WRONG_FORMAT: + warnx("TP_STATUS_WRONG_FORMAT occuries O_o. Frame %d, pkt len %d\n", txp->tx_index, length); + break; + + case TP_STATUS_AVAILABLE: + if (length > txp->treq->tp_frame_size) { + // TODO Fragment packet + warnx("[!] %d bytes from %d packet truncated\n", length - txp->treq->tp_frame_size, length); + length = txp->treq->tp_frame_size; + } + memcpy(to_data, data, length); + ps_header->tp_len = length; + ps_header->tp_status = TP_STATUS_SEND_REQUEST; + loop = 0; + break; + + default: + dbgx(2, + "TPACKET status %u at frame %d with length %d\n", + ps_header->tp_status, + txp->tx_index, + ps_header->tp_len); + usleep(0); + break; } txp->tx_index++; @@ -131,24 +128,23 @@ txring_put(txring_t *txp, const void * data, size_t length) errno = ENOBUFS; return -1; } - } while(loop == 1); + } while (loop == 1); return ps_header->tp_len; } - /** * \brief Build TX ring buffer request structure * * This builds a ring buffer request structure making sure * that we have buffers big enough so that a frame which * is the size of the MTU doesn't get truncated. We also - * need to structure things with minimum memory wastage + * need to structure things with minimum memory wastage */ void -txring_mkreq(struct tpacket_req* treq, unsigned int mtu) +txring_mkreq(struct tpacket_req *treq, unsigned int mtu) { - unsigned int pg,bs; + unsigned int pg, bs; unsigned int s; unsigned int mult = 1; unsigned nr_blocks = 1000; @@ -158,27 +154,30 @@ txring_mkreq(struct tpacket_req* treq, unsigned int mtu) memset(treq, 0, sizeof(struct tpacket_req)); if (bs <= s) { - while(bs < s) { + while (bs < s) { bs += pg; mult++; } treq->tp_block_size = bs; treq->tp_frame_size = bs / mult; - treq->tp_block_nr = nr_blocks; - treq->tp_frame_nr = mult * nr_blocks; + treq->tp_block_nr = nr_blocks; + treq->tp_frame_nr = mult * nr_blocks; } else { - while ((s * (mult + 1)) <=pg) { + while ((s * (mult + 1)) <= pg) { mult++; } treq->tp_block_size = pg; treq->tp_frame_size = pg / mult; - treq->tp_block_nr = nr_blocks; - treq->tp_frame_nr = mult * nr_blocks; + treq->tp_block_nr = nr_blocks; + treq->tp_frame_nr = mult * nr_blocks; } - dbgx(1, "txring: block_size=%d block_nr=%d frame_size=%d frame_nr=%d", - treq->tp_block_size, treq->tp_block_nr, treq->tp_frame_size, - treq->tp_frame_nr); + dbgx(1, + "txring: block_size=%d block_nr=%d frame_size=%d frame_nr=%d", + treq->tp_block_size, + treq->tp_block_nr, + treq->tp_frame_size, + treq->tp_frame_nr); } /** @@ -203,22 +202,19 @@ txring_init(int fd, unsigned int mtu) txp->tx_index = 0; /* Set index on start*/ /* Set PACKET_LOSS sockoption */ - if (setsockopt(fd, SOL_PACKET, PACKET_LOSS, (char *)&mode_loss, - sizeof(mode_loss)) < 0) { + if (setsockopt(fd, SOL_PACKET, PACKET_LOSS, (char *)&mode_loss, sizeof(mode_loss)) < 0) { perror("setsockopt: PACKET_LOSS"); return NULL; } /* Enable TX Ring */ - if (setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (char *)txp->treq, - sizeof(struct tpacket_req)) < 0) { + if (setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (char *)txp->treq, sizeof(struct tpacket_req)) < 0) { perror("Can't setsockopt PACKET_TX_RING"); return NULL; } - /* mmap unswapped memory with TX ring buffer*/ - txp->tx_head = mmap(0, txp->tx_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + txp->tx_head = mmap(0, txp->tx_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (txp->tx_head == MAP_FAILED) { perror("mmap() failed "); return NULL; diff --git a/src/common/txring.h b/src/common/txring.h index cfb181d3e..309da84cc 100644 --- a/src/common/txring.h +++ b/src/common/txring.h @@ -31,37 +31,33 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - -#ifndef COMMON_TXRING_H -#define COMMON_TXRING_H -#include "config.h" -#include "defines.h" +#pragma once #ifdef HAVE_TX_RING +#include "defines.h" +#include "config.h" + #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 +#include /* the L2 protocols */ #include -#include /* the L2 protocols */ #else #include +#include /* The L2 protocols */ #include -#include /* The L2 protocols */ #endif #include -struct txring_s -{ +struct txring_s { pthread_t tx_send; /*Poll TX thread*/ - volatile struct tpacket_hdr * tx_head; /* Pointer to mmaped memory with TX ring */ - struct tpacket_req* treq; /* TX ring parametrs */ - volatile unsigned int tx_index; /* TX index */ - int tx_size; /* Size of mmaped TX ring */ + volatile struct tpacket_hdr *tx_head; /* Pointer to mmaped memory with TX ring */ + struct tpacket_req *treq; /* TX ring parametrs */ + volatile unsigned int tx_index; /* TX index */ + int tx_size; /* Size of mmaped TX ring */ }; typedef struct txring_s txring_t; -int txring_put(txring_t *txp, const void * data, size_t length); -txring_t* txring_init(int fd, unsigned int mtu); +int txring_put(txring_t *txp, const void *data, size_t length); +txring_t *txring_init(int fd, unsigned int mtu); #endif /* HAVE_TX_RING */ - -#endif /*COMMON_TXRING_H */ diff --git a/src/common/utils.c b/src/common/utils.c index a641939d8..6aed5b327 100644 --- a/src/common/utils.c +++ b/src/common/utils.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,24 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include #include -#include -#include -#include +#include #ifdef HAVE_SYS_IOCTL_H #include #endif -#ifdef DEBUG -extern int debug; -#endif - /** * this is wrapped up in a #define safe_malloc * This function, detects failures to malloc memory and zeros out the @@ -43,13 +35,12 @@ extern int debug; */ void * -_our_safe_malloc(size_t len, const char *funcname, const int line, const char *file) +our_safe_malloc(size_t len, const char *funcname, int line, const char *file) { u_char *ptr; if ((ptr = malloc(len)) == NULL) { - fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n", - file, funcname, line, len); + fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n", file, funcname, line, len); exit(-1); } @@ -70,11 +61,15 @@ _our_safe_malloc(size_t len, const char *funcname, const int line, const char *f * ptr = safe_realloc(ptr, size) */ void * -_our_safe_realloc(void *ptr, size_t len, const char *funcname, const int line, const char *file) +our_safe_realloc(void *ptr, size_t len, const char *funcname, int line, const char *file) { - if ((ptr = realloc(ptr, len)) == NULL) { - fprintf(stderr, "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes", file, funcname, line, len); + fprintf(stderr, + "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes", + file, + funcname, + line, + len); exit(-1); } @@ -88,7 +83,7 @@ _our_safe_realloc(void *ptr, size_t len, const char *funcname, const int line, c * This function, detects failures to realloc memory */ char * -_our_safe_strdup(const char *str, const char *funcname, const int line, const char *file) +our_safe_strdup(const char *str, const char *funcname, int line, const char *file) { char *newstr; @@ -100,14 +95,13 @@ _our_safe_strdup(const char *str, const char *funcname, const int line, const ch memcpy(newstr, str, strlen(str) + 1); return newstr; - } /** * calls free and sets to NULL. */ void -_our_safe_free(void *ptr, const char *funcname, const int line, const char *file) +our_safe_free(void *ptr, const char *funcname, int line, const char *file) { assert(funcname); assert(line); @@ -122,28 +116,37 @@ _our_safe_free(void *ptr, const char *funcname, const int line, const char *file /** * get next packet in pcap file */ -u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, - const char *funcname, const int line, const char *file) +u_char * +our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, const char *funcname, int line, const char *file) { u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr); if (pktdata) { if (pkthdr->len > MAX_SNAPLEN) { - fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", - file, funcname, line, pkthdr->len, MAX_SNAPLEN); + fprintf(stderr, + "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", + file, + funcname, + line, + pkthdr->len, + MAX_SNAPLEN); exit(-1); } if (!pkthdr->len || !pkthdr->caplen) { - fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", - file, funcname, line, pkthdr->len, pkthdr->caplen); + fprintf(stderr, + "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", + file, + funcname, + line, + pkthdr->len, + pkthdr->caplen); exit(-1); } /* attempt to correct invalid captures */ if (pkthdr->len < pkthdr->caplen) { - dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", - pkthdr->caplen, pkthdr->len); + dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", pkthdr->caplen, pkthdr->len); pkthdr->caplen = pkthdr->len; } } else { @@ -157,34 +160,46 @@ u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, /** * get next packet in pcap file (extended) */ -int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, - const u_char **pktdata, const char *funcname, - const int line, const char *file) +int +our_safe_pcap_next_ex(pcap_t *pcap, + struct pcap_pkthdr **pkthdr, + const u_char **pktdata, + const char *funcname, + int line, + const char *file) { int res = pcap_next_ex(pcap, pkthdr, pktdata); if (*pktdata && *pkthdr) { if ((*pkthdr)->len > MAXPACKET) { - fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", - file, funcname, line, (*pkthdr)->len, MAXPACKET); + fprintf(stderr, + "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", + file, + funcname, + line, + (*pkthdr)->len, + MAXPACKET); exit(-1); } if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) { - fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", - file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen); + fprintf(stderr, + "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", + file, + funcname, + line, + (*pkthdr)->len, + (*pkthdr)->caplen); exit(-1); } if ((*pkthdr)->len < (*pkthdr)->caplen) { - dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", - (*pkthdr)->caplen, (*pkthdr)->len); + dbgx(1, "Correcting invalid packet capture length %d: packet length=%u", (*pkthdr)->caplen, (*pkthdr)->len); (*pkthdr)->caplen = (*pkthdr)->len; } } else { /* this will be reported as a failed packet in final report */ - dbgx(1, "No data found in packet 0x%p and/or header 0x%p", - *pktdata, *pkthdr); + dbgx(1, "No data found in packet 0x%p and/or header 0x%p", *pktdata, *pkthdr); } return res; @@ -218,10 +233,10 @@ packet_stats(const tcpreplay_stats_t *stats) if (stats->bytes_sent > 1000 * 1000 * 1000 && diff_us > 1000 * 1000) { bytes_sec_X10 = (stats->bytes_sent * 10 * 1000) / (diff_us / 1000); pkts_sec_X100 = (stats->pkts_sent * 100 * 1000) / (diff_us / 1000); - } else { + } else { bytes_sec_X10 = (stats->bytes_sent * 10 * 1000 * 1000) / diff_us; pkts_sec_X100 = (stats->pkts_sent * 100 * 1000 * 1000) / diff_us; - } + } bytes_sec = bytes_sec_X10 / 10; bytes_sec_10ths = bytes_sec_X10 % 10; @@ -238,23 +253,37 @@ packet_stats(const tcpreplay_stats_t *stats) if (diff_us >= 1000 * 1000) printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%02zd seconds\n", - stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)(diff.tv_usec / (10 * 1000))); + stats->pkts_sent, + stats->bytes_sent, + (ssize_t)diff.tv_sec, + (ssize_t)(diff.tv_usec / (10 * 1000))); else printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%06zd seconds\n", - stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)diff.tv_usec); - + stats->pkts_sent, + stats->bytes_sent, + (ssize_t)diff.tv_sec, + (ssize_t)diff.tv_usec); if (mb_sec >= 1) printf("Rated: %llu.%1u Bps, %llu.%02u Mbps, %llu.%02u pps\n", - bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_100ths, pkts_sec, pkts_sec_100ths); + bytes_sec, + bytes_sec_10ths, + mb_sec, + mb_sec_100ths, + pkts_sec, + pkts_sec_100ths); else printf("Rated: %llu.%1u Bps, %llu.%03u Mbps, %llu.%02u pps\n", - bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_1000ths, pkts_sec, pkts_sec_100ths); + bytes_sec, + bytes_sec_10ths, + mb_sec, + mb_sec_1000ths, + pkts_sec, + pkts_sec_100ths); fflush(NULL); - + if (stats->failed) - printf("Failed write attempts: " COUNTER_SPEC "\n", - stats->failed); + printf("Failed write attempts: " COUNTER_SPEC "\n", stats->failed); } /** @@ -265,7 +294,8 @@ packet_stats(const tcpreplay_stats_t *stats) * @param len: length of the buffer * @return: string containing date, or -1 on error */ -int format_date_time(struct timeval *when, char *buf, size_t len) +int +format_date_time(struct timeval *when, char *buf, size_t len) { struct tm *tm; char tmp[64]; @@ -286,7 +316,7 @@ int format_date_time(struct timeval *when, char *buf, size_t len) * it just calls errx() since all errors are fatal. */ int -read_hexstring(const char *l2string, u_char *hex, const int hexlen) +read_hexstring(const char *l2string, u_char *hex, int hexlen) { int numbytes = 0; unsigned int value; @@ -306,10 +336,12 @@ read_hexstring(const char *l2string, u_char *hex, const int hexlen) /* get the first byte */ l2byte = strtok_r(string, ",", &token); - sscanf(l2byte, "%x", &value); + if (l2byte == NULL) + err(-1, "Hex buffer must contain something"); + value = strtol(l2byte, NULL, 16); if (value > 0xff) errx(-1, "Invalid hex string byte: %s", l2byte); - databyte = (u_char) value; + databyte = (u_char)value; memcpy(&hex[numbytes], &databyte, 1); /* get remaining bytes */ @@ -319,10 +351,10 @@ read_hexstring(const char *l2string, u_char *hex, const int hexlen) warn("Hex buffer too small for data- skipping data"); goto done; } - sscanf(l2byte, "%x", &value); + value = strtol(l2byte, NULL, 16); if (value > 0xff) errx(-1, "Invalid hex string byte: %s", l2byte); - databyte = (u_char) value; + databyte = (u_char)value; memcpy(&hex[numbytes], &databyte, 1); } @@ -345,8 +377,9 @@ inet_aton(const char *name, struct in_addr *addr) } #endif -#if SIZEOF_LONG == 4 -uint32_t __div64_32(uint64_t *n, uint32_t base) +#if SIZEOF_LONG == 4 +uint32_t +__div64_32(uint64_t *n, uint32_t base) { uint64_t rem = *n; uint64_t b = base; @@ -357,13 +390,13 @@ uint32_t __div64_32(uint64_t *n, uint32_t base) res = 0; if (high >= base) { high /= base; - res = (uint64_t) high << 32; - rem -= (uint64_t) (high*base) << 32; + res = (uint64_t)high << 32; + rem -= (uint64_t)(high * base) << 32; } while ((int64_t)b > 0 && b < rem) { - b = b+b; - d = d+d; + b = b + b; + d = d + d; } do { @@ -387,28 +420,29 @@ uint32_t __div64_32(uint64_t *n, uint32_t base) * @param: seed * @return: random number */ -uint32_t tcpr_random(uint32_t *seed) +uint32_t +tcpr_random(uint32_t *seed) { - unsigned int next = *seed; - int result; + unsigned int next = *seed; + int result; - next *= 1103515245; - next += 12345; - result = (unsigned int) (next / 65536) % 2048; + next *= 1103515245; + next += 12345; + result = (int)(next / 65536) % 2048; - next *= 1103515245; - next += 12345; - result <<= 10; - result ^= (unsigned int) (next / 65536) % 1024; + next *= 1103515245; + next += 12345; + result <<= 10; + result ^= (int)(next / 65536) % 1024; - next *= 1103515245; - next += 12345; - result <<= 10; - result ^= (unsigned int) (next / 65536) % 1024; + next *= 1103515245; + next += 12345; + result <<= 10; + result ^= (int)(next / 65536) % 1024; - *seed = next; + *seed = next; - return result; + return result; } /** @@ -416,7 +450,8 @@ uint32_t tcpr_random(uint32_t *seed) * a program. BSD and Unix derivatives should utilize `FIONBIO` due to known * issues with reading from tty with a 0 byte read returning -1 opposed to 0. */ -void restore_stdin(void) +void +restore_stdin(void) { #ifdef FIONBIO int nb = 0; diff --git a/src/common/utils.h b/src/common/utils.h index 445b0f62d..c758f4723 100644 --- a/src/common/utils.h +++ b/src/common/utils.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ +#pragma once -#ifndef _UTILS_H_ -#define _UTILS_H_ - -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" typedef struct { @@ -44,34 +42,36 @@ typedef struct { COUNTER flows_invalid_packets; } tcpreplay_stats_t; - -int read_hexstring(const char *l2string, u_char *hex, const int hexlen); +int read_hexstring(const char *l2string, u_char *hex, int hexlen); void packet_stats(const tcpreplay_stats_t *stats); int format_date_time(struct timeval *when, char *buf, size_t len); uint32_t tcpr_random(uint32_t *seed); void restore_stdin(void); /* our "safe" implimentations of functions which allocate memory */ -#define safe_malloc(x) _our_safe_malloc(x, __FUNCTION__, __LINE__, __FILE__) -void *_our_safe_malloc(size_t len, const char *, const int, const char *); +#define safe_malloc(x) our_safe_malloc(x, __FUNCTION__, __LINE__, __FILE__) +void *our_safe_malloc(size_t len, const char *, int, const char *); -#define safe_realloc(x, y) _our_safe_realloc(x, y, __FUNCTION__, __LINE__, __FILE__) -void *_our_safe_realloc(void *ptr, size_t len, const char *, const int, const char *); +#define safe_realloc(x, y) our_safe_realloc(x, y, __FUNCTION__, __LINE__, __FILE__) +void *our_safe_realloc(void *ptr, size_t len, const char *, int, const char *); -#define safe_strdup(x) _our_safe_strdup(x, __FUNCTION__, __LINE__, __FILE__) -char *_our_safe_strdup(const char *str, const char *, const int, const char *); +#define safe_strdup(x) our_safe_strdup(x, __FUNCTION__, __LINE__, __FILE__) +char *our_safe_strdup(const char *str, const char *, int, const char *); -#define safe_free(x) _our_safe_free(x, __FUNCTION__, __LINE__, __FILE__) -void _our_safe_free(void *ptr, const char *, const int, const char *); +#define safe_free(x) our_safe_free(x, __FUNCTION__, __LINE__, __FILE__) +void our_safe_free(void *ptr, const char *, int, const char *); -#define safe_pcap_next(x, y) _our_safe_pcap_next(x, y, __FUNCTION__, __LINE__, __FILE__) -u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, - const char *funcname, const int line, const char *file); +#define safe_pcap_next(x, y) our_safe_pcap_next(x, y, __FUNCTION__, __LINE__, __FILE__) +u_char * +our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, const char *funcname, int line, const char *file); -#define safe_pcap_next_ex(x, y, z) _our_safe_pcap_next_ex(x, y, z, __FUNCTION__, __LINE__, __FILE__) -int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, - const u_char **pktdata, const char *funcname, - const int line, const char *file); +#define safe_pcap_next_ex(x, y, z) our_safe_pcap_next_ex(x, y, z, __FUNCTION__, __LINE__, __FILE__) +int our_safe_pcap_next_ex(pcap_t *pcap, + struct pcap_pkthdr **pkthdr, + const u_char **pktdata, + const char *funcname, + int line, + const char *file); #define MAX_ARGS 128 @@ -81,29 +81,28 @@ int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, int inet_aton(const char *name, struct in_addr *addr); #endif -#if SIZEOF_LONG == 8 -# define do_div(n,base) ({ \ - uint32_t __base = (base); \ - uint32_t __rem; \ - __rem = ((uint64_t)(n)) % __base; \ - (n) = ((uint64_t)(n)) / __base; \ - __rem; \ - }) -#elif SIZEOF_LONG == 4 +#if SIZEOF_LONG == 8 +#define do_div(n, base) \ + ({ \ + uint32_t __base = (base); \ + uint32_t __rem; \ + __rem = ((uint64_t)(n)) % __base; \ + (n) = ((uint64_t)(n)) / __base; \ + __rem; \ + }) +#elif SIZEOF_LONG == 4 extern uint32_t __div64_32(uint64_t *dividend, uint32_t divisor); -# define do_div(n,base) ({ \ - uint32_t __base = (base); \ - uint32_t __rem; \ - if (((n) >> 32) == 0) { \ - __rem = (uint32_t)(n) % __base; \ - (n) = (uint32_t)(n) / __base; \ - } else \ - __rem = __div64_32(&(n), __base); \ - __rem; \ - }) +#define do_div(n, base) \ + ({ \ + uint32_t __base = (base); \ + uint32_t __rem; \ + if (((n) >> 32) == 0) { \ + __rem = (uint32_t)(n) % __base; \ + (n) = (uint32_t)(n) / __base; \ + } else \ + __rem = __div64_32(&(n), __base); \ + __rem; \ + }) #else /* SIZEOF_LONG == ?? */ -# error do_div() does not yet support the C64 +#error do_div() does not yet support the C64 #endif /* SIZEOF_LONG */ - -#endif /* _UTILS_H_ */ - diff --git a/src/common/xX.c b/src/common/xX.c index 3b235d918..35528832f 100644 --- a/src/common/xX.c +++ b/src/common/xX.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,17 +19,15 @@ */ /* - * xX stands for "include or exclude" which is used with the + * xX stands for "include or exclude" which is used with the * -x and -X flags * * Functions for use to process args for or check data against in * tcpreplay/do_packets and tcpprep. */ -#include - -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" #include @@ -40,52 +38,52 @@ int parse_xX_str(tcpr_xX_t *xX, char *str, tcpr_bpf_t *bpf) { - int out = 0; + int out; dbgx(1, "Parsing string: %s", str); dbgx(1, "Switching on: %c", str[0]); switch (str[0]) { - case 'B': /* both ip's */ + case 'B': /* both ip's */ str = str + 2; out = xXBoth; if (!parse_cidr(&(xX->cidr), str, ",")) return xXError; break; - case 'D': /* dst ip */ + case 'D': /* dst ip */ str = str + 2; out = xXDest; if (!parse_cidr(&(xX->cidr), str, ",")) return xXError; break; - case 'E': /* either ip */ + case 'E': /* either ip */ str = str + 2; out = xXEither; if (!parse_cidr(&(xX->cidr), str, ",")) return xXError; break; - - case 'F': /* bpf filter */ + + case 'F': /* bpf filter */ str = str + 2; out = xXBPF; bpf->filter = safe_strdup(str); - /* + /* * note: it's temping to compile the BPF here, but we don't - * yet know what the link type is for the file, so we have + * yet know what the link type is for the file, so we have * to compile the BPF once we open the pcap file */ break; - - case 'P': /* packet id */ + + case 'P': /* packet id */ str = str + 2; out = xXPacket; if (!parse_list(&(xX->list), str)) return xXError; break; - case 'S': /* source ip */ + case 'S': /* source ip */ str = str + 2; out = xXSource; if (!parse_cidr(&(xX->cidr), str, ",")) @@ -94,13 +92,13 @@ parse_xX_str(tcpr_xX_t *xX, char *str, tcpr_bpf_t *bpf) default: errx(-1, "Invalid -%c option: %c", xX->mode, *str); - break; } - if (xX->mode == 'X') { /* run in exclude mode */ + if (xX->mode == 'X') { /* run in exclude mode */ out += xXExclude; if (bpf->filter != NULL) - err(-1, "Using a BPF filter with -X doesn't work.\n" + err(-1, + "Using a BPF filter with -X doesn't work.\n" "Try using -xF:\"not \" instead"); } @@ -108,78 +106,66 @@ parse_xX_str(tcpr_xX_t *xX, char *str, tcpr_bpf_t *bpf) return xX->mode; } - - /** * compare the source/destination IP address according to the mode * and return 1 if we should send the packet or 0 if not */ int -process_xX_by_cidr_ipv4(int mode, tcpr_cidr_t * cidr, ipv4_hdr_t * ip_hdr) +process_xX_by_cidr_ipv4(int mode, tcpr_cidr_t *cidr, ipv4_hdr_t *ip_hdr) { - if (mode & xXExclude) { /* Exclude mode */ switch (mode ^ xXExclude) { case xXSource: - /* note: check_ip_cidr() returns TCPR_DIR_C2S for true, TCPR_DIR_S2C for false + /* note: check_ip_cidr() returns TCPR_DIR_C2S for true, TCPR_DIR_S2C for false * and NOT true/false or 1/0, etc! */ return check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ? DONT_SEND : SEND; - break; - case xXDest: - return check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) ? DONT_SEND : SEND; + return check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) ? DONT_SEND : SEND; case xXBoth: - return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) && - check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ) ? DONT_SEND : SEND; - break; - + return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) && check_ip_cidr(cidr, ip_hdr->ip_src.s_addr)) + ? DONT_SEND + : SEND; case xXEither: - return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) || - check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ) ? DONT_SEND : SEND; - break; + return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) || check_ip_cidr(cidr, ip_hdr->ip_src.s_addr)) + ? DONT_SEND + : SEND; } - } - else { + } else { /* Include Mode */ switch (mode) { case xXSource: - return check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ? SEND : DONT_SEND; - break; - + return check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ? SEND : DONT_SEND; case xXDest: - return check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) ? SEND : DONT_SEND; - break; - + return check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) ? SEND : DONT_SEND; case xXBoth: - return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) && - check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ) ? SEND : DONT_SEND; - break; - + return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) && check_ip_cidr(cidr, ip_hdr->ip_src.s_addr)) + ? SEND + : DONT_SEND; case xXEither: - return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) || - check_ip_cidr(cidr, ip_hdr->ip_src.s_addr) ) ? SEND : DONT_SEND; - break; + return (check_ip_cidr(cidr, ip_hdr->ip_dst.s_addr) || check_ip_cidr(cidr, ip_hdr->ip_src.s_addr)) + ? SEND + : DONT_SEND; + default: + assert(false); } } /* total failure */ - if (mode &xXExclude) { + if (mode & xXExclude) { warn("Unable to determine action in CIDR filter mode. Default: Don't Send."); return DONT_SEND; } else { warn("Unable to determine action in CIDR filter mode. Default: Send."); return SEND; } - } int -process_xX_by_cidr_ipv6(int mode, tcpr_cidr_t * cidr, ipv6_hdr_t * ip6_hdr) +process_xX_by_cidr_ipv6(int mode, tcpr_cidr_t *cidr, ipv6_hdr_t *ip6_hdr) { - if (mode & xXExclude) { /* Exclude mode */ switch (mode ^ xXExclude) { @@ -188,52 +174,40 @@ process_xX_by_cidr_ipv6(int mode, tcpr_cidr_t * cidr, ipv6_hdr_t * ip6_hdr) * and NOT true/false or 1/0, etc! */ return check_ip6_cidr(cidr, &ip6_hdr->ip_src) ? DONT_SEND : SEND; - break; - case xXDest: - return check_ip6_cidr(cidr, &ip6_hdr->ip_dst) ? DONT_SEND : SEND; + return check_ip6_cidr(cidr, &ip6_hdr->ip_dst) ? DONT_SEND : SEND; case xXBoth: - return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) && - check_ip6_cidr(cidr, &ip6_hdr->ip_src) ) ? DONT_SEND : SEND; - break; - + return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) && check_ip6_cidr(cidr, &ip6_hdr->ip_src)) ? DONT_SEND + : SEND; case xXEither: - return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) || - check_ip6_cidr(cidr, &ip6_hdr->ip_src) ) ? DONT_SEND : SEND; - break; + return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) || check_ip6_cidr(cidr, &ip6_hdr->ip_src)) ? DONT_SEND + : SEND; } - } - else { + } else { /* Include Mode */ switch (mode) { case xXSource: - return check_ip6_cidr(cidr, &ip6_hdr->ip_src) ? SEND : DONT_SEND; - break; - + return check_ip6_cidr(cidr, &ip6_hdr->ip_src) ? SEND : DONT_SEND; case xXDest: - return check_ip6_cidr(cidr, &ip6_hdr->ip_dst) ? SEND : DONT_SEND; - break; - + return check_ip6_cidr(cidr, &ip6_hdr->ip_dst) ? SEND : DONT_SEND; case xXBoth: - return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) && - check_ip6_cidr(cidr, &ip6_hdr->ip_src) ) ? SEND : DONT_SEND; - break; - + return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) && check_ip6_cidr(cidr, &ip6_hdr->ip_src)) ? SEND + : DONT_SEND; case xXEither: - return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) || - check_ip6_cidr(cidr, &ip6_hdr->ip_src) ) ? SEND : DONT_SEND; - break; + return (check_ip6_cidr(cidr, &ip6_hdr->ip_dst) || check_ip6_cidr(cidr, &ip6_hdr->ip_src)) ? SEND + : DONT_SEND; + default: + assert(false); } } /* total failure */ - if (mode &xXExclude) { + if (mode & xXExclude) { warn("Unable to determine action in CIDR filter mode. Default: Don't Send."); return DONT_SEND; } else { warn("Unable to determine action in CIDR filter mode. Default: Send."); return SEND; } - } diff --git a/src/common/xX.h b/src/common/xX.h index a3090bf3b..b8a714e26 100644 --- a/src/common/xX.h +++ b/src/common/xX.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __xX_H__ -#define __xX_H__ +#pragma once /* * Functions for processing args/data generated by -x and -X @@ -40,6 +39,3 @@ int process_xX_by_cidr_ipv6(int, tcpr_cidr_t *, ipv6_hdr_t *); #define xXPacket 16 #define xXBPF 32 #define xXExclude 128 /* if exclude mode, add 128 to above value */ - - -#endif diff --git a/src/defines.h.in b/src/defines.h.in index ea50e0abd..6b651398a 100644 --- a/src/defines.h.in +++ b/src/defines.h.in @@ -1,5 +1,4 @@ -#ifndef __DEFINES_H__ -#define __DEFINES_H__ +#pragma once #include "config.h" @@ -50,15 +49,15 @@ #endif #if defined INCLUDE_PCAP_BPF_H_FILE && !defined PCAP_DONT_INCLUDE_PCAP_BPF_H -#include "@INCLUDE_PCAP_BPF_HEADER@" +#include <@INCLUDE_PCAP_BPF_HEADER@> #define PCAP_DONT_INCLUDE_PCAP_BPF_H 1 /* don't re-include it in pcap.h */ #endif -#include "@LPCAPINC@" +#include <@LPCAPINC@> /* include our own strlcat/strlcpy? */ #ifndef HAVE_STRLCPY -#include "lib/strlcpy.h" +#include #endif /* @@ -68,7 +67,7 @@ * The result is that I stole the DLT types from pcap-bpf.h and * put them in here. */ -#include "common/dlt_names.h" +#include #ifdef HAVE_BOOL_H #include @@ -89,8 +88,8 @@ #endif #define COUNTER_OVERFLOW_RISK (((COUNTER)~0) >> 20) -#include "common/list.h" -#include "common/cidr.h" +#include +#include typedef struct tcpr_ipv4_hdr ipv4_hdr_t; @@ -136,85 +135,75 @@ typedef struct tcpr_speed_s { /* speed modifiers */ int mode; #define SPEED_MULTIPLIER 1 -#define SPEED_MBPSRATE 2 +#define SPEED_MBPSRATE 2 #define SPEED_PACKETRATE 3 -#define SPEED_TOPSPEED 4 +#define SPEED_TOPSPEED 4 #define SPEED_ONEATATIME 5 COUNTER speed; float multiplier; int pps_multi; } tcpr_speed_t; -#define MAX_FILES 1024 /* Max number of files we can pass to tcpreplay */ +#define MAX_FILES 1024 /* Max number of files we can pass to tcpreplay */ -#define DEFAULT_MTU 1500 /* Max Transmission Unit of standard ethernet - * don't forget *frames* are MTU + L2 header! - */ +/* Max Transmission Unit of standard ethernet don't forget *frames* are MTU + L2 header! */ +#define DEFAULT_MTU 1500 -#define MAX_SNAPLEN 262144 /* tell libpcap to capture the entire packet - * this is the maximum size supported by libpcap - * (https://github.com/the-tcpdump-group/libpcap/blob/master/pcap-int.h#L99-L125) - */ +/* tell libpcap to capture the entire packet + * this is the maximum size supported by libpcap + * (https://github.com/the-tcpdump-group/libpcap/blob/master/pcap-int.h#L99-L125) + */ +#define MAX_SNAPLEN 262144 -#define MAXPACKET (MAX_SNAPLEN + 22) /* snap length plus some room for adding a - * couple VLAN headers or a L2 header - */ +/* snap length plus some room for adding a + * couple VLAN headers or a L2 header + */ +#define MAXPACKET (MAX_SNAPLEN + 22) -#define PACKET_HEADROOM 512 /* additional headroom allocated for packets to accommodate editing */ +#define PACKET_HEADROOM 512 /* additional headroom allocated for packets to accommodate editing */ #define DNS_RESOLVE 1 #define DNS_DONT_RESOLVE 0 -#define RESOLVE 0 /* disable dns lookups */ -#define BPF_OPTIMIZE 1 /* default is to optimize bpf program */ -#define PCAP_TIMEOUT 100 /* 100ms pcap_open_live timeout */ +#define RESOLVE 0 /* disable dns lookups */ +#define BPF_OPTIMIZE 1 /* default is to optimize bpf program */ +#define PCAP_TIMEOUT 100 /* 100ms pcap_open_live timeout */ #define DEFAULT_FUZZ_FACTOR 8 /* HP-UX already defines TRUE/FALSE */ #ifndef TRUE -typedef enum bool_e { - FALSE = 0, - TRUE -} bool_t; +typedef enum bool_e { FALSE = 0, TRUE } bool_t; #endif -#define EBUF_SIZE 1024 /* size of our error buffers */ -#define MAC_SIZE 7 /* size of the mac[] buffer */ +#define EBUF_SIZE 1024 /* size of our error buffers */ +#define MAC_SIZE 7 /* size of the mac[] buffer */ -typedef enum pad_e { - PAD_PACKET, - TRUNC_PACKET -} pad_t; +typedef enum pad_e { PAD_PACKET, TRUNC_PACKET } pad_t; #define DNS_QUERY_FLAG 0x8000 -typedef enum direction_e { - DIR_UNKNOWN = -1, - DIR_CLIENT = 0, - DIR_SERVER = 1, - DIR_ANY = 2 -} direction_t; +typedef enum direction_e { DIR_UNKNOWN = -1, DIR_CLIENT = 0, DIR_SERVER = 1, DIR_ANY = 2 } direction_t; typedef enum tcpprep_mode_e { - ERROR_MODE, /* Some kind of error has occurred */ - CIDR_MODE, /* single pass, CIDR netblock */ - REGEX_MODE, /* single pass, regex */ - PORT_MODE, /* single pass, use src/dst ports to split */ - MAC_MODE, /* single pass, use src mac to split */ - FIRST_MODE, /* single pass, use first seen to split */ - AUTO_MODE, /* first pass through in auto mode */ - ROUTER_MODE, /* second pass through in router mode */ - BRIDGE_MODE, /* second pass through in bridge mode */ - SERVER_MODE, /* second pass through in server (router) mode */ - CLIENT_MODE /* second pass through in client (router) mode */ + ERROR_MODE, /* Some kind of error has occurred */ + CIDR_MODE, /* single pass, CIDR netblock */ + REGEX_MODE, /* single pass, regex */ + PORT_MODE, /* single pass, use src/dst ports to split */ + MAC_MODE, /* single pass, use src mac to split */ + FIRST_MODE, /* single pass, use first seen to split */ + AUTO_MODE, /* first pass through in auto mode */ + ROUTER_MODE, /* second pass through in router mode */ + BRIDGE_MODE, /* second pass through in bridge mode */ + SERVER_MODE, /* second pass through in server (router) mode */ + CLIENT_MODE /* second pass through in client (router) mode */ } tcpprep_mode_t; -#define BROADCAST_MAC "\xff\xff\xff\xff\xff\xff" -#define IPV4_MULTICAST_MAC "\x01\x00\x5e\x00\x00\x00" -#define IPV6_MULTICAST_MAC "\x33\x33\x00\x00\x00\x00" -#define IPV4_VRRP "\x00\x00\x50\x00\x01\x00" -#define IPV6_VRRP "\x00\x00\x50\x00\x02\x00" +#define BROADCAST_MAC "\xff\xff\xff\xff\xff\xff" +#define IPV4_MULTICAST_MAC "\x01\x00\x5e\x00\x00\x00" +#define IPV6_MULTICAST_MAC "\x33\x33\x00\x00\x00\x00" +#define IPV4_VRRP "\x00\x00\x50\x00\x01\x00" +#define IPV6_VRRP "\x00\x00\x50\x00\x02\x00" /* MAC macros for printf */ #define MAC_FORMAT "%02X:%02X:%02X:%02X:%02X:%02X" @@ -231,13 +220,11 @@ typedef enum tcpprep_mode_e { /* force a word or half-word swap on both Big and Little endian systems */ #ifndef SWAPLONG -#define SWAPLONG(y) \ -((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff)) +#define SWAPLONG(y) ((((y)&0xff) << 24) | (((y)&0xff00) << 8) | (((y)&0xff0000) >> 8) | (((y) >> 24) & 0xff)) #endif #ifndef SWAPSHORT -#define SWAPSHORT(y) \ -( (((y)&0xff)<<8) | ((u_short)((y)&0xff00)>>8) ) +#define SWAPSHORT(y) ((((y)&0xff) << 8) | ((u_short)((y)&0xff00) >> 8)) #endif /* converts a 64bit int to network byte order */ @@ -248,21 +235,20 @@ typedef enum tcpprep_mode_e { #define htonll(x) (x) #else /* stolen from http://www.codeproject.com/cpp/endianness.asp */ -#define ntohll(x) (((u_int64_t)(ntohl((int)((x << 32) >> 32))) << 32) | \ - (unsigned int)ntohl(((int)(x >> 32)))) +#define ntohll(x) (((u_int64_t)(ntohl((int)((x << 32) >> 32))) << 32) | (unsigned int)ntohl(((int)(x >> 32)))) #define htonll(x) ntohll(x) #endif /* WORDS_BIGENDIAN */ #endif /* HAVE_NTOHLL */ #endif /* !ntohll && !htonll */ -#define DEBUG_INFO 1 /* informational only, lessthan 1 line per packet */ -#define DEBUG_BASIC 2 /* limited debugging, one line per packet */ -#define DEBUG_DETAIL 3 /* more detailed, a few lines per packet */ -#define DEBUG_MORE 4 /* even more detail */ -#define DEBUG_CODE 5 /* examines code & values, many lines per packet */ +#define DEBUG_INFO 1 /* informational only, lessthan 1 line per packet */ +#define DEBUG_BASIC 2 /* limited debugging, one line per packet */ +#define DEBUG_DETAIL 3 /* more detailed, a few lines per packet */ +#define DEBUG_MORE 4 /* even more detail */ +#define DEBUG_CODE 5 /* examines code & values, many lines per packet */ #if defined HAVE_IOPERM && defined __i386_ - #define HAVE_IOPORT_SLEEP +#define HAVE_IOPORT_SLEEP #endif /* Win32 doesn't know about PF_INET6 */ @@ -278,112 +264,112 @@ typedef enum tcpprep_mode_e { #define IPV6_EXTLEN_TO_BYTES(x) ((x * 4) + 8) #ifndef HAVE_UINT8_T -typedef u_int8_t uint8_t -typedef u_int16_t uint16_t -typedef u_int32_t uint32_t +typedef u_int8_t uint8_t typedef u_int16_t uint16_t typedef u_int32_t uint32_t #endif /* Support for flexible arrays. */ #undef __flexarr #if defined(__GNUC__) && ((__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)) /* GCC 2.97 supports C99 flexible array members. */ -# define __flexarr [] +#define __flexarr [] #else -# ifdef __GNUC__ -# define __flexarr [0] -# else -# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -# define __flexarr [] -# elif defined(_WIN32) +#ifdef __GNUC__ +#define __flexarr [0] +#else +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#define __flexarr [] +#elif defined(_WIN32) /* MS VC++ */ -# define __flexarr [] -# else +#define __flexarr [] +#else /* Some other non-C99 compiler. Approximate with [1]. */ -# define __flexarr [1] -# endif -# endif +#define __flexarr [1] +#endif +#endif #endif /* Time converters */ #define SEC_TO_MILLISEC(x) (x * 1000) #define SEC_TO_MICROSEC(x) (x * 1000000) -#define SEC_TO_NANOSEC(x) ((u_int64_t)x * 1000000000) +#define SEC_TO_NANOSEC(x) ((u_int64_t)x * 1000000000) #define MILLISEC_TO_SEC(x) (x / 1000) #define MICROSEC_TO_SEC(x) (x / 1000000) -#define NANOSEC_TO_SEC(x) ((u_int64_t)x / 1000000000) +#define NANOSEC_TO_SEC(x) ((u_int64_t)x / 1000000000) -#define TIMEVAL_TO_MILLISEC(x) (((x)->tv_sec * 1000) + ((x)->tv_usec / 1000)) -#define TIMEVAL_TO_MICROSEC(x) (((x)->tv_sec * 1000000) + (x)->tv_usec) -#define TIMEVAL_TO_NANOSEC(x) ((u_int64_t)((x)->tv_sec * 1000000000) + ((u_int64_t)(x)->tv_usec * 1000)) +#define TIMEVAL_TO_MILLISEC(x) (((x)->tv_sec * 1000) + ((x)->tv_usec / 1000)) +#define TIMEVAL_TO_MICROSEC(x) (((x)->tv_sec * 1000000) + (x)->tv_usec) +#define TIMEVAL_TO_NANOSEC(x) ((u_int64_t)((x)->tv_sec * 1000000000) + ((u_int64_t)(x)->tv_usec * 1000)) #define TIMSTAMP_TO_MICROSEC(x) (TIMEVAL_TO_MICROSEC(x)) -#define MILLISEC_TO_TIMEVAL(x, tv) \ - do { \ - (tv)->tv_sec = (x) / 1000; \ - (tv)->tv_usec = (x * 1000) - ((tv)->tv_sec * 1000000); \ - } while(0) - -#define MICROSEC_TO_TIMEVAL(x, tv) \ - do { \ - (tv)->tv_sec = (x) / 1000000; \ - (tv)->tv_usec = (x) - ((tv)->tv_sec * 1000000); \ - } while(0) - -#define NANOSEC_TO_TIMEVAL(x, tv) \ - do { \ - (tv)->tv_sec = (x) / 1000000000; \ - (tv)->tv_usec = ((x) % 1000000000) / 1000; \ - } while(0) - -#define NANOSEC_TO_TIMESPEC(x, ts) \ - do { \ - (ts)->tv_sec = (x) / 1000000000; \ - (ts)->tv_nsec = (x) % 1000000000; \ - } while(0) - -#define TIMESPEC_TO_MILLISEC(x) (((x)->tv_sec * 1000) + ((x)->tv_nsec / 1000000)) -#define TIMESPEC_TO_MICROSEC(x) (((x)->tv_sec * 1000000) + (x)->tv_nsec / 1000) +#define MILLISEC_TO_TIMEVAL(x, tv) \ + do { \ + (tv)->tv_sec = (x) / 1000; \ + (tv)->tv_usec = (x * 1000) - ((tv)->tv_sec * 1000000); \ + } while (0) + +#define MICROSEC_TO_TIMEVAL(x, tv) \ + do { \ + (tv)->tv_sec = (x) / 1000000; \ + (tv)->tv_usec = (x) - ((tv)->tv_sec * 1000000); \ + } while (0) + +#define NANOSEC_TO_TIMEVAL(x, tv) \ + do { \ + (tv)->tv_sec = (x) / 1000000000; \ + (tv)->tv_usec = ((x) % 1000000000) / 1000; \ + } while (0) + +#define NANOSEC_TO_TIMESPEC(x, ts) \ + do { \ + (ts)->tv_sec = (x) / 1000000000; \ + (ts)->tv_nsec = (x) % 1000000000; \ + } while (0) + +#define TIMESPEC_TO_MILLISEC(x) (((x)->tv_sec * 1000) + ((x)->tv_nsec / 1000000)) +#define TIMESPEC_TO_MICROSEC(x) (((x)->tv_sec * 1000000) + (x)->tv_nsec / 1000) #define TIMESPEC_TO_NANOSEC(x) ((u_int64_t)((x)->tv_sec * 1000000000) + ((u_int64_t)(x)->tv_nsec)) -#define TIMEVAL_SET(a, b) \ - do { \ - (a)->tv_sec = (b)->tv_sec; \ - (a)->tv_usec = (b)->tv_usec; \ - } while(0) +#define TIMEVAL_SET(a, b) \ + do { \ + (a)->tv_sec = (b)->tv_sec; \ + (a)->tv_usec = (b)->tv_usec; \ + } while (0) -#define TIMESPEC_SET(a, b) \ - do { \ - (a)->tv_sec = (b)->tv_sec; \ - (a)->tv_nsec = (b)->tv_nsec; \ - } while(0) +#define TIMESPEC_SET(a, b) \ + do { \ + (a)->tv_sec = (b)->tv_sec; \ + (a)->tv_nsec = (b)->tv_nsec; \ + } while (0) /* * Help suppress some compiler warnings * No problem if variable is actually used */ -#ifdef UNUSED -#elif defined(__GNUC__) -# define UNUSED(x) x __attribute__((unused)) -#elif defined(__LCLINT__) -# define UNUSED(x) /*@unused@*/ x -#else -# define UNUSED(x) x +#ifdef UNUSED +#elif defined(__GNUC__) +#define UNUSED(x) x __attribute__((unused)) +#elif defined(__LCLINT__) +#define UNUSED(x) /*@unused@*/ x +#else +#define UNUSED(x) x #endif #ifndef max -# define max(a,b) \ - ({ __typeof__ (a) _a = (a); \ - __typeof__ (b) _b = (b); \ - _a > _b ? _a : _b; }) +#define max(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a > _b ? _a : _b; \ + }) #endif #ifndef min -# define min(a,b) \ - ({ __typeof__ (a) _a = (a); \ - __typeof__ (b) _b = (b); \ - _a > _b ? _b : _a; }) +#define min(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a > _b ? _b : _a; \ + }) #endif - -#endif /* DEFINES */ diff --git a/src/fragroute/argv.c b/src/fragroute/argv.c index 2a0b36bc9..01c6aedc8 100644 --- a/src/fragroute/argv.c +++ b/src/fragroute/argv.c @@ -6,15 +6,13 @@ * $Id$ */ +#include "argv.h" #include "config.h" - #include #include #include #include -#include "argv.h" - int argv_create(char *p, int argc, char *argv[]) { diff --git a/src/fragroute/argv.h b/src/fragroute/argv.h index 5f6e8b6cd..3d70cf089 100644 --- a/src/fragroute/argv.h +++ b/src/fragroute/argv.h @@ -6,10 +6,7 @@ * $Id$ */ -#ifndef ARGV_H -#define ARGV_H +#pragma once int argv_create(char *p, int argc, char *argv[]); char *argv_copy(char *argv[]); - -#endif /* ARGV_H */ diff --git a/src/fragroute/bget.c b/src/fragroute/bget.c index 89a84e764..422b16990 100644 --- a/src/fragroute/bget.c +++ b/src/fragroute/bget.c @@ -399,55 +399,62 @@ */ #if 0 -#define TestProg 20000 /* Generate built-in test program - if defined. The value specifies - how many buffer allocation attempts - the test program should make. */ +#define TestProg \ + 20000 /* Generate built-in test program \ +if defined. The value specifies \ +how many buffer allocation attempts \ +the test program should make. */ #endif -#define SizeQuant 4 /* Buffer allocation size quantum: - all buffers allocated are a - multiple of this size. This - MUST be a power of two. */ +#define SizeQuant \ + 4 /* Buffer allocation size quantum: \ +all buffers allocated are a \ +multiple of this size. This \ +MUST be a power of two. */ #if 0 -#define BufDump 1 /* Define this symbol to enable the - bpoold() function which dumps the - buffers in a buffer pool. */ - -#define BufValid 1 /* Define this symbol to enable the - bpoolv() function for validating - a buffer pool. */ - -#define DumpData 1 /* Define this symbol to enable the - bufdump() function which allows - dumping the contents of an allocated - or free buffer. */ - -#define BufStats 1 /* Define this symbol to enable the - bstats() function which calculates - the total free space in the buffer - pool, the largest available - buffer, and the total space - currently allocated. */ - -#define FreeWipe 1 /* Wipe free buffers to a guaranteed - pattern of garbage to trip up - miscreants who attempt to use - pointers into released buffers. */ - -#define BestFit 1 /* Use a best fit algorithm when - searching for space for an - allocation request. This uses - memory more efficiently, but - allocation will be much slower. */ +#define BufDump \ + 1 /* Define this symbol to enable the \ +bpoold() function which dumps the \ +buffers in a buffer pool. */ + +#define BufValid \ + 1 /* Define this symbol to enable the \ +bpoolv() function for validating \ +a buffer pool. */ + +#define DumpData \ + 1 /* Define this symbol to enable the \ +bufdump() function which allows \ +dumping the contents of an allocated \ +or free buffer. */ + +#define BufStats \ + 1 /* Define this symbol to enable the \ +bstats() function which calculates \ +the total free space in the buffer \ +pool, the largest available \ +buffer, and the total space \ +currently allocated. */ + +#define FreeWipe \ + 1 /* Wipe free buffers to a guaranteed \ +pattern of garbage to trip up \ +miscreants who attempt to use \ +pointers into released buffers. */ + +#define BestFit \ + 1 /* Use a best fit algorithm when \ +searching for space for an \ +allocation request. This uses \ +memory more efficiently, but \ +allocation will be much slower. */ #endif -#define BECtl 1 /* Define this symbol to enable the - bectl() function for automatic - pool space control. */ - -#include +#define BECtl \ + 1 /* Define this symbol to enable the \ +bectl() function for automatic \ +pool space control. */ #ifdef lint -#define NDEBUG /* Exits in asserts confuse lint */ +#define NDEBUG /* Exits in asserts confuse lint */ /* LINTLIBRARY */ /* Don't complain about def, no ref */ extern char *sprintf(); /* Sun includes don't define sprintf */ #endif @@ -455,9 +462,9 @@ extern char *sprintf(); /* Sun includes don't define sprintf */ #include #include -#ifdef BufDump /* BufDump implies DumpData */ +#ifdef BufDump /* BufDump implies DumpData */ #ifndef DumpData -#define DumpData 1 +#define DumpData 1 #endif #endif @@ -470,48 +477,47 @@ extern char *sprintf(); /* Sun includes don't define sprintf */ #include "bget.h" -#define MemSize int /* Type for size arguments to memxxx() - functions such as memcmp(). */ +#define MemSize \ + int /* Type for size arguments to memxxx() \ +functions such as memcmp(). */ /* Queue links */ struct qlinks { - struct bfhead *flink; /* Forward link */ - struct bfhead *blink; /* Backward link */ + struct bfhead *flink; /* Forward link */ + struct bfhead *blink; /* Backward link */ }; /* Header in allocated and free buffers */ struct bhead { - bufsize prevfree; /* Relative link back to previous - free buffer in memory or 0 if - previous buffer is allocated. */ - bufsize bsize; /* Buffer size: positive if free, - negative if allocated. */ + bufsize prevfree; /* Relative link back to previous + free buffer in memory or 0 if + previous buffer is allocated. */ + bufsize bsize; /* Buffer size: positive if free, + negative if allocated. */ }; -#define BH(p) ((struct bhead *) (p)) +#define BH(p) ((struct bhead *)(p)) /* Header in directly allocated buffers (by acqfcn) */ struct bdhead { - bufsize tsize; /* Total size, including overhead */ - struct bhead bh; /* Common header */ + bufsize tsize; /* Total size, including overhead */ + struct bhead bh; /* Common header */ }; -#define BDH(p) ((struct bdhead *) (p)) +#define BDH(p) ((struct bdhead *)(p)) /* Header in free buffers */ struct bfhead { - struct bhead bh; /* Common allocated/free header */ - struct qlinks ql; /* Links on free list */ -}; -#define BFH(p) ((struct bfhead *) (p)) - -static struct bfhead freelist = { /* List of free buffers */ - {0, 0}, - {&freelist, &freelist} + struct bhead bh; /* Common allocated/free header */ + struct qlinks ql; /* Links on free list */ }; +#define BFH(p) ((struct bfhead *)(p)) +static struct bfhead freelist = {/* List of free buffers */ + {0, 0}, + {&freelist, &freelist}}; #ifdef BufStats static bufsize totalloc = 0; /* Total space currently allocated */ @@ -542,20 +548,21 @@ static bufsize pool_len = 0; /* 0: no bpool calls have been made /* Minimum allocation quantum: */ -#define QLSize (sizeof(struct qlinks)) -#define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize) +#define QLSize (sizeof(struct qlinks)) +#define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize) -#define V (void) /* To denote unwanted returned values */ +#define V (void)/* To denote unwanted returned values */ /* End sentinel: value placed in bsize field of dummy block delimiting end of pool block. The most negative number which will fit in a bufsize, defined in a way that the compiler will accept. */ -#define ESent ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2)) +#define ESent ((bufsize)(-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2)) /* BGET -- Allocate a buffer. */ -void *bget(requested_size) +void * +bget(requested_size) bufsize requested_size; { bufsize size = requested_size; @@ -570,8 +577,8 @@ bufsize requested_size; assert(size > 0); - if (size < (bufsize)SizeQ) { /* Need at least room for the */ - size = SizeQ; /* queue links. */ + if (size < (bufsize)SizeQ) { /* Need at least room for the */ + size = SizeQ; /* queue links. */ } #ifdef SizeQuant #if SizeQuant > 1 @@ -579,9 +586,9 @@ bufsize requested_size; #endif #endif - size += sizeof(struct bhead); /* Add overhead in allocated buffer - * to size required. - */ + size += sizeof(struct bhead); /* Add overhead in allocated buffer + * to size required. + */ #ifdef BECtl /* If a compact function was provided in the call to bectl(), wrap @@ -591,14 +598,13 @@ bufsize requested_size; while (1) { #endif - b = freelist.ql.flink; + b = freelist.ql.flink; #ifdef BestFit best = &freelist; #endif - - /* Scan the free list searching for the first buffer big enough - to hold the requested size buffer. */ + /* Scan the free list searching for the first buffer big enough + to hold the requested size buffer. */ #ifdef BestFit while (b != &freelist) { @@ -612,74 +618,73 @@ bufsize requested_size; b = best; #endif /* BestFit */ - while (b != &freelist) { - if ((bufsize) b->bh.bsize >= size) { - - /* Buffer is big enough to satisfy the request. Allocate it - * to the caller. We must decide whether the buffer is large - * enough to split into the part given to the caller and a - * free buffer that remains on the free list, or whether the - * entire buffer should be removed from the free list and - * given to the caller in its entirety. We only split the - * buffer if enough room remains for a header plus the minimum - * quantum of allocation. - */ + while (b != &freelist) { + if ((bufsize)b->bh.bsize >= size) { + /* Buffer is big enough to satisfy the request. Allocate it + * to the caller. We must decide whether the buffer is large + * enough to split into the part given to the caller and a + * free buffer that remains on the free list, or whether the + * entire buffer should be removed from the free list and + * given to the caller in its entirety. We only split the + * buffer if enough room remains for a header plus the minimum + * quantum of allocation. + */ - if ((b->bh.bsize - size) > (bufsize)(SizeQ + (sizeof(struct bhead)))) { - struct bhead *ba, *bn; - - ba = BH(((char *) b) + (b->bh.bsize - size)); - bn = BH(((char *) ba) + size); - assert(bn->prevfree == b->bh.bsize); - /* Subtract size from length of free block. */ - b->bh.bsize -= size; - /* Link allocated buffer to the previous free buffer. */ - ba->prevfree = b->bh.bsize; - /* Plug negative size into user buffer. */ - ba->bsize = -(bufsize) size; - /* Mark buffer after this one not preceded by free block. */ - bn->prevfree = 0; + if ((b->bh.bsize - size) > (bufsize)(SizeQ + (sizeof(struct bhead)))) { + struct bhead *ba, *bn; + + ba = BH(((char *)b) + (b->bh.bsize - size)); + bn = BH(((char *)ba) + size); + assert(bn->prevfree == b->bh.bsize); + /* Subtract size from length of free block. */ + b->bh.bsize -= size; + /* Link allocated buffer to the previous free buffer. */ + ba->prevfree = b->bh.bsize; + /* Plug negative size into user buffer. */ + ba->bsize = -(bufsize)size; + /* Mark buffer after this one not preceded by free block. */ + bn->prevfree = 0; #ifdef BufStats totalloc += size; numget++; /* Increment number of bget() calls */ #endif - buf = (void *) ((((char *) ba) + sizeof(struct bhead))); - return buf; - } else { - struct bhead *ba; + buf = (void *)((((char *)ba) + sizeof(struct bhead))); + return buf; + } else { + struct bhead *ba; - ba = BH(((char *) b) + b->bh.bsize); - assert(ba->prevfree == b->bh.bsize); + ba = BH(((char *)b) + b->bh.bsize); + assert(ba->prevfree == b->bh.bsize); - /* The buffer isn't big enough to split. Give the whole - * shebang to the caller and remove it from the free list. - */ + /* The buffer isn't big enough to split. Give the whole + * shebang to the caller and remove it from the free list. + */ - assert(b->ql.blink->ql.flink == b); - assert(b->ql.flink->ql.blink == b); - b->ql.blink->ql.flink = b->ql.flink; - b->ql.flink->ql.blink = b->ql.blink; + assert(b->ql.blink->ql.flink == b); + assert(b->ql.flink->ql.blink == b); + b->ql.blink->ql.flink = b->ql.flink; + b->ql.flink->ql.blink = b->ql.blink; #ifdef BufStats totalloc += b->bh.bsize; numget++; /* Increment number of bget() calls */ #endif - /* Negate size to mark buffer allocated. */ - b->bh.bsize = -(b->bh.bsize); + /* Negate size to mark buffer allocated. */ + b->bh.bsize = -(b->bh.bsize); - /* Zero the back pointer in the next buffer in memory - * to indicate that this buffer is allocated. - */ - ba->prevfree = 0; + /* Zero the back pointer in the next buffer in memory + * to indicate that this buffer is allocated. + */ + ba->prevfree = 0; - /* Give user buffer starting at queue links. */ - buf = (void *) &(b->ql); - return buf; - } + /* Give user buffer starting at queue links. */ + buf = (void *)&(b->ql); + return buf; } - b = b->ql.flink; /* Link to next buffer */ } + b = b->ql.flink; /* Link to next buffer */ + } #ifdef BECtl /* We failed to find a buffer. If there's a compact function @@ -749,29 +754,30 @@ bufsize requested_size; the entire contents of the buffer to zero, not just the region requested by the caller. */ -void *bgetz(size) - bufsize size; +void * +bgetz(size) +bufsize size; { - char *buf = (char *) bget(size); + char *buf = (char *)bget(size); if (buf != NULL) { - struct bhead *b; - bufsize rsize; + struct bhead *b; + bufsize rsize; - b = BH(buf - sizeof(struct bhead)); - rsize = -(b->bsize); - if (rsize == 0) { - struct bdhead *bd; + b = BH(buf - sizeof(struct bhead)); + rsize = -(b->bsize); + if (rsize == 0) { + struct bdhead *bd; - bd = BDH(buf - sizeof(struct bdhead)); - rsize = bd->tsize - sizeof(struct bdhead); - } else { - rsize -= sizeof(struct bhead); - } - assert(rsize >= size); - V memset(buf, 0, (MemSize) rsize); + bd = BDH(buf - sizeof(struct bdhead)); + rsize = bd->tsize - sizeof(struct bdhead); + } else { + rsize -= sizeof(struct bhead); + } + assert(rsize >= size); + V memset(buf, 0, (MemSize)rsize); } - return ((void *) buf); + return ((void *)buf); } /* BGETR -- Reallocate a buffer. This is a minimal implementation, @@ -779,12 +785,11 @@ void *bgetz(size) enhanced to allow the buffer to grow into adjacent free blocks and to avoid moving data unnecessarily. */ -void *bgetr(buf, size) - void *buf; - bufsize size; +void *bgetr(buf, size) void *buf; +bufsize size; { void *nbuf; - bufsize osize; /* Old size of buffer */ + bufsize osize; /* Old size of buffer */ struct bhead *b; if ((nbuf = bget(size)) == NULL) { /* Acquire new buffer */ @@ -793,7 +798,7 @@ void *bgetr(buf, size) if (buf == NULL) { return nbuf; } - b = BH(((char *) buf) - sizeof(struct bhead)); + b = BH(((char *)buf) - sizeof(struct bhead)); osize = -b->bsize; #ifdef BECtl if (osize == 0) { @@ -804,10 +809,11 @@ void *bgetr(buf, size) osize = bd->tsize - sizeof(struct bdhead); } else #endif - osize -= sizeof(struct bhead); + osize -= sizeof(struct bhead); assert(osize > 0); - V memcpy((char *) nbuf, (char *) buf, /* Copy the data */ - (MemSize) ((size < osize) ? size : osize)); + V memcpy((char *)nbuf, + (char *)buf, /* Copy the data */ + (MemSize)((size < osize) ? size : osize)); brel(buf); return nbuf; @@ -815,13 +821,12 @@ void *bgetr(buf, size) /* BREL -- Release a buffer. */ -void brel(buf) - void *buf; +void brel(buf) void *buf; { struct bfhead *b, *bn; assert(buf != NULL); - b = BFH(((char *) buf) - sizeof(struct bhead)); + b = BFH(((char *)buf) - sizeof(struct bhead)); #ifdef BufStats numrel++; /* Increment number of brel() calls */ #endif @@ -851,14 +856,14 @@ void brel(buf) allocated. */ if (b->bh.bsize >= 0) { - bn = NULL; + bn = NULL; } assert(b->bh.bsize < 0); /* Back pointer in next buffer must be zero, indicating the same thing: */ - assert(BH((char *) b - b->bh.bsize)->prevfree == 0); + assert(BH((char *)b - b->bh.bsize)->prevfree == 0); #ifdef BufStats totalloc += b->bh.bsize; @@ -868,31 +873,29 @@ void brel(buf) /* If the back link is nonzero, the previous buffer is free. */ if (b->bh.prevfree != 0) { + /* The previous buffer is free. Consolidate this buffer with it + by adding the length of this buffer to the previous free + buffer. Note that we subtract the size in the buffer being + released, since it's negative to indicate that the buffer is + allocated. */ - /* The previous buffer is free. Consolidate this buffer with it - by adding the length of this buffer to the previous free - buffer. Note that we subtract the size in the buffer being - released, since it's negative to indicate that the buffer is - allocated. */ - - register bufsize size = b->bh.bsize; + register bufsize size = b->bh.bsize; /* Make the previous buffer the one we're working on. */ - assert(BH((char *) b - b->bh.prevfree)->bsize == b->bh.prevfree); - b = BFH(((char *) b) - b->bh.prevfree); - b->bh.bsize -= size; + assert(BH((char *)b - b->bh.prevfree)->bsize == b->bh.prevfree); + b = BFH(((char *)b) - b->bh.prevfree); + b->bh.bsize -= size; } else { - /* The previous buffer isn't allocated. Insert this buffer on the free list as an isolated free block. */ - assert(freelist.ql.blink->ql.flink == &freelist); - assert(freelist.ql.flink->ql.blink == &freelist); - b->ql.flink = &freelist; - b->ql.blink = freelist.ql.blink; - freelist.ql.blink = b; - b->ql.blink->ql.flink = b; - b->bh.bsize = -b->bh.bsize; + assert(freelist.ql.blink->ql.flink == &freelist); + assert(freelist.ql.flink->ql.blink == &freelist); + b->ql.flink = &freelist; + b->ql.blink = freelist.ql.blink; + freelist.ql.blink = b; + b->ql.blink->ql.flink = b; + b->bh.bsize = -b->bh.bsize; } /* Now we look at the next buffer in memory, located by advancing from @@ -900,27 +903,26 @@ void brel(buf) free. If it is, we combine this buffer with the next one in memory, dechaining the second buffer from the free list. */ - bn = BFH(((char *) b) + b->bh.bsize); + bn = BFH(((char *)b) + b->bh.bsize); if (bn->bh.bsize > 0) { - - /* The buffer is free. Remove it from the free list and add - its size to that of our buffer. */ - - assert(BH((char *) bn + bn->bh.bsize)->prevfree == bn->bh.bsize); - assert(bn->ql.blink->ql.flink == bn); - assert(bn->ql.flink->ql.blink == bn); - bn->ql.blink->ql.flink = bn->ql.flink; - bn->ql.flink->ql.blink = bn->ql.blink; - b->bh.bsize += bn->bh.bsize; - - /* Finally, advance to the buffer that follows the newly - consolidated free block. We must set its backpointer to the - head of the consolidated free block. We know the next block - must be an allocated block because the process of recombination - guarantees that two free blocks will never be contiguous in - memory. */ - - bn = BFH(((char *) b) + b->bh.bsize); + /* The buffer is free. Remove it from the free list and add + its size to that of our buffer. */ + + assert(BH((char *)bn + bn->bh.bsize)->prevfree == bn->bh.bsize); + assert(bn->ql.blink->ql.flink == bn); + assert(bn->ql.flink->ql.blink == bn); + bn->ql.blink->ql.flink = bn->ql.flink; + bn->ql.flink->ql.blink = bn->ql.blink; + b->bh.bsize += bn->bh.bsize; + + /* Finally, advance to the buffer that follows the newly + consolidated free block. We must set its backpointer to the + head of the consolidated free block. We know the next block + must be an allocated block because the process of recombination + guarantees that two free blocks will never be contiguous in + memory. */ + + bn = BFH(((char *)b) + b->bh.bsize); } #ifdef FreeWipe V memset(((char *) b) + sizeof(struct bfhead), 0x55, @@ -979,9 +981,8 @@ void bectl(compact, acquire, release, pool_incr) /* BPOOL -- Add a region of memory to the buffer pool. */ -void bpool(buf, len) - void *buf; - bufsize len; +void bpool(buf, len) void *buf; +bufsize len; { struct bfhead *b = BFH(buf); struct bhead *bn; @@ -1006,7 +1007,7 @@ void bpool(buf, len) it had better not be (much) larger than the largest buffer whose size we can store in bhead.bsize. */ - assert(len - sizeof(struct bhead) <= -((bufsize) ESent + 1)); + assert(len - sizeof(struct bhead) <= -((bufsize)ESent + 1)); /* Clear the backpointer at the start of the block to indicate that there is no free block prior to this one. That blocks @@ -1032,13 +1033,13 @@ void bpool(buf, len) allocation and release functions). */ len -= sizeof(struct bhead); - b->bh.bsize = (bufsize) len; + b->bh.bsize = (bufsize)len; #ifdef FreeWipe V memset(((char *) b) + sizeof(struct bfhead), 0x55, (MemSize) (len - sizeof(struct bfhead))); #endif - bn = BH(((char *) b) + len); - bn->prevfree = (bufsize) len; + bn = BH(((char *)b) + len); + bn->prevfree = (bufsize)len; /* Definition of ESent assumes two's complement! */ assert((~0) == -1); bn->bsize = ESent; @@ -1245,34 +1246,34 @@ int bpoolv(buf) } #endif /* BufValid */ - /***********************\ - * * - * Built-in test program * - * * - \***********************/ +/***********************\ +* * +* Built-in test program * +* * +\***********************/ #ifdef TestProg -#define Repeatable 1 /* Repeatable pseudorandom sequence */ +#define Repeatable 1 /* Repeatable pseudorandom sequence */ /* If Repeatable is not defined, a time-seeded pseudorandom sequence is generated, exercising BGET with a different pattern of calls on each run. */ -#define OUR_RAND /* Use our own built-in version of - rand() to guarantee the test is - 100% repeatable. */ +#define OUR_RAND /* Use our own built-in version of \ + rand() to guarantee the test is \ + 100% repeatable. */ #ifdef BECtl -#define PoolSize 300000 /* Test buffer pool size */ +#define PoolSize 300000 /* Test buffer pool size */ #else -#define PoolSize 50000 /* Test buffer pool size */ +#define PoolSize 50000 /* Test buffer pool size */ #endif -#define ExpIncr 32768 /* Test expansion block size */ -#define CompactTries 10 /* Maximum tries at compacting */ +#define ExpIncr 32768 /* Test expansion block size */ +#define CompactTries 10 /* Maximum tries at compacting */ -#define dumpAlloc 0 /* Dump allocated buffers ? */ -#define dumpFree 0 /* Dump free buffers ? */ +#define dumpAlloc 0 /* Dump allocated buffers ? */ +#define dumpFree 0 /* Dump free buffers ? */ #ifndef Repeatable extern long time(); diff --git a/src/fragroute/bget.h b/src/fragroute/bget.h index 811c2e4c1..6ac8a702d 100644 --- a/src/fragroute/bget.h +++ b/src/fragroute/bget.h @@ -4,6 +4,8 @@ */ +#pragma once + #ifndef _ #ifdef PROTOTYPES #define _(x) x /* If compiler knows prototypes */ diff --git a/src/fragroute/fragroute.c b/src/fragroute/fragroute.c index b69866866..b7edd2b02 100644 --- a/src/fragroute/fragroute.c +++ b/src/fragroute/fragroute.c @@ -7,16 +7,13 @@ * $Id$ */ -#include "config.h" -#include "lib/queue.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include +#include "lib/queue.h" #include #include #include -#include #ifdef HAVE_LIBDNET /* need to undef these which are pulled in via defines.h, prior to importing dnet.h */ @@ -33,9 +30,8 @@ #endif #include "fragroute.h" -#include "pkt.h" #include "mod.h" -// #include "tun.h" +#include "pkt.h" void fragroute_close(fragroute_t *ctx) @@ -46,27 +42,22 @@ fragroute_close(fragroute_t *ctx) pkt_close(); } - int fragroute_process(fragroute_t *ctx, void *buf, size_t len) { struct pkt *pkt; assert(ctx); assert(buf); - + ctx->first_packet = 0; /* save the l2 header of the original packet for later */ - ctx->l2len = get_l2len(buf, len, ctx->dlt); + ctx->l2len = get_l2len(buf, (int)len, ctx->dlt); memcpy(ctx->l2header, buf, ctx->l2len); if ((pkt = pkt_new(len)) == NULL) { strcpy(ctx->errbuf, "unable to pkt_new()"); return -1; } -// if (len > PKT_BUF_LEN) { -// sprintf(ctx->errbuf, "skipping oversized packet: %zu", len); -// return -1; -// } memcpy(pkt->pkt_data, buf, len); pkt->pkt_end = pkt->pkt_data + len; @@ -77,11 +68,11 @@ fragroute_process(fragroute_t *ctx, void *buf, size_t len) strcpy(ctx->errbuf, "skipping non-IP packet"); return -1; } -/* Don't always checksum packets before being fragged - if (pkt->pkt_eth && htons(pkt->pkt_eth->eth_type) == ETH_TYPE_IP) { - ip_checksum(pkt->pkt_ip, len); - } -*/ + /* Don't always checksum packets before being fragged + if (pkt->pkt_eth && htons(pkt->pkt_eth->eth_type) == ETH_TYPE_IP) { + ip_checksum(pkt->pkt_ip, len); + } + */ TAILQ_INIT(ctx->pktq); TAILQ_INSERT_TAIL(ctx->pktq, pkt, pkt_next); @@ -103,23 +94,23 @@ fragroute_getfragment(fragroute_t *ctx, char **packet) static struct pkt *next = NULL; char *pkt_data = *packet; u_int32_t length; - + if (ctx->first_packet != 0) { pkt = next; } else { ctx->first_packet = 1; pkt = TAILQ_FIRST(ctx->pktq); } - + if (pkt != TAILQ_END(&(ctx->pktq))) { next = TAILQ_NEXT(pkt, pkt_next); memcpy(pkt_data, pkt->pkt_data, pkt->pkt_end - pkt->pkt_data); - + /* return the original L2 header */ memcpy(pkt_data, ctx->l2header, ctx->l2len); length = pkt->pkt_end - pkt->pkt_data; pkt = next; - return length; + return (int)length; } return 0; // nothing @@ -134,7 +125,6 @@ fragroute_init(const int mtu, const int dlt, const char *config, char *errbuf) sprintf(errbuf, "Fragroute only supports DLT_EN10MB pcap files"); return NULL; } - ctx = (fragroute_t *)safe_malloc(sizeof(fragroute_t)); ctx->pktq = (struct pktq *)safe_malloc(sizeof(struct pktq)); diff --git a/src/fragroute/fragroute.h b/src/fragroute/fragroute.h index 22535bc89..2931ad653 100644 --- a/src/fragroute/fragroute.h +++ b/src/fragroute/fragroute.h @@ -5,9 +5,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,33 +18,26 @@ * You should have received a copy of the GNU General Public License * along with the Tcpreplay Suite. If not, see . */ - + +#pragma once #include "config.h" #include "pkt.h" -#ifndef __FRAGROUTE_H__ -#define __FRAGROUTE_H__ - #define FRAGROUTE_ERRBUF_LEN 1024 /* Fragroute context. */ struct fragroute_s { - struct addr src; - struct addr dst; - struct addr smac; - struct addr dmac; - int dlt; - int mtu; - int first_packet; /* have we called getfragment() yet after process()? */ - int l2len; - u_char l2header[50]; -// arp_t *arp; -// eth_t *eth; -// intf_t *intf; -// route_t *route; -// tun_t *tun; - char errbuf[FRAGROUTE_ERRBUF_LEN]; + struct addr src; + struct addr dst; + struct addr smac; + struct addr dmac; + int dlt; + int mtu; + int first_packet; /* have we called getfragment() yet after process()? */ + int l2len; + u_char l2header[50]; + char errbuf[FRAGROUTE_ERRBUF_LEN]; struct pktq *pktq; /* packet chain */ }; @@ -52,7 +45,5 @@ typedef struct fragroute_s fragroute_t; int fragroute_process(fragroute_t *ctx, void *buf, size_t len); int fragroute_getfragment(fragroute_t *ctx, char **packet); -fragroute_t * fragroute_init(const int mtu, const int dlt, const char *config, char *errbuf); +fragroute_t *fragroute_init(const int mtu, const int dlt, const char *config, char *errbuf); void fragroute_close(fragroute_t *ctx); - -#endif /* __FRAGROUTE_H__ */ diff --git a/src/fragroute/iputil.c b/src/fragroute/iputil.c index e6ac56c25..febbc99fc 100644 --- a/src/fragroute/iputil.c +++ b/src/fragroute/iputil.c @@ -1,7 +1,6 @@ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" -#include "iputil.h" #ifdef HAVE_DNET_H #include #endif @@ -12,12 +11,10 @@ #include #include -static ssize_t -inet_add_option_6(void *buf, size_t len, int proto, const void *optbuf, size_t optlen); +static ssize_t inet_add_option_6(void *buf, size_t len, int proto, const void *optbuf, size_t optlen); ssize_t -inet_add_option(uint16_t eth_type, void *buf, size_t len, - int proto, const void *optbuf, size_t optlen) +inet_add_option(uint16_t eth_type, void *buf, size_t len, int proto, const void *optbuf, size_t optlen) { if (eth_type == ETH_TYPE_IP) { return ip_add_option(buf, len, proto, optbuf, optlen); @@ -52,15 +49,14 @@ inet_add_option_6(void *buf, size_t len, int proto, const void *optbuf, size_t o hl = tcp->th_off << 2; p = (u_char *)tcp + hl; - datalen = ntohs(ip6->ip6_plen) + IP6_HDR_LEN - (p - (u_char *)buf); + datalen = ntohs(ip6->ip6_plen) + IP6_HDR_LEN - (int)(p - (u_char *)buf); /* Compute padding to next word boundary. */ - if ((padlen = 4 - (optlen % 4)) == 4) + if ((padlen = 4 - (int)(optlen % 4)) == 4) padlen = 0; /* XXX - IP_HDR_LEN_MAX == TCP_HDR_LEN_MAX */ - if (hl + optlen + padlen > IP_HDR_LEN_MAX || - ntohs(ip6->ip6_plen) + IP6_HDR_LEN + optlen + padlen > len) { + if (hl + optlen + padlen > IP_HDR_LEN_MAX || ntohs(ip6->ip6_plen) + IP6_HDR_LEN + optlen + padlen > len) { errno = EINVAL; return (-1); } @@ -82,10 +78,9 @@ inet_add_option_6(void *buf, size_t len, int proto, const void *optbuf, size_t o ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen); - return (optlen); + return (ssize_t)optlen; } - void inet_checksum(uint16_t eth_type, void *buf, size_t len) { @@ -97,8 +92,7 @@ inet_checksum(uint16_t eth_type, void *buf, size_t len) } int -raw_ip_opt_parse(int argc, char *argv[], uint8_t *opt_type, uint8_t *opt_len, - uint8_t *buff, int buff_len) +raw_ip_opt_parse(int argc, char *argv[], uint8_t *opt_type, uint8_t *opt_len, uint8_t *buff, int buff_len) { int i, j; @@ -118,16 +112,14 @@ raw_ip_opt_parse(int argc, char *argv[], uint8_t *opt_type, uint8_t *opt_len, } } if (*opt_len != j + 2) { - warnx("invalid opt->len (%d) doesn't match data length (%d)", - *opt_len, j); + warnx("invalid opt->len (%d) doesn't match data length (%d)", *opt_len, j); return -1; } return 0; } int -raw_ip6_opt_parse(int argc, char *argv[], uint8_t *proto, int *len, - uint8_t *buff, int buff_len) +raw_ip6_opt_parse(int argc, char *argv[], uint8_t *proto, int *len, uint8_t *buff, int buff_len) { int i, j; diff --git a/src/fragroute/iputil.h b/src/fragroute/iputil.h index 3d2d4b18c..b017bc936 100644 --- a/src/fragroute/iputil.h +++ b/src/fragroute/iputil.h @@ -1,5 +1,6 @@ -#ifndef IPUTIL_H -#define IPUTIL_H +#pragma once + +#include "defines.h" ssize_t inet_add_option(uint16_t eth_type, void *buf, size_t len, int proto, const void *optbuf, size_t optlen); @@ -9,5 +10,3 @@ int raw_ip_opt_parse(int argc, char *argv[], uint8_t *type, uint8_t *len, uint8_t *buff, int buff_len); int raw_ip6_opt_parse(int argc, char *argv[], uint8_t *proto, int *len, uint8_t *buff, int buff_len); - -#endif /* IPUTIL_H */ diff --git a/src/fragroute/mod.c b/src/fragroute/mod.c index 8b923d078..bdc8376a0 100644 --- a/src/fragroute/mod.c +++ b/src/fragroute/mod.c @@ -7,66 +7,62 @@ * $Id$ */ -#include "config.h" -#include "lib/queue.h" +#include "mod.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include "argv.h" +#include "lib/queue.h" #include #include #include #include -#include "argv.h" -#include "mod.h" - -#define MAX_ARGS 128 +#define MAX_ARGS 128 struct rule { - struct mod *mod; - void *data; - TAILQ_ENTRY(rule) next; + struct mod *mod; + void *data; + TAILQ_ENTRY(rule) next; }; /* * new modules must be registered here. */ -extern struct mod mod_delay; -extern struct mod mod_drop; -extern struct mod mod_dup; -extern struct mod mod_echo; -extern struct mod mod_ip_chaff; -extern struct mod mod_ip_frag; -extern struct mod mod_ip_opt; -extern struct mod mod_ip_ttl; -extern struct mod mod_ip_tos; -extern struct mod mod_ip6_qos; -extern struct mod mod_ip6_opt; -extern struct mod mod_order; -extern struct mod mod_print; -extern struct mod mod_tcp_chaff; -extern struct mod mod_tcp_opt; -extern struct mod mod_tcp_seg; - -static struct mod *mods[] = { - &mod_delay, - &mod_drop, - &mod_dup, - &mod_echo, - &mod_ip_chaff, - &mod_ip_frag, - &mod_ip_opt, - &mod_ip_ttl, - &mod_ip_tos, - &mod_ip6_qos, - &mod_ip6_opt, - &mod_order, - &mod_print, - &mod_tcp_chaff, - &mod_tcp_opt, - &mod_tcp_seg, - NULL -}; +extern struct mod mod_delay; +extern struct mod mod_drop; +extern struct mod mod_dup; +extern struct mod mod_echo; +extern struct mod mod_ip_chaff; +extern struct mod mod_ip_frag; +extern struct mod mod_ip_opt; +extern struct mod mod_ip_ttl; +extern struct mod mod_ip_tos; +extern struct mod mod_ip6_qos; +extern struct mod mod_ip6_opt; +extern struct mod mod_order; +extern struct mod mod_print; +extern struct mod mod_tcp_chaff; +extern struct mod mod_tcp_opt; +extern struct mod mod_tcp_seg; + +static struct mod *mods[] = {&mod_delay, + &mod_drop, + &mod_dup, + &mod_echo, + &mod_ip_chaff, + &mod_ip_frag, + &mod_ip_opt, + &mod_ip_ttl, + &mod_ip_tos, + &mod_ip6_qos, + &mod_ip6_opt, + &mod_order, + &mod_print, + &mod_tcp_chaff, + &mod_tcp_opt, + &mod_tcp_seg, + NULL}; static TAILQ_HEAD(head, rule) rules; @@ -99,7 +95,6 @@ mod_open(const char *script, char *errbuf) dbg(1, "opened config file..."); /* read the file, one line at a time... */ for (i = 1; fgets(buf, sizeof(buf), fp) != NULL; i++) { - /* skip comments & blank lines */ if (*buf == '#' || *buf == '\r' || *buf == '\n') continue; @@ -136,10 +131,8 @@ mod_open(const char *script, char *errbuf) rule->mod = *m; /* pass the remaining args to the rule */ - if (rule->mod->open != NULL && - (rule->data = rule->mod->open(argc, argv)) == NULL) { - sprintf(errbuf, "invalid argument to directive '%s' (line %d)", - rule->mod->name, i); + if (rule->mod->open != NULL && (rule->data = rule->mod->open(argc, argv)) == NULL) { + sprintf(errbuf, "invalid argument to directive '%s' (line %d)", rule->mod->name, i); ret = -1; break; } @@ -150,10 +143,11 @@ mod_open(const char *script, char *errbuf) /* close the file */ fclose(fp); dbg(1, "close file..."); - + if (ret == 0) { buf[0] = '\0'; - TAILQ_FOREACH(rule, &rules, next) { + TAILQ_FOREACH(rule, &rules, next) + { strlcat(buf, rule->mod->name, sizeof(buf)); strlcat(buf, " -> ", sizeof(buf)); } @@ -172,7 +166,8 @@ mod_apply(struct pktq *pktq) { struct rule *rule; - TAILQ_FOREACH(rule, &rules, next) { + TAILQ_FOREACH(rule, &rules, next) + { rule->mod->apply(rule->data, pktq); } } @@ -182,7 +177,8 @@ mod_close(void) { struct rule *rule; - TAILQ_FOREACH_REVERSE(rule, &rules, next, head) { + TAILQ_FOREACH_REVERSE(rule, &rules, next, head) + { if (rule->mod->close != NULL) rule->data = rule->mod->close(rule->data); TAILQ_REMOVE(&rules, rule, next); diff --git a/src/fragroute/mod.h b/src/fragroute/mod.h index f1f493e47..5f7607cb3 100644 --- a/src/fragroute/mod.h +++ b/src/fragroute/mod.h @@ -6,8 +6,7 @@ * $Id$ */ -#ifndef MOD_H -#define MOD_H +#pragma once #include "pkt.h" @@ -23,5 +22,3 @@ void mod_usage(void); int mod_open(const char *script, char *errbuf); void mod_apply(struct pktq *pktq); void mod_close(void); - -#endif /* MOD_H */ diff --git a/src/fragroute/mod_delay.c b/src/fragroute/mod_delay.c index 6f7de5301..99db1c6df 100644 --- a/src/fragroute/mod_delay.c +++ b/src/fragroute/mod_delay.c @@ -7,22 +7,19 @@ */ #include "config.h" - -#include +#include "mod.h" +#include "pkt.h" #include #include -#include "pkt.h" -#include "mod.h" - -#define DELAY_FIRST 1 -#define DELAY_LAST 2 -#define DELAY_RANDOM 3 +#define DELAY_FIRST 1 +#define DELAY_LAST 2 +#define DELAY_RANDOM 3 struct delay_data { - rand_t *rnd; - int which; - struct timeval tv; + rand_t *rnd; + int which; + struct timeval tv; }; void * @@ -60,12 +57,12 @@ delay_open(int argc, char *argv[]) else return (delay_close(data)); - if ((usec = atoi(argv[2])) == 0) + if ((usec = strtol(argv[2], NULL, 10)) == 0) return (delay_close(data)); usec *= 1000; - data->tv.tv_sec = usec / 1000000; - data->tv.tv_usec = usec % 1000000; + data->tv.tv_sec = (time_t)(usec / 1000000); + data->tv.tv_usec = (suseconds_t)(usec % 1000000); return (data); } @@ -89,9 +86,9 @@ delay_apply(void *d, struct pktq *pktq) } struct mod mod_delay = { - "delay", /* name */ - "delay first|last|random ", /* usage */ - delay_open, /* open */ - delay_apply, /* apply */ - delay_close /* close */ + "delay", /* name */ + "delay first|last|random ", /* usage */ + delay_open, /* open */ + delay_apply, /* apply */ + delay_close /* close */ }; diff --git a/src/fragroute/mod_drop.c b/src/fragroute/mod_drop.c index 66b75c9cb..47711d548 100644 --- a/src/fragroute/mod_drop.c +++ b/src/fragroute/mod_drop.c @@ -7,22 +7,19 @@ */ #include "config.h" - -#include +#include "mod.h" +#include "pkt.h" #include #include -#include "pkt.h" -#include "mod.h" - -#define DROP_FIRST 1 -#define DROP_LAST 2 -#define DROP_RANDOM 3 +#define DROP_FIRST 1 +#define DROP_LAST 2 +#define DROP_RANDOM 3 struct drop_data { - rand_t *rnd; - int which; - int percent; + rand_t *rnd; + int which; + int percent; }; void * @@ -59,7 +56,7 @@ drop_open(int argc, char *argv[]) else return (drop_close(data)); - if ((data->percent = atoi(argv[2])) <= 0 || data->percent > 100) + if ((data->percent = (int)strtol(argv[2], NULL, 10)) <= 0 || data->percent > 100) return (drop_close(data)); return (data); @@ -71,8 +68,7 @@ drop_apply(void *d, struct pktq *pktq) struct drop_data *data = (struct drop_data *)d; struct pkt *pkt; - if (data->percent < 100 && - (rand_uint16(data->rnd) % 100) > data->percent) + if (data->percent < 100 && (rand_uint16(data->rnd) % 100) > data->percent) return (0); if (data->which == DROP_FIRST) @@ -91,9 +87,9 @@ drop_apply(void *d, struct pktq *pktq) } struct mod mod_drop = { - "drop", /* name */ - "drop first|last|random ", /* usage */ - drop_open, /* open */ - drop_apply, /* apply */ - drop_close /* close */ + "drop", /* name */ + "drop first|last|random ", /* usage */ + drop_open, /* open */ + drop_apply, /* apply */ + drop_close /* close */ }; diff --git a/src/fragroute/mod_dup.c b/src/fragroute/mod_dup.c index 5fde6c7ef..e64ab85e6 100644 --- a/src/fragroute/mod_dup.c +++ b/src/fragroute/mod_dup.c @@ -7,22 +7,19 @@ */ #include "config.h" - -#include +#include "mod.h" +#include "pkt.h" #include #include -#include "pkt.h" -#include "mod.h" - -#define DUP_FIRST 1 -#define DUP_LAST 2 -#define DUP_RANDOM 3 +#define DUP_FIRST 1 +#define DUP_LAST 2 +#define DUP_RANDOM 3 struct dup_data { - rand_t *rnd; - int which; - int percent; + rand_t *rnd; + int which; + int percent; }; void * @@ -59,7 +56,7 @@ dup_open(int argc, char *argv[]) else return (dup_close(data)); - if ((data->percent = atoi(argv[2])) <= 0 || data->percent > 100) + if ((data->percent = (int)strtol(argv[2], NULL, 10)) <= 0 || data->percent > 100) return (dup_close(data)); return (data); @@ -71,8 +68,7 @@ dup_apply(void *d, struct pktq *pktq) struct dup_data *data = (struct dup_data *)d; struct pkt *pkt, *new; - if (data->percent < 100 && - (rand_uint16(data->rnd) % 100) > data->percent) + if (data->percent < 100 && (rand_uint16(data->rnd) % 100) > data->percent) return (0); if (data->which == DUP_FIRST) @@ -95,9 +91,9 @@ dup_apply(void *d, struct pktq *pktq) } struct mod mod_dup = { - "dup", /* name */ - "dup first|last|random ", /* usage */ - dup_open, /* open */ - dup_apply, /* apply */ - dup_close /* close */ + "dup", /* name */ + "dup first|last|random ", /* usage */ + dup_open, /* open */ + dup_apply, /* apply */ + dup_close /* close */ }; diff --git a/src/fragroute/mod_echo.c b/src/fragroute/mod_echo.c index 31f64530c..3b84690f6 100644 --- a/src/fragroute/mod_echo.c +++ b/src/fragroute/mod_echo.c @@ -7,16 +7,12 @@ */ #include "config.h" - -#include - +#include "argv.h" +#include "mod.h" #include #include #include -#include "argv.h" -#include "mod.h" - void * echo_open(int argc, char *argv[]) { @@ -49,9 +45,9 @@ echo_close(void *d) } struct mod mod_echo = { - "echo", /* name */ - "echo ...", /* usage */ - echo_open, /* open */ - echo_apply, /* apply */ - echo_close /* close */ + "echo", /* name */ + "echo ...", /* usage */ + echo_open, /* open */ + echo_apply, /* apply */ + echo_close /* close */ }; diff --git a/src/fragroute/mod_ip6_opt.c b/src/fragroute/mod_ip6_opt.c index 523ffa367..7018f7acd 100644 --- a/src/fragroute/mod_ip6_opt.c +++ b/src/fragroute/mod_ip6_opt.c @@ -6,39 +6,33 @@ */ #include "config.h" - +#include "iputil.h" +#include "mod.h" +#include "pkt.h" #include #include #include #include -#include "pkt.h" -#include "mod.h" -#include "iputil.h" - #define MAX_ADDRS 32 -#define OPT6_TYPE_ROUTE 1 -#define OPT6_TYPE_RAW 2 +#define OPT6_TYPE_ROUTE 1 +#define OPT6_TYPE_RAW 2 -struct ip6_opt_data_route -{ +struct ip6_opt_data_route { int segments; struct addr addr[MAX_ADDRS]; }; -struct ip6_opt_data_raw -{ +struct ip6_opt_data_raw { int len; uint8_t proto; uint8_t data8[512]; }; -struct ip6_opt_data -{ +struct ip6_opt_data { int type; - union - { + union { struct ip6_opt_data_route route; struct ip6_opt_data_raw raw; } u; @@ -67,8 +61,7 @@ ip6_opt_open(int argc, char *argv[]) int i, j; opt->type = OPT6_TYPE_ROUTE; - if ((opt->u.route.segments = atoi(argv[2])) < 1 || - opt->u.route.segments > MAX_ADDRS) { + if ((opt->u.route.segments = (int)strtol(argv[2], NULL, 10)) < 1 || opt->u.route.segments > MAX_ADDRS) { warnx(" must be >= 1"); return (ip6_opt_close(opt)); } @@ -81,17 +74,19 @@ ip6_opt_open(int argc, char *argv[]) } for (; j < argc; i++, j++) { - if (addr_aton(argv[j], &opt->u.route.addr[i]) < 0 || - opt->u.route.addr[i].addr_type != ADDR_TYPE_IP6) { + if (addr_aton(argv[j], &opt->u.route.addr[i]) < 0 || opt->u.route.addr[i].addr_type != ADDR_TYPE_IP6) { return (ip6_opt_close(opt)); } } } else if (strcasecmp(argv[1], "raw") == 0) { opt->type = OPT6_TYPE_RAW; - if (raw_ip6_opt_parse(argc - 2, &argv[2], - &opt->u.raw.proto, &opt->u.raw.len, - &opt->u.raw.data8[2], sizeof(opt->u.raw.data8) - 2) != 0) + if (raw_ip6_opt_parse(argc - 2, + &argv[2], + &opt->u.raw.proto, + &opt->u.raw.len, + &opt->u.raw.data8[2], + sizeof(opt->u.raw.data8) - 2) != 0) return (ip6_opt_close(opt)); opt->u.raw.len += 2; opt->u.raw.data8[0] = 0; @@ -107,14 +102,15 @@ int ip6_opt_apply(void *d, struct pktq *pktq) { struct ip6_opt_data *opt = (struct ip6_opt_data *)d; - struct ip6_ext_hdr* ext; + struct ip6_ext_hdr *ext; int offset, len; struct pkt *pkt; uint8_t nxt, iph_nxt; - uint8_t* p; + uint8_t *p; int i; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type != ETH_TYPE_IPV6) { @@ -122,11 +118,11 @@ ip6_opt_apply(void *d, struct pktq *pktq) } nxt = pkt->pkt_ip6->ip6_nxt; - ext = (struct ip6_ext_hdr*)(((u_char*)pkt->pkt_ip6) + IP6_HDR_LEN); + ext = (struct ip6_ext_hdr *)(((u_char *)pkt->pkt_ip6) + IP6_HDR_LEN); if (opt->type == OPT6_TYPE_ROUTE) { offset = 8 + IP6_ADDR_LEN * opt->u.route.segments; - memmove(((u_char*)ext) + offset, ext, pkt->pkt_end - (u_char*)ext); + memmove(((u_char *)ext) + offset, ext, pkt->pkt_end - (u_char *)ext); pkt->pkt_end += offset; pkt->pkt_ip_data += offset; @@ -135,11 +131,11 @@ ip6_opt_apply(void *d, struct pktq *pktq) ext->ext_data.routing.type = 0; ext->ext_data.routing.segleft = opt->u.route.segments; - ((uint32_t*)ext)[1] = 0; /* reserved */ + ((uint32_t *)ext)[1] = 0; /* reserved */ iph_nxt = IP_PROTO_ROUTING; - p = (uint8_t*)(ext) + 8; + p = (uint8_t *)(ext) + 8; for (i = 0; i < opt->u.route.segments; ++i, p += IP6_ADDR_LEN) { memcpy(p, opt->u.route.addr[i].addr_data8, IP6_ADDR_LEN); @@ -147,14 +143,14 @@ ip6_opt_apply(void *d, struct pktq *pktq) } else if (opt->type == OPT6_TYPE_RAW) { offset = opt->u.raw.len; - memmove(((u_char*)ext) + offset, ext, pkt->pkt_end - (u_char*)ext); + memmove(((u_char *)ext) + offset, ext, pkt->pkt_end - (u_char *)ext); pkt->pkt_end += offset; pkt->pkt_ip_data += offset; iph_nxt = opt->u.raw.proto; - p = (uint8_t*)ext; + p = (uint8_t *)ext; memcpy(p, opt->u.raw.data8, opt->u.raw.len); #if 0 @@ -185,9 +181,9 @@ ip6_opt_apply(void *d, struct pktq *pktq) } struct mod mod_ip6_opt = { - "ip6_opt", /* name */ - "ip6_opt [route ...] | [raw ]", /* usage */ - ip6_opt_open, /* open */ - ip6_opt_apply, /* apply */ - ip6_opt_close /* close */ + "ip6_opt", /* name */ + "ip6_opt [route ...] | [raw ]", /* usage */ + ip6_opt_open, /* open */ + ip6_opt_apply, /* apply */ + ip6_opt_close /* close */ }; diff --git a/src/fragroute/mod_ip6_qos.c b/src/fragroute/mod_ip6_qos.c index 20edef74b..03392c9bd 100644 --- a/src/fragroute/mod_ip6_qos.c +++ b/src/fragroute/mod_ip6_qos.c @@ -6,19 +6,15 @@ */ #include "config.h" - +#include "mod.h" +#include "pkt.h" #include #include #include -#include "argv.h" -#include "mod.h" -#include "pkt.h" - -struct ip6_qos_data -{ - int ip6_tc; - int ip6_fl; +struct ip6_qos_data { + int ip6_tc; + int ip6_fl; }; static void * @@ -41,12 +37,10 @@ ip6_qos_open(int argc, char *argv[]) if ((data = calloc(1, sizeof(*data))) == NULL) return (NULL); - if (sscanf(argv[1], "%x", (unsigned int*)&data->ip6_tc) != 1 || - data->ip6_tc < 0 || data->ip6_tc > 255) + if (sscanf(argv[1], "%x", (unsigned int *)&data->ip6_tc) != 1 || data->ip6_tc < 0 || data->ip6_tc > 255) return (ip6_qos_close(data)); - if (sscanf(argv[2], "%x", (unsigned int*)&data->ip6_fl) != 1 || - data->ip6_fl < 0 || data->ip6_fl > 0x100000) + if (sscanf(argv[2], "%x", (unsigned int *)&data->ip6_fl) != 1 || data->ip6_fl < 0 || data->ip6_fl > 0x100000) return (ip6_qos_close(data)); printf("init: %x\n", data->ip6_fl); @@ -60,13 +54,13 @@ ip6_qos_apply(void *d, struct pktq *pktq) struct ip6_qos_data *data = (struct ip6_qos_data *)d; struct pkt *pkt; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IPV6) { if (data->ip6_tc || data->ip6_fl) { - pkt->pkt_ip6->ip6_flow = htonl((uint32_t)data->ip6_tc << 20 | - data->ip6_fl); + pkt->pkt_ip6->ip6_flow = htonl((uint32_t)data->ip6_tc << 20 | data->ip6_fl); pkt->pkt_ip6->ip6_vfc = (IP6_VERSION | (data->ip6_tc >> 4)); } } @@ -75,9 +69,9 @@ ip6_qos_apply(void *d, struct pktq *pktq) } struct mod mod_ip6_qos = { - "ip6_qos", /* name */ - "ip6_qos ", /* usage */ - ip6_qos_open, /* open */ - ip6_qos_apply, /* apply */ - ip6_qos_close /* close */ + "ip6_qos", /* name */ + "ip6_qos ", /* usage */ + ip6_qos_open, /* open */ + ip6_qos_apply, /* apply */ + ip6_qos_close /* close */ }; diff --git a/src/fragroute/mod_ip_chaff.c b/src/fragroute/mod_ip_chaff.c index bc08b8ba0..509170288 100644 --- a/src/fragroute/mod_ip_chaff.c +++ b/src/fragroute/mod_ip_chaff.c @@ -7,24 +7,22 @@ */ #include "config.h" - -#include -#include -#include - #include "mod.h" #include "pkt.h" #include "randutil.h" +#include +#include +#include -#define CHAFF_TYPE_DUP 1 -#define CHAFF_TYPE_OPT 2 -#define CHAFF_TYPE_TTL 3 +#define CHAFF_TYPE_DUP 1 +#define CHAFF_TYPE_OPT 2 +#define CHAFF_TYPE_TTL 3 struct ip_chaff_data { - rand_t *rnd; - int type; - int ttl; - struct pktq *pktq; + rand_t *rnd; + int type; + int ttl; + struct pktq *pktq; }; void * @@ -56,8 +54,8 @@ ip_chaff_open(int argc, char *argv[]) data->type = CHAFF_TYPE_DUP; } else if (strcasecmp(argv[1], "opt") == 0) { data->type = CHAFF_TYPE_OPT; - } else if ((data->ttl = atoi(argv[1])) >= 0 && data->ttl < 256) { - data->type = CHAFF_TYPE_TTL; + } else if ((data->ttl = strtol(argv[1], NULL, 10)) >= 0 && data->ttl < 256) { + data->type = CHAFF_TYPE_TTL; } else return (ip_chaff_close(data)); @@ -80,39 +78,33 @@ ip_chaff_apply(void *d, struct pktq *pktq) continue; new = pkt_dup(pkt); - rand_strset(data->rnd, new->pkt_ip_data, - new->pkt_end - new->pkt_ip_data + 1); + rand_strset(data->rnd, new->pkt_ip_data, new->pkt_end - new->pkt_ip_data + 1); switch (data->type) { case CHAFF_TYPE_DUP: new->pkt_ts.tv_usec = 1; if (eth_type == ETH_TYPE_IP) { - ip_checksum(new->pkt_ip, new->pkt_ip_data - - new->pkt_eth_data); + ip_checksum(new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); } break; case CHAFF_TYPE_OPT: if (eth_type == ETH_TYPE_IP) { - opt.opt_type = 0x42; - opt.opt_len = IP_OPT_LEN; - i = ip_add_option(new->pkt_ip, - new->pkt_buf_size - ETH_HDR_LEN, IP_PROTO_IP, - &opt, opt.opt_len); - /* XXX - whack opt with random crap */ - *(uint32_t *)new->pkt_ip_data = rand_uint32(data->rnd); - new->pkt_ip_data += i; - new->pkt_end += i; - ip_checksum(new->pkt_ip, new->pkt_ip_data - - new->pkt_eth_data); + opt.opt_type = 0x42; + opt.opt_len = IP_OPT_LEN; + i = ip_add_option(new->pkt_ip, new->pkt_buf_size - ETH_HDR_LEN, IP_PROTO_IP, &opt, opt.opt_len); + /* XXX - whack opt with random crap */ + *(uint32_t *)new->pkt_ip_data = rand_uint32(data->rnd); + new->pkt_ip_data += i; + new->pkt_end += i; + ip_checksum(new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); } else if (eth_type == ETH_TYPE_IPV6) { continue; } - /* no break */ + /* fall through */ case CHAFF_TYPE_TTL: if (eth_type == ETH_TYPE_IP) { - new->pkt_ip->ip_ttl = data->ttl; - ip_checksum(new->pkt_ip, new->pkt_ip_data - - new->pkt_eth_data); + new->pkt_ip->ip_ttl = data->ttl; + ip_checksum(new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); } else if (eth_type == ETH_TYPE_IPV6) { pkt->pkt_ip6->ip6_hlim = data->ttl; } @@ -129,9 +121,9 @@ ip_chaff_apply(void *d, struct pktq *pktq) } struct mod mod_ip_chaff = { - "ip_chaff", /* name */ - "ip_chaff dup|opt|", /* usage */ - ip_chaff_open, /* open */ - ip_chaff_apply, /* apply */ - ip_chaff_close /* close */ + "ip_chaff", /* name */ + "ip_chaff dup|opt|", /* usage */ + ip_chaff_open, /* open */ + ip_chaff_apply, /* apply */ + ip_chaff_close /* close */ }; diff --git a/src/fragroute/mod_ip_frag.c b/src/fragroute/mod_ip_frag.c index 0cb234f71..781844d82 100644 --- a/src/fragroute/mod_ip_frag.c +++ b/src/fragroute/mod_ip_frag.c @@ -6,37 +6,32 @@ * $Id$ */ -#include "config.h" -#include "lib/queue.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include -#include -#include - +#include "lib/queue.h" #include "mod.h" #include "pkt.h" #include "randutil.h" +#include +#include +#include #ifndef MAX -#define MAX(a,b) (((a)>(b))?(a):(b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif -#define FAVOR_OLD 1 -#define FAVOR_NEW 2 +#define FAVOR_OLD 1 +#define FAVOR_NEW 2 -static int -ip_frag_apply_ipv4(void *d, struct pktq *pktq); +static int ip_frag_apply_ipv4(void *d, struct pktq *pktq); -static int -ip_frag_apply_ipv6(void *d, struct pktq *pktq); +static int ip_frag_apply_ipv6(void *d, struct pktq *pktq); -static struct ip_frag_data -{ - rand_t *rnd; - int size; - int overlap; +static struct ip_frag_data { + rand_t *rnd; + int size; + int overlap; uint32_t ident; } ip_frag_data; @@ -57,18 +52,16 @@ ip_frag_open(int argc, char *argv[]) return (NULL); } ip_frag_data.rnd = rand_open(); - ip_frag_data.size = atoi(argv[1]); + ip_frag_data.size = (int)strtol(argv[1], NULL, 10); if (ip_frag_data.size == 0 || (ip_frag_data.size % 8) != 0) { warn("fragment size must be a multiple of 8"); return (ip_frag_close(&ip_frag_data)); } if (argc == 3) { - if (strcmp(argv[2], "old") == 0 || - strcmp(argv[2], "win32") == 0) + if (strcmp(argv[2], "old") == 0 || strcmp(argv[2], "win32") == 0) ip_frag_data.overlap = FAVOR_OLD; - else if (strcmp(argv[2], "new") == 0 || - strcmp(argv[2], "unix") == 0) + else if (strcmp(argv[2], "new") == 0 || strcmp(argv[2], "unix") == 0) ip_frag_data.overlap = FAVOR_NEW; else return (ip_frag_close(&ip_frag_data)); @@ -126,8 +119,7 @@ ip_frag_apply_ipv4(_U_ void *d, struct pktq *pktq) fraglen = MAX(UDP_HDR_LEN, ip_frag_data.size); break; case IP_PROTO_TCP: - fraglen = MAX(pkt->pkt_tcp->th_off << 2, - ip_frag_data.size); + fraglen = MAX(pkt->pkt_tcp->th_off << 2, ip_frag_data.size); break; default: fraglen = ip_frag_data.size; @@ -139,24 +131,22 @@ ip_frag_apply_ipv4(_U_ void *d, struct pktq *pktq) if (pkt->pkt_end - pkt->pkt_ip_data < fraglen) continue; - for (p = pkt->pkt_ip_data; p < pkt->pkt_end; ) { + for (p = pkt->pkt_ip_data; p < pkt->pkt_end;) { new = pkt_new(pkt->pkt_buf_size); - memcpy(new->pkt_eth, pkt->pkt_eth, (u_char*)pkt->pkt_eth_data - (u_char*)pkt->pkt_eth); + memcpy(new->pkt_eth, pkt->pkt_eth, (u_char *)pkt->pkt_eth_data - (u_char *)pkt->pkt_eth); memcpy(new->pkt_ip, pkt->pkt_ip, hl); new->pkt_ip_data = new->pkt_eth_data + hl; p1 = p, p2 = NULL; off = (p - pkt->pkt_ip_data) >> 3; - if (ip_frag_data.overlap != 0 && (off & 1) != 0 && - p + (fraglen << 1) < pkt->pkt_end) { + if (ip_frag_data.overlap != 0 && (off & 1) != 0 && p + (fraglen << 1) < pkt->pkt_end) { struct pkt tmp; u_char tmp_buf[pkt->pkt_buf_size]; tmp.pkt_buf = tmp_buf; tmp.pkt_buf_size = pkt->pkt_buf_size; - rand_strset(ip_frag_data.rnd, tmp.pkt_buf, - fraglen); + rand_strset(ip_frag_data.rnd, tmp.pkt_buf, fraglen); if (ip_frag_data.overlap == FAVOR_OLD) { p1 = p + fraglen; p2 = tmp.pkt_buf; @@ -164,11 +154,9 @@ ip_frag_apply_ipv4(_U_ void *d, struct pktq *pktq) p1 = tmp.pkt_buf; p2 = p + fraglen; } - new->pkt_ip->ip_off = htons(IP_MF | - (off + (fraglen >> 3))); + new->pkt_ip->ip_off = htons(IP_MF | (off + (fraglen >> 3))); } else { - new->pkt_ip->ip_off = htons(off | - ((p + fraglen < pkt->pkt_end) ? IP_MF: 0)); + new->pkt_ip->ip_off = htons(off | ((p + fraglen < pkt->pkt_end) ? IP_MF : 0)); } new->pkt_ip->ip_len = htons(hl + fraglen); ip_checksum(new->pkt_ip, hl + fraglen); @@ -181,12 +169,12 @@ ip_frag_apply_ipv4(_U_ void *d, struct pktq *pktq) new = pkt_dup(new); new->pkt_ts.tv_usec = 1; new->pkt_ip->ip_off = htons(IP_MF | off); - new->pkt_ip->ip_len = htons(hl + (fraglen<<1)); - ip_checksum(new->pkt_ip, hl + (fraglen<<1)); + new->pkt_ip->ip_len = htons(hl + (fraglen << 1)); + ip_checksum(new->pkt_ip, hl + (fraglen << 1)); memcpy(new->pkt_ip_data, p, fraglen); - memcpy(new->pkt_ip_data+fraglen, p2, fraglen); - new->pkt_end = new->pkt_ip_data + (fraglen<<1); + memcpy(new->pkt_ip_data + fraglen, p2, fraglen); + new->pkt_end = new->pkt_ip_data + (fraglen << 1); TAILQ_INSERT_BEFORE(pkt, new, pkt_next); p += (fraglen << 1); } else @@ -201,7 +189,6 @@ ip_frag_apply_ipv4(_U_ void *d, struct pktq *pktq) return (0); } - static int ip_frag_apply_ipv6(_U_ void *d, struct pktq *pktq) { @@ -233,8 +220,7 @@ ip_frag_apply_ipv6(_U_ void *d, struct pktq *pktq) fraglen = MAX(UDP_HDR_LEN, ip_frag_data.size); break; case IP_PROTO_TCP: - fraglen = MAX(pkt->pkt_tcp->th_off << 2, - ip_frag_data.size); + fraglen = MAX(pkt->pkt_tcp->th_off << 2, ip_frag_data.size); break; default: fraglen = ip_frag_data.size; @@ -248,32 +234,28 @@ ip_frag_apply_ipv6(_U_ void *d, struct pktq *pktq) next_hdr = pkt->pkt_ip6->ip6_nxt; - for (p = pkt->pkt_ip_data; p < pkt->pkt_end; ) { + for (p = pkt->pkt_ip_data; p < pkt->pkt_end;) { new = pkt_new(pkt->pkt_buf_size); - memcpy(new->pkt_eth, pkt->pkt_eth, (u_char*)pkt->pkt_eth_data - (u_char*)pkt->pkt_eth); + memcpy(new->pkt_eth, pkt->pkt_eth, (u_char *)pkt->pkt_eth_data - (u_char *)pkt->pkt_eth); memcpy(new->pkt_ip, pkt->pkt_ip, hl); - ext = (struct ip6_ext_hdr *)((u_char*)new->pkt_eth_data + hl); - new->pkt_ip_data = (u_char *)(ext) + 2 + - sizeof(struct ip6_ext_data_fragment); + ext = (struct ip6_ext_hdr *)((u_char *)new->pkt_eth_data + hl); + new->pkt_ip_data = (u_char *)(ext) + 2 + sizeof(struct ip6_ext_data_fragment); new->pkt_ip6->ip6_nxt = IP_PROTO_FRAGMENT; ext->ext_nxt = next_hdr; ext->ext_len = 0; /* ip6 fragf reserved */ ext->ext_data.fragment.ident = ip_frag_data.ident; - p1 = p, p2 = NULL; off = (p - pkt->pkt_ip_data) >> 3; - if (ip_frag_data.overlap != 0 && (off & 1) != 0 && - p + (fraglen << 1) < pkt->pkt_end) { + if (ip_frag_data.overlap != 0 && (off & 1) != 0 && p + (fraglen << 1) < pkt->pkt_end) { struct pkt tmp; u_char tmp_buf[pkt->pkt_buf_size]; tmp.pkt_buf = tmp_buf; tmp.pkt_buf_size = pkt->pkt_buf_size; - rand_strset(ip_frag_data.rnd, tmp.pkt_buf, - fraglen); + rand_strset(ip_frag_data.rnd, tmp.pkt_buf, fraglen); if (ip_frag_data.overlap == FAVOR_OLD) { p1 = p + fraglen; p2 = tmp.pkt_buf; @@ -281,11 +263,9 @@ ip_frag_apply_ipv6(_U_ void *d, struct pktq *pktq) p1 = tmp.pkt_buf; p2 = p + fraglen; } - ext->ext_data.fragment.offlg = - htons((off /*+ (fraglen >> 3)*/) << 3) | IP6_MORE_FRAG; + ext->ext_data.fragment.offlg = htons((off /*+ (fraglen >> 3)*/) << 3) | IP6_MORE_FRAG; } else { - ext->ext_data.fragment.offlg = htons(off << 3) | - ((p + fraglen < pkt->pkt_end) ? IP6_MORE_FRAG : 0); + ext->ext_data.fragment.offlg = htons(off << 3) | ((p + fraglen < pkt->pkt_end) ? IP6_MORE_FRAG : 0); } new->pkt_ip6->ip6_plen = htons(fraglen + 8); @@ -319,9 +299,9 @@ ip_frag_apply_ipv6(_U_ void *d, struct pktq *pktq) } struct mod mod_ip_frag = { - "ip_frag", /* name */ - "ip_frag [old|new]", /* usage */ - ip_frag_open, /* open */ - ip_frag_apply, /* apply */ - ip_frag_close /* close */ + "ip_frag", /* name */ + "ip_frag [old|new]", /* usage */ + ip_frag_open, /* open */ + ip_frag_apply, /* apply */ + ip_frag_close /* close */ }; diff --git a/src/fragroute/mod_ip_opt.c b/src/fragroute/mod_ip_opt.c index 43dabd546..1935383ed 100644 --- a/src/fragroute/mod_ip_opt.c +++ b/src/fragroute/mod_ip_opt.c @@ -6,18 +6,16 @@ * $Id$ */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include "iputil.h" +#include "mod.h" +#include "pkt.h" #include #include #include -#include "pkt.h" -#include "mod.h" -#include "iputil.h" - void * ip_opt_close(void *d) { @@ -44,14 +42,18 @@ ip_opt_open(int argc, char *argv[]) } else if (strcasecmp(argv[1], "ssrr") == 0) { opt->opt_type = IP_OPT_SSRR; } else if (strcasecmp(argv[1], "raw") == 0) { - if (raw_ip_opt_parse(argc - 2, &argv[2], &opt->opt_type, &opt->opt_len, - &opt->opt_data.data8[0], sizeof(opt->opt_data.data8)) != 0) + if (raw_ip_opt_parse(argc - 2, + &argv[2], + &opt->opt_type, + &opt->opt_len, + &opt->opt_data.data8[0], + sizeof(opt->opt_data.data8)) != 0) return (ip_opt_close(opt)); return opt; } else return (ip_opt_close(opt)); - if ((i = atoi(argv[2])) < 4 || i > 0xff) { + if ((i = (int)strtol(argv[2], NULL, 10)) < 4 || i > 0xff) { warn(" must be >= 4, and should be a multiple of 4"); return (ip_opt_close(opt)); } @@ -75,28 +77,27 @@ ip_opt_apply(void *d, struct pktq *pktq) struct pkt *pkt; size_t len; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IP) { - len = ip_add_option(pkt->pkt_ip, PKT_BUF_LEN - ETH_HDR_LEN, - IP_PROTO_IP, opt, opt->opt_len); + len = ip_add_option(pkt->pkt_ip, PKT_BUF_LEN - ETH_HDR_LEN, IP_PROTO_IP, opt, opt->opt_len); - if (len > 0) { - pkt->pkt_end += len; - pkt_decorate(pkt); - ip_checksum(pkt->pkt_ip, - pkt->pkt_end - pkt->pkt_eth_data); + if (len > 0) { + pkt->pkt_end += len; + pkt_decorate(pkt); + ip_checksum(pkt->pkt_ip, pkt->pkt_end - pkt->pkt_eth_data); + } } } - } return (0); } struct mod mod_ip_opt = { - "ip_opt", /* name */ - "ip_opt [lsrr|ssrr ...] | [raw ]", /* usage */ - ip_opt_open, /* open */ - ip_opt_apply, /* apply */ - ip_opt_close /* close */ + "ip_opt", /* name */ + "ip_opt [lsrr|ssrr ...] | [raw ]", /* usage */ + ip_opt_open, /* open */ + ip_opt_apply, /* apply */ + ip_opt_close /* close */ }; diff --git a/src/fragroute/mod_ip_tos.c b/src/fragroute/mod_ip_tos.c index 914bf40db..659383331 100644 --- a/src/fragroute/mod_ip_tos.c +++ b/src/fragroute/mod_ip_tos.c @@ -7,17 +7,15 @@ */ #include "config.h" - -#include -#include -#include - #include "argv.h" #include "mod.h" #include "pkt.h" +#include +#include +#include struct ip_tos_data { - int tos; + int tos; }; void * @@ -39,8 +37,7 @@ ip_tos_open(int argc, char *argv[]) if ((data = calloc(1, sizeof(*data))) == NULL) return (NULL); - if (sscanf(argv[1], "%i", &data->tos) != 1 || - data->tos < 0 || data->tos > 255) + if (sscanf(argv[1], "%i", &data->tos) != 1 || data->tos < 0 || data->tos > 255) return (ip_tos_close(data)); return (data); @@ -52,22 +49,23 @@ ip_tos_apply(void *d, struct pktq *pktq) struct ip_tos_data *data = (struct ip_tos_data *)d; struct pkt *pkt; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IP) { - pkt->pkt_ip->ip_tos = data->tos; - /* XXX - do incremental checksum */ - ip_checksum(pkt->pkt_ip, pkt->pkt_ip_data - pkt->pkt_eth_data); - } + pkt->pkt_ip->ip_tos = data->tos; + /* XXX - do incremental checksum */ + ip_checksum(pkt->pkt_ip, pkt->pkt_ip_data - pkt->pkt_eth_data); + } } return (0); } struct mod mod_ip_tos = { - "ip_tos", /* name */ - "ip_tos ", /* usage */ - ip_tos_open, /* open */ - ip_tos_apply, /* apply */ - ip_tos_close /* close */ + "ip_tos", /* name */ + "ip_tos ", /* usage */ + ip_tos_open, /* open */ + ip_tos_apply, /* apply */ + ip_tos_close /* close */ }; diff --git a/src/fragroute/mod_ip_ttl.c b/src/fragroute/mod_ip_ttl.c index 7a0829ed9..775d5188e 100644 --- a/src/fragroute/mod_ip_ttl.c +++ b/src/fragroute/mod_ip_ttl.c @@ -7,17 +7,15 @@ */ #include "config.h" - -#include -#include -#include - #include "argv.h" #include "mod.h" #include "pkt.h" +#include +#include +#include struct ip_ttl_data { - int ttl; + int ttl; }; void * @@ -39,7 +37,7 @@ ip_ttl_open(int argc, char *argv[]) if ((data = calloc(1, sizeof(*data))) == NULL) return (NULL); - if ((data->ttl = atoi(argv[1])) <= 0 || data->ttl > 255) + if ((data->ttl = strtol(argv[1], NULL, 10)) <= 0 || data->ttl > 255) return (ip_ttl_close(data)); return (data); @@ -52,17 +50,18 @@ ip_ttl_apply(void *d, struct pktq *pktq) struct pkt *pkt; int ttldec; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IP) { - ttldec = pkt->pkt_ip->ip_ttl - data->ttl; - pkt->pkt_ip->ip_ttl = data->ttl; + ttldec = pkt->pkt_ip->ip_ttl - data->ttl; + pkt->pkt_ip->ip_ttl = data->ttl; - if (pkt->pkt_ip->ip_sum >= htons(0xffff - (ttldec << 8))) - pkt->pkt_ip->ip_sum += htons(ttldec << 8) + 1; - else - pkt->pkt_ip->ip_sum += htons(ttldec << 8); + if (pkt->pkt_ip->ip_sum >= htons(0xffff - (ttldec << 8))) + pkt->pkt_ip->ip_sum += htons(ttldec << 8) + 1; + else + pkt->pkt_ip->ip_sum += htons(ttldec << 8); } else if (eth_type == ETH_TYPE_IPV6) { pkt->pkt_ip6->ip6_hlim = data->ttl; } @@ -71,9 +70,9 @@ ip_ttl_apply(void *d, struct pktq *pktq) } struct mod mod_ip_ttl = { - "ip_ttl", /* name */ - "ip_ttl ", /* usage */ - ip_ttl_open, /* open */ - ip_ttl_apply, /* apply */ - ip_ttl_close /* close */ + "ip_ttl", /* name */ + "ip_ttl ", /* usage */ + ip_ttl_open, /* open */ + ip_ttl_apply, /* apply */ + ip_ttl_close /* close */ }; diff --git a/src/fragroute/mod_order.c b/src/fragroute/mod_order.c index 54b113a62..41b837100 100644 --- a/src/fragroute/mod_order.c +++ b/src/fragroute/mod_order.c @@ -7,19 +7,17 @@ */ #include "config.h" - +#include "mod.h" #include #include #include -#include "mod.h" - -#define ORDER_RANDOM 1 -#define ORDER_REVERSE 2 +#define ORDER_RANDOM 1 +#define ORDER_REVERSE 2 struct order_data { - rand_t *rnd; - int type; + rand_t *rnd; + int type; }; void * @@ -71,9 +69,9 @@ order_apply(void *d, struct pktq *pktq) } struct mod mod_order = { - "order", /* name */ - "order random|reverse", /* usage */ - order_open, /* open */ - order_apply, /* apply */ - order_close /* close */ + "order", /* name */ + "order random|reverse", /* usage */ + order_open, /* open */ + order_apply, /* apply */ + order_close /* close */ }; diff --git a/src/fragroute/mod_print.c b/src/fragroute/mod_print.c index 0c5f02f86..b60f64143 100644 --- a/src/fragroute/mod_print.c +++ b/src/fragroute/mod_print.c @@ -7,25 +7,23 @@ */ #include "config.h" - +#include "mod.h" +#include "pkt.h" #include #include #include -#include "mod.h" -#include "pkt.h" - #ifndef INET6_ADDRSTRLEN #define INET6_ADDRSTRLEN 46 #endif -#define EXTRACT_16BITS(p) ((uint16_t)ntohs(*(uint16_t *)(p))) -#define EXTRACT_32BITS(p) ((uint32_t)ntohl(*(uint32_t *)(p))) +#define EXTRACT_16BITS(p) ((uint16_t)ntohs(*(uint16_t *)(p))) +#define EXTRACT_32BITS(p) ((uint32_t)ntohl(*(uint32_t *)(p))) /* XXX - _print_* routines adapted from tcpdump */ static void -_print_icmp(u_char *p, _U_ int length) +print_icmp(u_char *p, _U_ int length) { struct ip_hdr *ip; struct icmp_hdr *icmp; @@ -39,7 +37,7 @@ _print_icmp(u_char *p, _U_ int length) } static void -_print_icmp6(u_char *p, _U_ int length) +print_icmp6(u_char *p, _U_ int length) { struct ip6_hdr *ip6; struct icmp_hdr *icmp; @@ -53,7 +51,7 @@ _print_icmp6(u_char *p, _U_ int length) } void -_print_tcp(int family, unsigned char *p, int length) +print_tcp(int family, unsigned char *p, int length) { struct tcp_hdr *tcp; u_short sport, dport, win, urp; @@ -64,21 +62,21 @@ _print_tcp(int family, unsigned char *p, int length) char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN]; if (family == AF_INET6) { - struct ip6_hdr *ip6 = (struct ip6_hdr *)p; - tcp = (struct tcp_hdr *)(p + IP6_HDR_LEN); - len = length; + struct ip6_hdr *ip6 = (struct ip6_hdr *)p; + tcp = (struct tcp_hdr *)(p + IP6_HDR_LEN); + len = length; - ip6_ntop(&ip6->ip6_src, src, sizeof(src)); - ip6_ntop(&ip6->ip6_dst, dst, sizeof(dst)); + ip6_ntop(&ip6->ip6_src, src, sizeof(src)); + ip6_ntop(&ip6->ip6_dst, dst, sizeof(dst)); } else { - struct ip_hdr *ip; + struct ip_hdr *ip; - ip = (struct ip_hdr *)p; - tcp = (struct tcp_hdr *)(p + (ip->ip_hl * 4)); - len = length - (ip->ip_hl * 4); + ip = (struct ip_hdr *)p; + tcp = (struct tcp_hdr *)(p + (ip->ip_hl * 4)); + len = length - (ip->ip_hl * 4); - ip_ntop(&ip->ip_src, src, sizeof(src)); - ip_ntop(&ip->ip_dst, dst, sizeof(dst)); + ip_ntop(&ip->ip_src, src, sizeof(src)); + ip_ntop(&ip->ip_dst, dst, sizeof(dst)); } if (len < TCP_HDR_LEN) { @@ -95,11 +93,15 @@ _print_tcp(int family, unsigned char *p, int length) printf("%s.%d > %s.%d: ", src, sport, dst, dport); - if (tcp->th_flags & (TH_SYN|TH_FIN|TH_RST|TH_PUSH)) { - if (tcp->th_flags & TH_SYN) putchar('S'); - if (tcp->th_flags & TH_FIN) putchar('F'); - if (tcp->th_flags & TH_RST) putchar('R'); - if (tcp->th_flags & TH_PUSH) putchar('P'); + if (tcp->th_flags & (TH_SYN | TH_FIN | TH_RST | TH_PUSH)) { + if (tcp->th_flags & TH_SYN) + putchar('S'); + if (tcp->th_flags & TH_FIN) + putchar('F'); + if (tcp->th_flags & TH_RST) + putchar('R'); + if (tcp->th_flags & TH_PUSH) + putchar('P'); } else putchar('.'); @@ -133,16 +135,20 @@ _print_tcp(int family, unsigned char *p, int length) if (TCP_OPT_TYPEONLY(opt)) { len = 1; } else { - len = *cp++; /* total including type, len */ + len = *cp++; /* total including type, len */ if (len < 2 || len > tcp_hl) goto bad; - --tcp_hl; /* account for length byte */ + --tcp_hl; /* account for length byte */ } - --tcp_hl; /* account for type byte */ + --tcp_hl; /* account for type byte */ datalen = 0; /* Bail if "l" bytes of data are not left or were not captured */ -#define LENCHECK(l) { if ((l) > tcp_hl) goto bad; } +#define LENCHECK(l) \ + { \ + if ((l) > tcp_hl) \ + goto bad; \ + } switch (opt) { case TCP_OPT_MSS: @@ -170,8 +176,7 @@ _print_tcp(int family, unsigned char *p, int length) break; case TCP_OPT_SACK: datalen = len - 2; - if ((datalen % 8) != 0 || - !(tcp->th_flags & TH_ACK)) { + if ((datalen % 8) != 0 || !(tcp->th_flags & TH_ACK)) { printf("malformed sack "); printf("[len %d] ", datalen); break; @@ -230,9 +235,9 @@ _print_tcp(int family, unsigned char *p, int length) tcp_hl -= datalen; /* Check specification against observed length */ - ++datalen; /* option octet */ + ++datalen; /* option octet */ if (!TCP_OPT_TYPEONLY(opt)) - ++datalen; /* size octet */ + ++datalen; /* size octet */ if (datalen != len) printf("[len %d]", len); ch = ','; @@ -242,7 +247,7 @@ _print_tcp(int family, unsigned char *p, int length) putchar('>'); } return; - bad: +bad: fputs("[bad opt]", stdout); if (ch != '\0') putchar('>'); @@ -250,35 +255,34 @@ _print_tcp(int family, unsigned char *p, int length) } static void -_print_udp(int family, u_char *p, _U_ int length) +print_udp(int family, u_char *p, _U_ int length) { struct udp_hdr *udp; char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN]; if (family == AF_INET6) { - struct ip6_hdr *ip6 = (struct ip6_hdr *)p; - udp = (struct udp_hdr *)(p + IP6_HDR_LEN); + struct ip6_hdr *ip6 = (struct ip6_hdr *)p; + udp = (struct udp_hdr *)(p + IP6_HDR_LEN); - ip6_ntop(&ip6->ip6_src, src, sizeof(src)); - ip6_ntop(&ip6->ip6_dst, dst, sizeof(dst)); + ip6_ntop(&ip6->ip6_src, src, sizeof(src)); + ip6_ntop(&ip6->ip6_dst, dst, sizeof(dst)); } else { - struct ip_hdr *ip; + struct ip_hdr *ip; - ip = (struct ip_hdr *)p; - udp = (struct udp_hdr *)(p + (ip->ip_hl * 4)); + ip = (struct ip_hdr *)p; + udp = (struct udp_hdr *)(p + (ip->ip_hl * 4)); - ip_ntop(&ip->ip_src, src, sizeof(src)); - ip_ntop(&ip->ip_dst, dst, sizeof(dst)); + ip_ntop(&ip->ip_src, src, sizeof(src)); + ip_ntop(&ip->ip_dst, dst, sizeof(dst)); } /* XXX - truncation? */ - printf("%s.%d > %s.%d:", src, ntohs(udp->uh_sport), - dst, ntohs(udp->uh_dport)); + printf("%s.%d > %s.%d:", src, ntohs(udp->uh_sport), dst, ntohs(udp->uh_dport)); printf(" udp %d", ntohs(udp->uh_ulen) - UDP_HDR_LEN); } static void -_print_frag6(u_char *p, _U_ int length) +print_frag6(u_char *p, _U_ int length) { struct ip6_hdr *ip6; struct ip6_ext_hdr *ext; @@ -291,13 +295,14 @@ _print_frag6(u_char *p, _U_ int length) printf("%s > %s:", ip6_ntoa(&ip6->ip6_src), ip6_ntoa(&ip6->ip6_dst)); printf(" fragment: next %hhu offset %d%s ident 0x%08x", - ext->ext_nxt, off, - (ext->ext_data.fragment.offlg & IP6_MORE_FRAG) ? " MF" : "", - htonl(ext->ext_data.fragment.ident)); + ext->ext_nxt, + off, + (ext->ext_data.fragment.offlg & IP6_MORE_FRAG) ? " MF" : "", + htonl(ext->ext_data.fragment.ident)); } static void -_print_ip(u_char *p, int length) +print_ip(u_char *p, int length) { struct ip_hdr *ip; int ip_off, ip_hl, ip_len; @@ -321,28 +326,29 @@ _print_ip(u_char *p, int length) if ((ip_off & IP_OFFMASK) == 0) { switch (ip->ip_p) { case IP_PROTO_TCP: - _print_tcp(AF_INET, p, ip_len); + print_tcp(AF_INET, p, ip_len); break; case IP_PROTO_UDP: - _print_udp(AF_INET, p, ip_len); + print_udp(AF_INET, p, ip_len); break; case IP_PROTO_ICMP: - _print_icmp(p, ip_len); + print_icmp(p, ip_len); break; default: - printf("%s > %s:", ip_ntoa(&ip->ip_src), - ip_ntoa(&ip->ip_dst)); + printf("%s > %s:", ip_ntoa(&ip->ip_src), ip_ntoa(&ip->ip_dst)); printf(" ip-proto-%d %d", ip->ip_p, ip_len); break; } } /* Handle more frags. */ - if (ip_off & (IP_MF|IP_OFFMASK)) { + if (ip_off & (IP_MF | IP_OFFMASK)) { if (ip_off & IP_OFFMASK) - printf("%s > %s:", ip_ntoa(&ip->ip_src), - ip_ntoa(&ip->ip_dst)); - printf(" (frag %d:%d@%d%s)", ntohs(ip->ip_id), ip_len - ip_hl, - (ip_off & IP_OFFMASK) << 3, (ip_off & IP_MF) ? "+" : ""); + printf("%s > %s:", ip_ntoa(&ip->ip_src), ip_ntoa(&ip->ip_dst)); + printf(" (frag %d:%d@%d%s)", + ntohs(ip->ip_id), + ip_len - ip_hl, + (ip_off & IP_OFFMASK) << 3, + (ip_off & IP_MF) ? "+" : ""); } else if (ip_off & IP_DF) printf(" (DF)"); @@ -353,7 +359,7 @@ _print_ip(u_char *p, int length) } static void -_print_ip6(u_char *p, int length) +print_ip6(u_char *p, int length) { struct ip6_hdr *ip6; int plen; @@ -368,24 +374,22 @@ _print_ip6(u_char *p, int length) plen = htons(ip6->ip6_plen); switch (ip6->ip6_nxt) { - case IP_PROTO_TCP: - _print_tcp(AF_INET6, p, plen); - break; - case IP_PROTO_UDP: - _print_udp(AF_INET6, p, plen); - break; - case IP_PROTO_ICMPV6: - _print_icmp6(p, plen); - break; - case IP_PROTO_FRAGMENT: - _print_frag6(p, plen); - break; - default: - printf("%s > %s:", ip6_ntoa(&ip6->ip6_src), - ip6_ntoa(&ip6->ip6_dst)); - printf(" ip-proto-%hhu ttl %hhu payload len %d", ip6->ip6_nxt, - ip6->ip6_hlim, plen); - break; + case IP_PROTO_TCP: + print_tcp(AF_INET6, p, plen); + break; + case IP_PROTO_UDP: + print_udp(AF_INET6, p, plen); + break; + case IP_PROTO_ICMPV6: + print_icmp6(p, plen); + break; + case IP_PROTO_FRAGMENT: + print_frag6(p, plen); + break; + default: + printf("%s > %s:", ip6_ntoa(&ip6->ip6_src), ip6_ntoa(&ip6->ip6_dst)); + printf(" ip-proto-%hhu ttl %hhu payload len %d", ip6->ip6_nxt, ip6->ip6_hlim, plen); + break; } if (ip6->ip6_hlim <= 1) @@ -393,13 +397,13 @@ _print_ip6(u_char *p, int length) } static void -_print_eth(struct eth_hdr* e, int length) +print_eth(struct eth_hdr *e, int length) { - char d[20], s[20]; - eth_ntop(&e->eth_dst, &d[0], sizeof(d)); - eth_ntop(&e->eth_src, &s[0], sizeof(s)); + char d[20], s[20]; + eth_ntop(&e->eth_dst, &d[0], sizeof(d)); + eth_ntop(&e->eth_src, &s[0], sizeof(s)); - printf("%s > %s type 0x%04hx length %d", d, s, htons(e->eth_type), length); + printf("%s > %s type 0x%04hx length %d", d, s, htons(e->eth_type), length); } static char * @@ -410,8 +414,7 @@ timerntoa(struct timeval *tv) usec = (tv->tv_sec * 1000000) + tv->tv_usec; - snprintf(buf, sizeof(buf), "%d.%03d ms", - (int)(usec / 1000), (int)(usec % 1000)); + snprintf(buf, sizeof(buf), "%d.%03d ms", (int)(usec / 1000), (int)(usec % 1000)); return (buf); } @@ -421,15 +424,16 @@ print_apply(_U_ void *d, struct pktq *pktq) { struct pkt *pkt; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { uint16_t eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IP) - _print_ip(pkt->pkt_eth_data, pkt->pkt_end - pkt->pkt_eth_data); + print_ip(pkt->pkt_eth_data, pkt->pkt_end - pkt->pkt_eth_data); else if (eth_type == ETH_TYPE_IPV6) - _print_ip6(pkt->pkt_eth_data, pkt->pkt_end - pkt->pkt_eth_data); + print_ip6(pkt->pkt_eth_data, pkt->pkt_end - pkt->pkt_eth_data); else - _print_eth(pkt->pkt_eth, pkt->pkt_end - pkt->pkt_data); + print_eth(pkt->pkt_eth, pkt->pkt_end - pkt->pkt_data); if (timerisset(&pkt->pkt_ts)) printf(" [delay %s]", timerntoa(&pkt->pkt_ts)); printf("\n"); @@ -438,9 +442,9 @@ print_apply(_U_ void *d, struct pktq *pktq) } struct mod mod_print = { - "print", /* name */ - "print", /* usage */ - NULL, /* init */ - print_apply, /* apply */ - NULL /* close */ + "print", /* name */ + "print", /* usage */ + NULL, /* init */ + print_apply, /* apply */ + NULL /* close */ }; diff --git a/src/fragroute/mod_tcp_chaff.c b/src/fragroute/mod_tcp_chaff.c index 9ec2c2760..d332c6077 100644 --- a/src/fragroute/mod_tcp_chaff.c +++ b/src/fragroute/mod_tcp_chaff.c @@ -7,28 +7,26 @@ */ #include "config.h" - +#include "iputil.h" +#include "mod.h" +#include "pkt.h" +#include "randutil.h" #include #include #include -#include "pkt.h" -#include "mod.h" -#include "randutil.h" -#include "iputil.h" - -#define CHAFF_TYPE_CKSUM 1 -#define CHAFF_TYPE_NULL 2 -#define CHAFF_TYPE_PAWS 3 -#define CHAFF_TYPE_REXMIT 4 -#define CHAFF_TYPE_SEQ 5 -#define CHAFF_TYPE_SYN 6 -#define CHAFF_TYPE_TTL 7 +#define CHAFF_TYPE_CKSUM 1 +#define CHAFF_TYPE_NULL 2 +#define CHAFF_TYPE_PAWS 3 +#define CHAFF_TYPE_REXMIT 4 +#define CHAFF_TYPE_SEQ 5 +#define CHAFF_TYPE_SYN 6 +#define CHAFF_TYPE_TTL 7 struct tcp_chaff_data { - rand_t *rnd; - int type; - int ttl; + rand_t *rnd; + int type; + int ttl; }; void * @@ -68,7 +66,7 @@ tcp_chaff_open(int argc, char *argv[]) data->type = CHAFF_TYPE_SEQ; else if (strcasecmp(argv[1], "syn") == 0) data->type = CHAFF_TYPE_SYN; - else if ((data->ttl = atoi(argv[1])) > 0 && data->ttl < 256) + else if ((data->ttl = (int)strtol(argv[1], NULL, 10)) > 0 && data->ttl < 256) data->type = CHAFF_TYPE_TTL; else return (tcp_chaff_close(data)); @@ -101,61 +99,56 @@ tcp_chaff_apply(void *d, struct pktq *pktq) continue; } - if (nxt != IP_PROTO_TCP || - pkt->pkt_tcp == NULL || pkt->pkt_tcp_data == NULL || - (pkt->pkt_tcp->th_flags & TH_ACK) == 0) + if (nxt != IP_PROTO_TCP || pkt->pkt_tcp == NULL || pkt->pkt_tcp_data == NULL || + (pkt->pkt_tcp->th_flags & TH_ACK) == 0) continue; new = pkt_dup(pkt); - rand_strset(data->rnd, new->pkt_tcp_data, new->pkt_end - - new->pkt_tcp_data + 1); + rand_strset(data->rnd, new->pkt_tcp_data, new->pkt_end - new->pkt_tcp_data + 1); switch (data->type) { case CHAFF_TYPE_CKSUM: - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); new->pkt_tcp->th_sum = rand_uint16(data->rnd); break; case CHAFF_TYPE_NULL: new->pkt_tcp->th_flags = 0; - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); break; case CHAFF_TYPE_PAWS: /* Delete any existing TCP options. */ i = (new->pkt_tcp->th_off << 2) - TCP_HDR_LEN; new->pkt_tcp->th_off = 5; new->pkt_end -= i; - new->pkt_ip->ip_len = htons(new->pkt_end - - new->pkt_eth_data); + new->pkt_ip->ip_len = htons(new->pkt_end - new->pkt_eth_data); /* Insert initial timestamp, for PAWS elimination. */ opt.opt_type = TCP_OPT_TIMESTAMP; opt.opt_len = TCP_OPT_LEN + 8; opt.opt_data.timestamp[0] = 0; opt.opt_data.timestamp[1] = 0; - if ((i = inet_add_option(eth_type, new->pkt_ip, - PKT_BUF_LEN - ETH_HDR_LEN, - IP_PROTO_TCP, &opt, opt.opt_len)) < 0) { + if ((i = (int)inet_add_option(eth_type, + new->pkt_ip, + PKT_BUF_LEN - ETH_HDR_LEN, + IP_PROTO_TCP, + &opt, + opt.opt_len)) < 0) { pkt_free(new); continue; } new->pkt_end += i; - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); pkt_decorate(new); break; case CHAFF_TYPE_REXMIT: new->pkt_ts.tv_usec = 1; - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); break; case CHAFF_TYPE_SEQ: /* XXX - dunno recv window? */ new->pkt_tcp->th_seq = htonl(666); new->pkt_tcp->th_ack = htonl(666); - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); break; case CHAFF_TYPE_SYN: new->pkt_tcp->th_flags = TH_SYN; @@ -163,16 +156,13 @@ tcp_chaff_apply(void *d, struct pktq *pktq) new->pkt_tcp->th_ack = 0; new->pkt_end = new->pkt_tcp_data; new->pkt_tcp_data = NULL; - new->pkt_ip->ip_len = htons(new->pkt_end - - new->pkt_eth_data); - inet_checksum(eth_type, new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + new->pkt_ip->ip_len = htons(new->pkt_end - new->pkt_eth_data); + inet_checksum(eth_type, new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); break; case CHAFF_TYPE_TTL: if (eth_type == ETH_TYPE_IP) { - new->pkt_ip->ip_ttl = data->ttl; - ip_checksum(new->pkt_ip, - new->pkt_ip_data - new->pkt_eth_data); + new->pkt_ip->ip_ttl = data->ttl; + ip_checksum(new->pkt_ip, new->pkt_ip_data - new->pkt_eth_data); } else if (eth_type == ETH_TYPE_IPV6) { new->pkt_ip6->ip6_hlim = data->ttl; } @@ -188,9 +178,9 @@ tcp_chaff_apply(void *d, struct pktq *pktq) } struct mod mod_tcp_chaff = { - "tcp_chaff", /* name */ - "tcp_chaff cksum|null|paws|rexmit|seq|syn|", /* usage */ - tcp_chaff_open, /* open */ - tcp_chaff_apply, /* apply */ - tcp_chaff_close /* close */ + "tcp_chaff", /* name */ + "tcp_chaff cksum|null|paws|rexmit|seq|syn|", /* usage */ + tcp_chaff_open, /* open */ + tcp_chaff_apply, /* apply */ + tcp_chaff_close /* close */ }; diff --git a/src/fragroute/mod_tcp_opt.c b/src/fragroute/mod_tcp_opt.c index e645fcc59..2007ee91f 100644 --- a/src/fragroute/mod_tcp_opt.c +++ b/src/fragroute/mod_tcp_opt.c @@ -6,18 +6,16 @@ * $Id$ */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include "iputil.h" +#include "mod.h" +#include "pkt.h" #include #include #include -#include "pkt.h" -#include "mod.h" -#include "iputil.h" - void * tcp_opt_close(void *d) { @@ -42,7 +40,7 @@ tcp_opt_open(int argc, char *argv[]) opt->opt_type = TCP_OPT_MSS; opt->opt_len = TCP_OPT_LEN + 2; - if ((i = atoi(argv[2])) <= 0 || i > 0xffff) { + if ((i = (int)strtol(argv[2], NULL, 10)) <= 0 || i > 0xffff) { warn("mss must be from 0-65535"); return (tcp_opt_close(opt)); } @@ -51,14 +49,18 @@ tcp_opt_open(int argc, char *argv[]) opt->opt_type = TCP_OPT_WSCALE; opt->opt_len = TCP_OPT_LEN + 2; - if ((i = atoi(argv[2])) <= 0 || i > 0xff) { + if ((i = (int)strtol(argv[2], NULL, 10)) <= 0 || i > 0xff) { warn("wscale must be from 0-255"); return (tcp_opt_close(opt)); } opt->opt_data.wscale = i; } else if (strcasecmp(argv[1], "raw") == 0) { - if (raw_ip_opt_parse(argc - 2, &argv[2], &opt->opt_type, &opt->opt_len, - &opt->opt_data.data8[0], sizeof(opt->opt_data.data8)) != 0) + if (raw_ip_opt_parse(argc - 2, + &argv[2], + &opt->opt_type, + &opt->opt_len, + &opt->opt_data.data8[0], + sizeof(opt->opt_data.data8)) != 0) return (tcp_opt_close(opt)); } else return (tcp_opt_close(opt)); @@ -72,13 +74,17 @@ tcp_opt_apply(void *d, struct pktq *pktq) struct tcp_opt *opt = (struct tcp_opt *)d; struct pkt *pkt; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { size_t len; uint16_t eth_type = htons(pkt->pkt_eth->eth_type); - len = inet_add_option(eth_type, pkt->pkt_ip, - sizeof(pkt->pkt_data) - ETH_HDR_LEN, - IP_PROTO_TCP, opt, opt->opt_len); + len = inet_add_option(eth_type, + pkt->pkt_ip, + sizeof(pkt->pkt_data) - ETH_HDR_LEN, + IP_PROTO_TCP, + opt, + opt->opt_len); if (len > 0) { pkt->pkt_end += len; @@ -90,9 +96,9 @@ tcp_opt_apply(void *d, struct pktq *pktq) } struct mod mod_tcp_opt = { - "tcp_opt", /* name */ - "tcp_opt mss|wscale |raw ", /* usage */ - tcp_opt_open, /* open */ - tcp_opt_apply, /* apply */ - tcp_opt_close /* close */ + "tcp_opt", /* name */ + "tcp_opt mss|wscale |raw ", /* usage */ + tcp_opt_open, /* open */ + tcp_opt_apply, /* apply */ + tcp_opt_close /* close */ }; diff --git a/src/fragroute/mod_tcp_seg.c b/src/fragroute/mod_tcp_seg.c index abfd77a1e..b7d3dc28c 100644 --- a/src/fragroute/mod_tcp_seg.c +++ b/src/fragroute/mod_tcp_seg.c @@ -6,31 +6,29 @@ * $Id$ */ -#include "config.h" -#include "lib/queue.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include -#include -#include - +#include "iputil.h" +#include "lib/queue.h" #include "mod.h" #include "pkt.h" #include "randutil.h" -#include "iputil.h" +#include +#include +#include #ifndef MIN -#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif -#define FAVOR_OLD 1 -#define FAVOR_NEW 2 +#define FAVOR_OLD 1 +#define FAVOR_NEW 2 static struct tcp_seg_data { - rand_t *rnd; - int size; - int overlap; + rand_t *rnd; + int size; + int overlap; } tcp_seg_data; void * @@ -51,16 +49,14 @@ tcp_seg_open(int argc, char *argv[]) } tcp_seg_data.rnd = rand_open(); - if ((tcp_seg_data.size = atoi(argv[1])) == 0) { + if ((tcp_seg_data.size = (int)strtol(argv[1], NULL, 10)) == 0) { warnx("invalid segment size '%s'", argv[1]); return (tcp_seg_close(&tcp_seg_data)); } if (argc == 3) { - if (strcmp(argv[2], "old") == 0 || - strcmp(argv[2], "win32") == 0) + if (strcmp(argv[2], "old") == 0 || strcmp(argv[2], "win32") == 0) tcp_seg_data.overlap = FAVOR_OLD; - else if (strcmp(argv[2], "new") == 0 || - strcmp(argv[2], "unix") == 0) + else if (strcmp(argv[2], "new") == 0 || strcmp(argv[2], "unix") == 0) tcp_seg_data.overlap = FAVOR_NEW; else return (tcp_seg_close(&tcp_seg_data)); @@ -95,14 +91,12 @@ tcp_seg_apply(_U_ void *d, struct pktq *pktq) continue; } - if (nxt != IP_PROTO_TCP || - pkt->pkt_tcp == NULL || pkt->pkt_tcp_data == NULL || - (pkt->pkt_tcp->th_flags & TH_ACK) == 0 || - pkt->pkt_end - pkt->pkt_tcp_data <= tcp_seg_data.size) + if (nxt != IP_PROTO_TCP || pkt->pkt_tcp == NULL || pkt->pkt_tcp_data == NULL || + (pkt->pkt_tcp->th_flags & TH_ACK) == 0 || pkt->pkt_end - pkt->pkt_tcp_data <= tcp_seg_data.size) continue; if (eth_type == ETH_TYPE_IP) { - hl = pkt->pkt_ip->ip_hl << 2; + hl = pkt->pkt_ip->ip_hl << 2; } else if (eth_type == ETH_TYPE_IPV6) { hl = IP6_HDR_LEN; } else { @@ -116,18 +110,17 @@ tcp_seg_apply(_U_ void *d, struct pktq *pktq) u_char *p1, *p2; new = pkt_new(pkt->pkt_buf_size); - memcpy(new->pkt_eth, pkt->pkt_eth, (u_char*)pkt->pkt_eth_data - (u_char*)pkt->pkt_eth); + memcpy(new->pkt_eth, pkt->pkt_eth, (u_char *)pkt->pkt_eth_data - (u_char *)pkt->pkt_eth); p1 = p, p2 = NULL; len = MIN(pkt->pkt_end - p, tcp_seg_data.size); - if (tcp_seg_data.overlap != 0 && - p + (len << 1) < pkt->pkt_end) { + if (tcp_seg_data.overlap != 0 && p + (len << 1) < pkt->pkt_end) { struct pkt tmp; u_char tmp_buf[pkt->pkt_buf_size]; tmp.pkt_buf = tmp_buf; tmp.pkt_buf_size = pkt->pkt_buf_size; - rand_strset(tcp_seg_data.rnd, tmp.pkt_buf,len); + rand_strset(tcp_seg_data.rnd, tmp.pkt_buf, len); if (tcp_seg_data.overlap == FAVOR_OLD) { p1 = p + len; @@ -146,8 +139,8 @@ tcp_seg_apply(_U_ void *d, struct pktq *pktq) new->pkt_end = new->pkt_tcp_data + len; if (eth_type == ETH_TYPE_IP) { - new->pkt_ip->ip_id = rand_uint16(tcp_seg_data.rnd); - new->pkt_ip->ip_len = htons(hl + tl + len); + new->pkt_ip->ip_id = rand_uint16(tcp_seg_data.rnd); + new->pkt_ip->ip_len = htons(hl + tl + len); } else { new->pkt_ip6->ip6_plen = htons(tl + len); } @@ -183,9 +176,9 @@ tcp_seg_apply(_U_ void *d, struct pktq *pktq) } struct mod mod_tcp_seg = { - "tcp_seg", /* name */ - "tcp_seg [old|new]", /* usage */ - tcp_seg_open, /* open */ - tcp_seg_apply, /* apply */ - tcp_seg_close /* close */ + "tcp_seg", /* name */ + "tcp_seg [old|new]", /* usage */ + tcp_seg_open, /* open */ + tcp_seg_apply, /* apply */ + tcp_seg_close /* close */ }; diff --git a/src/fragroute/pkt.c b/src/fragroute/pkt.c index 8dbd09ee3..1868ab5f1 100644 --- a/src/fragroute/pkt.c +++ b/src/fragroute/pkt.c @@ -6,17 +6,14 @@ * $Id$ */ +#include "pkt.h" #include "config.h" +#include "bget.h" #include "common/err.h" - -#include - #include #include #include - -#include "bget.h" -#include "pkt.h" +#include static struct pkt **pvbase; static int pvlen; @@ -32,7 +29,7 @@ pkt_close(void) { if (pvbase) { pvlen = 0; - free (pvbase); + free(pvbase); } } @@ -83,17 +80,13 @@ pkt_dup(struct pkt *pkt) new->pkt_data = pkt->pkt_data + off; - new->pkt_eth = (pkt->pkt_eth != NULL) ? - (struct eth_hdr *)new->pkt_data : NULL; + new->pkt_eth = (pkt->pkt_eth != NULL) ? (struct eth_hdr *)new->pkt_data : NULL; - new->pkt_eth_data = (pkt->pkt_eth_data != NULL) ? - pkt->pkt_eth_data + off : NULL; + new->pkt_eth_data = (pkt->pkt_eth_data != NULL) ? pkt->pkt_eth_data + off : NULL; - new->pkt_ip_data = (pkt->pkt_ip_data != NULL) ? - pkt->pkt_ip_data + off : NULL; + new->pkt_ip_data = (pkt->pkt_ip_data != NULL) ? pkt->pkt_ip_data + off : NULL; - new->pkt_tcp_data = (pkt->pkt_tcp_data != NULL) ? - pkt->pkt_tcp_data + off : NULL; + new->pkt_tcp_data = (pkt->pkt_tcp_data != NULL) ? pkt->pkt_tcp_data + off : NULL; memcpy(new->pkt_data, pkt->pkt_data, pkt->pkt_end - pkt->pkt_data); @@ -102,9 +95,8 @@ pkt_dup(struct pkt *pkt) return (new); } -#define IP6_IS_EXT(n) \ - ((n) == IP_PROTO_HOPOPTS || (n) == IP_PROTO_DSTOPTS || \ - (n) == IP_PROTO_ROUTING || (n) == IP_PROTO_FRAGMENT) +#define IP6_IS_EXT(n) \ + ((n) == IP_PROTO_HOPOPTS || (n) == IP_PROTO_DSTOPTS || (n) == IP_PROTO_ROUTING || (n) == IP_PROTO_FRAGMENT) void pkt_decorate(struct pkt *pkt) @@ -132,39 +124,39 @@ pkt_decorate(struct pkt *pkt) eth_type = htons(pkt->pkt_eth->eth_type); if (eth_type == ETH_TYPE_IP) { - if (p + IP_HDR_LEN > pkt->pkt_end) - return; + if (p + IP_HDR_LEN > pkt->pkt_end) + return; - pkt->pkt_eth_data = p; + pkt->pkt_eth_data = p; - /* If IP header length is longer than packet length, stop. */ - hl = pkt->pkt_ip->ip_hl << 2; - if (p + hl > pkt->pkt_end) { - pkt->pkt_ip = NULL; - return; - } + /* If IP header length is longer than packet length, stop. */ + hl = pkt->pkt_ip->ip_hl << 2; + if (p + hl > pkt->pkt_end) { + pkt->pkt_ip = NULL; + return; + } - len = ntohs(pkt->pkt_ip->ip_len); + len = ntohs(pkt->pkt_ip->ip_len); - /* If IP length is 0, this packet was generated by wireshark - on systems with TCP Segmentation offloading to NIC enabled. - Calculate the IP length from packet end and packet data pointers. - */ - if (0 == len) - len = (pkt->pkt_end - (pkt->pkt_data + ETH_HDR_LEN)); + /* If IP length is 0, this packet was generated by wireshark + on systems with TCP Segmentation offloading to NIC enabled. + Calculate the IP length from packet end and packet data pointers. + */ + if (0 == len) + len = (int)(pkt->pkt_end - (pkt->pkt_data + ETH_HDR_LEN)); - /* If IP length is longer than packet length, stop. - */ - if (p + len > pkt->pkt_end) - return; + /* If IP length is longer than packet length, stop. + */ + if (p + len > pkt->pkt_end) + return; - /* If IP fragment, stop. */ - off = ntohs(pkt->pkt_ip->ip_off); - if ((off & IP_OFFMASK) != 0 || (off & IP_MF) != 0) - return; + /* If IP fragment, stop. */ + off = ntohs(pkt->pkt_ip->ip_off); + if ((off & IP_OFFMASK) != 0 || (off & IP_MF) != 0) + return; - pkt->pkt_end = p + len; - p += hl; + pkt->pkt_end = p + len; + p += hl; next_hdr = pkt->pkt_ip->ip_p; } else if (eth_type == ETH_TYPE_IPV6) { if (p + IP6_HDR_LEN > pkt->pkt_end) @@ -252,7 +244,7 @@ pkt_decorate(struct pkt *pkt) hl = sizeof(pkt->pkt_icmp_msg->dnsreply); break; default: - hl = pkt->pkt_end - p + 1; + hl = (int)(pkt->pkt_end - p + 1); break; } if (p + hl > pkt->pkt_end) @@ -266,8 +258,7 @@ pkt_decorate(struct pkt *pkt) pkt->pkt_tcp_data = p; break; case IP_PROTO_UDP: - if (pkt->pkt_ip_data + ntohs(pkt->pkt_udp->uh_ulen) <= - pkt->pkt_end) + if (pkt->pkt_ip_data + ntohs(pkt->pkt_udp->uh_ulen) <= pkt->pkt_end) pkt->pkt_udp_data = p; break; } @@ -304,7 +295,8 @@ pktq_shuffle(rand_t *r, struct pktq *pktq) int i; i = 0; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { i++; } if (i > 0 && i > pvlen) { @@ -313,13 +305,13 @@ pktq_shuffle(rand_t *r, struct pktq *pktq) pvbase = malloc(sizeof(pkt) * pvlen); else pvbase = realloc(pvbase, sizeof(pkt) * pvlen); - } if (!pvbase) err(-1, "out of memory\n"); i = 0; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { pvbase[i++] = pkt; } TAILQ_INIT(pktq); @@ -338,7 +330,8 @@ pktq_random(rand_t *r, struct pktq *pktq) unsigned int i; i = 0; - TAILQ_FOREACH(pkt, pktq, pkt_next) { + TAILQ_FOREACH(pkt, pktq, pkt_next) + { i++; } diff --git a/src/fragroute/pkt.h b/src/fragroute/pkt.h index 76bd23944..44938fce6 100644 --- a/src/fragroute/pkt.h +++ b/src/fragroute/pkt.h @@ -6,12 +6,11 @@ * $Id$ */ -#ifndef PKT_H -#define PKT_H +#pragma once +#include "defines.h" #include "config.h" #include "lib/queue.h" -#include "defines.h" #include #ifdef HAVE_LIBDNET @@ -28,8 +27,8 @@ #endif #endif -#define PKT_BUF_LEN (ETH_HDR_LEN + ETH_MTU) -#define PKT_BUF_ALIGN 2 +#define PKT_BUF_LEN (ETH_HDR_LEN + ETH_MTU) +#define PKT_BUF_ALIGN 2 struct pkt { struct timeval pkt_ts; @@ -58,31 +57,29 @@ struct pkt { TAILQ_ENTRY(pkt) pkt_next; }; -#define pkt_ip pkt_n_hdr_u.ip -#define pkt_ip6 pkt_n_hdr_u.ip6 -#define pkt_eth_data pkt_n_hdr_u.eth_data +#define pkt_ip pkt_n_hdr_u.ip +#define pkt_ip6 pkt_n_hdr_u.ip6 +#define pkt_eth_data pkt_n_hdr_u.eth_data -#define pkt_icmp pkt_t_hdr_u.icmp -#define pkt_tcp pkt_t_hdr_u.tcp -#define pkt_udp pkt_t_hdr_u.udp -#define pkt_ip_data pkt_t_hdr_u.ip_data +#define pkt_icmp pkt_t_hdr_u.icmp +#define pkt_tcp pkt_t_hdr_u.tcp +#define pkt_udp pkt_t_hdr_u.udp +#define pkt_ip_data pkt_t_hdr_u.ip_data -#define pkt_tcp_data pkt_t_data_u.t_data -#define pkt_udp_data pkt_t_data_u.t_data -#define pkt_icmp_msg pkt_t_data_u.icmp +#define pkt_tcp_data pkt_t_data_u.t_data +#define pkt_udp_data pkt_t_data_u.t_data +#define pkt_icmp_msg pkt_t_data_u.icmp TAILQ_HEAD(pktq, pkt); -void pkt_init(int size); -void pkt_close(void); - -struct pkt *pkt_new(size_t len); -struct pkt *pkt_dup(struct pkt *); -void pkt_decorate(struct pkt *pkt); -void pkt_free(struct pkt *pkt); +void pkt_init(int size); +void pkt_close(void); -void pktq_reverse(struct pktq *pktq); -void pktq_shuffle(rand_t *r, struct pktq *pktq); -struct pkt *pktq_random(rand_t *r, struct pktq *pktq); +struct pkt *pkt_new(size_t len); +struct pkt *pkt_dup(struct pkt *); +void pkt_decorate(struct pkt *pkt); +void pkt_free(struct pkt *pkt); -#endif /* PKT_H */ +void pktq_reverse(struct pktq *pktq); +void pktq_shuffle(rand_t *r, struct pktq *pktq); +struct pkt *pktq_random(rand_t *r, struct pktq *pktq); diff --git a/src/fragroute/randutil.c b/src/fragroute/randutil.c index dff0881e1..e5c099e06 100644 --- a/src/fragroute/randutil.c +++ b/src/fragroute/randutil.c @@ -22,15 +22,13 @@ #endif #endif +#include "randutil.h" #include #include #include #include -#include "randutil.h" - -static const char base64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; void rand_strset(rand_t *r, void *buf, size_t len) @@ -45,15 +43,19 @@ rand_strset(rand_t *r, void *buf, size_t len) /* XXX - more Duff's device tomfoolery. */ switch (len % 4) { - case 0: do { - u = rand_uint32(r); - *p++ = base64[(u >> 18) & 0x3f]; - case 3: - *p++ = base64[(u >> 12) & 0x3f]; - case 2: - *p++ = base64[(u >> 6) & 0x3f]; - case 1: - *p++ = base64[(u >> 0) & 0x3f]; + case 0: + do { + u = rand_uint32(r); + *p++ = base64[(u >> 18) & 0x3f]; + /* fall through */ + case 3: + *p++ = base64[(u >> 12) & 0x3f]; + /* fall through */ + case 2: + *p++ = base64[(u >> 6) & 0x3f]; + /* fall through */ + case 1: + *p++ = base64[(u >> 0) & 0x3f]; } while (--i > 0); } p[-1] = '\0'; diff --git a/src/fragroute/randutil.h b/src/fragroute/randutil.h index 864e6deea..eceef66c9 100644 --- a/src/fragroute/randutil.h +++ b/src/fragroute/randutil.h @@ -6,9 +6,6 @@ * $Id$ */ -#ifndef RANDUTIL_H -#define RANDUTIL_H +#pragma once -void rand_strset(rand_t *r, void *buf, size_t len); - -#endif /* RANDUTIL_H */ +void rand_strset(rand_t *r, void *buf, size_t len); diff --git a/src/replay.c b/src/replay.c index b3334ae6a..c39665268 100644 --- a/src/replay.c +++ b/src/replay.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" -#include "tcpreplay_api.h" #include "send_packets.h" - +#include "tcpreplay_api.h" +#include static int replay_file(tcpreplay_t *ctx, int idx); static int replay_two_files(tcpreplay_t *ctx, int idx1, int idx2); @@ -40,7 +37,7 @@ static int replay_two_fds(tcpreplay_t *ctx, int idx1, int idx2); * * This is used by tcpreplay_replay() to actually send the packets */ -int +int tcpr_replay_index(tcpreplay_t *ctx) { int rcode = 0; @@ -48,25 +45,23 @@ tcpr_replay_index(tcpreplay_t *ctx) assert(ctx); /* only process a single file */ - if (! ctx->options->dualfile) { + if (!ctx->options->dualfile) { /* process each pcap file in order */ for (idx = 0; idx < ctx->options->source_cnt && !ctx->abort; idx++) { /* reset cache markers for each iteration */ - ctx->cache_byte = 0; - ctx->cache_bit = 0; - switch(ctx->options->sources[idx].type) { - case source_filename: - rcode = replay_file(ctx, idx); - break; - case source_fd: - rcode = replay_fd(ctx, idx); - break; - case source_cache: - rcode = replay_cache(ctx, idx); - break; - default: - tcpreplay_seterr(ctx, "Invalid source type: %d", ctx->options->sources[idx].type); - rcode = -1; + switch (ctx->options->sources[idx].type) { + case source_filename: + rcode = replay_file(ctx, idx); + break; + case source_fd: + rcode = replay_fd(ctx, idx); + break; + case source_cache: + rcode = replay_cache(ctx, idx); + break; + default: + tcpreplay_seterr(ctx, "Invalid source type: %d", ctx->options->sources[idx].type); + rcode = -1; } } } @@ -75,27 +70,25 @@ tcpr_replay_index(tcpreplay_t *ctx) else { /* process each pcap file in order */ for (idx = 0; idx < ctx->options->source_cnt && !ctx->abort; idx += 2) { - if (ctx->options->sources[idx].type != ctx->options->sources[(idx+1)].type) { - tcpreplay_seterr(ctx, "Both source indexes (%d, %d) must be of the same type", idx, (idx+1)); + if (ctx->options->sources[idx].type != ctx->options->sources[(idx + 1)].type) { + tcpreplay_seterr(ctx, "Both source indexes (%d, %d) must be of the same type", idx, (idx + 1)); return -1; } - switch(ctx->options->sources[idx].type) { - case source_filename: - rcode = replay_two_files(ctx, idx, (idx+1)); - break; - case source_fd: - rcode = replay_two_fds(ctx, idx, (idx+1)); - break; - case source_cache: - rcode = replay_two_caches(ctx, idx, (idx+1)); - break; - default: - tcpreplay_seterr(ctx, "Invalid source type: %d", ctx->options->sources[idx].type); - rcode = -1; + switch (ctx->options->sources[idx].type) { + case source_filename: + rcode = replay_two_files(ctx, idx, (idx + 1)); + break; + case source_fd: + rcode = replay_two_fds(ctx, idx, (idx + 1)); + break; + case source_cache: + rcode = replay_two_caches(ctx, idx, (idx + 1)); + break; + default: + tcpreplay_seterr(ctx, "Invalid source type: %d", ctx->options->sources[idx].type); + rcode = -1; } - } - } if (rcode < 0) { ctx->running = false; @@ -105,7 +98,6 @@ tcpr_replay_index(tcpreplay_t *ctx) return rcode; } - /** * \brief replay a pcap file out interface(s) * @@ -135,7 +127,8 @@ replay_file(tcpreplay_t *ctx, int idx) #ifdef HAVE_PCAP_SNAPSHOT if (pcap_snapshot(pcap) < 65535) warnx("%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", - path, pcap_snapshot(pcap)); + path, + pcap_snapshot(pcap)); #endif } else { @@ -153,8 +146,8 @@ replay_file(tcpreplay_t *ctx, int idx) /* in cache mode, we may not have opened the file */ if (pcap == NULL) if ((pcap = pcap_open_offline(path, ebuf)) == NULL) { - tcpreplay_seterr(ctx, "Error opening pcap file: %s", ebuf); - return -1; + tcpreplay_seterr(ctx, "Error opening pcap file: %s", ebuf); + return -1; } ctx->options->file_cache[idx].dlt = pcap_datalink(pcap); @@ -173,9 +166,12 @@ replay_file(tcpreplay_t *ctx, int idx) ctx->options->intf1->device, pcap_datalink_val_to_name(ctx->intf1dlt)); #endif if (ctx->intf1dlt != ctx->options->file_cache[idx].dlt) - tcpreplay_setwarn(ctx, "%s DLT (%s) does not match that of the outbound interface: %s (%s)", - path, pcap_datalink_val_to_name(pcap_datalink(pcap)), - ctx->intf1->device, pcap_datalink_val_to_name(ctx->intf1dlt)); + tcpreplay_setwarn(ctx, + "%s DLT (%s) does not match that of the outbound interface: %s (%s)", + path, + pcap_datalink_val_to_name(pcap_datalink(pcap)), + ctx->intf1->device, + pcap_datalink_val_to_name(ctx->intf1dlt)); } ctx->stats.active_pcap = ctx->options->sources[idx].filename; @@ -190,7 +186,6 @@ replay_file(tcpreplay_t *ctx, int idx) return 0; } - /** * \brief replay two pcap files out two interfaces * @@ -200,7 +195,7 @@ static int replay_two_files(tcpreplay_t *ctx, int idx1, int idx2) { char *path1, *path2; - pcap_t *pcap1 = NULL, *pcap2 = NULL; + pcap_t *pcap1 = NULL, *pcap2 = NULL; char ebuf[PCAP_ERRBUF_SIZE]; int rcode = 0; @@ -211,10 +206,8 @@ replay_two_files(tcpreplay_t *ctx, int idx1, int idx2) path1 = ctx->options->sources[idx1].filename; path2 = ctx->options->sources[idx2].filename; - /* can't use stdin in dualfile mode */ - if ((strncmp(path1, "-", strlen(path1)) == 0) || - (strncmp(path2, "-", strlen(path2)) == 0)) { + if ((strncmp(path1, "-", strlen(path1)) == 0) || (strncmp(path2, "-", strlen(path2)) == 0)) { tcpreplay_seterr(ctx, "%s", "Invalid use of STDIN '-' in dual file mode"); return -1; } @@ -251,45 +244,53 @@ replay_two_files(tcpreplay_t *ctx, int idx1, int idx2) if (pcap1 != NULL) { #ifdef HAVE_PCAP_SNAPSHOT if (pcap_snapshot(pcap1) < 65535) { - tcpreplay_setwarn(ctx, "%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", - path1, pcap_snapshot(pcap1)); + tcpreplay_setwarn(ctx, + "%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", + path1, + pcap_snapshot(pcap1)); rcode = -2; } if (pcap_snapshot(pcap2) < 65535) { - tcpreplay_setwarn(ctx, "%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", - path2, pcap_snapshot(pcap2)); + tcpreplay_setwarn(ctx, + "%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", + path2, + pcap_snapshot(pcap2)); rcode = -2; } #endif if (ctx->intf1dlt == -1) ctx->intf1dlt = sendpacket_get_dlt(ctx->intf1); if ((ctx->intf1dlt >= 0) && (ctx->intf1dlt != pcap_datalink(pcap1))) { - tcpreplay_setwarn(ctx, "%s DLT (%s) does not match that of the outbound interface: %s (%s)", - path1, pcap_datalink_val_to_name(pcap_datalink(pcap1)), - ctx->intf1->device, pcap_datalink_val_to_name(ctx->intf1dlt)); + tcpreplay_setwarn(ctx, + "%s DLT (%s) does not match that of the outbound interface: %s (%s)", + path1, + pcap_datalink_val_to_name(pcap_datalink(pcap1)), + ctx->intf1->device, + pcap_datalink_val_to_name(ctx->intf1dlt)); rcode = -2; } if (ctx->intf2dlt == -1) ctx->intf2dlt = sendpacket_get_dlt(ctx->intf2); if ((ctx->intf2dlt >= 0) && (ctx->intf2dlt != pcap_datalink(pcap2))) { - tcpreplay_setwarn(ctx, "%s DLT (%s) does not match that of the outbound interface: %s (%s)", - path2, pcap_datalink_val_to_name(pcap_datalink(pcap2)), - ctx->intf2->device, pcap_datalink_val_to_name(ctx->intf2dlt)); + tcpreplay_setwarn(ctx, + "%s DLT (%s) does not match that of the outbound interface: %s (%s)", + path2, + pcap_datalink_val_to_name(pcap_datalink(pcap2)), + ctx->intf2->device, + pcap_datalink_val_to_name(ctx->intf2dlt)); rcode = -2; } if (ctx->intf1dlt != ctx->intf2dlt) { - tcpreplay_seterr(ctx, "DLT mismatch for %s (%d) and %s (%d)", - path1, ctx->intf1dlt, path2, ctx->intf2dlt); + tcpreplay_seterr(ctx, "DLT mismatch for %s (%d) and %s (%d)", path1, ctx->intf1dlt, path2, ctx->intf2dlt); return -1; } } #ifdef ENABLE_VERBOSE if (ctx->options->verbose) { - /* in cache mode, we may not have opened the file */ if (pcap1 == NULL) { if ((pcap1 = pcap_open_offline(path1, ebuf)) == NULL) { @@ -303,7 +304,6 @@ replay_two_files(tcpreplay_t *ctx, int idx1, int idx2) } #endif - send_dual_packets(ctx, pcap1, idx1, pcap2, idx2); if (pcap1 != NULL) @@ -319,30 +319,27 @@ replay_two_files(tcpreplay_t *ctx, int idx1, int idx2) return rcode; } - /** - * \brief Replay index using existing memory cache + * \brief Replay index using existing memory cache * * FIXME */ static int replay_cache(tcpreplay_t *ctx, int idx) { - assert(ctx); assert(ctx->options->sources[idx].type == source_cache); return 0; } /** - * \brief Replay two indexes using existing memory cache + * \brief Replay two indexes using existing memory cache * * FIXME */ static int replay_two_caches(tcpreplay_t *ctx, int idx1, int idx2) { - assert(ctx); assert(ctx->options->sources[idx1].type == source_cache); assert(ctx->options->sources[idx2].type == source_cache); @@ -350,28 +347,26 @@ replay_two_caches(tcpreplay_t *ctx, int idx1, int idx2) } /** - * \brief Replay index which is a file descriptor + * \brief Replay index which is a file descriptor * * FIXME */ static int replay_fd(tcpreplay_t *ctx, int idx) { - assert(ctx); assert(ctx->options->sources[idx].type == source_fd); return 0; } /** - * \brief Replay two indexes which are a file descriptor + * \brief Replay two indexes which are a file descriptor * * FIXME */ static int replay_two_fds(tcpreplay_t *ctx, int idx1, int idx2) { - assert(ctx); assert(ctx->options->sources[idx1].type == source_fd); assert(ctx->options->sources[idx2].type == source_fd); diff --git a/src/replay.h b/src/replay.h index 1d6f29327..4a4becdf8 100644 --- a/src/replay.h +++ b/src/replay.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,6 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _REPLAY_H_ -#define _REPLAY_H_ +#pragma once int tcpr_replay_index(tcpreplay_t *ctx); - -#endif /* _REPLAY_H_ */ diff --git a/src/send_packets.c b/src/send_packets.c index 2d992712e..a09d7d5e4 100644 --- a/src/send_packets.c +++ b/src/send_packets.c @@ -1,13 +1,12 @@ /* $Id$ */ - /* * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,38 +18,34 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include -#include -#include -#include -#include +#include "tcpreplay_api.h" +#include "timestamp_trace.h" #include +#include +#include #include +#include +#include +#include #include -#include - -#include "tcpreplay_api.h" -#include "timestamp_trace.h" -#include "../lib/sll.h" #ifdef HAVE_NETMAP #ifdef HAVE_SYS_POLL_H #include #endif -#include #include #include +#include #endif /* HAVE_NETMAP */ #ifdef TCPREPLAY #ifdef TCPREPLAY_EDIT -#include "tcpreplay_edit_opts.h" #include "tcpedit/tcpedit.h" +#include "tcpreplay_edit_opts.h" extern tcpedit_t *tcpedit; #else #include "tcpreplay_opts.h" @@ -61,34 +56,31 @@ extern tcpedit_t *tcpedit; #include "send_packets.h" #include "sleep.h" -#ifdef DEBUG -extern int debug; -#endif - -static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_time, - struct timeval *last, COUNTER len, - sendpacket_t *sp, COUNTER counter, timestamp_t *sent_timestamp, - COUNTER start_us, COUNTER *skip_length); -static void tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp _U_, - struct timespec *nap_this_time, struct timeval *now); -static u_char *get_next_packet(tcpreplay_t *ctx, pcap_t *pcap, - struct pcap_pkthdr *pkthdr, - int file_idx, - packet_cache_t **prev_packet); +static void calc_sleep_time(tcpreplay_t *ctx, + struct timeval *pkt_ts_delta, + struct timeval *time_delta, + COUNTER len, + sendpacket_t *sp, + COUNTER counter, + timestamp_t *sent_timestamp, + COUNTER start_us, + COUNTER *skip_length); +static void tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp _U_, struct timespec *nap_this_time, struct timeval *now); +static u_char * +get_next_packet(tcpreplay_t *ctx, pcap_t *pcap, struct pcap_pkthdr *pkthdr, int file_idx, packet_cache_t **prev_packet); static uint32_t get_user_count(tcpreplay_t *ctx, sendpacket_t *sp, COUNTER counter); -static inline void wake_send_queues(sendpacket_t *sp _U_, - tcpreplay_opt_t *options _U_) -{ #ifdef HAVE_NETMAP +static inline void +wake_send_queues(sendpacket_t *sp _U_, tcpreplay_opt_t *options _U_) +{ if (options->netmap) - ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ -#endif + ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ } +#endif static inline int -fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, - COUNTER iteration, bool cached, int datalink) +fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, COUNTER iteration, bool cached, int datalink) { uint32_t pkt_len = pkthdr->caplen; u_char *packet = *pktdata; @@ -102,19 +94,11 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, uint32_t l2len; int res; - res = get_l2len_protocol(packet, - pkt_len, - datalink, - ðer_type, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(packet, pkt_len, datalink, ðer_type, &l2len, &l2offset, &vlan_offset); if (res < 0) return res; - assert(l2len > 0); - switch (ether_type) { case ETHERTYPE_IP: if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv4_hdr_t))) { @@ -143,8 +127,7 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, dbgx(2, "Layer 3 protocol type is: 0x%04x", ether_type); /* swap src/dst IP's in a manner that does not affect CRC */ - if ((!cached && dst_ip > src_ip) || - (cached && (dst_ip - iteration) > (src_ip - 1 - iteration))) { + if ((!cached && dst_ip > src_ip) || (cached && (dst_ip - iteration) > (src_ip - 1 - iteration))) { if (cached) { --src_ip; ++dst_ip; @@ -155,13 +138,29 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, /* CRC compensations for wrap conditions */ if (src_ip > src_ip_orig && dst_ip > dst_ip_orig) { - dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(1) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); + dbgx(1, + "dst_ip > src_ip(" COUNTER_SPEC "): before(1) src_ip=0x%08x dst_ip=0x%08x", + iteration, + src_ip, + dst_ip); --src_ip; - dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(1) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); + dbgx(1, + "dst_ip > src_ip(" COUNTER_SPEC "): after(1) src_ip=0x%08x dst_ip=0x%08x", + iteration, + src_ip, + dst_ip); } else if (dst_ip < dst_ip_orig && src_ip < src_ip_orig) { - dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(2) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); + dbgx(1, + "dst_ip > src_ip(" COUNTER_SPEC "): before(2) src_ip=0x%08x dst_ip=0x%08x", + iteration, + src_ip, + dst_ip); ++dst_ip; - dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(2) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip); + dbgx(1, + "dst_ip > src_ip(" COUNTER_SPEC "): after(2) src_ip=0x%08x dst_ip=0x%08x", + iteration, + src_ip, + dst_ip); } } else { if (cached) { @@ -174,13 +173,29 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, /* CRC compensations for wrap conditions */ if (dst_ip > dst_ip_orig && src_ip > src_ip_orig) { - dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(1) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); + dbgx(1, + "src_ip > dst_ip(" COUNTER_SPEC "): before(1) dst_ip=0x%08x src_ip=0x%08x", + iteration, + dst_ip, + src_ip); --dst_ip; - dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(1) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); + dbgx(1, + "src_ip > dst_ip(" COUNTER_SPEC "): after(1) dst_ip=0x%08x src_ip=0x%08x", + iteration, + dst_ip, + src_ip); } else if (src_ip < src_ip_orig && dst_ip < dst_ip_orig) { - dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(2) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); + dbgx(1, + "src_ip > dst_ip(" COUNTER_SPEC "): before(2) dst_ip=0x%08x src_ip=0x%08x", + iteration, + dst_ip, + src_ip); ++src_ip; - dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(2) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip); + dbgx(1, + "src_ip > dst_ip(" COUNTER_SPEC "): after(2) dst_ip=0x%08x src_ip=0x%08x", + iteration, + dst_ip, + src_ip); } } @@ -196,6 +211,7 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, ip6_hdr->ip_src.__u6_addr.__u6_addr32[3] = htonl(src_ip); ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3] = htonl(dst_ip); break; + default:; } return 0; @@ -206,11 +222,14 @@ fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata, * * Finds out if flow is unique and updates stats. */ -static inline void update_flow_stats(tcpreplay_t *ctx, sendpacket_t *sp, - const struct pcap_pkthdr *pkthdr, const u_char *pktdata, int datalink) +static inline void +update_flow_stats(tcpreplay_t *ctx, + sendpacket_t *sp, + const struct pcap_pkthdr *pkthdr, + const u_char *pktdata, + int datalink) { - flow_entry_type_t res = flow_decode(ctx->flow_hash_table, - pkthdr, pktdata, datalink, ctx->options->flow_expiry); + flow_entry_type_t res = flow_decode(ctx->flow_hash_table, pkthdr, pktdata, datalink, ctx->options->flow_expiry); switch (res) { case FLOW_ENTRY_NEW: @@ -239,7 +258,7 @@ static inline void update_flow_stats(tcpreplay_t *ctx, sendpacket_t *sp, ++sp->flows; ++sp->flow_packets; } - break; + break; case FLOW_ENTRY_NON_IP: ++ctx->stats.flow_non_flow_packets; @@ -255,7 +274,7 @@ static inline void update_flow_stats(tcpreplay_t *ctx, sendpacket_t *sp, } } /** - * \brief Preloads the memory cache for the given pcap file_idx + * \brief Preloads the memory cache for the given pcap file_idx * * Preloading can be used with or without --loop */ @@ -270,7 +289,6 @@ preload_pcap_file(tcpreplay_t *ctx, int idx) struct pcap_pkthdr pkthdr; packet_cache_t *cached_packet = NULL; packet_cache_t **prev_packet = &cached_packet; - COUNTER packetnum = 0; int dlt; /* close stdin if reading from it (needed for some OS's) */ @@ -284,7 +302,6 @@ preload_pcap_file(tcpreplay_t *ctx, int idx) dlt = pcap_datalink(pcap); /* loop through the pcap. get_next_packet() builds the cache for us! */ while ((pktdata = get_next_packet(ctx, pcap, &pkthdr, idx, prev_packet)) != NULL) { - packetnum++; if (options->flow_stats) update_flow_stats(ctx, NULL, &pkthdr, pktdata, dlt); } @@ -295,7 +312,8 @@ preload_pcap_file(tcpreplay_t *ctx, int idx) pcap_close(pcap); } -static void increment_iteration(tcpreplay_t *ctx) +static void +increment_iteration(tcpreplay_t *ctx) { tcpreplay_opt_t *options = ctx->options; @@ -303,9 +321,7 @@ static void increment_iteration(tcpreplay_t *ctx) ++ctx->iteration; if (options->unique_ip) { assert(options->unique_loops > 0.0); - ctx->unique_iteration = - ((ctx->iteration * 1000) / (COUNTER)(options->unique_loops * 1000.0)) - + 1; + ctx->unique_iteration = ((ctx->iteration * 1000) / (COUNTER)(options->unique_loops * 1000.0)) + 1; } } @@ -316,7 +332,6 @@ static void increment_iteration(tcpreplay_t *ctx) void send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) { - struct timeval print_delta, now, last_pkt_ts; tcpreplay_opt_t *options = ctx->options; tcpreplay_stats_t *stats = &ctx->stats; @@ -336,7 +351,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) COUNTER end_us; bool preload = options->file_cache[idx].cached; bool top_speed = (options->speed.mode == speed_topspeed || - (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); + (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); bool now_is_now = true; gettimeofday(&now, NULL); @@ -352,8 +367,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) ctx->skip_packets = 0; timerclear(&last_pkt_ts); if (options->limit_time > 0) - end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + - SEC_TO_MICROSEC(options->limit_time); + end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + SEC_TO_MICROSEC(options->limit_time); else end_us = 0; @@ -363,13 +377,11 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) prev_packet = NULL; } - /* MAIN LOOP + /* MAIN LOOP * Keep sending while we have packets or until * we've sent enough packets */ - while (!ctx->abort && - (pktdata = get_next_packet(ctx, pcap, &pkthdr, idx, prev_packet)) != NULL) { - + while (!ctx->abort && (pktdata = get_next_packet(ctx, pcap, &pkthdr, idx, prev_packet)) != NULL) { now_is_now = false; packetnum++; #if defined TCPREPLAY || defined TCPREPLAY_EDIT @@ -400,11 +412,9 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr_ptr->len : (COUNTER)pkthdr_ptr->caplen; #endif - if (ctx->options->unique_ip && ctx->unique_iteration && - ctx->unique_iteration > ctx->last_unique_iteration) { + if (ctx->options->unique_ip && ctx->unique_iteration && ctx->unique_iteration > ctx->last_unique_iteration) { /* edit packet to ensure every pass has unique IP addresses */ - if (fast_edit_packet(&pkthdr, &pktdata, ctx->unique_iteration - 1, - preload, datalink) == -1) { + if (fast_edit_packet(&pkthdr, &pktdata, ctx->unique_iteration - 1, preload, datalink) == -1) { ++stats->failed; continue; } @@ -412,8 +422,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) /* update flow stats */ if (options->flow_stats && !preload) - update_flow_stats(ctx, - options->cache_packets ? sp : NULL, &pkthdr, pktdata, datalink); + update_flow_stats(ctx, options->cache_packets ? sp : NULL, &pkthdr, pktdata, datalink); /* * this accelerator improves performance by avoiding expensive @@ -429,8 +438,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) * time stamping is expensive, but now is the * time to do it. */ - dbgx(4, "This packet time: " TIMEVAL_FORMAT, pkthdr.ts.tv_sec, - pkthdr.ts.tv_usec); + dbgx(4, "This packet time: " TIMEVAL_FORMAT, pkthdr.ts.tv_sec, pkthdr.ts.tv_usec); skip_length = 0; ctx->skip_packets = 0; @@ -444,9 +452,6 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) timeradd(&stats->pkt_ts_delta, &delta, &stats->pkt_ts_delta); TIMEVAL_SET(&last_pkt_ts, &pkthdr.ts); } - - if (!timerisset(&stats->time_delta)) - TIMEVAL_SET(&stats->pkt_ts_delta, &stats->pkt_ts_delta); } if (!top_speed) { @@ -460,9 +465,15 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) * This also sets skip_length and skip_packets which will avoid * timestamping for a given number of packets. */ - calc_sleep_time(ctx, &stats->pkt_ts_delta, &stats->time_delta, - pktlen, sp, packetnum, &stats->end_time, - TIMEVAL_TO_MICROSEC(&stats->start_time), &skip_length); + calc_sleep_time(ctx, + &stats->pkt_ts_delta, + &stats->time_delta, + pktlen, + sp, + packetnum, + &stats->end_time, + TIMEVAL_TO_MICROSEC(&stats->start_time), + &skip_length); /* * Track the time of the "last packet sent". @@ -490,7 +501,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) /* write packet out on network */ if (sendpacket(sp, pktdata, pktlen, &pkthdr) < (int)pktlen) { warnx("Unable to send packet: %s", sendpacket_geterr(sp)); - break; + continue; } /* @@ -507,7 +518,7 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) /* print stats during the run? */ if (options->stats > 0) { - if (! timerisset(&stats->last_print)) { + if (!timerisset(&stats->last_print)) { TIMEVAL_SET(&stats->last_print, &now); } else { timersub(&now, &stats->last_print, &print_delta); @@ -527,13 +538,12 @@ send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) #endif /* stop sending based on the duration limit... */ if ((end_us > 0 && (COUNTER)TIMEVAL_TO_MICROSEC(&now) > end_us) || - /* ... or stop sending based on the limit -L? */ - (limit_send > 0 && stats->pkts_sent >= limit_send)) { + /* ... or stop sending based on the limit -L? */ + (limit_send > 0 && stats->pkts_sent >= limit_send)) { ctx->abort = true; } } /* while */ - #ifdef HAVE_NETMAP /* when completing test, wait until the last packet is sent */ if (options->netmap && (ctx->abort || options->loop == 1)) { @@ -581,7 +591,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * COUNTER end_us; COUNTER skip_length = 0; bool top_speed = (options->speed.mode == speed_topspeed || - (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); + (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); bool now_is_now = true; gettimeofday(&now, NULL); @@ -597,8 +607,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * ctx->skip_packets = 0; timerclear(&last_pkt_ts); if (options->limit_time > 0) - end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + - SEC_TO_MICROSEC(options->limit_time); + end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + SEC_TO_MICROSEC(options->limit_time); else end_us = 0; @@ -613,50 +622,34 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * pktdata1 = get_next_packet(ctx, pcap1, &pkthdr1, cache_file_idx1, prev_packet1); pktdata2 = get_next_packet(ctx, pcap2, &pkthdr2, cache_file_idx2, prev_packet2); - /* MAIN LOOP + /* MAIN LOOP * Keep sending while we have packets or until * we've sent enough packets */ - while (!ctx->abort && - !(pktdata1 == NULL && pktdata2 == NULL)) { - + while (!ctx->abort && !(pktdata1 == NULL && pktdata2 == NULL)) { now_is_now = false; packetnum++; - /* figure out which pcap file we need to process next - * when get_next_packet() returns null for pktdata, the pkthdr + /* figure out which pcap file we need to process next + * when get_next_packet() returns null for pktdata, the pkthdr * will still have the old values from the previous call. This * means we can't always trust the timestamps to tell us which * file to process. */ - if (pktdata1 == NULL) { + if (pktdata1 == NULL || (pktdata2 != NULL && timercmp(&pkthdr1.ts, &pkthdr2.ts, >))) { /* file 2 is next */ sp = ctx->intf2; datalink = options->file_cache[cache_file_idx2].dlt; pkthdr_ptr = &pkthdr2; cache_file_idx = cache_file_idx2; pktdata = pktdata2; - } else if (pktdata2 == NULL) { - /* file 1 is next */ - sp = ctx->intf1; - datalink = options->file_cache[cache_file_idx1].dlt; - pkthdr_ptr = &pkthdr1; - cache_file_idx = cache_file_idx1; - pktdata = pktdata1; - } else if (timercmp(&pkthdr1.ts, &pkthdr2.ts, <=)) { + } else { /* file 1 is next */ sp = ctx->intf1; datalink = options->file_cache[cache_file_idx1].dlt; pkthdr_ptr = &pkthdr1; cache_file_idx = cache_file_idx1; pktdata = pktdata1; - } else { - /* file 2 is next */ - sp = ctx->intf2; - datalink = options->file_cache[cache_file_idx2].dlt; - pkthdr_ptr = &pkthdr2; - cache_file_idx = cache_file_idx2; - pktdata = pktdata2; } #if defined TCPREPLAY || defined TCPREPLAY_EDIT @@ -677,11 +670,13 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr_ptr->len : (COUNTER)pkthdr_ptr->caplen; #endif - if (ctx->options->unique_ip && ctx->unique_iteration && - ctx->unique_iteration > ctx->last_unique_iteration) { + if (ctx->options->unique_ip && ctx->unique_iteration && ctx->unique_iteration > ctx->last_unique_iteration) { /* edit packet to ensure every pass is unique */ - if (fast_edit_packet(pkthdr_ptr, &pktdata, ctx->unique_iteration - 1, - options->file_cache[cache_file_idx].cached, datalink) == -1) { + if (fast_edit_packet(pkthdr_ptr, + &pktdata, + ctx->unique_iteration - 1, + options->file_cache[cache_file_idx].cached, + datalink) == -1) { ++stats->failed; continue; } @@ -705,8 +700,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * * time stamping is expensive, but now is the * time to do it. */ - dbgx(4, "This packet time: " TIMEVAL_FORMAT, pkthdr_ptr->ts.tv_sec, - pkthdr_ptr->ts.tv_usec); + dbgx(4, "This packet time: " TIMEVAL_FORMAT, pkthdr_ptr->ts.tv_sec, pkthdr_ptr->ts.tv_usec); skip_length = 0; ctx->skip_packets = 0; @@ -736,9 +730,15 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * * This also sets skip_length and skip_packets which will avoid * timestamping for a given number of packets. */ - calc_sleep_time(ctx, &stats->pkt_ts_delta, &stats->time_delta, - pktlen, sp, packetnum, &stats->end_time, - TIMEVAL_TO_MICROSEC(&stats->start_time), &skip_length); + calc_sleep_time(ctx, + &stats->pkt_ts_delta, + &stats->time_delta, + pktlen, + sp, + packetnum, + &stats->end_time, + TIMEVAL_TO_MICROSEC(&stats->start_time), + &skip_length); /* * Track the time of the "last packet sent". @@ -766,7 +766,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * /* write packet out on network */ if (sendpacket(sp, pktdata, pktlen, pkthdr_ptr) < (int)pktlen) { warnx("Unable to send packet: %s", sendpacket_geterr(sp)); - break; + continue; } /* @@ -779,7 +779,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * /* print stats during the run? */ if (options->stats > 0) { - if (! timerisset(&stats->last_print)) { + if (!timerisset(&stats->last_print)) { TIMEVAL_SET(&stats->last_print, &now); } else { timersub(&now, &stats->last_print, &print_delta); @@ -807,8 +807,8 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * /* stop sending based on the duration limit... */ if ((end_us > 0 && (COUNTER)TIMEVAL_TO_MICROSEC(&now) > end_us) || - /* ... or stop sending based on the limit -L? */ - (limit_send > 0 && stats->pkts_sent >= limit_send)) { + /* ... or stop sending based on the limit -L? */ + (limit_send > 0 && stats->pkts_sent >= limit_send)) { ctx->abort = true; } } /* while */ @@ -836,8 +836,6 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * increment_iteration(ctx); } - - /** * Gets the next packet to be sent out. This will either read from the pcap file * or will retrieve the packet from the internal cache. @@ -847,8 +845,7 @@ send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int cache_file_idx1, pcap_t * * will be updated as new entries are added (or retrieved) from the cache list. */ u_char * -get_next_packet(tcpreplay_t *ctx, pcap_t *pcap, struct pcap_pkthdr *pkthdr, int idx, - packet_cache_t **prev_packet) +get_next_packet(tcpreplay_t *ctx, pcap_t *pcap, struct pcap_pkthdr *pkthdr, int idx, packet_cache_t **prev_packet) { tcpreplay_opt_t *options = ctx->options; u_char *pktdata = NULL; @@ -924,9 +921,9 @@ get_next_packet(tcpreplay_t *ctx, pcap_t *pcap, struct pcap_pkthdr *pkthdr, int } /** - * determines based upon the cachedata which interface the given packet + * determines based upon the cachedata which interface the given packet * should go out. Also rewrites any layer 2 data we might need to adjust. - * Returns a void cased pointer to the ctx->intfX of the corresponding + * Returns a void cased pointer to the ctx->intfX of the corresponding * interface or NULL on error */ void * @@ -945,16 +942,13 @@ cache_mode(tcpreplay_t *ctx, char *cachedata, COUNTER packet_num) if (result == TCPR_DIR_NOSEND) { dbgx(2, "Cache: Not sending packet " COUNTER_SPEC ".", packet_num); return NULL; - } - else if (result == TCPR_DIR_C2S) { + } else if (result == TCPR_DIR_C2S) { dbgx(2, "Cache: Sending packet " COUNTER_SPEC " out primary interface.", packet_num); sp = ctx->intf1; - } - else if (result == TCPR_DIR_S2C) { + } else if (result == TCPR_DIR_S2C) { dbgx(2, "Cache: Sending packet " COUNTER_SPEC " out secondary interface.", packet_num); sp = ctx->intf2; - } - else { + } else { tcpreplay_seterr(ctx, "Invalid cache value: %i", result); return NULL; } @@ -962,16 +956,21 @@ cache_mode(tcpreplay_t *ctx, char *cachedata, COUNTER packet_num) return sp; } - /** * Given the timestamp on the current packet and the last packet sent, * calculate the appropriate amount of time to sleep. Sleep time * will be in ctx->nap. */ -static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, - struct timeval *time_delta, COUNTER len, - sendpacket_t *sp, COUNTER counter, timestamp_t *sent_timestamp, - COUNTER start_us, COUNTER *skip_length) +static void +calc_sleep_time(tcpreplay_t *ctx, + struct timeval *pkt_ts_delta, + struct timeval *time_delta, + COUNTER len, + sendpacket_t *sp, + COUNTER counter, + timestamp_t *sent_timestamp, + COUNTER start_us, + COUNTER *skip_length) { tcpreplay_opt_t *options = ctx->options; struct timeval nap_for; @@ -993,7 +992,7 @@ static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, return; } - switch(options->speed.mode) { + switch (options->speed.mode) { case speed_multiplier: /* * Replay packets a factor of the time they were originally sent. @@ -1003,11 +1002,9 @@ static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, /* pkt_time_delta has increased, so handle normally */ timersub(pkt_ts_delta, time_delta, &nap_for); TIMEVAL_TO_TIMESPEC(&nap_for, &ctx->nap); - dbgx(3, "original packet delta time: " TIMESPEC_FORMAT, - ctx->nap.tv_sec, ctx->nap.tv_nsec); + dbgx(3, "original packet delta time: " TIMESPEC_FORMAT, ctx->nap.tv_sec, ctx->nap.tv_nsec); timesdiv_float(&ctx->nap, options->speed.multiplier); - dbgx(3, "original packet delta/div: " TIMESPEC_FORMAT, - ctx->nap.tv_sec, ctx->nap.tv_nsec); + dbgx(3, "original packet delta/div: " TIMESPEC_FORMAT, ctx->nap.tv_sec, ctx->nap.tv_nsec); } break; @@ -1040,48 +1037,48 @@ static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, *skip_length = ((tx_us - next_tx_us) * bps) / 8000000; } - update_current_timestamp_trace_entry(ctx->stats.bytes_sent + - (COUNTER)len, now_us, tx_us, next_tx_us); + update_current_timestamp_trace_entry(ctx->stats.bytes_sent + (COUNTER)len, now_us, tx_us, next_tx_us); } - dbgx(3, "packet size=" COUNTER_SPEC "\t\tnap=" TIMESPEC_FORMAT, len, - ctx->nap.tv_sec, ctx->nap.tv_nsec); + dbgx(3, "packet size=" COUNTER_SPEC "\t\tnap=" TIMESPEC_FORMAT, len, ctx->nap.tv_sec, ctx->nap.tv_nsec); break; case speed_packetrate: /* - * Ignore the time supplied by the capture file and send data at - * a constant rate (packets per second). - */ - now_us = TIMSTAMP_TO_MICROSEC(sent_timestamp); - if (now_us) { - COUNTER next_tx_us; - COUNTER pph = ctx->options->speed.speed; - COUNTER pkts_sent = ctx->stats.pkts_sent; - COUNTER tx_us = now_us - start_us; - /* - * packets * 1000000 divided by pps = microseconds - * packets per sec (pps) = packets per hour / (60 * 60) - * - * Adjust for long running tests with high PPS to prevent overflow. - * When active, adjusted calculation may add a bit of jitter. - */ - if ((pkts_sent < COUNTER_OVERFLOW_RISK)) - next_tx_us = (pkts_sent * 1000000) * (60 * 60) / pph; - else - next_tx_us = ((pkts_sent * 1000000) / pph) * (60 * 60); - - if (next_tx_us > tx_us) - NANOSEC_TO_TIMESPEC((next_tx_us - tx_us) * 1000, &ctx->nap); - else - ctx->skip_packets = options->speed.pps_multi; - - update_current_timestamp_trace_entry(ctx->stats.bytes_sent + - (COUNTER)len, now_us, tx_us, next_tx_us); - } - - dbgx(3, "packet count=" COUNTER_SPEC "\t\tnap=" TIMESPEC_FORMAT, - ctx->stats.pkts_sent, ctx->nap.tv_sec, ctx->nap.tv_nsec); + * Ignore the time supplied by the capture file and send data at + * a constant rate (packets per second). + */ + now_us = TIMSTAMP_TO_MICROSEC(sent_timestamp); + if (now_us) { + COUNTER next_tx_us; + COUNTER pph = ctx->options->speed.speed; + COUNTER pkts_sent = ctx->stats.pkts_sent; + COUNTER tx_us = now_us - start_us; + /* + * packets * 1000000 divided by pps = microseconds + * packets per sec (pps) = packets per hour / (60 * 60) + * + * Adjust for long running tests with high PPS to prevent overflow. + * When active, adjusted calculation may add a bit of jitter. + */ + if ((pkts_sent < COUNTER_OVERFLOW_RISK)) + next_tx_us = (pkts_sent * 1000000) * (60 * 60) / pph; + else + next_tx_us = ((pkts_sent * 1000000) / pph) * (60 * 60); + + if (next_tx_us > tx_us) + NANOSEC_TO_TIMESPEC((next_tx_us - tx_us) * 1000, &ctx->nap); + else + ctx->skip_packets = options->speed.pps_multi; + + update_current_timestamp_trace_entry(ctx->stats.bytes_sent + (COUNTER)len, now_us, tx_us, next_tx_us); + } + + dbgx(3, + "packet count=" COUNTER_SPEC "\t\tnap=" TIMESPEC_FORMAT, + ctx->stats.pkts_sent, + ctx->nap.tv_sec, + ctx->nap.tv_nsec); break; case speed_oneatatime: @@ -1091,7 +1088,8 @@ static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, } /* decrement our send counter */ - printf("Sending packet " COUNTER_SPEC " out: %s\n", counter, + printf("Sending packet " COUNTER_SPEC " out: %s\n", + counter, sp == ctx->intf1 ? options->intf1_name : options->intf2_name); ctx->skip_packets--; @@ -1103,12 +1101,11 @@ static void calc_sleep_time(tcpreplay_t *ctx, struct timeval *pkt_ts_delta, default: errx(-1, "Unknown/supported speed mode: %d", options->speed.mode); - break; } } -static void tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp, - struct timespec *nap_this_time, struct timeval *now) +static void +tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp, struct timespec *nap_this_time, struct timeval *now) { tcpreplay_opt_t *options = ctx->options; bool flush = @@ -1118,24 +1115,27 @@ static void tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp, false; #endif - /* don't sleep if nap = {0, 0} */ if (!timesisset(nap_this_time)) return; /* do we need to limit the total time we sleep? */ if (timesisset(&(options->maxsleep)) && (timescmp(nap_this_time, &(options->maxsleep), >))) { - dbgx(2, "Was going to sleep for " TIMESPEC_FORMAT " but maxsleeping for " TIMESPEC_FORMAT, - nap_this_time->tv_sec, nap_this_time->tv_nsec, options->maxsleep.tv_sec, - options->maxsleep.tv_nsec); + dbgx(2, + "Was going to sleep for " TIMESPEC_FORMAT " but maxsleeping for " TIMESPEC_FORMAT, + nap_this_time->tv_sec, + nap_this_time->tv_nsec, + options->maxsleep.tv_sec, + options->maxsleep.tv_nsec); TIMESPEC_SET(nap_this_time, &options->maxsleep); } +#ifdef HAVE_NETMAP if (flush) wake_send_queues(sp, options); +#endif - dbgx(2, "Sleeping: " TIMESPEC_FORMAT, - nap_this_time->tv_sec, nap_this_time->tv_nsec); + dbgx(2, "Sleeping: " TIMESPEC_FORMAT, nap_this_time->tv_sec, nap_this_time->tv_nsec); /* * Depending on the accurate method & packet rate computation method @@ -1171,21 +1171,22 @@ static void tcpr_sleep(tcpreplay_t *ctx, sendpacket_t *sp, * Ask the user how many packets they want to send. */ static uint32_t -get_user_count(tcpreplay_t *ctx, sendpacket_t *sp, COUNTER counter) +get_user_count(tcpreplay_t *ctx, sendpacket_t *sp, COUNTER counter) { tcpreplay_opt_t *options = ctx->options; - struct pollfd poller[1]; /* use poll to read from the keyboard */ + struct pollfd poller[1]; /* use poll to read from the keyboard */ char input[EBUF_SIZE]; unsigned long send = 0; printf("**** Next packet #" COUNTER_SPEC " out %s. How many packets do you wish to send? ", - counter, (sp == ctx->intf1 ? options->intf1_name : options->intf2_name)); + counter, + (sp == ctx->intf1 ? options->intf1_name : options->intf2_name)); fflush(NULL); poller[0].fd = STDIN_FILENO; poller[0].events = POLLIN | POLLPRI | POLLNVAL; poller[0].revents = 0; - if (fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK)) + if (fcntl(0, F_SETFL, fcntl(0, F_GETFL) & ~O_NONBLOCK)) errx(-1, "Unable to clear non-blocking flag on stdin: %s", strerror(errno)); /* wait for the input */ @@ -1195,7 +1196,7 @@ get_user_count(tcpreplay_t *ctx, sendpacket_t *sp, COUNTER counter) /* * read to the end of the line or EBUF_SIZE, * Note, if people are stupid, and type in more text then EBUF_SIZE - * then the next fgets() will pull in that data, which will have poor + * then the next fgets() will pull in that data, which will have poor * results. fuck them. */ if (fgets(input, sizeof(input), stdin) == NULL) { @@ -1212,5 +1213,5 @@ get_user_count(tcpreplay_t *ctx, sendpacket_t *sp, COUNTER counter) send = 1; } - return(uint32_t)send; + return (uint32_t)send; } diff --git a/src/send_packets.h b/src/send_packets.h index 316faa325..eb60be404 100644 --- a/src/send_packets.h +++ b/src/send_packets.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include "tcpreplay_api.h" +#pragma once -#ifndef __SEND_PACKETS_H__ -#define __SEND_PACKETS_H__ +#include "tcpreplay_api.h" +#include void send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx); void send_dual_packets(tcpreplay_t *ctx, pcap_t *pcap1, int idx1, pcap_t *pcap2, int idx2); void *cache_mode(tcpreplay_t *ctx, char *cachedata, COUNTER packet_num); void preload_pcap_file(tcpreplay_t *ctx, int idx); - -#endif diff --git a/src/signal_handler.c b/src/signal_handler.c index ddc43efb3..9bfd56ee6 100644 --- a/src/signal_handler.c +++ b/src/signal_handler.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,22 +18,18 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" +#include "signal_handler.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include +#include "tcpreplay_api.h" +#include #include -#include #include -#include -#include +#include #include -#include - -#include "tcpreplay.h" -#include "tcpreplay_api.h" -#include "signal_handler.h" +#include +#include struct timeval suspend_time; static struct timeval suspend_start; @@ -81,7 +77,7 @@ reset_suspend_time() /** * \brief suspend signal handler * - * Signal handler for signal SIGUSR1. SIGSTOP cannot be + * Signal handler for signal SIGUSR1. SIGSTOP cannot be * caught, so SIGUSR1 is caught and it throws SIGSTOP. */ static void @@ -134,4 +130,3 @@ abort_handler(int signo) tcpreplay_abort(ctx); } } - diff --git a/src/signal_handler.h b/src/signal_handler.h index 990abfe72..db1ef91cb 100644 --- a/src/signal_handler.h +++ b/src/signal_handler.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef SIGNAL_HANDLER_H -#define SIGNAL_HANDLER_H +#pragma once void init_signal_handlers(); void reset_suspend_time(); - -#endif - - diff --git a/src/sleep.c b/src/sleep.c index 9042bc131..05b2ef10b 100644 --- a/src/sleep.c +++ b/src/sleep.c @@ -16,23 +16,18 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "sleep.h" #include "config.h" -#include "defines.h" #include "common.h" -#include "sleep.h" - -#include -#include -#include -#include #include +#include #ifdef HAVE_SYS_EVENT #include #endif /* necessary for ioport_sleep() functions */ -#ifdef HAVE_SYS_IO_H /* Linux */ +#if defined HAVE_IOPORT_SLEEP__ && defined HAVE_SYS_IO_H /* Linux */ #include #elif defined HAVE_ARCHITECTURE_I386_PIO_H /* OS X */ #include @@ -42,20 +37,19 @@ static int ioport_sleep_value; #endif -void -ioport_sleep_init(void) +void +ioport_sleep_init(void) { #if defined HAVE_IOPORT_SLEEP__ ioperm(0x80, 1, 1); - ioport_sleep_value = inb(0x80); + ioport_sleep_value = inb(0x80); #else err(-1, "Platform does not support IO Port for timing"); #endif } -void -ioport_sleep(sendpacket_t *sp _U_, const struct timespec *nap _U_, - struct timeval *now _U_, bool flush _U_) +void +ioport_sleep(sendpacket_t *sp _U_, const struct timespec *nap _U_, struct timeval *now _U_, bool flush _U_) { #if defined HAVE_IOPORT_SLEEP__ struct timeval nap_for; @@ -64,33 +58,26 @@ ioport_sleep(sendpacket_t *sp _U_, const struct timespec *nap _U_, TIMESPEC_TO_TIMEVAL(&nap_for, nap); - /* - * process the seconds, we do this in a loop so we don't have to + /* + * process the seconds, we do this in a loop so we don't have to * use slower 64bit integers or worry about integer overflows. */ - for (i = 0; i < nap_for.tv_sec; i ++) { + for (i = 0; i < nap_for.tv_sec; i++) { usec = SEC_TO_MICROSEC(nap_for.tv_sec); while (usec > 0) { - usec --; + usec--; outb(ioport_sleep_value, 0x80); } } /* process the usec */ usec = nap->tv_nsec / 1000; - usec --; /* fudge factor for all the above */ + usec--; /* fudge factor for all the above */ while (usec > 0) { - usec --; - outb(ioport_sleep_value, 0x80); + usec--; + outb(ioport_sleep_value, 0x80); } #else err(-1, "Platform does not support IO Port for timing"); #endif - -#ifdef HAVE_NETMAP - if (flush) - ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ -#endif /* HAVE_NETMAP */ - - gettimeofday(now, NULL); } diff --git a/src/sleep.h b/src/sleep.h index 5f67ca585..0606a0e4b 100644 --- a/src/sleep.h +++ b/src/sleep.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,19 +18,21 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" +#pragma once + #include "defines.h" +#include "config.h" #include "common.h" -#ifdef HAVE_SYS_SELECT /* According to POSIX 1003.1-2001 */ +#ifdef HAVE_SYS_SELECT /* According to POSIX 1003.1-2001 */ #include -#endif +#endif -#include -#include -#include #include #include +#include +#include +#include #ifdef HAVE_SYS_EVENT #include #endif @@ -43,29 +45,23 @@ #endif #ifdef HAVE_NETMAP -#include #include #include +#include #endif /* HAVE_NETMAP */ - -#ifndef __SLEEP_H__ -#define __SLEEP_H__ - static inline void -nanosleep_sleep(sendpacket_t *sp _U_, const struct timespec *nap, - struct timeval *now, bool flush _U_) +nanosleep_sleep(sendpacket_t *sp _U_, const struct timespec *nap, struct timeval *now, bool flush _U_) { nanosleep(nap, NULL); #ifdef HAVE_NETMAP if (flush) - ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ -#endif /* HAVE_NETMAP */ + ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ +#endif /* HAVE_NETMAP */ gettimeofday(now, NULL); } - /* * Straight forward... keep calling gettimeofday() until the appropriate amount * of time has passed. Pretty damn accurate. @@ -73,8 +69,7 @@ nanosleep_sleep(sendpacket_t *sp _U_, const struct timespec *nap, * Note: make sure "now" has recently been updated. */ static inline void -gettimeofday_sleep(sendpacket_t *sp _U_, struct timespec *nap, - struct timeval *now, bool flush _U_) +gettimeofday_sleep(sendpacket_t *sp _U_, struct timespec *nap, struct timeval *now, bool flush _U_) { struct timeval sleep_until, nap_for; #ifdef HAVE_NETMAP @@ -86,7 +81,7 @@ gettimeofday_sleep(sendpacket_t *sp _U_, struct timespec *nap, TIMESPEC_TO_TIMEVAL(&nap_for, nap); timeradd(now, &nap_for, &sleep_until); - + while (!sp->abort) { #ifdef HAVE_NETMAP if (flush && timercmp(now, &last, !=)) { @@ -108,21 +103,20 @@ gettimeofday_sleep(sendpacket_t *sp _U_, struct timespec *nap, } #ifdef HAVE_SELECT -/* - * sleep for some time using the select() call timeout method. This is +/* + * sleep for some time using the select() call timeout method. This is * highly portable for sub-second sleeping, but only for about 1msec * resolution which is pretty much useless for our needs. Keeping it here * for future reference */ -static inline void -select_sleep(sendpacket_t *sp _U_, const struct timespec *nap, - struct timeval *now, bool flush _U_) +static inline void +select_sleep(sendpacket_t *sp _U_, const struct timespec *nap, struct timeval *now, bool flush _U_) { struct timeval timeout; #ifdef HAVE_NETMAP if (flush) - ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ -#endif /* HAVE_NETMAP */ + ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ +#endif /* HAVE_NETMAP */ TIMESPEC_TO_TIMEVAL(&timeout, nap); @@ -131,7 +125,7 @@ select_sleep(sendpacket_t *sp _U_, const struct timespec *nap, #ifdef HAVE_NETMAP if (flush) - ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ + ioctl(sp->handle.fd, NIOCTXSYNC, NULL); /* flush TX buffer */ #endif gettimeofday(now, NULL); @@ -141,7 +135,7 @@ select_sleep(sendpacket_t *sp _U_, const struct timespec *nap, /* * ioport_sleep() only works on Intel 32-bit and quite possibly only Linux. * But the basic idea is to write to the IO Port 0x80 which should - * take exactly 1usec regardless of the CPU speed and without + * take exactly 1usec regardless of the CPU speed and without * calling a sleep method which allows the kernel to service another thread * Idea stolen from: http://c-faq.com/osdep/sd25.html */ @@ -149,7 +143,4 @@ select_sleep(sendpacket_t *sp _U_, const struct timespec *nap, /* before calling port_sleep(), you have to call port_sleep_init() */ void ioport_sleep_init(void); -void ioport_sleep(sendpacket_t *sp _U_, const struct timespec *nap, - struct timeval *now, bool flush); - -#endif /* __SLEEP_H__ */ +void ioport_sleep(sendpacket_t *sp _U_, const struct timespec *nap, struct timeval *now, bool flush); diff --git a/src/tcpbridge.c b/src/tcpbridge.c index b1e4f5683..be7dc19db 100644 --- a/src/tcpbridge.c +++ b/src/tcpbridge.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -20,35 +20,29 @@ /* * Purpose: Modify packets in a pcap file based on rules provided by the - * user to offload work from tcpreplay and provide a easier means of + * user to offload work from tcpreplay and provide a easier means of * reproducing traffic for testing purposes. */ - -#include "config.h" +#include "tcpbridge.h" #include "defines.h" +#include "config.h" #include "common.h" - -#include +#include "bridge.h" +#include "tcpbridge_opts.h" +#include "tcpedit/tcpedit.h" +#include #include #include #include #include #include #include -#include - -#include "tcpbridge.h" -#include "tcpbridge_opts.h" -#include "bridge.h" -#include "tcpedit/tcpedit.h" #ifdef DEBUG int debug; #endif - -COUNTER cache_packets; tcpreplay_stats_t stats; tcpbridge_opt_t options; tcpedit_t *tcpedit; @@ -57,7 +51,7 @@ tcpedit_t *tcpedit; void init(void); void post_args(int argc, char *argv[]); -int +int main(int argc, char *argv[]) { int optct, rcode; @@ -87,13 +81,12 @@ main(int argc, char *argv[]) if (tcpedit_validate(tcpedit) < 0) { tcpedit_close(&tcpedit); - errx(-1, "Unable to edit packets given options:\n%s", - tcpedit_geterr(tcpedit)); + errx(-1, "Unable to edit packets given options:\n%s", tcpedit_geterr(tcpedit)); } #ifdef ENABLE_VERBOSE if (options.verbose) { - options.tcpdump = (tcpdump_t*)safe_malloc(sizeof(tcpdump_t)); + options.tcpdump = (tcpdump_t *)safe_malloc(sizeof(tcpdump_t)); tcpdump_open(options.tcpdump, options.pcap1); } #endif @@ -122,10 +115,9 @@ main(int argc, char *argv[]) return 0; } -void +void init(void) { - memset(&stats, 0, sizeof(stats)); memset(&options, 0, sizeof(options)); @@ -135,11 +127,9 @@ init(void) if (fcntl(STDERR_FILENO, F_SETFL, O_NONBLOCK) < 0) warnx("Unable to set STDERR to non-blocking: %s", strerror(errno)); - } - -void +void post_args(_U_ int argc, _U_ char *argv[]) { char ebuf[SENDPACKET_ERRBUF_SIZE]; @@ -160,7 +150,6 @@ post_args(_U_ int argc, _U_ char *argv[]) warn("not configured with --enable-debug. Debugging disabled."); #endif - #ifdef ENABLE_VERBOSE if (HAVE_OPT(VERBOSE)) options.verbose = 1; @@ -175,11 +164,11 @@ post_args(_U_ int argc, _U_ char *argv[]) if (HAVE_OPT(LIMIT)) options.limit_send = OPT_VALUE_LIMIT; /* default is -1 */ - if ((intname = get_interface(intlist, OPT_ARG(INTF1))) == NULL) { if (!strncmp(OPT_ARG(INTF1), "netmap:", 7) || !strncmp(OPT_ARG(INTF1), "vale", 4)) - errx(-1, "Unable to connect to netmap interface %s. Ensure netmap module is installed (see INSTALL).", - OPT_ARG(INTF1)); + errx(-1, + "Unable to connect to netmap interface %s. Ensure netmap module is installed (see INSTALL).", + OPT_ARG(INTF1)); else errx(-1, "Invalid interface name/alias: %s", OPT_ARG(INTF1)); } @@ -195,7 +184,7 @@ post_args(_U_ int argc, _U_ char *argv[]) if (HAVE_OPT(MAC)) { int ct = STACKCT_OPT(MAC); - char **list = (char**)STACKLST_OPT(MAC); + char **list = (char **)STACKLST_OPT(MAC); int first = 1; do { char *p = *list++; @@ -207,9 +196,9 @@ post_args(_U_ int argc, _U_ char *argv[]) } while (--ct > 0); } - /* + /* * Figure out MAC addresses of sending interface(s) - * if user doesn't specify MAC address on CLI, query for it + * if user doesn't specify MAC address on CLI, query for it */ if (memcmp(options.intf1_mac, "\00\00\00\00\00\00", ETHER_ADDR_LEN) == 0) { if ((sp = sendpacket_open(options.intf1, ebuf, TCPR_DIR_C2S, SP_TYPE_NONE, NULL)) == NULL) @@ -237,21 +226,17 @@ post_args(_U_ int argc, _U_ char *argv[]) sendpacket_close(sp); } - /* - * Open interfaces for sending & receiving + /* + * Open interfaces for sending & receiving */ - if ((options.pcap1 = pcap_open_live(options.intf1, options.snaplen, - options.promisc, options.to_ms, ebuf)) == NULL) + if ((options.pcap1 = pcap_open_live(options.intf1, options.snaplen, options.promisc, options.to_ms, ebuf)) == NULL) errx(-1, "Unable to open interface %s: %s", options.intf1, ebuf); - if (strcmp(options.intf1, options.intf2) == 0) errx(-1, "Whoa tiger! You don't want to use %s twice!", options.intf1); - /* we always have to open the other pcap handle to send, but we may not listen */ - if ((options.pcap2 = pcap_open_live(options.intf2, options.snaplen, - options.promisc, options.to_ms, ebuf)) == NULL) + if ((options.pcap2 = pcap_open_live(options.intf2, options.snaplen, options.promisc, options.to_ms, ebuf)) == NULL) errx(-1, "Unable to open interface %s: %s", options.intf2, ebuf); /* poll should be -1 to wait indefinitely */ diff --git a/src/tcpbridge.h b/src/tcpbridge.h index b2567416b..717bf2185 100644 --- a/src/tcpbridge.h +++ b/src/tcpbridge.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,27 +18,24 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TCPBRIDGE_H__ -#define __TCPBRIDGE_H__ +#pragma once /* we don't support endpoints w/ tcpbridge */ #define TCPEDIT_ENDPOINTS_DISABLE 1 -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" #include "tcpedit/tcpedit.h" - -#include -#include #include #include +#include +#include #ifdef ENABLE_DMALLOC #include #endif - /* run-time options */ typedef struct { char *intf1; @@ -80,7 +77,3 @@ typedef struct { u_int16_t l2proto; u_int16_t l2_mem_align; /* keep things 4 byte aligned */ } tcpbridge_opt_t; - - -#endif - diff --git a/src/tcpcapinfo.c b/src/tcpcapinfo.c index e92395688..4182a68ca 100644 --- a/src/tcpcapinfo.c +++ b/src/tcpcapinfo.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2012 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,25 +18,19 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include "tcpcapinfo_opts.h" +#include #include -#include -#include -#include +#include #include -#include #include #include -#include -#include - -#define __STDC_FORMAT_MACROS 1 -#include - -#include "tcpcapinfo_opts.h" +#include +#include +#include static int do_checksum_math(u_int16_t *data, int len); @@ -52,26 +46,24 @@ char is_not_swapped[] = "little-endian"; char is_swapped[] = "big-endian"; #endif -int read_packet(int fd, uint32_t len, char *fname); - /* * Standard libpcap format. */ -#define TCPDUMP_MAGIC 0xa1b2c3d4 +#define TCPDUMP_MAGIC 0xa1b2c3d4 /* * Alexey Kuznetzov's modified libpcap format. */ #define KUZNETZOV_TCPDUMP_MAGIC 0xa1b2cd34 struct pcap_timeval { - bpf_int32 tv_sec; /* seconds */ - bpf_int32 tv_usec; /* microseconds */ + bpf_int32 tv_sec; /* seconds */ + bpf_int32 tv_usec; /* microseconds */ }; struct pcap_sf_patched_pkthdr { - struct pcap_timeval ts; /* time stamp */ - bpf_u_int32 caplen; /* length of portion present */ - bpf_u_int32 len; /* length this packet (off wire) */ - int index; + struct pcap_timeval ts; /* time stamp */ + bpf_u_int32 caplen; /* length of portion present */ + bpf_u_int32 len; /* length this packet (off wire) */ + int index; unsigned short protocol; unsigned char pkt_type; }; @@ -86,19 +78,18 @@ struct pcap_sf_patched_pkthdr { * Navtel Communcations' format, with nanosecond timestamps, * as per a request from Dumas Hwang . */ -#define NAVTEL_TCPDUMP_MAGIC 0xa12b3c4d +#define NAVTEL_TCPDUMP_MAGIC 0xa12b3c4d /* * Normal libpcap format, except for seconds/nanoseconds timestamps, * as per a request by Ulf Lamping */ -#define NSEC_TCPDUMP_MAGIC 0xa1b23c4d - +#define NSEC_TCPDUMP_MAGIC 0xa1b23c4d int main(int argc, char *argv[]) { - int i, fd, swapped, pkthdrlen, ret, optct, backwards, caplentoobig; + int i, fd, swapped, pkthdrlen, optct, backwards, caplentoobig; struct pcap_file_header pcap_fh; struct pcap_pkthdr pcap_ph; struct pcap_sf_patched_pkthdr pcap_patched_ph; /* Kuznetzov */ @@ -107,6 +98,7 @@ main(int argc, char *argv[]) uint64_t pktcnt; uint32_t readword; int32_t last_sec, last_usec, caplen, maxread; + ssize_t ret; optct = optionProcess(&tcpcapinfoOptions, argc, argv); argc -= optct; @@ -125,12 +117,12 @@ main(int argc, char *argv[]) if (fstat(fd, &statinfo) < 0) errx(-1, "Error getting file stat info %s: %s", argv[i], strerror(errno)); - printf("file size = %"PRIu64" bytes\n", (uint64_t)statinfo.st_size); + printf("file size = %" PRIu64 " bytes\n", (uint64_t)statinfo.st_size); - if ((ret = read(fd, &buf, sizeof(pcap_fh))) != sizeof(pcap_fh)) + if ((ret = read(fd, &buf, sizeof(pcap_fh))) != (int)sizeof(pcap_fh)) errx(-1, "File too small. Unable to read pcap_file_header from %s", argv[i]); - dbgx(3, "Read %d bytes for file header", ret); + dbgx(3, "Read %ld bytes for file header", ret); swapped = 0; @@ -139,55 +131,55 @@ main(int argc, char *argv[]) pkthdrlen = 16; /* pcap_pkthdr isn't the actual on-disk format for 64bit systems! */ switch (pcap_fh.magic) { - case TCPDUMP_MAGIC: - printf("magic = 0x%08"PRIx32" (tcpdump) (%s)\n", pcap_fh.magic, is_not_swapped); + case TCPDUMP_MAGIC: + printf("magic = 0x%08" PRIx32 " (tcpdump) (%s)\n", pcap_fh.magic, is_not_swapped); break; - case SWAPLONG(TCPDUMP_MAGIC): - printf("magic = 0x%08"PRIx32" (tcpdump/swapped) (%s)\n", pcap_fh.magic, is_swapped); + case SWAPLONG(TCPDUMP_MAGIC): + printf("magic = 0x%08" PRIx32 " (tcpdump/swapped) (%s)\n", pcap_fh.magic, is_swapped); swapped = 1; break; - case KUZNETZOV_TCPDUMP_MAGIC: + case KUZNETZOV_TCPDUMP_MAGIC: pkthdrlen = sizeof(pcap_patched_ph); - printf("magic = 0x%08"PRIx32" (Kuznetzov) (%s)\n", pcap_fh.magic, is_not_swapped); + printf("magic = 0x%08" PRIx32 " (Kuznetzov) (%s)\n", pcap_fh.magic, is_not_swapped); break; - case SWAPLONG(KUZNETZOV_TCPDUMP_MAGIC): + case SWAPLONG(KUZNETZOV_TCPDUMP_MAGIC): pkthdrlen = sizeof(pcap_patched_ph); - printf("magic = 0x%08"PRIx32" (Kuznetzov/swapped) (%s)\n", pcap_fh.magic, is_swapped); + printf("magic = 0x%08" PRIx32 " (Kuznetzov/swapped) (%s)\n", pcap_fh.magic, is_swapped); swapped = 1; break; - case FMESQUITA_TCPDUMP_MAGIC: - printf("magic = 0x%08"PRIx32" (Fmesquita) (%s)\n", pcap_fh.magic, is_not_swapped); + case FMESQUITA_TCPDUMP_MAGIC: + printf("magic = 0x%08" PRIx32 " (Fmesquita) (%s)\n", pcap_fh.magic, is_not_swapped); break; - case SWAPLONG(FMESQUITA_TCPDUMP_MAGIC): - printf("magic = 0x%08"PRIx32" (Fmesquita) (%s)\n", pcap_fh.magic, is_swapped); + case SWAPLONG(FMESQUITA_TCPDUMP_MAGIC): + printf("magic = 0x%08" PRIx32 " (Fmesquita) (%s)\n", pcap_fh.magic, is_swapped); swapped = 1; break; - case NAVTEL_TCPDUMP_MAGIC: - printf("magic = 0x%08"PRIx32" (Navtel) (%s)\n", pcap_fh.magic, is_not_swapped); + case NAVTEL_TCPDUMP_MAGIC: + printf("magic = 0x%08" PRIx32 " (Navtel) (%s)\n", pcap_fh.magic, is_not_swapped); break; - case SWAPLONG(NAVTEL_TCPDUMP_MAGIC): - printf("magic = 0x%08"PRIx32" (Navtel/swapped) (%s)\n", pcap_fh.magic, is_swapped); + case SWAPLONG(NAVTEL_TCPDUMP_MAGIC): + printf("magic = 0x%08" PRIx32 " (Navtel/swapped) (%s)\n", pcap_fh.magic, is_swapped); swapped = 1; break; - case NSEC_TCPDUMP_MAGIC: - printf("magic = 0x%08"PRIx32" (Nsec) (%s)\n", pcap_fh.magic, is_not_swapped); + case NSEC_TCPDUMP_MAGIC: + printf("magic = 0x%08" PRIx32 " (Nsec) (%s)\n", pcap_fh.magic, is_not_swapped); break; - case SWAPLONG(NSEC_TCPDUMP_MAGIC): - printf("magic = 0x%08"PRIx32" (Nsec/swapped) (%s)\n", pcap_fh.magic, is_swapped); + case SWAPLONG(NSEC_TCPDUMP_MAGIC): + printf("magic = 0x%08" PRIx32 " (Nsec/swapped) (%s)\n", pcap_fh.magic, is_swapped); swapped = 1; break; - default: - printf("magic = 0x%08"PRIx32" (unknown)\n", pcap_fh.magic); + default: + printf("magic = 0x%08" PRIx32 " (unknown)\n", pcap_fh.magic); } if (swapped == 1) { @@ -200,10 +192,10 @@ main(int argc, char *argv[]) } printf("version = %hu.%hu\n", pcap_fh.version_major, pcap_fh.version_minor); - printf("thiszone = 0x%08"PRIx32"\n", pcap_fh.thiszone); - printf("sigfigs = 0x%08"PRIx32"\n", pcap_fh.sigfigs); - printf("snaplen = %"PRIu32"\n", pcap_fh.snaplen); - printf("linktype = 0x%08"PRIx32"\n", pcap_fh.linktype); + printf("thiszone = 0x%08" PRIx32 "\n", pcap_fh.thiszone); + printf("sigfigs = 0x%08" PRIx32 "\n", pcap_fh.sigfigs); + printf("snaplen = %" PRIu32 "\n", pcap_fh.snaplen); + printf("linktype = 0x%08" PRIx32 "\n", pcap_fh.linktype); if (pcap_fh.version_major != 2 && pcap_fh.version_minor != 4) { printf("Sorry, we only support file format version 2.4\n"); @@ -222,11 +214,11 @@ main(int argc, char *argv[]) pktcnt = 0; last_sec = 0; last_usec = 0; - while ((ret = read(fd, &buf, pkthdrlen)) == pkthdrlen) { - pktcnt ++; + while ((ret = read(fd, &buf, (size_t)pkthdrlen)) == pkthdrlen) { + pktcnt++; backwards = 0; caplentoobig = 0; - dbgx(3, "Read %d bytes for packet %"PRIu64" header", ret, pktcnt); + dbgx(3, "Read %ld bytes for packet %" PRIu64 " header", ret, pktcnt); memset(&pcap_ph, 0, sizeof(pcap_ph)); @@ -243,17 +235,22 @@ main(int argc, char *argv[]) pcap_patched_ph.index = SWAPLONG(pcap_patched_ph.index); pcap_patched_ph.protocol = SWAPSHORT(pcap_patched_ph.protocol); } - printf("%"PRIu64"\t%4"PRIu32"\t\t%4"PRIu32"\t\t%" - PRIx32".%"PRIx32"\t\t%4"PRIu32"\t%4hu\t%4hhu", - pktcnt, pcap_patched_ph.len, pcap_patched_ph.caplen, - pcap_patched_ph.ts.tv_sec, pcap_patched_ph.ts.tv_usec, - pcap_patched_ph.index, pcap_patched_ph.protocol, pcap_patched_ph.pkt_type); + printf("%" PRIu64 "\t%4" PRIu32 "\t\t%4" PRIu32 "\t\t%" PRIx32 ".%" PRIx32 "\t\t%4" PRIu32 + "\t%4hu\t%4hhu", + pktcnt, + pcap_patched_ph.len, + pcap_patched_ph.caplen, + pcap_patched_ph.ts.tv_sec, + pcap_patched_ph.ts.tv_usec, + pcap_patched_ph.index, + pcap_patched_ph.protocol, + pcap_patched_ph.pkt_type); if (pcap_fh.snaplen < pcap_patched_ph.caplen) { caplentoobig = 1; } - caplen = pcap_patched_ph.caplen; + caplen = (int32_t)pcap_patched_ph.caplen; } else { /* manually map on-disk bytes to our memory structure */ @@ -271,30 +268,22 @@ main(int argc, char *argv[]) pcap_ph.ts.tv_sec = SWAPLONG(pcap_ph.ts.tv_sec); pcap_ph.ts.tv_usec = SWAPLONG(pcap_ph.ts.tv_usec); } - printf("%"PRIu64"\t%4"PRIu32"\t\t%4"PRIu32"\t\t%" - PRIx32".%"PRIx32, - pktcnt, pcap_ph.len, pcap_ph.caplen, - (unsigned int)pcap_ph.ts.tv_sec, (unsigned int)pcap_ph.ts.tv_usec); + printf("%" PRIu64 "\t%4" PRIu32 "\t\t%4" PRIu32 "\t\t%" PRIx32 ".%" PRIx32, + pktcnt, + pcap_ph.len, + pcap_ph.caplen, + (unsigned int)pcap_ph.ts.tv_sec, + (unsigned int)pcap_ph.ts.tv_usec); if (pcap_fh.snaplen < pcap_ph.caplen || pcap_ph.caplen > MAX_SNAPLEN) { caplentoobig = 1; } - caplen = pcap_ph.caplen; - } - - if (caplentoobig) { - printf("\n\nCapture file appears to be damaged or corrupt.\n" - "Contains packet of size %d, bigger than snap length %u\n", - caplen, pcap_fh.snaplen); - - close(fd); - break; + caplen = (int32_t)pcap_ph.caplen; } /* check to make sure timestamps don't go backwards */ if (last_sec > 0 && last_usec > 0) { - if ((pcap_ph.ts.tv_sec == last_sec) ? - (pcap_ph.ts.tv_usec < last_usec) : - (pcap_ph.ts.tv_sec < last_sec)) { + if ((pcap_ph.ts.tv_sec == last_sec) ? (pcap_ph.ts.tv_usec < last_usec) + : (pcap_ph.ts.tv_sec < last_sec)) { backwards = 1; } } @@ -302,8 +291,8 @@ main(int argc, char *argv[]) last_sec = pcap_patched_ph.ts.tv_sec; last_usec = pcap_patched_ph.ts.tv_usec; } else { - last_sec = pcap_ph.ts.tv_sec; - last_usec = pcap_ph.ts.tv_usec; + last_sec = (int32_t)pcap_ph.ts.tv_sec; + last_usec = (int32_t)pcap_ph.ts.tv_usec; } /* read the frame */ @@ -323,15 +312,24 @@ main(int argc, char *argv[]) printf("\t%x\t", do_checksum_math((u_int16_t *)buf, maxread)); /* print the Note */ - if (! backwards && ! caplentoobig) { + if (!backwards && !caplentoobig) printf("OK\n"); - } else if (backwards && ! caplentoobig) { + else if (backwards && !caplentoobig) printf("BAD_TS\n"); - } else if (caplentoobig && ! backwards) { + else if (caplentoobig && !backwards) printf("TOOBIG\n"); - } else if (backwards && caplentoobig) { + else if (backwards && caplentoobig) printf("BAD_TS|TOOBIG"); - } + + if (caplentoobig) { + printf("\n\nCapture file appears to be damaged or corrupt.\n" + "Contains packet of size %d, bigger than snap length %u\n", + caplen, + pcap_fh.snaplen); + + close(fd); + break; + } } } @@ -364,4 +362,3 @@ do_checksum_math(u_int16_t *data, int len) return (sum); } - diff --git a/src/tcpedit/checksum.c b/src/tcpedit/checksum.c index cec60504a..07abe5da4 100644 --- a/src/tcpedit/checksum.c +++ b/src/tcpedit/checksum.c @@ -23,18 +23,17 @@ * checksumming code from Libnet 1.1.3 */ -#include "config.h" -#include "tcpedit.h" #include "checksum.h" +#include "config.h" static int do_checksum_math(uint16_t *, int); - /** * Returns -1 on error and 0 on success, 1 on warn */ int -do_checksum(tcpedit_t *tcpedit, uint8_t *data, int proto, int len) { +do_checksum(tcpedit_t *tcpedit, uint8_t *data, int proto, int len, const u_char *end_ptr) +{ ipv4_hdr_t *ipv4; ipv6_hdr_t *ipv6; tcp_hdr_t *tcp; @@ -60,16 +59,16 @@ do_checksum(tcpedit_t *tcpedit, uint8_t *data, int proto, int len) { ipv6 = (ipv6_hdr_t *)data; ipv4 = NULL; - proto = get_ipv6_l4proto(ipv6, len + sizeof(ipv6_hdr_t)); + proto = get_ipv6_l4proto(ipv6, end_ptr); dbgx(3, "layer4 proto is 0x%hx", (uint16_t)proto); - layer = (u_char*)get_layer4_v6(ipv6, len + sizeof(ipv6_hdr_t)); + layer = (u_char *)get_layer4_v6(ipv6, end_ptr); if (!layer) { tcpedit_setwarn(tcpedit, "%s", "Packet to short for checksum"); return TCPEDIT_WARN; } - ip_hl = layer - (u_char*)data; + ip_hl = (int)(layer - (u_char *)data); dbgx(3, "ip_hl proto is 0x%d", ip_hl); len -= (ip_hl - TCPR_IPV6_H); @@ -78,91 +77,91 @@ do_checksum(tcpedit_t *tcpedit, uint8_t *data, int proto, int len) { } switch (proto) { - case IPPROTO_TCP: - if (len < (int)sizeof(tcp_hdr_t)) { - tcpedit_setwarn(tcpedit, "%s", "Unable to checksum TCP with insufficient L4 data"); - return TCPEDIT_WARN; - } + case IPPROTO_TCP: + if (len < (int)sizeof(tcp_hdr_t)) { + tcpedit_setwarn(tcpedit, "%s", "Unable to checksum TCP with insufficient L4 data"); + return TCPEDIT_WARN; + } - tcp = (tcp_hdr_t *)(data + ip_hl); + tcp = (tcp_hdr_t *)(data + ip_hl); #ifdef STUPID_SOLARIS_CHECKSUM_BUG - tcp->th_sum = tcp->th_off << 2; - return (TCPEDIT_OK); + tcp->th_sum = tcp->th_off << 2; + return (TCPEDIT_OK); #endif - tcp->th_sum = 0; - - /* Note, we do both src & dst IP's at the same time, that's why the - * length is 2x a single IP - */ - if (ipv6 != NULL) { - sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); - } else { - sum = do_checksum_math((uint16_t *)&ipv4->ip_src, 8); - } - sum += ntohs(IPPROTO_TCP + len); - sum += do_checksum_math((uint16_t *)tcp, len); - tcp->th_sum = CHECKSUM_CARRY(sum); - break; - - case IPPROTO_UDP: - if (len < (int)sizeof(udp_hdr_t)) { - tcpedit_setwarn(tcpedit, "%s", "Unable to checksum UDP with insufficient L4 data"); - return TCPEDIT_WARN; - } - udp = (udp_hdr_t *)(data + ip_hl); - /* No need to recalculate UDP checksums if already 0 */ - if (udp->uh_sum == 0) - break; - udp->uh_sum = 0; - if (ipv6 != NULL) { - sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); - } else { - sum = do_checksum_math((uint16_t *)&ipv4->ip_src, 8); - } - sum += ntohs(IPPROTO_UDP + len); - sum += do_checksum_math((uint16_t *)udp, len); - udp->uh_sum = CHECKSUM_CARRY(sum); + tcp->th_sum = 0; + + /* Note, we do both src & dst IP's at the same time, that's why the + * length is 2x a single IP + */ + if (ipv6 != NULL) { + sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); + } else { + sum = do_checksum_math((uint16_t *)&ipv4->ip_src, 8); + } + sum += ntohs(IPPROTO_TCP + len); + sum += do_checksum_math((uint16_t *)tcp, len); + tcp->th_sum = CHECKSUM_CARRY(sum); + break; + + case IPPROTO_UDP: + if (len < (int)sizeof(udp_hdr_t)) { + tcpedit_setwarn(tcpedit, "%s", "Unable to checksum UDP with insufficient L4 data"); + return TCPEDIT_WARN; + } + udp = (udp_hdr_t *)(data + ip_hl); + /* No need to recalculate UDP checksums if already 0 */ + if (udp->uh_sum == 0) break; - - case IPPROTO_ICMP: - if (len < (int)sizeof(icmpv4_hdr_t)) { - tcpedit_setwarn(tcpedit, "%s", "Unable to checksum ICMP with insufficient L4 data"); - return TCPEDIT_WARN; - } - icmp = (icmpv4_hdr_t *)(data + ip_hl); - icmp->icmp_sum = 0; - if (ipv6 != NULL) { - sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); - icmp->icmp_sum = CHECKSUM_CARRY(sum); - } - sum += do_checksum_math((uint16_t *)icmp, len); + udp->uh_sum = 0; + if (ipv6 != NULL) { + sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); + } else { + sum = do_checksum_math((uint16_t *)&ipv4->ip_src, 8); + } + sum += ntohs(IPPROTO_UDP + len); + sum += do_checksum_math((uint16_t *)udp, len); + udp->uh_sum = CHECKSUM_CARRY(sum); + break; + + case IPPROTO_ICMP: + if (len < (int)sizeof(icmpv4_hdr_t)) { + tcpedit_setwarn(tcpedit, "%s", "Unable to checksum ICMP with insufficient L4 data"); + return TCPEDIT_WARN; + } + icmp = (icmpv4_hdr_t *)(data + ip_hl); + icmp->icmp_sum = 0; + if (ipv6 != NULL) { + sum = do_checksum_math((uint16_t *)&ipv6->ip_src, 32); icmp->icmp_sum = CHECKSUM_CARRY(sum); - break; - - case IPPROTO_ICMP6: - if (len < (int)sizeof(icmpv6_hdr_t)) { - tcpedit_setwarn(tcpedit, "%s", "Unable to checksum ICMP6 with insufficient L4 data"); - return TCPEDIT_WARN; - } - icmp6 = (icmpv6_hdr_t *)(data + ip_hl); - icmp6->icmp_sum = 0; - if (ipv6 != NULL) { - sum = do_checksum_math((u_int16_t *)&ipv6->ip_src, 32); - } - sum += ntohs(IPPROTO_ICMP6 + len); - sum += do_checksum_math((u_int16_t *)icmp6, len); - icmp6->icmp_sum = CHECKSUM_CARRY(sum); - break; + } + sum += do_checksum_math((uint16_t *)icmp, len); + icmp->icmp_sum = CHECKSUM_CARRY(sum); + break; - default: - if (ipv4) { - ipv4->ip_sum = 0; - sum = do_checksum_math((uint16_t *)data, ip_hl); - ipv4->ip_sum = CHECKSUM_CARRY(sum); - } else { - tcpedit_setwarn(tcpedit, "Unsupported protocol for checksum: 0x%x", proto); - return TCPEDIT_WARN; - } + case IPPROTO_ICMP6: + if (len < (int)sizeof(icmpv6_hdr_t)) { + tcpedit_setwarn(tcpedit, "%s", "Unable to checksum ICMP6 with insufficient L4 data"); + return TCPEDIT_WARN; + } + icmp6 = (icmpv6_hdr_t *)(data + ip_hl); + icmp6->icmp_sum = 0; + if (ipv6 != NULL) { + sum = do_checksum_math((u_int16_t *)&ipv6->ip_src, 32); + } + sum += ntohs(IPPROTO_ICMP6 + len); + sum += do_checksum_math((u_int16_t *)icmp6, len); + icmp6->icmp_sum = CHECKSUM_CARRY(sum); + break; + + default: + if (ipv4) { + ipv4->ip_sum = 0; + sum = do_checksum_math((uint16_t *)data, ip_hl); + ipv4->ip_sum = CHECKSUM_CARRY(sum); + } else { + tcpedit_setwarn(tcpedit, "Unsupported protocol for checksum: 0x%x", proto); + return TCPEDIT_WARN; + } } return TCPEDIT_OK; @@ -193,4 +192,3 @@ do_checksum_math(uint16_t *data, int len) return (sum); } - diff --git a/src/tcpedit/checksum.h b/src/tcpedit/checksum.h index 09fbe81ea..aa5d13810 100644 --- a/src/tcpedit/checksum.h +++ b/src/tcpedit/checksum.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _CHECKSUM_H_ -#define _CHECKSUM_H_ +#pragma once -#define CHECKSUM_CARRY(x) \ - (x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff)) +#include "tcpedit.h" -int do_checksum(tcpedit_t *, u_int8_t *, int, int); +#define CHECKSUM_CARRY(x) (x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff)) -#endif +int do_checksum(tcpedit_t *, u_int8_t *, int, int, const u_char *); diff --git a/src/tcpedit/dlt.c b/src/tcpedit/dlt.c index 4a377955c..56d64b1f3 100644 --- a/src/tcpedit/dlt.c +++ b/src/tcpedit/dlt.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,11 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#include +#include "dlt.h" #include "config.h" -#include "defines.h" #include "tcpedit.h" -#include "dlt.h" +#include /** * takes in a libpcap DLT_ type and returns the length of the layer2 header @@ -33,44 +32,44 @@ dlt2layer2len(tcpedit_t *tcpedit, int dlt) { assert(tcpedit); int len; - switch(dlt) { + switch (dlt) { + /* + case DLT_USER: + len = tcpedit->l2.len; + break; + */ + case DLT_NULL: + len = 2; + break; + + case DLT_RAW: + len = 0; + break; + + case DLT_EN10MB: + len = 12; + break; /* - case DLT_USER: - len = tcpedit->l2.len; - break; - */ - case DLT_NULL: - len = 2; - break; - - case DLT_RAW: - len = 0; - break; - - case DLT_EN10MB: - len = 12; - break; - /* - case DLT_VLAN: - len = 14; - break; - */ - case DLT_LINUX_SLL: - len = 16; - break; - - case DLT_PPP_SERIAL: - case DLT_C_HDLC: - len = 4; - break; - - case DLT_JUNIPER_ETHER: - len = 36; - break; - - default: - tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); - len = -1; + case DLT_VLAN: + len = 14; + break; + */ + case DLT_LINUX_SLL: + len = 16; + break; + + case DLT_PPP_SERIAL: + case DLT_C_HDLC: + len = 4; + break; + + case DLT_JUNIPER_ETHER: + len = 36; + break; + + default: + tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); + len = -1; } return len; @@ -87,30 +86,30 @@ dltrequires(tcpedit_t *tcpedit, int dlt) assert(tcpedit); int req = TCPEDIT_DLT_OK; // no change required by default - switch(dlt) { - case DLT_JUNIPER_ETHER: - case DLT_EN10MB: -/* case DLT_USER: - case DLT_VLAN: */ - /* we have everything we need in the original packet */ - break; - - case DLT_NULL: - case DLT_RAW: - case DLT_C_HDLC: - case DLT_PPP_SERIAL: - req = TCPEDIT_DLT_SRC + TCPEDIT_DLT_DST; - /* we just have the proto */ - break; - - case DLT_LINUX_SLL: - /* we have proto & SRC address */ - req = TCPEDIT_DLT_DST; - break; - - default: - tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); - req = -1; + switch (dlt) { + case DLT_JUNIPER_ETHER: + case DLT_EN10MB: + /* case DLT_USER: + case DLT_VLAN: */ + /* we have everything we need in the original packet */ + break; + + case DLT_NULL: + case DLT_RAW: + case DLT_C_HDLC: + case DLT_PPP_SERIAL: + req = TCPEDIT_DLT_SRC + TCPEDIT_DLT_DST; + /* we just have the proto */ + break; + + case DLT_LINUX_SLL: + /* we have proto & SRC address */ + req = TCPEDIT_DLT_DST; + break; + + default: + tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); + req = -1; } return req; @@ -120,41 +119,41 @@ dltrequires(tcpedit_t *tcpedit, int dlt) * returns the default MTU size for the given DLT type. Returns -1 * for invalid DLT */ -int +int dlt2mtu(tcpedit_t *tcpedit, int dlt) { int mtu; assert(tcpedit); switch (dlt) { -/* case DLT_VLAN: - case DLT_USER: */ - case DLT_PPP_SERIAL: - case DLT_EN10MB: - case DLT_RAW: - case DLT_C_HDLC: - case DLT_JUNIPER_ETHER: - mtu = 1500; - break; - - case DLT_LINUX_SLL: - mtu = 16436; - break; - - case DLT_LOOP: - mtu = 16384; - break; - - default: - tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); - mtu = -1; - break; + /* case DLT_VLAN: + case DLT_USER: */ + case DLT_PPP_SERIAL: + case DLT_EN10MB: + case DLT_RAW: + case DLT_C_HDLC: + case DLT_JUNIPER_ETHER: + mtu = 1500; + break; + + case DLT_LINUX_SLL: + mtu = 16436; + break; + + case DLT_LOOP: + mtu = 16384; + break; + + default: + tcpedit_seterr(tcpedit, "Invalid DLT Type: %d", dlt); + mtu = -1; + break; } return mtu; } /** - * Returns the current layer 2 len based on the + * Returns the current layer 2 len based on the * DLT of the pcap or the --dlink value or -1 on error. * You need to call this function AFTER rewriting the layer 2 header * for it to be at all useful. @@ -166,8 +165,5 @@ layer2len(tcpedit_t *tcpedit, u_char *packet, uint32_t caplen) assert(tcpedit->dlt_ctx); assert(tcpedit->dlt_ctx->encoder); - return tcpedit->dlt_ctx->encoder->plugin_l2len(tcpedit->dlt_ctx, - packet, - caplen); + return tcpedit->dlt_ctx->encoder->plugin_l2len(tcpedit->dlt_ctx, packet, caplen); } - diff --git a/src/tcpedit/dlt.h b/src/tcpedit/dlt.h index 5707eb723..18bc969a4 100644 --- a/src/tcpedit/dlt.h +++ b/src/tcpedit/dlt.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_H_ -#define _DLT_H_ +#pragma once +#include "defines.h" #include "tcpedit.h" #define TCPEDIT_DLT_OK 0 @@ -28,12 +28,7 @@ #define TCPEDIT_DLT_DST 2 #define TCPEDIT_DLT_PROTO 4 - int dlt2layer2len(tcpedit_t *tcpedit, int dlt); int dltrequires(tcpedit_t *tcpedit, int dlt); int dlt2mtu(tcpedit_t *tcpedit, int dlt); int layer2len(tcpedit_t *tcpedit, u_char *packet, uint32_t caplen); - -#endif /* _DLT_H_ */ - - diff --git a/src/tcpedit/edit_packet.c b/src/tcpedit/edit_packet.c index 7de29fda5..a55ada2b4 100644 --- a/src/tcpedit/edit_packet.c +++ b/src/tcpedit/edit_packet.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,37 +18,30 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" -#include "defines.h" -#include "common.h" - -#include "tcpedit.h" #include "edit_packet.h" +#include "config.h" #include "checksum.h" -#include "incremental_checksum.h" -#include "lib/sll.h" #include "dlt.h" - -#include +#include "incremental_checksum.h" +#include "tcpedit.h" +#include #include -#include +#include #include -#include -#include +#include static uint32_t randomize_ipv4_addr(tcpedit_t *tcpedit, uint32_t ip); -static uint32_t remap_ipv4(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, const uint32_t original); +static uint32_t remap_ipv4(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, uint32_t original); static int is_unicast_ipv4(tcpedit_t *tcpedit, uint32_t ip); static void randomize_ipv6_addr(tcpedit_t *tcpedit, struct tcpr_in6_addr *addr); static int remap_ipv6(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, struct tcpr_in6_addr *addr); static int is_multicast_ipv6(tcpedit_t *tcpedit, struct tcpr_in6_addr *addr); -static int ipv6_header_length(ipv6_hdr_t const * ip6_hdr, const size_t pkt_len, - const size_t l2len); +static int ipv6_header_length(ipv6_hdr_t const *ip6_hdr, size_t pkt_len, size_t l2len); /** * this code re-calcs the IP and Layer 4 checksums - * the IMPORTANT THING is that the Layer 4 header + * the IMPORTANT THING is that the Layer 4 header * is contiguous in memory after *ip_hdr we're actually * writing to the layer 4 header via the ip_hdr ptr. * (Yes, this sucks, but that's the way libnet works, and @@ -56,52 +49,60 @@ static int ipv6_header_length(ipv6_hdr_t const * ip6_hdr, const size_t pkt_len, * Returns 0 on success, -1 on error */ int -fix_ipv4_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - ipv4_hdr_t *ip_hdr, const size_t l2len) +fix_ipv4_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, size_t l2len) { - int ret1 = 0, ret2 = 0, ip_len; + int ret1 = 0; + int ret2; + int ip_len; assert(tcpedit); assert(pkthdr); assert(ip_hdr); if (pkthdr->caplen < (sizeof(*ip_hdr) + l2len)) { - tcpedit_setwarn(tcpedit, "caplen too small to read IPv4 header: caplen=%u: pkt=" COUNTER_SPEC, - pkthdr->caplen, tcpedit->runtime.packetnum); + tcpedit_setwarn(tcpedit, + "caplen too small to read IPv4 header: caplen=%u: pkt=" COUNTER_SPEC, + pkthdr->caplen, + tcpedit->runtime.packetnum); return TCPEDIT_WARN; } if (ip_hdr->ip_v != 4) { - tcpedit_seterr(tcpedit, "Invalid packet: Expected IPv4 packet: got %u: pkt=" COUNTER_SPEC, - ip_hdr->ip_v, tcpedit->runtime.packetnum); + tcpedit_seterr(tcpedit, + "Invalid packet: Expected IPv4 packet: got %u: pkt=" COUNTER_SPEC, + ip_hdr->ip_v, + tcpedit->runtime.packetnum); return TCPEDIT_ERROR; } ip_len = (int)ntohs(ip_hdr->ip_len); /* calc the L4 checksum if we have the whole packet && not a frag or first frag */ - if (pkthdr->caplen == pkthdr->len && - (htons(ip_hdr->ip_off) & (IP_MF | IP_OFFMASK)) == 0) { + if (pkthdr->caplen == pkthdr->len && (htons(ip_hdr->ip_off) & (IP_MF | IP_OFFMASK)) == 0) { if (ip_len != (int)(pkthdr->caplen - l2len)) { tcpedit_seterr(tcpedit, "caplen minus L2 length %u does IPv4 header length %u: pkt=" COUNTER_SPEC, - pkthdr->caplen - l2len, ip_len, + pkthdr->caplen - l2len, + ip_len, tcpedit->runtime.packetnum); return TCPEDIT_ERROR; } - ret1 = do_checksum(tcpedit, (u_char*)ip_hdr, ip_hdr->ip_p, - ip_len - (ip_hdr->ip_hl << 2)); + ret1 = do_checksum(tcpedit, + (u_char *)ip_hdr, + ip_hdr->ip_p, + ip_len - (ip_hdr->ip_hl << 2), + (u_char *)ip_hdr + pkthdr->caplen - l2len); if (ret1 < 0) return TCPEDIT_ERROR; } - + /* calc IP checksum */ - ret2 = do_checksum(tcpedit, (u_char *) ip_hdr, IPPROTO_IP, ip_len); + ret2 = do_checksum(tcpedit, (u_char *)ip_hdr, IPPROTO_IP, ip_len, (u_char *)ip_hdr + pkthdr->caplen - l2len); if (ret2 < 0) return TCPEDIT_ERROR; /* what do we return? */ if (ret1 == TCPEDIT_WARN || ret2 == TCPEDIT_WARN) return TCPEDIT_WARN; - + return TCPEDIT_OK; } @@ -110,10 +111,9 @@ fix_ipv4_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, * -1 on error */ static int -ipv6_header_length(ipv6_hdr_t const * ip6_hdr, const size_t pkt_len, - const size_t l2len) +ipv6_header_length(ipv6_hdr_t const *ip6_hdr, size_t pkt_len, size_t l2len) { - struct tcpr_ipv6_ext_hdr_base const * nhdr; + struct tcpr_ipv6_ext_hdr_base const *nhdr; uint8_t next_header; int offset; @@ -121,13 +121,12 @@ ipv6_header_length(ipv6_hdr_t const * ip6_hdr, const size_t pkt_len, next_header = ip6_hdr->ip_nh; while (sizeof(*nhdr) + offset + l2len < (size_t)pkt_len) { - if (next_header != TCPR_IPV6_NH_HBH - && next_header != TCPR_IPV6_NH_ROUTING - && next_header != TCPR_IPV6_NH_FRAGMENT) { + if (next_header != TCPR_IPV6_NH_HBH && next_header != TCPR_IPV6_NH_ROUTING && + next_header != TCPR_IPV6_NH_FRAGMENT) { return offset; } - nhdr = (struct tcpr_ipv6_ext_hdr_base const *) (((uint8_t const *)ip6_hdr) + offset); + nhdr = (struct tcpr_ipv6_ext_hdr_base const *)(((uint8_t const *)ip6_hdr) + offset); next_header = nhdr->ip_nh; offset += ((nhdr->ip_len + 1) << 3); } @@ -136,8 +135,7 @@ ipv6_header_length(ipv6_hdr_t const * ip6_hdr, const size_t pkt_len, } int -fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - ipv6_hdr_t *ip6_hdr, const size_t l2len) +fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, size_t l2len) { int ret = 0; assert(tcpedit); @@ -145,12 +143,14 @@ fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, assert(ip6_hdr); if (pkthdr->caplen < (sizeof(*ip6_hdr) + l2len)) { - tcpedit_setwarn(tcpedit, "caplen too small to read IPv6 header: caplen=%u pkt=" COUNTER_SPEC, - pkthdr->caplen, tcpedit->runtime.packetnum); + tcpedit_setwarn(tcpedit, + "caplen too small to read IPv6 header: caplen=%u pkt=" COUNTER_SPEC, + pkthdr->caplen, + tcpedit->runtime.packetnum); return TCPEDIT_WARN; } - ipv4_hdr_t *ip_hdr = (ipv4_hdr_t*)ip6_hdr; + ipv4_hdr_t *ip_hdr = (ipv4_hdr_t *)ip6_hdr; if (ip_hdr->ip_v != 6) { tcpedit_seterr(tcpedit, "Invalid packet: Expected IPv6 packet: got %u", ip_hdr->ip_v); return TCPEDIT_ERROR; @@ -160,12 +160,18 @@ fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, if (pkthdr->caplen == pkthdr->len) { int ip6_len = ipv6_header_length(ip6_hdr, pkthdr->len, l2len); if (ip6_hdr->ip_len < ip6_len) { - tcpedit_setwarn(tcpedit, "Unable to checksum IPv6 packet with invalid: pkt=" COUNTER_SPEC " IP length=%u caplen=" COUNTER_SPEC, - tcpedit->runtime.packetnum, ip6_hdr->ip_len); + tcpedit_setwarn(tcpedit, + "Unable to checksum IPv6 packet with invalid: pkt=" COUNTER_SPEC " IP length=%u caplen=%u", + tcpedit->runtime.packetnum, + ip6_hdr->ip_len, + pkthdr->caplen); return TCPEDIT_WARN; } - ret = do_checksum(tcpedit, (u_char *)ip6_hdr, ip6_hdr->ip_nh, - htons(ip6_hdr->ip_len)); + ret = do_checksum(tcpedit, + (u_char *)ip6_hdr, + ip6_hdr->ip_nh, + htons(ip6_hdr->ip_len), + (u_char *)ip6_hdr + pkthdr->caplen - l2len); if (ret < 0) return TCPEDIT_ERROR; } @@ -177,9 +183,8 @@ fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, return TCPEDIT_OK; } - -static void ipv4_l34_csum_replace(uint8_t *data, uint8_t protocol, - uint32_t old, uint32_t new) +static void +ipv4_l34_csum_replace(uint8_t *data, uint8_t protocol, uint32_t old, uint32_t new) { ipv4_hdr_t *ipv4; tcp_hdr_t *tcp_hdr; @@ -207,11 +212,10 @@ static void ipv4_l34_csum_replace(uint8_t *data, uint8_t protocol, default: assert(false); } - } -static void ipv6_l34_csum_replace(uint8_t *data, uint8_t protocol, - uint32_t *old, uint32_t *new) +static void +ipv6_l34_csum_replace(uint8_t *data, uint8_t protocol, uint32_t *old, uint32_t *new) { tcp_hdr_t *tcp_hdr; udp_hdr_t *udp_hdr; @@ -221,7 +225,6 @@ static void ipv6_l34_csum_replace(uint8_t *data, uint8_t protocol, assert(data); switch (protocol) { - case IPPROTO_TCP: tcp_hdr = (tcp_hdr_t *)data; csum_replace16(&tcp_hdr->th_sum, old, new); @@ -246,11 +249,10 @@ static void ipv6_l34_csum_replace(uint8_t *data, uint8_t protocol, default: assert(false); } - } -static void ipv4_addr_csum_replace(ipv4_hdr_t *ip_hdr, uint32_t old_ip, - uint32_t new_ip, const int l3len) +static void +ipv4_addr_csum_replace(ipv4_hdr_t *ip_hdr, uint32_t old_ip, uint32_t new_ip, int l3len) { uint8_t *l4, protocol; int len = l3len; @@ -260,18 +262,18 @@ static void ipv4_addr_csum_replace(ipv4_hdr_t *ip_hdr, uint32_t old_ip, if ((size_t)len < sizeof(*ip_hdr)) return; - ipv4_l34_csum_replace((uint8_t*)ip_hdr, IPPROTO_IP, old_ip, new_ip); + ipv4_l34_csum_replace((uint8_t *)ip_hdr, IPPROTO_IP, old_ip, new_ip); protocol = ip_hdr->ip_p; switch (protocol) { case IPPROTO_UDP: - l4 = get_layer4_v4(ip_hdr, len); + l4 = get_layer4_v4(ip_hdr, (u_char *)ip_hdr + l3len); len -= ip_hdr->ip_hl << 2; len -= TCPR_UDP_H; break; case IPPROTO_TCP: - l4 = get_layer4_v4(ip_hdr, len); + l4 = get_layer4_v4(ip_hdr, (u_char *)ip_hdr + l3len); len -= ip_hdr->ip_hl << 2; len -= TCPR_TCP_H; break; @@ -288,45 +290,34 @@ static void ipv4_addr_csum_replace(ipv4_hdr_t *ip_hdr, uint32_t old_ip, ipv4_l34_csum_replace(l4, protocol, old_ip, new_ip); } -static void ipv6_addr_csum_replace(ipv6_hdr_t *ip6_hdr, - struct tcpr_in6_addr *old_ip, struct tcpr_in6_addr *new_ip, - const int l3len) +static void +ipv6_addr_csum_replace(ipv6_hdr_t *ip6_hdr, struct tcpr_in6_addr *old_ip, struct tcpr_in6_addr *new_ip, int l3len) { uint8_t *l4, protocol; - int len = l3len; assert(ip6_hdr); - if ((size_t)len < sizeof(*ip6_hdr)) + if ((size_t)l3len < sizeof(*ip6_hdr)) return; - protocol = get_ipv6_l4proto(ip6_hdr, len); + protocol = get_ipv6_l4proto(ip6_hdr, (u_char *)ip6_hdr + l3len); switch (protocol) { case IPPROTO_UDP: - l4 = get_layer4_v6(ip6_hdr, len); - len -= sizeof(*ip6_hdr); - len -= TCPR_UDP_H; - break; - case IPPROTO_TCP: - l4 = get_layer4_v6(ip6_hdr, len); - len -= sizeof(*ip6_hdr); - len -= TCPR_TCP_H; + l4 = get_layer4_v6(ip6_hdr, (u_char *)ip6_hdr + l3len); break; - default: l4 = NULL; } - if (!l4 || len < 0) + if (!l4) return; - ipv6_l34_csum_replace(l4, protocol, (uint32_t*)old_ip, (uint32_t*)new_ip); + ipv6_l34_csum_replace(l4, protocol, (uint32_t *)old_ip, (uint32_t *)new_ip); } - /** - * returns a new 32bit integer which is the randomized IP + * returns a new 32bit integer which is the randomized IP * based upon the user specified seed */ static uint32_t @@ -365,8 +356,8 @@ randomize_ipv6_addr(tcpedit_t *tcpedit, struct tcpr_in6_addr *addr) } } -int fix_ipv4_length(struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, - const size_t l2len) +int +fix_ipv4_length(struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, size_t l2len) { int ip_len = (int)ntohs(ip_hdr->ip_len); int ip_len_want = (int)(pkthdr->len - l2len); @@ -385,8 +376,8 @@ int fix_ipv4_length(struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, return 0; } -int fix_ipv6_length(struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, - const size_t l2len) +int +fix_ipv6_length(struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, size_t l2len) { int ip_len = ntohs((uint16_t)ip6_hdr->ip_len); int ip_len_want = (int)(pkthdr->len - l2len - sizeof(*ip6_hdr)); @@ -404,13 +395,12 @@ int fix_ipv6_length(struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, } /** - * randomizes the source and destination IP addresses based on a + * randomizes the source and destination IP addresses based on a * pseudo-random number which is generated via the seed. * return 1 since we changed one or more IP addresses */ int -randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char *pktdata, ipv4_hdr_t *ip_hdr, const int l3len) +randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, const u_char *pktdata, ipv4_hdr_t *ip_hdr, int l3len) { #ifdef DEBUG char srcip[16], dstip[16]; @@ -429,27 +419,26 @@ randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, dbgx(1, "Old Src IP: %s\tOld Dst IP: %s", srcip, dstip); if (l3len < (int)ip_hdr->ip_hl << 2) { - tcpedit_seterr(tcpedit, "Unable to randomize IP header due to packet capture snap length %u", - pkthdr->caplen); + tcpedit_seterr(tcpedit, "Unable to randomize IP header due to packet capture snap length %u", pkthdr->caplen); return TCPEDIT_ERROR; } /* don't rewrite broadcast addresses */ - if ((tcpedit->skip_broadcast && is_unicast_ipv4(tcpedit, (u_int32_t)ip_hdr->ip_dst.s_addr)) - || !tcpedit->skip_broadcast) { + if ((tcpedit->skip_broadcast && is_unicast_ipv4(tcpedit, (u_int32_t)ip_hdr->ip_dst.s_addr)) || + !tcpedit->skip_broadcast) { uint32_t old_ip = ip_hdr->ip_dst.s_addr; ip_hdr->ip_dst.s_addr = randomize_ipv4_addr(tcpedit, ip_hdr->ip_dst.s_addr); ipv4_addr_csum_replace(ip_hdr, old_ip, ip_hdr->ip_dst.s_addr, l3len); } - - if ((tcpedit->skip_broadcast && is_unicast_ipv4(tcpedit, (u_int32_t)ip_hdr->ip_src.s_addr)) - || !tcpedit->skip_broadcast) { + + if ((tcpedit->skip_broadcast && is_unicast_ipv4(tcpedit, (u_int32_t)ip_hdr->ip_src.s_addr)) || + !tcpedit->skip_broadcast) { uint32_t old_ip = ip_hdr->ip_src.s_addr; ip_hdr->ip_src.s_addr = randomize_ipv4_addr(tcpedit, ip_hdr->ip_src.s_addr); ipv4_addr_csum_replace(ip_hdr, old_ip, ip_hdr->ip_src.s_addr, l3len); } -#ifdef DEBUG +#ifdef DEBUG strlcpy(srcip, get_addr2name4(ip_hdr->ip_src.s_addr, RESOLVE), 16); strlcpy(dstip, get_addr2name4(ip_hdr->ip_dst.s_addr, RESOLVE), 16); #endif @@ -460,8 +449,7 @@ randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, } int -randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char *pktdata, ipv6_hdr_t *ip6_hdr, const int l3len) +randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, const u_char *pktdata, ipv6_hdr_t *ip6_hdr, int l3len) { #ifdef DEBUG char srcip[INET6_ADDRSTRLEN], dstip[INET6_ADDRSTRLEN]; @@ -479,22 +467,22 @@ randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, /* randomize IP addresses based on the value of random */ dbgx(1, "Old Src IP: %s\tOld Dst IP: %s", srcip, dstip); if (l3len < (int)sizeof(ipv6_hdr_t)) { - tcpedit_seterr(tcpedit, "Unable to randomize IPv6 header due to packet capture snap length %u: pkt=" COUNTER_SPEC, - pkthdr->caplen, tcpedit->runtime.packetnum); + tcpedit_seterr(tcpedit, + "Unable to randomize IPv6 header due to packet capture snap length %u: pkt=" COUNTER_SPEC, + pkthdr->caplen, + tcpedit->runtime.packetnum); return TCPEDIT_ERROR; } /* don't rewrite broadcast addresses */ - if ((tcpedit->skip_broadcast && !is_multicast_ipv6(tcpedit, &ip6_hdr->ip_dst)) - || !tcpedit->skip_broadcast) { + if ((tcpedit->skip_broadcast && !is_multicast_ipv6(tcpedit, &ip6_hdr->ip_dst)) || !tcpedit->skip_broadcast) { struct tcpr_in6_addr old_ip6; memcpy(&old_ip6, &ip6_hdr->ip_dst, sizeof(old_ip6)); randomize_ipv6_addr(tcpedit, &ip6_hdr->ip_dst); ipv6_addr_csum_replace(ip6_hdr, &old_ip6, &ip6_hdr->ip_dst, l3len); } - if ((tcpedit->skip_broadcast && !is_multicast_ipv6(tcpedit, &ip6_hdr->ip_src)) - || !tcpedit->skip_broadcast) { + if ((tcpedit->skip_broadcast && !is_multicast_ipv6(tcpedit, &ip6_hdr->ip_src)) || !tcpedit->skip_broadcast) { struct tcpr_in6_addr old_ip6; memcpy(&old_ip6, &ip6_hdr->ip_src, sizeof(old_ip6)); randomize_ipv6_addr(tcpedit, &ip6_hdr->ip_src); @@ -513,13 +501,16 @@ randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, /** * this code will untruncate a packet via padding it with null - * or resetting the actual IPv4 packet len to the snaplen - L2 header. + * or resetting the actual IPv4 packet len to the snaplen - L2 header. * return 0 if no change, 1 if change, -1 on error. */ int -untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char **pktdata, ipv4_hdr_t *ip_hdr, ipv6_hdr_t *ip6_hdr) +untrunc_packet(tcpedit_t *tcpedit, + struct pcap_pkthdr *pkthdr, + u_char **pktdata, + ipv4_hdr_t *ip_hdr, + ipv6_hdr_t *ip6_hdr) { int l2len; int chksum = 1; @@ -537,10 +528,10 @@ untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, /* if actual len == cap len or there's no IP header, don't do anything */ if ((pkthdr->caplen == pkthdr->len) || (ip_hdr == NULL && ip6_hdr == NULL)) { /* unless we're in MTU truncate mode */ - if (! tcpedit->mtu_truncate) - return(0); + if (!tcpedit->mtu_truncate) + return (0); } - + if ((l2len = layer2len(tcpedit, packet, pkthdr->caplen)) < 0) { tcpedit_seterr(tcpedit, "Non-sensical layer 2 length: %d", l2len); return -1; @@ -554,11 +545,10 @@ untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, if (ip_hdr) { if ((htons(ip_hdr->ip_off) & IP_OFFMASK) != 0) { chksum = 0; - } else if (ip_hdr->ip_p == IPPROTO_UDP && - (htons(ip_hdr->ip_off) & IP_MF) != 0) { - dataptr = (u_char*)ip_hdr; + } else if (ip_hdr->ip_p == IPPROTO_UDP && (htons(ip_hdr->ip_off) & IP_MF) != 0) { + dataptr = (u_char *)ip_hdr; dataptr += ip_hdr->ip_hl << 2; - udp_hdr = (udp_hdr_t*)dataptr; + udp_hdr = (udp_hdr_t *)dataptr; udp_hdr->uh_sum = 0; chksum = 0; } @@ -568,44 +558,41 @@ untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, if (tcpedit->fixlen == TCPEDIT_FIXLEN_PAD) { /* * this should be an unnecessary check - * but I've gotten a report that sometimes the caplen > len - * which seems like a corrupted pcap - */ + * but I've gotten a report that sometimes the caplen > len + * which seems like a corrupted pcap + */ if (pkthdr->len > pkthdr->caplen) { packet = safe_realloc(packet, pkthdr->len + PACKET_HEADROOM); memset(packet + pkthdr->caplen, '\0', pkthdr->len - pkthdr->caplen); pkthdr->caplen = pkthdr->len; } else if (pkthdr->len < pkthdr->caplen) { /* i guess this is necessary if we've got a bogus pcap */ - //ip_hdr->ip_len = htons(pkthdr->caplen - l2len); + // ip_hdr->ip_len = htons(pkthdr->caplen - l2len); tcpedit_seterr(tcpedit, "%s", "WTF? Why is your packet larger then the capture len?"); chksum = -1; goto done; } - } - else if (tcpedit->fixlen == TCPEDIT_FIXLEN_TRUNC) { + } else if (tcpedit->fixlen == TCPEDIT_FIXLEN_TRUNC) { if (ip_hdr && pkthdr->len != pkthdr->caplen) ip_hdr->ip_len = htons(pkthdr->caplen - l2len); pkthdr->len = pkthdr->caplen; - } - else if (tcpedit->mtu_truncate) { + } else if (tcpedit->mtu_truncate) { if (pkthdr->len > (uint32_t)(tcpedit->mtu + l2len)) { /* first truncate the packet */ pkthdr->len = pkthdr->caplen = l2len + tcpedit->mtu; - + /* if ip_hdr exists, update the length */ - if (ip_hdr != NULL) { + if (ip_hdr) { ip_hdr->ip_len = htons(tcpedit->mtu); - } else if (ip6_hdr != NULL) { + } else if (ip6_hdr) { ip6_hdr->ip_len = htons(tcpedit->mtu - sizeof(*ip6_hdr)); } else { - /* for non-IP frames, don't try to fix checksums */ + /* for non-IP frames, don't try to fix checksums */ chksum = 0; goto done; } } - } - else { + } else { tcpedit_seterr(tcpedit, "Invalid fixlen value: 0x%x", tcpedit->fixlen); chksum = -1; goto done; @@ -618,7 +605,7 @@ untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, /** * rewrites an IPv4 packet's TTL based on the rules - * return 0 if no change, 1 if changed + * return 0 if no change, 1 if changed */ int rewrite_ipv4_ttl(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr) @@ -629,13 +616,13 @@ rewrite_ipv4_ttl(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr) /* make sure there's something to edit */ if (ip_hdr == NULL || tcpedit->ttl_mode == false) - return(0); - + return (0); + oldval = (uint16_t)ip_hdr->ip_ttl; - switch(tcpedit->ttl_mode) { + switch (tcpedit->ttl_mode) { case TCPEDIT_TTL_MODE_SET: if (ip_hdr->ip_ttl == tcpedit->ttl_value) - return 0; /* no change required */ + return 0; /* no change required */ ip_hdr->ip_ttl = tcpedit->ttl_value; break; case TCPEDIT_TTL_MODE_ADD: @@ -659,7 +646,7 @@ rewrite_ipv4_ttl(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr) newval = (uint16_t)ip_hdr->ip_ttl; csum_replace2(&ip_hdr->ip_sum, oldval, newval); - return 0; + return 1; } /** @@ -673,12 +660,12 @@ rewrite_ipv6_hlim(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr) /* make sure there's something to edit */ if (ip6_hdr == NULL || tcpedit->ttl_mode == TCPEDIT_TTL_MODE_OFF) - return(0); + return (0); - switch(tcpedit->ttl_mode) { + switch (tcpedit->ttl_mode) { case TCPEDIT_TTL_MODE_SET: if (ip6_hdr->ip_hl == tcpedit->ttl_value) - return(0); /* no change required */ + return (0); /* no change required */ ip6_hdr->ip_hl = tcpedit->ttl_value; break; case TCPEDIT_TTL_MODE_ADD: @@ -698,7 +685,7 @@ rewrite_ipv6_hlim(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr) default: errx(1, "invalid ttl_mode: %d", tcpedit->ttl_mode); } - return 0; + return 1; } /** @@ -707,13 +694,13 @@ rewrite_ipv6_hlim(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr) * while 10.150.9.0/24 and 192.168.55.123 -> 10.150.9.123 */ static uint32_t -remap_ipv4(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, const uint32_t original) +remap_ipv4(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, uint32_t original) { - uint32_t ipaddr = 0, network = 0, mask = 0, result = 0; + uint32_t ipaddr, network, mask, result; assert(tcpedit); assert(cidr); - + if (cidr->family != AF_INET) { return 0; } @@ -736,9 +723,9 @@ remap_ipv4(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, const uint32_t original) /* merge the network portion and ip portions */ result = network ^ ipaddr; - + /* return the result in network byte order */ - return(htonl(result)); + return (htonl(result)); } static int @@ -768,8 +755,8 @@ remap_ipv6(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, struct tcpr_in6_addr *addr) k = (uint32_t)~0 << (8 - k); i = addr->tcpr_s6_addr[i] & k; - addr->tcpr_s6_addr[i] = (cidr->u.network6.tcpr_s6_addr[j] & (0xff << (8 - k))) | - (addr->tcpr_s6_addr[i] & (0xff >> k)); + addr->tcpr_s6_addr[i] = + (cidr->u.network6.tcpr_s6_addr[j] & (0xff << (8 - k))) | (addr->tcpr_s6_addr[i] & (0xff >> k)); return 1; } @@ -781,8 +768,7 @@ remap_ipv6(tcpedit_t *tcpedit, tcpr_cidr_t *cidr, struct tcpr_in6_addr *addr) * return 0 if no change, 1 or 2 if changed */ int -rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, - int len) +rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, int len) { tcpr_cidrmap_t *cidrmap1 = NULL, *cidrmap2 = NULL; int didsrc = 0, diddst = 0, loop = 1; @@ -818,7 +804,7 @@ rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, /* anything else to rewrite? */ if (tcpedit->cidrmap1 == NULL) - return(0); + return (0); /* don't play with the main pointers */ if (direction == TCPR_DIR_C2S) { @@ -828,18 +814,17 @@ rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, cidrmap1 = tcpedit->cidrmap2; cidrmap2 = tcpedit->cidrmap1; } - /* loop through the cidrmap to rewrite */ do { - if ((! diddst) && ip_in_cidr(cidrmap2->from, ip_hdr->ip_dst.s_addr)) { + if ((!diddst) && ip_in_cidr(cidrmap2->from, ip_hdr->ip_dst.s_addr)) { uint32_t old_ip = ip_hdr->ip_dst.s_addr; ip_hdr->ip_dst.s_addr = remap_ipv4(tcpedit, cidrmap2->to, ip_hdr->ip_dst.s_addr); ipv4_addr_csum_replace(ip_hdr, old_ip, ip_hdr->ip_dst.s_addr, len); dbgx(2, "Remapped dst addr to: %s", get_addr2name4(ip_hdr->ip_dst.s_addr, RESOLVE)); diddst = 1; } - if ((! didsrc) && ip_in_cidr(cidrmap1->from, ip_hdr->ip_src.s_addr)) { + if ((!didsrc) && ip_in_cidr(cidrmap1->from, ip_hdr->ip_src.s_addr)) { uint32_t old_ip = ip_hdr->ip_src.s_addr; ip_hdr->ip_src.s_addr = remap_ipv4(tcpedit, cidrmap1->to, ip_hdr->ip_src.s_addr); ipv4_addr_csum_replace(ip_hdr, old_ip, ip_hdr->ip_src.s_addr, len); @@ -851,9 +836,7 @@ rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, * loop while we haven't modified both src/dst AND * at least one of the cidr maps have a next pointer */ - if ((! (diddst && didsrc)) && - (! ((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { - + if ((!(diddst && didsrc)) && (!((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { /* increment our ptr's if possible */ if (cidrmap1->next != NULL) cidrmap1 = cidrmap1->next; @@ -872,13 +855,14 @@ rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, } while (loop); - /* return how many changes we require checksum updates (none) */ + /* return how many changes we require checksum updates + * (none required - checksum is already updated) + */ return 0; } int -rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, - int l3len) +rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, int l3len) { tcpr_cidrmap_t *cidrmap1 = NULL, *cidrmap2 = NULL; int didsrc = 0, diddst = 0, loop = 1; @@ -916,7 +900,7 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, /* anything else to rewrite? */ if (tcpedit->cidrmap1 == NULL) - return(0); + return (0); /* don't play with the main pointers */ if (direction == TCPR_DIR_C2S) { @@ -927,10 +911,9 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, cidrmap2 = tcpedit->cidrmap1; } - /* loop through the cidrmap to rewrite */ do { - if ((! diddst) && ip6_in_cidr(cidrmap2->from, &ip6_hdr->ip_dst)) { + if ((!diddst) && ip6_in_cidr(cidrmap2->from, &ip6_hdr->ip_dst)) { struct tcpr_in6_addr old_ip6; memcpy(&old_ip6, &ip6_hdr->ip_dst, sizeof(old_ip6)); remap_ipv6(tcpedit, cidrmap2->to, &ip6_hdr->ip_dst); @@ -938,7 +921,7 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, dbgx(2, "Remapped dst addr to: %s", get_addr2name6(&ip6_hdr->ip_dst, RESOLVE)); diddst = 1; } - if ((! didsrc) && ip6_in_cidr(cidrmap1->from, &ip6_hdr->ip_src)) { + if ((!didsrc) && ip6_in_cidr(cidrmap1->from, &ip6_hdr->ip_src)) { struct tcpr_in6_addr old_ip6; memcpy(&old_ip6, &ip6_hdr->ip_src, sizeof(old_ip6)); remap_ipv6(tcpedit, cidrmap1->to, &ip6_hdr->ip_src); @@ -951,9 +934,7 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, * loop while we haven't modified both src/dst AND * at least one of the cidr maps have a next pointer */ - if ((! (diddst && didsrc)) && - (! ((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { - + if ((!(diddst && didsrc)) && (!((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { /* increment our ptr's if possible */ if (cidrmap1->next != NULL) cidrmap1 = cidrmap1->next; @@ -972,7 +953,9 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, } while (loop); - /* return how many changes we made (none) */ + /* return how many changes we require checksum updates + * (none required - checksum is already updated) + */ return 0; } @@ -980,11 +963,10 @@ rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr, tcpr_dir_t direction, * Randomize the IP addresses in an ARP packet based on the user seed * return 0 if no change, or 1 for a change */ -int -randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char *pktdata, int datalink, const int l3len) +int +randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, const u_char *pktdata, int datalink, int l3len) { - arp_hdr_t *arp_hdr ; + arp_hdr_t *arp_hdr; int l2len; #ifdef FORCE_ALIGN uint32_t iptemp; @@ -995,12 +977,11 @@ randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, assert(pktdata); if (l3len < (int)sizeof(arp_hdr_t)) { - tcpedit_seterr(tcpedit, "Unable to randomize ARP packet due to packet capture snap length %u", - pkthdr->caplen); + tcpedit_seterr(tcpedit, "Unable to randomize ARP packet due to packet capture snap length %u", pkthdr->caplen); return TCPEDIT_ERROR; } - l2len = get_l2len(pktdata, pkthdr->caplen, datalink); + l2len = get_l2len(pktdata, (int)pkthdr->caplen, datalink); arp_hdr = (arp_hdr_t *)(pktdata + l2len); @@ -1008,12 +989,10 @@ randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, * only rewrite IP addresses from REPLY/REQUEST's */ if ((ntohs(arp_hdr->ar_pro) == ETHERTYPE_IP) && - ((ntohs(arp_hdr->ar_op) == ARPOP_REQUEST) || - (ntohs(arp_hdr->ar_op) == ARPOP_REPLY))) { + ((ntohs(arp_hdr->ar_op) == ARPOP_REQUEST) || (ntohs(arp_hdr->ar_op) == ARPOP_REPLY))) { /* jump to the addresses */ uint32_t *ip; - u_char *add_hdr = ((u_char *)arp_hdr) + sizeof(arp_hdr_t) + - arp_hdr->ar_hln; + u_char *add_hdr = ((u_char *)arp_hdr) + sizeof(arp_hdr_t) + arp_hdr->ar_hln; #ifdef FORCE_ALIGN /* copy IP to a temporary buffer for processing */ @@ -1067,7 +1046,7 @@ rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int cache_mode) assert(tcpedit); assert(arp_hdr); - /* figure out what mapping to use */ + /* figure out what mapping to use */ if (cache_mode == TCPR_DIR_C2S) { cidrmap1 = tcpedit->cidrmap1; cidrmap2 = tcpedit->cidrmap2; @@ -1078,17 +1057,15 @@ rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int cache_mode) /* anything to rewrite? */ if (cidrmap1 == NULL || cidrmap2 == NULL) - return(0); + return (0); /* - * must be IPv4 and request or reply + * must be IPv4 and request or reply * Do other op codes use the same subheader stub? * If so we won't need to check the op code. */ if ((ntohs(arp_hdr->ar_pro) == ETHERTYPE_IP) && - ((ntohs(arp_hdr->ar_op) == ARPOP_REQUEST) || - (ntohs(arp_hdr->ar_op) == ARPOP_REPLY))) - { + ((ntohs(arp_hdr->ar_op) == ARPOP_REQUEST) || (ntohs(arp_hdr->ar_op) == ARPOP_REPLY))) { /* jump to the addresses */ add_hdr = (u_char *)arp_hdr; add_hdr += sizeof(arp_hdr_t) + arp_hdr->ar_hln; @@ -1101,7 +1078,6 @@ rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int cache_mode) #else ip2 = (uint32_t *)add_hdr; #endif - /* loop through the cidrmap to rewrite */ do { @@ -1117,7 +1093,7 @@ rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int cache_mode) memcpy(ip2, &newip, 4); didsrc = 1; } - } + } /* else it's an arp reply */ else { if ((!diddst) && ip_in_cidr(cidrmap2->from, *ip2)) { @@ -1141,27 +1117,25 @@ rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int cache_mode) * loop while we haven't modified both src/dst AND * at least one of the cidr maps have a next pointer */ - if ((! (diddst && didsrc)) && - (! ((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { - + if ((!(diddst && didsrc)) && (!((cidrmap1->next == NULL) && (cidrmap2->next == NULL)))) { /* increment our ptr's if possible */ if (cidrmap1->next != NULL) cidrmap1 = cidrmap1->next; - + if (cidrmap2->next != NULL) cidrmap2 = cidrmap2->next; - + } else { loop = 0; } } while (loop); - + } else { warn("ARP packet isn't for IPv4! Can't rewrite IP's"); } - return(didsrc + diddst); + return (didsrc + diddst); } /** @@ -1172,11 +1146,11 @@ static int is_unicast_ipv4(tcpedit_t *tcpedit, uint32_t ip) { assert(tcpedit); - + /* multicast/broadcast is 224.0.0.0 to 239.255.255.255 */ if ((ntohl(ip) & 0xf0000000) == 0xe0000000) return 0; - + return 1; } diff --git a/src/tcpedit/edit_packet.h b/src/tcpedit/edit_packet.h index c4972fcd2..d221cc8b2 100644 --- a/src/tcpedit/edit_packet.h +++ b/src/tcpedit/edit_packet.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,44 +18,38 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _EDIT_PACKETS_H_ -#define _EDIT_PACKETS_H_ +#pragma once -#include "tcpedit.h" #include "common.h" +#include "tcpedit.h" -int untrunc_packet(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char **pktdata, ipv4_hdr_t *ip_hdr, ipv6_hdr_t *ip6_hdr); +int untrunc_packet(tcpedit_t *tcpedit, + struct pcap_pkthdr *pkthdr, + u_char **pktdata, + ipv4_hdr_t *ip_hdr, + ipv6_hdr_t *ip6_hdr); -int randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pktdhr, - u_char *pktdata, ipv4_hdr_t *ip_hdr, const int l3len); +int +randomize_ipv4(tcpedit_t *tcpedit, struct pcap_pkthdr *pktdhr, const u_char *pktdata, ipv4_hdr_t *ip_hdr, int l3len); -int randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pktdhr, - u_char *pktdata, ipv6_hdr_t *ip_hdr, const int l3len); +int +randomize_ipv6(tcpedit_t *tcpedit, struct pcap_pkthdr *pktdhr, const u_char *pktdata, ipv6_hdr_t *ip_hdr, int l3len); -int randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char *pktdata, int datalink, const int l3len); +int randomize_iparp(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, const u_char *pktdata, int datalink, int l3len); -int fix_ipv4_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkdhdr, - ipv4_hdr_t *ip_hdr, const size_t l2len); +int fix_ipv4_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkdhdr, ipv4_hdr_t *ip_hdr, size_t l2len); -int fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkdhdr, - ipv6_hdr_t *ip_hdr, const size_t l2len); +int fix_ipv6_checksums(tcpedit_t *tcpedit, struct pcap_pkthdr *pkdhdr, ipv6_hdr_t *ip_hdr, size_t l2len); -int fix_ipv4_length(struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, - const size_t l2len); +int fix_ipv4_length(struct pcap_pkthdr *pkthdr, ipv4_hdr_t *ip_hdr, size_t l2len); -int fix_ipv6_length(struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, - const size_t l2len); +int fix_ipv6_length(struct pcap_pkthdr *pkthdr, ipv6_hdr_t *ip6_hdr, size_t l2len); -int extract_data(tcpedit_t *tcpedit, const u_char *pktdata, - int caplen, char *l7data[]); +int extract_data(tcpedit_t *tcpedit, const u_char *pktdata, int caplen, char *l7data[]); -int rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, - int l3len); +int rewrite_ipv4l3(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr, tcpr_dir_t direction, int l3len); -int rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip_hdr, tcpr_dir_t direction, - int l3len); +int rewrite_ipv6l3(tcpedit_t *tcpedit, ipv6_hdr_t *ip_hdr, tcpr_dir_t direction, int l3len); int rewrite_iparp(tcpedit_t *tcpedit, arp_hdr_t *arp_hdr, int direction); @@ -63,15 +57,8 @@ int rewrite_ipv4_ttl(tcpedit_t *tcpedit, ipv4_hdr_t *ip_hdr); int rewrite_ipv6_hlim(tcpedit_t *tcpedit, ipv6_hdr_t *ip6_hdr); -int extract_ipv4_multicast_mac(tcpedit_t *tcpedit, - uint32_t ip, - u_char *mac[ETHER_ADDR_LEN]); - -int extract_ipv6_multicast_mac(tcpedit_t *tcpedit, - struct tcpr_in6_addr *ip6, - u_char *mac[ETHER_ADDR_LEN]); +int extract_ipv4_multicast_mac(tcpedit_t *tcpedit, uint32_t ip, u_char *mac[ETHER_ADDR_LEN]); +int extract_ipv6_multicast_mac(tcpedit_t *tcpedit, struct tcpr_in6_addr *ip6, u_char *mac[ETHER_ADDR_LEN]); #define BROADCAST_IP 4294967295 - -#endif diff --git a/src/tcpedit/fuzzing.c b/src/tcpedit/fuzzing.c index 9ed5b79de..ed44f0d48 100644 --- a/src/tcpedit/fuzzing.c +++ b/src/tcpedit/fuzzing.c @@ -1,20 +1,14 @@ +#include "fuzzing.h" +#include #include #include #include #include -#include "defines.h" -#include "fuzzing.h" - -#include "common/utils.h" - -#include "tcpedit/tcpedit.h" - static unsigned int fuzz_seed; static unsigned int fuzz_factor; static unsigned int fuzz_running; - void fuzzing_init(uint32_t _fuzz_seed, uint32_t _fuzz_factor) { @@ -41,18 +35,15 @@ fuzz_get_sgt_size(uint32_t r, uint32_t caplen) } static inline int -fuzz_reduce_packet_size(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - uint32_t new_len) +fuzz_reduce_packet_size(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, uint32_t new_len) { if (pkthdr->len < pkthdr->caplen) { - tcpedit_seterr(tcpedit, "Packet length %u smaller than capture length %u", - pkthdr->len, pkthdr->caplen); + tcpedit_seterr(tcpedit, "Packet length %u smaller than capture length %u", pkthdr->len, pkthdr->caplen); return -1; } if (new_len > pkthdr->caplen) { - tcpedit_seterr(tcpedit, "Cannot fuzz packet of capture length %u to length %u", - pkthdr->caplen, new_len); + tcpedit_seterr(tcpedit, "Cannot fuzz packet of capture length %u to length %u", pkthdr->caplen, new_len); return -1; } @@ -70,14 +61,13 @@ fuzz_reduce_packet_size(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, } int -fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, - u_char **pktdata) +fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, u_char **pktdata) { - int packet_changed = 0; + int chksum_update_required = 0; uint32_t r, s; uint16_t l2proto; uint8_t l4proto; - u_char *packet, *l3data, *l4data; + u_char *packet, *l3data, *l4data, *end_ptr; tcpeditdlt_plugin_t *plugin; int l2len, l4len; tcpeditdlt_t *ctx; @@ -102,6 +92,7 @@ fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, /* initializations */ ctx = tcpedit->dlt_ctx; packet = *pktdata; + end_ptr = packet + pkthdr->caplen; plugin = tcpedit->dlt_ctx->encoder; l2len = plugin->plugin_l2len(ctx, packet, pkthdr->caplen); l2proto = ntohs(plugin->plugin_proto(ctx, packet, pkthdr->caplen)); @@ -119,83 +110,78 @@ fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, if (!l3data) goto done; - l4len = pkthdr->caplen - l2len; switch (l2proto) { - case (ETHERTYPE_IP): - { - l4data = get_layer4_v4((ipv4_hdr_t*)l3data, pkthdr->caplen - l2len); + case (ETHERTYPE_IP): { + l4data = get_layer4_v4((ipv4_hdr_t *)(packet + l2len), end_ptr); if (!l4data) goto done; + l4len = l4data - packet; l4proto = ((ipv4_hdr_t *)l3data)->ip_p; break; } case (ETHERTYPE_IP6): { - l4data = get_layer4_v6((ipv6_hdr_t*)l3data, pkthdr->caplen - l2len); + l4data = get_layer4_v6((ipv6_hdr_t *)(packet + l2len), end_ptr); if (!l4data) goto done; + l4len = l4data - packet; l4proto = ((ipv6_hdr_t *)l3data)->ip_nh; break; } default: /* apply fuzzing on unknown packet types */ - l4data = l3data; - l4proto = IPPROTO_RAW; - + l4len = pkthdr->caplen - l2len; + l4data = packet + l2len; + l4proto = IPPROTO_RAW; } /* adjust payload length based on layer 3 protocol */ switch (l4proto) { case IPPROTO_TCP: l4len -= sizeof(tcp_hdr_t); + l4data += sizeof(tcp_hdr_t); break; case IPPROTO_UDP: l4len -= sizeof(udp_hdr_t); + l4data += sizeof(udp_hdr_t); break; } - if (l4len <= 1) + if (l4len <= 1 || l4data > end_ptr) goto done; /* add some additional randomization */ r ^= r >> 16; s = r % FUZZING_TOTAL_ACTION_NUMBER; - - dbgx(3, "packet fuzzed : %d", s); switch (s) { - case FUZZING_DROP_PACKET: - { + case FUZZING_DROP_PACKET: { /* simulate dropping the packet */ if (fuzz_reduce_packet_size(tcpedit, pkthdr, 0) < 0) /* could not change packet size, so packet left unchanged */ goto done; - packet_changed = 1; break; } - case FUZZING_REDUCE_SIZE: - { + case FUZZING_REDUCE_SIZE: { /* reduce packet size */ - uint32_t new_len = (r % ((l4len) - 1)) + 1; + uint32_t new_len = (r % (l4len - 1)) + 1; if (fuzz_reduce_packet_size(tcpedit, pkthdr, new_len) < 0) /* could not change packet size, so packet left unchanged */ goto done; - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_START_ZERO: - { + case FUZZING_CHANGE_START_ZERO: { /* fuzz random-size segment at the beginning of the packet with 0x00 */ uint32_t sgt_size = fuzz_get_sgt_size(r, l4len); memset(l4data, 0x00, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_START_RANDOM: - { + case FUZZING_CHANGE_START_RANDOM: { /* * fuzz random-size segment at the beginning of the packet payload * with random bytes @@ -208,11 +194,10 @@ fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, for (i = 0; i < sgt_size; i++) l4data[i] = l4data[i] ^ (u_char)(r >> 4); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_START_FF: - { + case FUZZING_CHANGE_START_FF: { /* * fuzz random-size segment at the beginning of the packet * payload with 0xff @@ -222,96 +207,91 @@ fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, goto done; memset(l4data, 0xff, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_MID_ZERO: - { + case FUZZING_CHANGE_MID_ZERO: { /* fuzz random-size segment inside the packet payload with 0x00 */ + if (l4len <= 2) + goto done; + uint32_t offset = ((r >> 16) % (l4len - 1)) + 1; uint32_t sgt_size = fuzz_get_sgt_size(r, l4len - offset); if (!sgt_size) goto done; memset(l4data + offset, 0x00, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_MID_FF: - { + case FUZZING_CHANGE_MID_FF: { /* fuzz random-size segment inside the packet payload with 0xff */ + if (l4len <= 2) + goto done; + uint32_t offset = ((r >> 16) % (l4len - 1)) + 1; uint32_t sgt_size = fuzz_get_sgt_size(r, l4len - offset); if (!sgt_size) goto done; memset(l4data + offset, 0xff, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_END_ZERO: - { + case FUZZING_CHANGE_END_ZERO: { /* fuzz random-sized segment at the end of the packet payload with 0x00 */ - uint32_t sgt_size = fuzz_get_sgt_size(r, l4len); - if (!sgt_size) + int sgt_size = fuzz_get_sgt_size(r, l4len); + if (!sgt_size || sgt_size > l4len) goto done; memset(l4data + l4len - sgt_size, 0x00, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_END_RANDOM: - { + case FUZZING_CHANGE_END_RANDOM: { /* fuzz random-sized segment at the end of the packet with random Bytes */ int i; - uint32_t sgt_size = fuzz_get_sgt_size(r, l4len); - if (!sgt_size) + int sgt_size = fuzz_get_sgt_size(r, l4len); + if (!sgt_size || sgt_size > l4len) goto done; for (i = (l4len - sgt_size); i < l4len; i++) l4data[i] = l4data[i] ^ (u_char)(r >> 4); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_END_FF: - { + case FUZZING_CHANGE_END_FF: { /* fuzz random-sized segment at the end of the packet with 0xff00 */ - uint32_t sgt_size = fuzz_get_sgt_size(r, l4len); - if (!sgt_size) + int sgt_size = fuzz_get_sgt_size(r, l4len); + if (!sgt_size || sgt_size > l4len) goto done; memset(l4data + l4len - sgt_size, 0xff, sgt_size); - packet_changed = 1; + chksum_update_required = 1; break; } - case FUZZING_CHANGE_MID_RANDOM: - { + case FUZZING_CHANGE_MID_RANDOM: { /* fuzz random-size segment inside the packet with random Bytes */ size_t i; uint32_t offset = ((r >> 16) % (l4len - 1)) + 1; - uint32_t sgt_size = fuzz_get_sgt_size(r, l4len - offset); - if (!sgt_size) + int sgt_size = fuzz_get_sgt_size(r, l4len - offset); + if (!sgt_size || sgt_size > l4len) goto done; for (i = offset; i < offset + sgt_size; i++) l4data[i] = l4data[i] ^ (u_char)(r >> 4); - packet_changed = 1; + chksum_update_required = 1; break; } default: assert(false); } - /* in cases where 'l3data' is a working buffer, copy it back to '*pkthdr' */ - plugin->plugin_merge_layer3(ctx, - packet, - pkthdr->caplen, - (l2proto == ETHERTYPE_IP) ? l4data : NULL, - (l2proto == ETHERTYPE_IP6) ? l4data : NULL); + dbgx(3, "packet %llu fuzzed : %d", tcpedit->runtime.packetnum, s); done: - return packet_changed; + return chksum_update_required; } diff --git a/src/tcpedit/fuzzing.h b/src/tcpedit/fuzzing.h index e645cad73..cffed6041 100644 --- a/src/tcpedit/fuzzing.h +++ b/src/tcpedit/fuzzing.h @@ -1,12 +1,10 @@ -#ifndef FUZZING_H -#define FUZZING_H +#pragma once +#include "defines.h" +#include #include #include -#include "defines.h" -#include "tcpedit/tcpedit_types.h" - enum { FUZZING_DROP_PACKET, FUZZING_REDUCE_SIZE, @@ -25,8 +23,7 @@ enum { /** * init fuzz seed and allocate buffer. */ -void -fuzzing_init(uint32_t _fuzz_seed, uint32_t _fuzz_factor); +void fuzzing_init(uint32_t _fuzz_seed, uint32_t _fuzz_factor); /* * fuzz packet data. @@ -34,7 +31,4 @@ fuzzing_init(uint32_t _fuzz_seed, uint32_t _fuzz_factor); * fuzzed packets get one random modification from the enum above. * Returns whether the packet has been modified (1, or 0) */ -int -fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, u_char **pktdata); - -#endif /* FUZZING_H */ +int fuzzing(tcpedit_t *tcpedit, struct pcap_pkthdr *pkthdr, u_char **pktdata); diff --git a/src/tcpedit/incremental_checksum.c b/src/tcpedit/incremental_checksum.c index 146846af8..8f98a3bef 100644 --- a/src/tcpedit/incremental_checksum.c +++ b/src/tcpedit/incremental_checksum.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2015 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,16 +19,16 @@ */ /* - * This code is heavily based on (some might even say stolen from) Mike Shiffman's + * This code is heavily based on (some might even say stolen from) Mike Shiffman's * checksumming code from Libnet 1.1.3 */ - + +#include "incremental_checksum.h" #include "config.h" #include "tcpedit.h" -#include "incremental_checksum.h" - -static inline unsigned short from32to16(unsigned int x) +static inline unsigned short +from32to16(unsigned int x) { /* add up 16-bit and 16-bit for 16+c bit */ x = (x & 0xffff) + (x >> 16); @@ -37,14 +37,15 @@ static inline unsigned short from32to16(unsigned int x) return x; } -static unsigned int do_csum(const unsigned char *buff, int len) +static unsigned int +do_csum(const unsigned char *buff, int len) { int odd; unsigned int result = 0; if (len <= 0) goto out; - odd = 1 & (unsigned long) buff; + odd = 1 & (unsigned long)buff; if (odd) { #ifdef WORDS_BIGENDIAN result = *buff; @@ -55,8 +56,8 @@ static unsigned int do_csum(const unsigned char *buff, int len) buff++; } if (len >= 2) { - if (2 & (unsigned long) buff) { - result += *(unsigned short *) buff; + if (2 & (unsigned long)buff) { + result += *(unsigned short *)buff; len -= 2; buff += 2; } @@ -64,7 +65,7 @@ static unsigned int do_csum(const unsigned char *buff, int len) const unsigned char *end = buff + ((unsigned)len & ~3); unsigned int carry = 0; do { - unsigned int w = *(unsigned int *) buff; + unsigned int w = *(unsigned int *)buff; buff += 4; result += carry; result += w; @@ -74,7 +75,7 @@ static unsigned int do_csum(const unsigned char *buff, int len) result = (result & 0xffff) + (result >> 16); } if (len & 2) { - result += *(unsigned short *) buff; + result += *(unsigned short *)buff; buff += 2; } } @@ -91,7 +92,6 @@ static unsigned int do_csum(const unsigned char *buff, int len) return result; } - /* * computes the checksum of a memory block at buff, length len, * and adds in "sum" (32-bit) @@ -104,9 +104,10 @@ static unsigned int do_csum(const unsigned char *buff, int len) * * it's best to have buff aligned on a 32-bit boundary */ -__wsum csum_partial(const void *buff, int len, __wsum wsum) +__wsum +csum_partial(const void *buff, int len, __wsum wsum) { - unsigned int sum = ( unsigned int)wsum; + unsigned int sum = (unsigned int)wsum; unsigned int result = do_csum(buff, len); /* add in old sum, and carry.. */ @@ -115,5 +116,3 @@ __wsum csum_partial(const void *buff, int len, __wsum wsum) result += 1; return (__wsum)result; } - - diff --git a/src/tcpedit/incremental_checksum.h b/src/tcpedit/incremental_checksum.h index 441c0461e..354d394a2 100644 --- a/src/tcpedit/incremental_checksum.h +++ b/src/tcpedit/incremental_checksum.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2015 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _INCREMENTAL_CHECKSUM_H_ -#define _INCREMENTAL_CHECKSUM_H_ +#pragma once +#include "defines.h" #include "config.h" /* @@ -32,18 +32,19 @@ * m : old value of a 16bit field * m' : new value of a 16bit field */ -typedef uint16_t __le16; -typedef uint16_t __be16; -typedef uint32_t __le32; -typedef uint32_t __be32; +typedef uint16_t __le16; +typedef uint16_t __be16; +typedef uint32_t __le32; +typedef uint32_t __be32; -typedef uint16_t __sum16; -typedef uint32_t __wsum; +typedef uint16_t __sum16; +typedef uint32_t __wsum; /* * Fold a partial checksum */ -static inline __sum16 csum_fold(__wsum csum) +static inline __sum16 +csum_fold(__wsum csum) { uint32_t sum = (uint32_t)csum; sum = (sum & 0xffff) + (sum >> 16); @@ -51,19 +52,22 @@ static inline __sum16 csum_fold(__wsum csum) return (__sum16)~sum; } -static inline __wsum csum_add(__wsum csum, __wsum addend) +static inline __wsum +csum_add(__wsum csum, __wsum addend) { uint32_t res = (uint32_t)csum; res += (uint32_t)addend; return (__wsum)(res + (res < (uint32_t)addend)); } -static inline __wsum csum_sub(__wsum csum, __wsum addend) +static inline __wsum +csum_sub(__wsum csum, __wsum addend) { return csum_add(csum, ~addend); } -static inline __sum16 csum16_add(__sum16 csum, __be16 addend) +static inline __sum16 +csum16_add(__sum16 csum, __be16 addend) { uint16_t res = (uint16_t)csum; @@ -71,35 +75,44 @@ static inline __sum16 csum16_add(__sum16 csum, __be16 addend) return (__sum16)(res + (res < (uint16_t)addend)); } -static inline __sum16 csum16_sub(__sum16 csum, __be16 addend) +static inline __sum16 +csum16_sub(__sum16 csum, __be16 addend) { return csum16_add(csum, ~addend); } -static inline __wsum csum_unfold(__sum16 n) +static inline __wsum +csum_unfold(__sum16 n) { return (__wsum)n; } __wsum csum_partial(const void *buff, int len, __wsum wsum); -static inline void csum_replace16(__sum16 *sum, const __be32 *from, const __be32 *to) +static inline void +csum_replace16(__sum16 *sum, const __be32 *from, const __be32 *to) { __be32 diff[] = { - ~from[0], ~from[1], ~from[2], ~from[3], - to[0], to[1], to[2], to[3], + ~from[0], + ~from[1], + ~from[2], + ~from[3], + to[0], + to[1], + to[2], + to[3], }; *sum = csum_fold(csum_partial(diff, sizeof(diff), ~csum_unfold(*sum))); } -static inline void csum_replace4(__sum16 *sum, __be32 from, __be32 to) +static inline void +csum_replace4(__sum16 *sum, __be32 from, __be32 to) { *sum = csum_fold(csum_add(csum_sub(~csum_unfold(*sum), from), to)); } -static inline void csum_replace2(__sum16 *sum, __be16 from, __be16 to) +static inline void +csum_replace2(__sum16 *sum, __be16 from, __be16 to) { *sum = ~csum16_add(csum16_sub(~(*sum), from), to); } - -#endif /* _INCREMENTAL_CHECKSUM_H_ */ diff --git a/src/tcpedit/parse_args.c b/src/tcpedit/parse_args.c index 233b35824..b18cb4106 100644 --- a/src/tcpedit/parse_args.c +++ b/src/tcpedit/parse_args.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,26 +18,23 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "parse_args.h" #include "config.h" -#include "defines.h" -#include "common.h" +#include "portmap.h" #include "tcpedit.h" #include "tcpedit_stub.h" -#include "parse_args.h" -#include "portmap.h" - -#include #include - +#include /** * returns 0 for success w/o errors * returns 1 for success w/ warnings * returns -1 for error */ -int -tcpedit_post_args(tcpedit_t *tcpedit) { - int rcode = 0; +int +tcpedit_post_args(tcpedit_t *tcpedit) +{ + int rcode; int i; uint32_t seed = 1, rand_num; @@ -46,7 +43,7 @@ tcpedit_post_args(tcpedit_t *tcpedit) { /* --pnat */ if (HAVE_OPT(PNAT)) { int ct = STACKCT_OPT(PNAT); - char **list = (char**)STACKLST_OPT(PNAT); + char **list = (char **)STACKLST_OPT(PNAT); int first = 1; tcpedit->rewrite_ip = true; @@ -54,29 +51,26 @@ tcpedit_post_args(tcpedit_t *tcpedit) { do { char *p = *list++; if (first) { - if (! parse_cidr_map(&tcpedit->cidrmap1, p)) { - tcpedit_seterr(tcpedit, - "Unable to parse first --pnat=%s", p); + if (!parse_cidr_map(&tcpedit->cidrmap1, p)) { + tcpedit_seterr(tcpedit, "Unable to parse first --pnat=%s", p); return -1; } } else { - if (! parse_cidr_map(&tcpedit->cidrmap2, p)) { - tcpedit_seterr(tcpedit, - "Unable to parse second --pnat=%s", p); + if (!parse_cidr_map(&tcpedit->cidrmap2, p)) { + tcpedit_seterr(tcpedit, "Unable to parse second --pnat=%s", p); return -1; } } - + first = 0; } while (--ct > 0); } - + /* --srcipmap */ if (HAVE_OPT(SRCIPMAP)) { tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->srcipmap, OPT_ARG(SRCIPMAP))) { - tcpedit_seterr(tcpedit, - "Unable to parse --srcipmap=%s", OPT_ARG(SRCIPMAP)); + if (!parse_cidr_map(&tcpedit->srcipmap, OPT_ARG(SRCIPMAP))) { + tcpedit_seterr(tcpedit, "Unable to parse --srcipmap=%s", OPT_ARG(SRCIPMAP)); return -1; } } @@ -84,9 +78,8 @@ tcpedit_post_args(tcpedit_t *tcpedit) { /* --dstipmap */ if (HAVE_OPT(DSTIPMAP)) { tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->dstipmap, OPT_ARG(DSTIPMAP))) { - tcpedit_seterr(tcpedit, - "Unable to parse --dstipmap=%s", OPT_ARG(DSTIPMAP)); + if (!parse_cidr_map(&tcpedit->dstipmap, OPT_ARG(DSTIPMAP))) { + tcpedit_seterr(tcpedit, "Unable to parse --dstipmap=%s", OPT_ARG(DSTIPMAP)); return -1; } } @@ -111,7 +104,7 @@ tcpedit_post_args(tcpedit_t *tcpedit) { } /* --efcs */ - if (HAVE_OPT(EFCS)) + if (HAVE_OPT(EFCS)) tcpedit->efcs = true; /* --ttl */ @@ -119,17 +112,17 @@ tcpedit_post_args(tcpedit_t *tcpedit) { long ttl; if (strchr(OPT_ARG(TTL), '+')) { - tcpedit->ttl_mode = TCPEDIT_TTL_MODE_ADD; + tcpedit->ttl_mode = TCPEDIT_TTL_MODE_ADD; } else if (strchr(OPT_ARG(TTL), '-')) { - tcpedit->ttl_mode = TCPEDIT_TTL_MODE_SUB; + tcpedit->ttl_mode = TCPEDIT_TTL_MODE_SUB; } else { - tcpedit->ttl_mode = TCPEDIT_TTL_MODE_SET; + tcpedit->ttl_mode = TCPEDIT_TTL_MODE_SET; } ttl = strtol(OPT_ARG(TTL), (char **)NULL, 10); if (ttl < 0) ttl *= -1; /* convert to positive value */ - + if (ttl > 255) { tcpedit_seterr(tcpedit, "Invalid --ttl value (must be 0-255): %ld", ttl); return -1; @@ -137,7 +130,7 @@ tcpedit_post_args(tcpedit_t *tcpedit) { tcpedit->ttl_value = (u_int8_t)ttl; } - + /* --tos */ if (HAVE_OPT(TOS)) tcpedit->tos = OPT_VALUE_TOS; @@ -145,7 +138,7 @@ tcpedit_post_args(tcpedit_t *tcpedit) { /* --tclass */ if (HAVE_OPT(TCLASS)) tcpedit->tclass = OPT_VALUE_TCLASS; - + /* --flowlabel */ if (HAVE_OPT(FLOWLABEL)) tcpedit->flowlabel = OPT_VALUE_FLOWLABEL; @@ -153,11 +146,11 @@ tcpedit_post_args(tcpedit_t *tcpedit) { /* --mtu */ if (HAVE_OPT(MTU)) tcpedit->mtu = OPT_VALUE_MTU; - + /* --mtu-trunc */ if (HAVE_OPT(MTU_TRUNC)) tcpedit->mtu_truncate = true; - + /* --skipbroadcast */ if (HAVE_OPT(SKIPBROADCAST)) tcpedit->skip_broadcast = true; @@ -189,19 +182,19 @@ tcpedit_post_args(tcpedit_t *tcpedit) { /* TCP/UDP port rewriting */ if (HAVE_OPT(PORTMAP)) { int ct = STACKCT_OPT(PORTMAP); - char **list = (char**)STACKLST_OPT(PORTMAP); + char **list = (char **)STACKLST_OPT(PORTMAP); int first = 1; tcpedit_portmap_t *portmap_head, *portmap; do { char *p = *list++; if (first) { - if (! parse_portmap(&tcpedit->portmap, p)) { + if (!parse_portmap(&tcpedit->portmap, p)) { tcpedit_seterr(tcpedit, "Unable to parse --portmap=%s", p); return -1; } } else { - if (! parse_portmap(&portmap, p)) { + if (!parse_portmap(&portmap, p)) { tcpedit_seterr(tcpedit, "Unable to parse --portmap=%s", p); return -1; } @@ -211,7 +204,6 @@ tcpedit_post_args(tcpedit_t *tcpedit) { while (portmap_head->next != NULL) portmap_head = portmap_head->next; portmap_head->next = portmap; - } first = 0; } while (--ct > 0); @@ -248,10 +240,8 @@ tcpedit_post_args(tcpedit_t *tcpedit) { if (HAVE_OPT(ENDPOINTS)) { tcpedit->rewrite_ip = true; - if (! parse_endpoints(&tcpedit->cidrmap1, &tcpedit->cidrmap2, - OPT_ARG(ENDPOINTS))) { - tcpedit_seterr(tcpedit, - "Unable to parse --endpoints=%s", OPT_ARG(ENDPOINTS)); + if (!parse_endpoints(&tcpedit->cidrmap1, &tcpedit->cidrmap2, OPT_ARG(ENDPOINTS))) { + tcpedit_seterr(tcpedit, "Unable to parse --endpoints=%s", OPT_ARG(ENDPOINTS)); return -1; } } @@ -263,9 +253,6 @@ tcpedit_post_args(tcpedit_t *tcpedit) { } else if (rcode == 1) { warnx("%s", tcpedit_geterr(tcpedit)); } - return 0; } - - diff --git a/src/tcpedit/parse_args.h b/src/tcpedit/parse_args.h index de2699f3f..c6ecd81b6 100644 --- a/src/tcpedit/parse_args.h +++ b/src/tcpedit/parse_args.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,8 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _PARSE_ARGS_H_ -#define _PARSE_ARGS_H_ +#pragma once #include "tcpedit_types.h" int tcpedit_post_args(tcpedit_t *tcpedit); - -#endif - diff --git a/src/tcpedit/plugins.h b/src/tcpedit/plugins.h index a744cc39b..02eedb0b2 100644 --- a/src/tcpedit/plugins.h +++ b/src/tcpedit/plugins.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,18 +18,14 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _PLUGINS_H_ -#define _PLUGINS_H_ +#pragma once -#include "plugins_types.h" #include "plugins_api.h" -/* - * Encoder DLT plugin authors who create API functions should add their +/* + * Encoder DLT plugin authors who create API functions should add their * API header files here */ #include "plugins/dlt_en10mb/en10mb_api.h" #include "plugins/dlt_hdlc/hdlc_api.h" #include "plugins/dlt_user/user_api.h" - -#endif diff --git a/src/tcpedit/plugins/dlt_en10mb/en10mb.c b/src/tcpedit/plugins/dlt_en10mb/en10mb.c index 671572ec7..0c24d8e5f 100644 --- a/src/tcpedit/plugins/dlt_en10mb/en10mb.c +++ b/src/tcpedit/plugins/dlt_en10mb/en10mb.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,17 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "en10mb.h" +#include "../ethernet.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "../ethernet.h" -#include "en10mb.h" - +#include +#include static char dlt_name[] = "en10mb"; static char dlt_prefix[] = "enet"; @@ -45,7 +41,7 @@ static uint16_t dlt_value = DLT_EN10MB; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_en10mb_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -64,8 +60,8 @@ dlt_en10mb_register(tcpeditdlt_t *ctx) /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_en10mb_init; @@ -79,36 +75,34 @@ dlt_en10mb_register(tcpeditdlt_t *ctx) plugin->plugin_get_layer3 = dlt_en10mb_get_layer3; plugin->plugin_merge_layer3 = dlt_en10mb_merge_layer3; plugin->plugin_get_mac = dlt_en10mb_get_mac; - + /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_en10mb_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; en10mb_config_t *config; assert(ctx); - + /* vlan tags need an additional 4 bytes */ if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "%s", "Unable to initialize unregistered plugin en10mb"); return TCPEDIT_ERROR; } - + if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(en10mb_extra_t)) { ctx->decoded_extra_size = sizeof(en10mb_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(en10mb_extra_t); @@ -118,15 +112,15 @@ dlt_en10mb_init(tcpeditdlt_t *ctx) plugin->config_size = sizeof(en10mb_config_t); plugin->config = safe_malloc(plugin->config_size); config = (en10mb_config_t *)plugin->config; - + /* init vlan user values to -1 to indicate not set */ config->vlan_tag = 65535; config->vlan_pri = 255; config->vlan_cfi = 255; - + /* VLAN protocol = 802.1q */ config->vlan_proto = ETHERTYPE_VLAN; - + return TCPEDIT_OK; /* success */ } @@ -135,7 +129,7 @@ dlt_en10mb_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_en10mb_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_en10mb_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -143,15 +137,14 @@ dlt_en10mb_cleanup(tcpeditdlt_t *ctx) assert(ctx); if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { - tcpedit_seterr(ctx->tcpedit, "Unable to cleanup unregistered plugin %s", - dlt_name); + tcpedit_seterr(ctx->tcpedit, "Unable to cleanup unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } safe_free(plugin->name); plugin->name = NULL; if (plugin->config != NULL) { - en10mb_config_t *config = (en10mb_config_t*)plugin->config; + en10mb_config_t *config = (en10mb_config_t *)plugin->config; safe_free(config->subs.entries); safe_free(plugin->config); plugin->config = NULL; @@ -164,7 +157,7 @@ dlt_en10mb_cleanup(tcpeditdlt_t *ctx) int dlt_en10mb_parse_subsmac_entry(const char *raw, en10mb_sub_entry_t *entry) { - char *candidate = safe_strdup(raw); + char *candidate = safe_strdup(raw); int parse_result = dualmac2hex(candidate, entry->target, entry->rewrite, SUBSMAC_ENTRY_LEN); free(candidate); @@ -177,9 +170,7 @@ dlt_en10mb_realloc_merge(en10mb_sub_conf_t config, en10mb_sub_entry_t *new_entri { int i; - config.entries = safe_realloc(config.entries, - (config.count + entries_count) - * sizeof(en10mb_sub_entry_t)); + config.entries = safe_realloc(config.entries, (config.count + entries_count) * sizeof(en10mb_sub_entry_t)); for (i = 0; i < entries_count; i++) { config.entries[config.count + i] = new_entries[i]; @@ -191,15 +182,14 @@ dlt_en10mb_realloc_merge(en10mb_sub_conf_t config, en10mb_sub_entry_t *new_entri int dlt_en10mb_parse_subsmac(tcpeditdlt_t *ctx, en10mb_config_t *config, const char *input) { - int input_len = strlen(input); - - int possible_entries_number = (input_len / (SUBSMAC_ENTRY_LEN + 1)) + 1; - int entry = 0; + size_t input_len = strlen(input); + size_t possible_entries_number = (input_len / (SUBSMAC_ENTRY_LEN + 1)) + 1; + int entry; en10mb_sub_entry_t *entries = safe_malloc(possible_entries_number * sizeof(en10mb_sub_entry_t)); for (entry = 0; entry < possible_entries_number; entry++) { - const int read_offset = entry + entry * SUBSMAC_ENTRY_LEN; + const size_t read_offset = entry + entry * SUBSMAC_ENTRY_LEN; if (input_len - read_offset < SUBSMAC_ENTRY_LEN) { free(entries); @@ -207,19 +197,19 @@ dlt_en10mb_parse_subsmac(tcpeditdlt_t *ctx, en10mb_config_t *config, const char return TCPEDIT_ERROR; } - switch(dlt_en10mb_parse_subsmac_entry(input + read_offset, &entries[entry])) { - case 3: - /* Both read; This is what we want */ - break; - default: - free(entries); - tcpedit_seterr(ctx->tcpedit, "Unable to parse --enet-subsmac=%s", input); - return TCPEDIT_ERROR; + switch (dlt_en10mb_parse_subsmac_entry(input + read_offset, &entries[entry])) { + case 3: + /* Both read; This is what we want */ + break; + default: + free(entries); + tcpedit_seterr(ctx->tcpedit, "Unable to parse --enet-subsmac=%s", input); + return TCPEDIT_ERROR; } } - config->subs.entries = dlt_en10mb_realloc_merge(config->subs, entries, possible_entries_number); - config->subs.count += possible_entries_number; + config->subs.entries = dlt_en10mb_realloc_merge(config->subs, entries, (int)possible_entries_number); + config->subs.count += (int)possible_entries_number; free(entries); @@ -232,7 +222,7 @@ dlt_en10mb_parse_subsmac(tcpeditdlt_t *ctx, en10mb_config_t *config, const char * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -250,7 +240,7 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) /* --subsmacs */ if (HAVE_OPT(ENET_SUBSMAC)) { int i, count = STACKCT_OPT(ENET_SUBSMAC); - char **list = (char**) STACKLST_OPT(ENET_SUBSMAC); + char **list = (char **)STACKLST_OPT(ENET_SUBSMAC); for (i = 0; i < count; i++) { int parse_result = dlt_en10mb_parse_subsmac(ctx, config, list[i]); if (parse_result == TCPEDIT_ERROR) { @@ -261,81 +251,81 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) /* --mac-seed */ if (HAVE_OPT(ENET_MAC_SEED)) { - int i,j; + int i, j; config->random.set = OPT_VALUE_ENET_MAC_SEED; for (i = 0; i < 6; i++) { - config->random.mask[i] = (u_char)tcpr_random(&config->random.set) % 256; - /* only unique numbers */ - for (j = 0; j < i; j++) { - if (config->random.mask[i] == config->random.mask[j]) { - i--; - break; + config->random.mask[i] = (u_char)tcpr_random(&config->random.set) % 256; + /* only unique numbers */ + for (j = 0; j < i; j++) { + if (config->random.mask[i] == config->random.mask[j]) { + i--; + break; + } } - } } if (HAVE_OPT(ENET_MAC_SEED_KEEP_BYTES)) { - config->random.keep = OPT_VALUE_ENET_MAC_SEED_KEEP_BYTES; + config->random.keep = OPT_VALUE_ENET_MAC_SEED_KEEP_BYTES; } } /* --dmac */ if (HAVE_OPT(ENET_DMAC)) { int macparse; - macparse = dualmac2hex(OPT_ARG(ENET_DMAC), config->intf1_dmac, - config->intf2_dmac, strlen(OPT_ARG(ENET_DMAC))); + macparse = dualmac2hex(OPT_ARG(ENET_DMAC), + config->intf1_dmac, + config->intf2_dmac, + (int)strlen(OPT_ARG(ENET_DMAC))); switch (macparse) { - case 1: - config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; - break; - case 2: - config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; - break; - case 3: - config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; - config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; - break; - case 0: - /* nothing to do */ - break; - default: - tcpedit_seterr(ctx->tcpedit, - "Unable to parse --enet-dmac=%s", OPT_ARG(ENET_DMAC)); - return TCPEDIT_ERROR; - break; + case 1: + config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; + break; + case 2: + config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; + break; + case 3: + config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; + config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; + break; + case 0: + /* nothing to do */ + break; + default: + tcpedit_seterr(ctx->tcpedit, "Unable to parse --enet-dmac=%s", OPT_ARG(ENET_DMAC)); + return TCPEDIT_ERROR; } plugin->requires -= PLUGIN_MASK_DSTADDR; - } /* --smac */ if (HAVE_OPT(ENET_SMAC)) { int macparse; - macparse = dualmac2hex(OPT_ARG(ENET_SMAC), config->intf1_smac, - config->intf2_smac, strlen(OPT_ARG(ENET_SMAC))); + macparse = dualmac2hex(OPT_ARG(ENET_SMAC), + config->intf1_smac, + config->intf2_smac, + (int)strlen(OPT_ARG(ENET_SMAC))); switch (macparse) { - case 1: - config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; - break; - case 2: - config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; - break; - case 3: - config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; - config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; - break; - case 0: - /* nothing to do */ - break; - default: - tcpedit_seterr(ctx->tcpedit, - "Unable to parse --enet-smac=%s", OPT_ARG(ENET_SMAC)); - return TCPEDIT_ERROR; - break; + case 1: + config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; + break; + case 2: + config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; + break; + case 3: + config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; + config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; + break; + case 0: + /* nothing to do */ + break; + default: + tcpedit_seterr(ctx->tcpedit, "Unable to parse --enet-smac=%s", OPT_ARG(ENET_SMAC)); + return TCPEDIT_ERROR; } + plugin->requires -= PLUGIN_MASK_SRCADDR; } @@ -354,10 +344,11 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) if (config->vlan != TCPEDIT_VLAN_OFF) { if (config->vlan == TCPEDIT_VLAN_ADD) { - if (! HAVE_OPT(ENET_VLAN_TAG)) { - tcpedit_seterr(ctx->tcpedit, "%s", - "Must specify a new 802.1 VLAN tag if vlan " - "mode is add"); + if (!HAVE_OPT(ENET_VLAN_TAG)) { + tcpedit_seterr(ctx->tcpedit, + "%s", + "Must specify a new 802.1 VLAN tag if vlan " + "mode is add"); return TCPEDIT_ERROR; } @@ -366,14 +357,13 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) */ config->vlan_tag = OPT_VALUE_ENET_VLAN_TAG; - dbgx(1, "We will %s 802.1q headers", - config->vlan == TCPEDIT_VLAN_DEL ? "delete" : "add/modify"); + dbgx(1, "We will %s 802.1q headers", config->vlan == TCPEDIT_VLAN_DEL ? "delete" : "add/modify"); - if (HAVE_OPT(ENET_VLAN_PRI)) - config->vlan_pri = OPT_VALUE_ENET_VLAN_PRI; + if (HAVE_OPT(ENET_VLAN_PRI)) + config->vlan_pri = OPT_VALUE_ENET_VLAN_PRI; - if (HAVE_OPT(ENET_VLAN_CFI)) - config->vlan_cfi = OPT_VALUE_ENET_VLAN_CFI; + if (HAVE_OPT(ENET_VLAN_CFI)) + config->vlan_cfi = OPT_VALUE_ENET_VLAN_CFI; } if (HAVE_OPT(ENET_VLAN_PROTO)) { @@ -382,15 +372,13 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) } else if (strcasecmp(OPT_ARG(ENET_VLAN_PROTO), "802.1ad") == 0) { config->vlan_proto = ETHERTYPE_Q_IN_Q; } else { - tcpedit_seterr(ctx->tcpedit, "VLAN protocol \"%s\" is invalid", - OPT_ARG(ENET_VLAN_PROTO)); + tcpedit_seterr(ctx->tcpedit, "VLAN protocol \"%s\" is invalid", OPT_ARG(ENET_VLAN_PROTO)); return TCPEDIT_ERROR; } } } } - return TCPEDIT_OK; /* success */ } @@ -398,8 +386,8 @@ dlt_en10mb_parse_opts(tcpeditdlt_t *ctx) * Function to decode the layer 2 header in the packet * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { struct tcpr_ethernet_hdr *eth_hdr; uint32_t pkt_len = pktlen; @@ -409,31 +397,24 @@ dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) uint32_t l2offset; uint32_t l2len; int res; - + assert(ctx); assert(packet); extra = (en10mb_extra_t *)ctx->decoded_extra; if (ctx->decoded_extra_size < sizeof(*extra)) { - tcpedit_seterr(ctx->tcpedit, "Decode extra size too short! %d < %u", - ctx->decoded_extra_size, sizeof(*extra)); + tcpedit_seterr(ctx->tcpedit, "Decode extra size too short! %d < %u", ctx->decoded_extra_size, sizeof(*extra)); return TCPEDIT_ERROR; } - res = get_l2len_protocol(packet, - pkt_len, - dlt_value, - &protcol, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(packet, pkt_len, dlt_value, &protcol, &l2len, &l2offset, &vlan_offset); if (res == -1) return TCPEDIT_ERROR; if (pkt_len < TCPR_802_3_H + l2offset) return TCPEDIT_ERROR; - eth_hdr = (struct tcpr_ethernet_hdr*)(packet + l2offset); + eth_hdr = (struct tcpr_ethernet_hdr *)(packet + l2offset); protcol = ntohs(eth_hdr->ether_type); memcpy(&(ctx->dstaddr.ethernet), eth_hdr, ETHER_ADDR_LEN); memcpy(&(ctx->srcaddr.ethernet), &(eth_hdr->ether_shost), ETHER_ADDR_LEN); @@ -442,7 +423,7 @@ dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (vlan_offset != 0) { if (vlan_offset == l2offset + sizeof(*eth_hdr)) { vlan_hdr_t *vlan_hdr; - vlan_hdr = (vlan_hdr_t*)(packet + vlan_offset); + vlan_hdr = (vlan_hdr_t *)(packet + vlan_offset); if (pkt_len < vlan_offset + sizeof(*vlan_hdr)) { tcpedit_seterr(ctx->tcpedit, "Frame is too short for VLAN headers! %d < %d", @@ -472,8 +453,8 @@ dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) } ctx->proto = ntohs(protcol); - ctx->l2offset = l2offset; - ctx->l2len = l2len; + ctx->l2offset = (int)l2offset; + ctx->l2len = (int)l2len; return TCPEDIT_OK; /* success */ } @@ -482,7 +463,7 @@ dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) { struct tcpr_802_1q_hdr *vlan_hdr; @@ -490,16 +471,16 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) tcpeditdlt_plugin_t *plugin; en10mb_config_t *config; en10mb_extra_t *extra; - int newl2len = 0; - int oldl2len = 0; + uint32_t newl2len = 0; + uint32_t oldl2len = 0; assert(ctx); assert(packet); if (pktlen < TCPR_802_3_H) { - tcpedit_seterr(ctx->tcpedit, - "Unable to process packet #" COUNTER_SPEC " since it is less then 14 bytes.", - ctx->tcpedit->runtime.packetnum); + tcpedit_seterr(ctx->tcpedit, + "Unable to process packet #" COUNTER_SPEC " since it is less then 14 bytes.", + ctx->tcpedit->runtime.packetnum); return TCPEDIT_ERROR; } @@ -545,23 +526,27 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) if (pktlen < newl2len || pktlen + newl2len - ctx->l2len > MAXPACKET) { tcpedit_seterr(ctx->tcpedit, - "Unable to process packet #" COUNTER_SPEC " since its new length is %d bytes.", - ctx->tcpedit->runtime.packetnum, newl2len); + "Unable to process packet #" COUNTER_SPEC " since its new length is %d bytes.", + ctx->tcpedit->runtime.packetnum, + newl2len); return TCPEDIT_ERROR; } if (pktlen < ctx->l2len) { tcpedit_seterr(ctx->tcpedit, - "Unable to process packet #" COUNTER_SPEC " since its new length less then %d L2 bytes.", - ctx->tcpedit->runtime.packetnum, ctx->l2len); + "Unable to process packet #" COUNTER_SPEC " since its new length less then %d L2 bytes.", + ctx->tcpedit->runtime.packetnum, + ctx->l2len); return TCPEDIT_ERROR; } /* Make space for our new L2 header */ if (newl2len > 0 && newl2len != oldl2len) { if (pktlen + (newl2len - oldl2len) > MAXPACKET) { - tcpedit_seterr(ctx->tcpedit, "New frame too big, new length %d exceeds %d", - pktlen + (newl2len - ctx->l2len), MAXPACKET); + tcpedit_seterr(ctx->tcpedit, + "New frame too big, new length %d exceeds %d", + pktlen + (newl2len - ctx->l2len), + MAXPACKET); return TCPEDIT_ERROR; } @@ -569,22 +554,21 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) } /* update the total packet length */ - pktlen += newl2len - oldl2len; - ctx->l2len += newl2len - oldl2len; - + pktlen += (int)(newl2len - oldl2len); + ctx->l2len += (int)(newl2len - oldl2len); + /* set the src & dst address as the first 12 bytes */ eth = (struct tcpr_ethernet_hdr *)(packet + ctx->l2offset); - + if (dir == TCPR_DIR_C2S) { /* copy user supplied SRC MAC if provided or from original packet */ if (config->mac_mask & TCPEDIT_MAC_MASK_SMAC1) { - if ((ctx->addr_type == ETHERNET && - ((ctx->skip_broadcast && - is_unicast_ethernet(ctx, ctx->srcaddr.ethernet)) || !ctx->skip_broadcast)) - || ctx->addr_type != ETHERNET) { + if ((ctx->addr_type == ETHERNET && + ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->srcaddr.ethernet)) || !ctx->skip_broadcast)) || + ctx->addr_type != ETHERNET) { memcpy(eth->ether_shost, config->intf1_smac, ETHER_ADDR_LEN); } else { - memcpy(eth->ether_shost, ctx->srcaddr.ethernet, ETHER_ADDR_LEN); + memcpy(eth->ether_shost, ctx->srcaddr.ethernet, ETHER_ADDR_LEN); } } else if (ctx->addr_type == ETHERNET) { extra->src_modified = memcmp(eth->ether_shost, ctx->srcaddr.ethernet, ETHER_ADDR_LEN); @@ -594,11 +578,11 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) return TCPEDIT_ERROR; } - /* copy user supplied DMAC MAC if provided or from original packet */ + /* copy user supplied DMAC MAC if provided or from original packet */ if (config->mac_mask & TCPEDIT_MAC_MASK_DMAC1) { - if ((ctx->addr_type == ETHERNET && - ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->dstaddr.ethernet)) || !ctx->skip_broadcast)) - || ctx->addr_type != ETHERNET) { + if ((ctx->addr_type == ETHERNET && + ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->dstaddr.ethernet)) || !ctx->skip_broadcast)) || + ctx->addr_type != ETHERNET) { memcpy(eth->ether_dhost, config->intf1_dmac, ETHER_ADDR_LEN); } else { memcpy(eth->ether_dhost, ctx->dstaddr.ethernet, ETHER_ADDR_LEN); @@ -608,15 +592,15 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) memcpy(eth->ether_dhost, ctx->dstaddr.ethernet, ETHER_ADDR_LEN); } else { tcpedit_seterr(ctx->tcpedit, "%s", "Please provide a destination address"); - return TCPEDIT_ERROR; + return TCPEDIT_ERROR; } - + } else if (dir == TCPR_DIR_S2C) { /* copy user supplied SRC MAC if provided or from original packet */ if (config->mac_mask & TCPEDIT_MAC_MASK_SMAC2) { - if ((ctx->addr_type == ETHERNET && - ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->srcaddr.ethernet)) || !ctx->skip_broadcast)) - || ctx->addr_type != ETHERNET) { + if ((ctx->addr_type == ETHERNET && + ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->srcaddr.ethernet)) || !ctx->skip_broadcast)) || + ctx->addr_type != ETHERNET) { memcpy(eth->ether_shost, config->intf2_smac, ETHER_ADDR_LEN); } else { memcpy(eth->ether_shost, ctx->srcaddr.ethernet, ETHER_ADDR_LEN); @@ -630,9 +614,9 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) /* copy user supplied DMAC MAC if provided or from original packet */ if (config->mac_mask & TCPEDIT_MAC_MASK_DMAC2) { - if ((ctx->addr_type == ETHERNET && - ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->dstaddr.ethernet)) || !ctx->skip_broadcast)) - || ctx->addr_type != ETHERNET) { + if ((ctx->addr_type == ETHERNET && + ((ctx->skip_broadcast && is_unicast_ethernet(ctx, ctx->dstaddr.ethernet)) || !ctx->skip_broadcast)) || + ctx->addr_type != ETHERNET) { memcpy(eth->ether_dhost, config->intf2_dmac, ETHER_ADDR_LEN); } else { memcpy(eth->ether_dhost, ctx->dstaddr.ethernet, ETHER_ADDR_LEN); @@ -644,65 +628,62 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) return TCPEDIT_ERROR; } - } else { tcpedit_seterr(ctx->tcpedit, "%s", "Encoders only support C2S or C2S!"); return TCPEDIT_ERROR; } if (config->subs.entries) { - int entry = 0; - for (entry = 0 ; entry < config->subs.count; entry++) { - en10mb_sub_entry_t *current = &config->subs.entries[entry]; + int entry = 0; + for (entry = 0; entry < config->subs.count; entry++) { + en10mb_sub_entry_t *current = &config->subs.entries[entry]; - if (!memcmp(eth->ether_dhost, current->target, ETHER_ADDR_LEN)) { - memcpy(eth->ether_dhost, current->rewrite, ETHER_ADDR_LEN); - } + if (!memcmp(eth->ether_dhost, current->target, ETHER_ADDR_LEN)) { + memcpy(eth->ether_dhost, current->rewrite, ETHER_ADDR_LEN); + } - if (!memcmp(eth->ether_shost, current->target, ETHER_ADDR_LEN)) { - memcpy(eth->ether_shost, current->rewrite, ETHER_ADDR_LEN); + if (!memcmp(eth->ether_shost, current->target, ETHER_ADDR_LEN)) { + memcpy(eth->ether_shost, current->rewrite, ETHER_ADDR_LEN); + } } - } } if (config->random.set) { - int unicast_src = is_unicast_ethernet(ctx, eth->ether_shost); - int unicast_dst = is_unicast_ethernet(ctx, eth->ether_dhost); - - int i = config->random.keep; - for ( ; i < ETHER_ADDR_LEN; i++) { - eth->ether_shost[i] = MAC_MASK_APPLY(eth->ether_shost[i], config->random.mask[i], unicast_src); - eth->ether_dhost[i] = MAC_MASK_APPLY(eth->ether_dhost[i], config->random.mask[i], unicast_dst); - } - - /* avoid making unicast packets multicast */ - if (!config->random.keep) { - eth->ether_shost[0] &= ~(0x01 * unicast_src); - eth->ether_dhost[0] &= ~(0x01 * unicast_dst); - } + int unicast_src = is_unicast_ethernet(ctx, eth->ether_shost); + int unicast_dst = is_unicast_ethernet(ctx, eth->ether_dhost); + + int i = config->random.keep; + for (; i < ETHER_ADDR_LEN; i++) { + eth->ether_shost[i] = MAC_MASK_APPLY(eth->ether_shost[i], config->random.mask[i], unicast_src); + eth->ether_dhost[i] = MAC_MASK_APPLY(eth->ether_dhost[i], config->random.mask[i], unicast_dst); + } + + /* avoid making unicast packets multicast */ + if (!config->random.keep) { + eth->ether_shost[0] &= ~(0x01 * unicast_src); + eth->ether_dhost[0] &= ~(0x01 * unicast_dst); + } } - if (config->vlan == TCPEDIT_VLAN_ADD - || (config->vlan == TCPEDIT_VLAN_OFF && extra->vlan)) { + if (config->vlan == TCPEDIT_VLAN_ADD || (config->vlan == TCPEDIT_VLAN_OFF && extra->vlan)) { vlan_hdr = (struct tcpr_802_1q_hdr *)(packet + extra->vlan_offset); if (config->vlan == TCPEDIT_VLAN_ADD) { struct tcpr_ethernet_hdr *eth_hdr; - eth_hdr = (struct tcpr_ethernet_hdr*)(packet + ctx->l2offset); + eth_hdr = (struct tcpr_ethernet_hdr *)(packet + ctx->l2offset); eth_hdr->ether_type = htons(config->vlan_proto); vlan_hdr->vlan_tpid = htons(ctx->proto_vlan_tag); } /* are we changing VLAN info? */ if (config->vlan_tag < 65535) { - vlan_hdr->vlan_tci = - htons((uint16_t)config->vlan_tag & TCPR_802_1Q_VIDMASK); + vlan_hdr->vlan_tci = htons((uint16_t)config->vlan_tag & TCPR_802_1Q_VIDMASK); } else if (extra->vlan) { vlan_hdr->vlan_tci = htons(extra->vlan_tag); } else { tcpedit_seterr(ctx->tcpedit, "%s", "Non-VLAN tagged packet requires --enet-vlan-tag"); return TCPEDIT_ERROR; } - + if (config->vlan_pri < 255) { vlan_hdr->vlan_tci += htons((uint16_t)config->vlan_pri << 13); } else if (extra->vlan) { @@ -729,12 +710,11 @@ dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) return pktlen; } - /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { uint32_t _U_ vlan_offset; uint16_t ether_type; @@ -744,19 +724,12 @@ dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) assert(ctx); assert(packet); - if (pktlen < (int) sizeof(struct tcpr_ethernet_hdr)) { - tcpedit_seterr(ctx->tcpedit, "Ethernet packet length too short: %d", - pktlen); + if (pktlen < (int)sizeof(struct tcpr_ethernet_hdr)) { + tcpedit_seterr(ctx->tcpedit, "Ethernet packet length too short: %d", pktlen); return TCPEDIT_ERROR; } - res = get_l2len_protocol(packet, - pktlen, - dlt_value, - ðer_type, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(packet, pktlen, dlt_value, ðer_type, &l2len, &l2offset, &vlan_offset); if (res == -1) return TCPEDIT_ERROR; @@ -767,12 +740,12 @@ dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_en10mb_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_en10mb_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); assert(packet); - + l2len = dlt_en10mb_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; @@ -785,17 +758,17 @@ dlt_en10mb_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * ip: 32-bit IP address in network order * mac: pointer to packet ethernet source or destination address (6 bytes) */ -static void dlt_en10mb_ipv4_multicast_mac_update(const uint32_t ip, - uint8_t mac[]) +static void +dlt_en10mb_ipv4_multicast_mac_update(const uint32_t ip, uint8_t mac[]) { /* only modify multicast packets */ if ((ntohl(ip) & 0xf0000000) != 0xe0000000) return; mac[2] = (ntohl(ip) & 0x7fffff); - mac[0] =0x01; - mac[1] =0x0; - mac[2] =0x5e; + mac[0] = 0x01; + mac[1] = 0x0; + mac[2] = 0x5e; } /* @@ -803,11 +776,11 @@ static void dlt_en10mb_ipv4_multicast_mac_update(const uint32_t ip, * ip6: 128-bit IPv6 address in network order * mac: pointer to packet ethernet source or destination address (6 bytes) */ -static void dlt_en10mb_ipv6_multicast_mac_update(const struct tcpr_in6_addr *ip6, - uint8_t mac[]) +static void +dlt_en10mb_ipv6_multicast_mac_update(const struct tcpr_in6_addr *ip6, uint8_t mac[]) { /* only modify multicast packets */ - if (ip6->tcpr_s6_addr[0] == 0xff) + if (ip6->tcpr_s6_addr[0] != 0xff) return; mac[0] = 0x33; @@ -825,11 +798,7 @@ static void dlt_en10mb_ipv6_multicast_mac_update(const struct tcpr_in6_addr *ip6 * like SPARC */ u_char * -dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { en10mb_extra_t *extra; struct tcpr_ethernet_hdr *eth; @@ -838,7 +807,7 @@ dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, assert(ctx); assert(packet); - + l2len = dlt_en10mb_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; @@ -850,26 +819,22 @@ dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, /* modify source/destination MAC if source/destination IP is multicast */ if (ipv4_data) { if ((size_t)pktlen >= sizeof(*eth) + sizeof(struct tcpr_ipv4_hdr)) { - struct tcpr_ipv4_hdr *ip_hdr = (struct tcpr_ipv4_hdr*)ipv4_data; + struct tcpr_ipv4_hdr *ip_hdr = (struct tcpr_ipv4_hdr *)ipv4_data; if (!extra->src_modified) - dlt_en10mb_ipv4_multicast_mac_update(ip_hdr->ip_src.s_addr, - eth->ether_shost); + dlt_en10mb_ipv4_multicast_mac_update(ip_hdr->ip_src.s_addr, eth->ether_shost); if (!extra->dst_modified) - dlt_en10mb_ipv4_multicast_mac_update(ip_hdr->ip_dst.s_addr, - eth->ether_dhost); + dlt_en10mb_ipv4_multicast_mac_update(ip_hdr->ip_dst.s_addr, eth->ether_dhost); } return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data, l2len); } else if (ipv6_data) { if ((size_t)pktlen >= sizeof(*eth) + sizeof(struct tcpr_ipv6_hdr)) { - struct tcpr_ipv6_hdr *ip6_hdr = (struct tcpr_ipv6_hdr*)ipv6_data; + struct tcpr_ipv6_hdr *ip6_hdr = (struct tcpr_ipv6_hdr *)ipv6_data; if (!extra->src_modified) - dlt_en10mb_ipv6_multicast_mac_update(&ip6_hdr->ip_src, - eth->ether_shost); + dlt_en10mb_ipv6_multicast_mac_update(&ip6_hdr->ip_src, eth->ether_shost); if (!extra->dst_modified) - dlt_en10mb_ipv6_multicast_mac_update(&ip6_hdr->ip_dst, - eth->ether_dhost); + dlt_en10mb_ipv6_multicast_mac_update(&ip6_hdr->ip_dst, eth->ether_dhost); } return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv6_data, l2len); } @@ -880,9 +845,9 @@ dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_en10mb_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_en10mb_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -890,37 +855,31 @@ dlt_en10mb_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *p return NULL; /* FIXME: return a ptr to the source or dest mac address. */ - switch(mac) { + switch (mac) { case SRC_MAC: memcpy(ctx->srcmac, &packet[6], ETHER_ADDR_LEN); - return(ctx->srcmac); - break; - + return (ctx->srcmac); case DST_MAC: memcpy(ctx->dstmac, packet, ETHER_ADDR_LEN); - return(ctx->dstmac); - break; - + return (ctx->dstmac); default: errx(1, "Invalid tcpeditdlt_mac_type_t: %d", mac); } - return(NULL); } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_en10mb_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_en10mb_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int l2len; - + assert(ctx); assert(packet); if (pktlen < (int)sizeof(eth_hdr_t)) { - tcpedit_seterr(ctx->tcpedit, "dlt_en10mb_l2len: pktlen=%u is less than size of Ethernet header", - pktlen); + tcpedit_seterr(ctx->tcpedit, "dlt_en10mb_l2len: pktlen=%u is less than size of Ethernet header", pktlen); return TCPEDIT_ERROR; } @@ -928,8 +887,7 @@ dlt_en10mb_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (l2len > 0) { if (pktlen < l2len) { /* can happen if fuzzing is enabled */ - tcpedit_seterr(ctx->tcpedit, "dlt_en10mb_l2len: pktlen=%u is less than l2len=%u", - pktlen, l2len); + tcpedit_seterr(ctx->tcpedit, "dlt_en10mb_l2len: pktlen=%u is less than l2len=%u", pktlen, l2len); return TCPEDIT_ERROR; } diff --git a/src/tcpedit/plugins/dlt_en10mb/en10mb.h b/src/tcpedit/plugins/dlt_en10mb/en10mb.h index 2b842476c..efc1e5500 100644 --- a/src/tcpedit/plugins/dlt_en10mb/en10mb.h +++ b/src/tcpedit/plugins/dlt_en10mb/en10mb.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_en10mb_H_ -#define _DLT_en10mb_H_ +#pragma once #include "plugins_types.h" #include "en10mb_types.h" @@ -38,17 +37,17 @@ int dlt_en10mb_register(tcpeditdlt_t *ctx); int dlt_en10mb_init(tcpeditdlt_t *ctx); int dlt_en10mb_cleanup(tcpeditdlt_t *ctx); int dlt_en10mb_parse_opts(tcpeditdlt_t *ctx); -int dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_en10mb_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_en10mb_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_en10mb_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); +int dlt_en10mb_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_en10mb_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); u_char *dlt_en10mb_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, - const int pktlen, + int pktlen, u_char *ipv4_data, u_char *ipv6_data); -int dlt_en10mb_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_en10mb_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_en10mb_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_en10mb_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); tcpeditdlt_l2addr_type_t dlt_en10mb_l2addr_type(void); @@ -56,6 +55,3 @@ tcpeditdlt_l2addr_type_t dlt_en10mb_l2addr_type(void); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_en10mb/en10mb_api.c b/src/tcpedit/plugins/dlt_en10mb/en10mb_api.c index d8102424d..6fa31a863 100644 --- a/src/tcpedit/plugins/dlt_en10mb/en10mb_api.c +++ b/src/tcpedit/plugins/dlt_en10mb/en10mb_api.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,26 +18,23 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - +#include "en10mb_api.h" #include "defines.h" #include "common.h" - -#include "tcpedit.h" #include "en10mb.h" - -#include "en10mb_api.h" +#include "tcpedit.h" +#include +#include /** * \brief Allows you to rewrite source & destination MAC addresses * - * Pass the new MAC address in null terminated string format - * "00:00:00:00:00:00\0" as well as the mac_mask value for which mac - * address to rewrite. You can call this function up to 4 times, + * Pass the new MAC address in null terminated string format + * "00:00:00:00:00:00\0" as well as the mac_mask value for which mac + * address to rewrite. You can call this function up to 4 times, * once for each mac_mask value. */ -int +int tcpedit_en10mb_set_mac(tcpedit_t *tcpedit, char *mac, tcpedit_mac_mask mask) { u_char mac_addr[ETHER_ADDR_LEN]; @@ -58,37 +55,45 @@ tcpedit_en10mb_set_mac(tcpedit_t *tcpedit, char *mac, tcpedit_mac_mask mask) mac2hex(mac, mac_addr, strlen(mac)); switch (mask) { - case TCPEDIT_MAC_MASK_DMAC1: - config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; - memcpy(config->intf1_dmac, mac_addr, ETHER_ADDR_LEN); - break; - - case TCPEDIT_MAC_MASK_DMAC2: - config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; - memcpy(config->intf2_dmac, mac_addr, ETHER_ADDR_LEN); - break; - - case TCPEDIT_MAC_MASK_SMAC1: - config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; - memcpy(config->intf1_smac, mac_addr, ETHER_ADDR_LEN); - break; - - case TCPEDIT_MAC_MASK_SMAC2: - config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; - memcpy(config->intf2_smac, mac_addr, ETHER_ADDR_LEN); - break; + case TCPEDIT_MAC_MASK_DMAC1: + config->mac_mask += TCPEDIT_MAC_MASK_DMAC1; + memcpy(config->intf1_dmac, mac_addr, ETHER_ADDR_LEN); + break; + + case TCPEDIT_MAC_MASK_DMAC2: + config->mac_mask += TCPEDIT_MAC_MASK_DMAC2; + memcpy(config->intf2_dmac, mac_addr, ETHER_ADDR_LEN); + break; + + case TCPEDIT_MAC_MASK_SMAC1: + config->mac_mask += TCPEDIT_MAC_MASK_SMAC1; + memcpy(config->intf1_smac, mac_addr, ETHER_ADDR_LEN); + break; + + case TCPEDIT_MAC_MASK_SMAC2: + config->mac_mask += TCPEDIT_MAC_MASK_SMAC2; + memcpy(config->intf2_smac, mac_addr, ETHER_ADDR_LEN); + break; } switch (mask) { - case TCPEDIT_MAC_MASK_DMAC1: - case TCPEDIT_MAC_MASK_DMAC2: - plugin->requires = plugin->requires & (0xffffffff ^ PLUGIN_MASK_DSTADDR); - break; - - case TCPEDIT_MAC_MASK_SMAC1: - case TCPEDIT_MAC_MASK_SMAC2: - plugin->requires = plugin->requires & (0xffffffff ^ PLUGIN_MASK_SRCADDR); - break; + case TCPEDIT_MAC_MASK_DMAC1: + case TCPEDIT_MAC_MASK_DMAC2: + plugin-> + requires + = plugin-> + requires + & (0xffffffff ^ PLUGIN_MASK_DSTADDR); + break; + + case TCPEDIT_MAC_MASK_SMAC1: + case TCPEDIT_MAC_MASK_SMAC2: + plugin-> + requires + = plugin-> + requires + & (0xffffffff ^ PLUGIN_MASK_SRCADDR); + break; } return TCPEDIT_OK; @@ -97,7 +102,7 @@ tcpedit_en10mb_set_mac(tcpedit_t *tcpedit, char *mac, tcpedit_mac_mask mask) /** * Sets the 802.1q VLAN mode (add, delete, etc..) */ -int +int tcpedit_en10mb_set_vlan_mode(tcpedit_t *tcpedit, tcpedit_vlan vlan) { tcpeditdlt_t *ctx; @@ -113,14 +118,14 @@ tcpedit_en10mb_set_vlan_mode(tcpedit_t *tcpedit, tcpedit_vlan vlan) config = (en10mb_config_t *)plugin->config; config->vlan = vlan; - + return TCPEDIT_OK; } /** * Sets the VLAN tag value in add or edit mode */ -int +int tcpedit_en10mb_set_vlan_tag(tcpedit_t *tcpedit, uint16_t tag) { tcpeditdlt_t *ctx; @@ -136,14 +141,14 @@ tcpedit_en10mb_set_vlan_tag(tcpedit_t *tcpedit, uint16_t tag) config = (en10mb_config_t *)plugin->config; config->vlan_tag = tag; - + return TCPEDIT_OK; } /** * Sets the VLAN priority field in add or edit mode */ -int +int tcpedit_en10mb_set_vlan_priority(tcpedit_t *tcpedit, uint8_t priority) { tcpeditdlt_t *ctx; @@ -159,14 +164,14 @@ tcpedit_en10mb_set_vlan_priority(tcpedit_t *tcpedit, uint8_t priority) config = (en10mb_config_t *)plugin->config; config->vlan_pri = priority; - + return TCPEDIT_OK; } /** * Sets the VLAN CFI field in add or edit mode */ -int +int tcpedit_en10mb_set_vlan_cfi(tcpedit_t *tcpedit, uint8_t cfi) { tcpeditdlt_t *ctx; @@ -182,6 +187,6 @@ tcpedit_en10mb_set_vlan_cfi(tcpedit_t *tcpedit, uint8_t cfi) config = (en10mb_config_t *)plugin->config; config->vlan_cfi = cfi; - + return TCPEDIT_OK; } diff --git a/src/tcpedit/plugins/dlt_en10mb/en10mb_api.h b/src/tcpedit/plugins/dlt_en10mb/en10mb_api.h index 3ac753b89..20940e23b 100644 --- a/src/tcpedit/plugins/dlt_en10mb/en10mb_api.h +++ b/src/tcpedit/plugins/dlt_en10mb/en10mb_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,22 +18,20 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_en10mb_API_H_ -#define _DLT_en10mb_API_H_ +#pragma once -#include "tcpedit_types.h" -#include "plugins_types.h" #include "en10mb_types.h" +#include "plugins_types.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { #endif - /** * \brief EN10MB (Ethernet) Plugin API functions for modifying the 802.3 Ethernet header * - * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR + * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR * if there is a problem. You can use tcpedit_geterr() to get the reason * for the failure */ @@ -46,6 +44,3 @@ int tcpedit_en10mb_set_vlan_cfi(tcpedit_t *tcpedit, u_int8_t cfi); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_en10mb/en10mb_types.h b/src/tcpedit/plugins/dlt_en10mb/en10mb_types.h index c4cd831db..77cedacec 100644 --- a/src/tcpedit/plugins/dlt_en10mb/en10mb_types.h +++ b/src/tcpedit/plugins/dlt_en10mb/en10mb_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_en10mb_TYPES_H_ -#define _DLT_en10mb_TYPES_H_ +#pragma once #include "plugins_types.h" @@ -29,7 +28,7 @@ extern "C" { typedef struct { int vlan; /* set to 1 for vlan_ fields being filled out */ - + u_int32_t vlan_offset; u_int16_t vlan_tag; u_int16_t vlan_pri; @@ -48,8 +47,8 @@ typedef enum { typedef enum { TCPEDIT_VLAN_OFF = 0, - TCPEDIT_VLAN_DEL, /* strip 802.1q and rewrite as standard 802.3 Ethernet */ - TCPEDIT_VLAN_ADD /* add/replace 802.1q vlan tag */ + TCPEDIT_VLAN_DEL, /* strip 802.1q and rewrite as standard 802.3 Ethernet */ + TCPEDIT_VLAN_ADD /* add/replace 802.1q vlan tag */ } tcpedit_vlan; typedef struct { @@ -79,25 +78,20 @@ typedef struct { en10mb_random_conf_t random; /* we use the mask to say which are valid values */ - tcpedit_mac_mask mac_mask; + tcpedit_mac_mask mac_mask; /* 802.1q VLAN tag stuff */ tcpedit_vlan vlan; /* user defined values, -1 means unset! */ u_int16_t vlan_tag; - u_int8_t vlan_pri; - u_int8_t vlan_cfi; + u_int8_t vlan_pri; + u_int8_t vlan_cfi; /* 802.1Q/802.1ad VLAN Q-in-Q - 0 means 802.1Q */ u_int16_t vlan_proto; } en10mb_config_t; - - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_hdlc/hdlc.c b/src/tcpedit/plugins/dlt_hdlc/hdlc.c index 37ac448f6..d2cbcda12 100644 --- a/src/tcpedit/plugins/dlt_hdlc/hdlc.c +++ b/src/tcpedit/plugins/dlt_hdlc/hdlc.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "hdlc.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "hdlc.h" +#include +#include static char dlt_name[] = "hdlc"; static char _U_ dlt_prefix[] = "hdlc"; @@ -43,7 +40,7 @@ static uint16_t dlt_value = DLT_C_HDLC; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_hdlc_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -54,16 +51,18 @@ dlt_hdlc_register(tcpeditdlt_t *ctx) /* FIXME: set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO; - plugin->requires += PLUGIN_MASK_PROTO; + plugin-> + requires + += PLUGIN_MASK_PROTO; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_hdlc_init; @@ -77,36 +76,34 @@ dlt_hdlc_register(tcpeditdlt_t *ctx) plugin->plugin_get_layer3 = dlt_hdlc_get_layer3; plugin->plugin_merge_layer3 = dlt_hdlc_merge_layer3; plugin->plugin_get_mac = dlt_hdlc_get_mac; - + /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_hdlc_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; hdlc_config_t *config; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + /* allocate memory for our deocde extra data */ if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(hdlc_extra_t)) { ctx->decoded_extra_size = sizeof(hdlc_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(hdlc_extra_t); @@ -129,7 +126,7 @@ dlt_hdlc_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_hdlc_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_hdlc_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -155,14 +152,13 @@ dlt_hdlc_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_hdlc_parse_opts(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; hdlc_config_t *config; assert(ctx); - plugin = tcpedit_dlt_getplugin(ctx, dlt_value); if (!plugin) return TCPEDIT_ERROR; @@ -174,11 +170,11 @@ dlt_hdlc_parse_opts(tcpeditdlt_t *ctx) if (HAVE_OPT(HDLC_CONTROL)) { config->control = (uint16_t)OPT_VALUE_HDLC_CONTROL; } - + if (HAVE_OPT(HDLC_ADDRESS)) { config->address = (uint16_t)OPT_VALUE_HDLC_ADDRESS; } - + return TCPEDIT_OK; /* success */ } @@ -192,8 +188,8 @@ dlt_hdlc_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { cisco_hdlc_t *hdlc; hdlc_extra_t *extra; @@ -202,20 +198,20 @@ dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if ((size_t)pktlen < sizeof(*hdlc)) return TCPEDIT_ERROR; - + if (ctx->decoded_extra_size < sizeof(*extra)) return TCPEDIT_ERROR; extra = (hdlc_extra_t *)ctx->decoded_extra; hdlc = (cisco_hdlc_t *)packet; - + ctx->proto = hdlc->protocol; ctx->l2len = 4; - + extra->address = hdlc->address; extra->control = hdlc->control; - + return TCPEDIT_OK; /* success */ } @@ -223,7 +219,7 @@ dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int +int dlt_hdlc_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t dir) { cisco_hdlc_t *hdlc; @@ -250,11 +246,11 @@ dlt_hdlc_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t di memcpy(packet + 4, (tmpbuff + ctx->l2len), pktlen - ctx->l2len); safe_free(tmpbuff); } - + /* update the total packet length */ newpktlen = pktlen + 4 - ctx->l2len; - - /* + + /* * HDLC doesn't support direction, since we have no real src/dst addresses * to deal with, so we just use the original packet data or option data */ @@ -280,7 +276,7 @@ dlt_hdlc_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t di tcpedit_seterr(ctx->tcpedit, "%s", "Non-HDLC packet requires --hdlc-address"); return TCPEDIT_ERROR; } - + /* set the control field */ if (config->control < 65535) { hdlc->control = (uint8_t)config->control; @@ -288,20 +284,20 @@ dlt_hdlc_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t di hdlc->control = extra->hdlc; } else { tcpedit_seterr(ctx->tcpedit, "%s", "Non-HDLC packet requires --hdlc-control"); - return TCPEDIT_ERROR; + return TCPEDIT_ERROR; } - + /* copy over our protocol */ hdlc->protocol = ctx->proto; - + return newpktlen; /* success */ } /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { cisco_hdlc_t *hdlc; assert(ctx); @@ -309,9 +305,9 @@ dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (pktlen < 4) return TCPEDIT_ERROR; - + hdlc = (cisco_hdlc_t *)packet; - + return hdlc->protocol; } @@ -319,7 +315,7 @@ dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_hdlc_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_hdlc_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -339,29 +335,25 @@ dlt_hdlc_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_hdlc_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_hdlc_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + l2len = dlt_hdlc_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_hdlc_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_hdlc_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -376,9 +368,9 @@ dlt_hdlc_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_hdlc_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_hdlc_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -387,25 +379,19 @@ dlt_hdlc_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *pac return NULL; /* FIXME: return a ptr to the source or dest mac address. */ - switch(mac) { + switch (mac) { case SRC_MAC: - return(NULL); - break; - + return (NULL); case DST_MAC: memcpy(ctx->dstmac, packet, 2); - return(ctx->dstmac); - break; - + return (ctx->dstmac); default: errx(-1, "Invalid tcpeditdlt_mac_type_t: %d", mac); } - return(NULL); } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_hdlc_l2addr_type(void) { return C_HDLC; } - diff --git a/src/tcpedit/plugins/dlt_hdlc/hdlc.h b/src/tcpedit/plugins/dlt_hdlc/hdlc.h index b09d99928..379d17280 100644 --- a/src/tcpedit/plugins/dlt_hdlc/hdlc.h +++ b/src/tcpedit/plugins/dlt_hdlc/hdlc.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,29 +18,20 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_hdlc_H_ -#define _DLT_hdlc_H_ +#pragma once -#include "plugins_types.h" #include "hdlc_types.h" - +#include "plugins_types.h" int dlt_hdlc_register(tcpeditdlt_t *ctx); int dlt_hdlc_init(tcpeditdlt_t *ctx); int dlt_hdlc_cleanup(tcpeditdlt_t *ctx); int dlt_hdlc_parse_opts(tcpeditdlt_t *ctx); -int dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_hdlc_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_hdlc_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_hdlc_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_hdlc_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_hdlc_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_hdlc_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char *dlt_hdlc_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_hdlc_l2addr_type(void); -int dlt_hdlc_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_hdlc_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); - -#endif - +int dlt_hdlc_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_hdlc_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); diff --git a/src/tcpedit/plugins/dlt_hdlc/hdlc_api.c b/src/tcpedit/plugins/dlt_hdlc/hdlc_api.c index 4847ecd98..516dcfac4 100644 --- a/src/tcpedit/plugins/dlt_hdlc/hdlc_api.c +++ b/src/tcpedit/plugins/dlt_hdlc/hdlc_api.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,6 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "defines.h" -#include "common.h" - -#include "tcpedit.h" -#include "hdlc.h" - #include "hdlc_api.h" /** @@ -31,7 +25,7 @@ * * Reasonable values are 0-255 */ -int +int tcpedit_hdlc_set_control(tcpedit_t *tcpedit, uint8_t control) { tcpeditdlt_t *ctx; @@ -48,7 +42,6 @@ tcpedit_hdlc_set_control(tcpedit_t *tcpedit, uint8_t control) config->control = control; return TCPEDIT_OK; - } /** @@ -74,6 +67,4 @@ tcpedit_hdlc_set_address(tcpedit_t *tcpedit, uint8_t address) config->address = address; return TCPEDIT_OK; - } - diff --git a/src/tcpedit/plugins/dlt_hdlc/hdlc_api.h b/src/tcpedit/plugins/dlt_hdlc/hdlc_api.h index 594623ad7..c5851cb4c 100644 --- a/src/tcpedit/plugins/dlt_hdlc/hdlc_api.h +++ b/src/tcpedit/plugins/dlt_hdlc/hdlc_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,13 +18,11 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_hdlc_API_H_ -#define _DLT_hdlc_API_H_ +#pragma once -#include "tcpedit_types.h" -#include "plugins_types.h" #include "hdlc_types.h" - +#include "plugins_types.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { @@ -33,7 +31,7 @@ extern "C" { /** * \brief HDLC Plugin API functions for modifying the HDLC header * - * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR + * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR * if there is a problem. You can use tcpedit_geterr() to get the reason * for the failure */ @@ -41,10 +39,6 @@ extern "C" { int tcpedit_hdlc_set_control(tcpedit_t *tcpedit, u_int8_t control); int tcpedit_hdlc_set_address(tcpedit_t *tcpedit, u_int8_t address); - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_hdlc/hdlc_types.h b/src/tcpedit/plugins/dlt_hdlc/hdlc_types.h index 1afd86fdf..60d2c519e 100644 --- a/src/tcpedit/plugins/dlt_hdlc/hdlc_types.h +++ b/src/tcpedit/plugins/dlt_hdlc/hdlc_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_hdlc_TYPES_H_ -#define _DLT_hdlc_TYPES_H_ +#pragma once #include "plugins_types.h" @@ -27,7 +26,6 @@ extern "C" { #endif - /* * structure to hold any data parsed from the packet by the decoder. * Example: Ethernet VLAN tag info @@ -43,39 +41,32 @@ typedef struct { }; } hdlc_extra_t; - -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ typedef struct { /* user defined values. 65535 == unset */ - u_int16_t address; - u_int16_t control; + u_int16_t address; + u_int16_t control; } hdlc_config_t; - /* Cisco HDLC has a simple 32 bit header */ #define CISCO_HDLC_LEN 4 - typedef struct { u_int8_t address; -#define CISCO_HDLC_ADDR_UNICAST 0x0F +#define CISCO_HDLC_ADDR_UNICAST 0x0F #define CISCO_HDLC_ADDR_BROADCAST 0x8F u_int8_t control; // always zero u_int16_t protocol; } cisco_hdlc_t; - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_ieee80211/ieee80211.c b/src/tcpedit/plugins/dlt_ieee80211/ieee80211.c index 15d086ba6..092bddf9c 100644 --- a/src/tcpedit/plugins/dlt_ieee80211/ieee80211.c +++ b/src/tcpedit/plugins/dlt_ieee80211/ieee80211.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,16 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" -#include "dlt_utils.h" -#include "tcpedit_stub.h" #include "ieee80211.h" +#include "dlt_utils.h" #include "ieee80211_hdr.h" +#include "tcpedit.h" +#include "tcpedit_stub.h" +#include +#include /* * Notes about the ieee80211 plugin: @@ -51,7 +48,7 @@ static uint16_t dlt_value = DLT_IEEE802_11; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_ieee80211_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -62,16 +59,18 @@ dlt_ieee80211_register(tcpeditdlt_t *ctx) /* we're a decoder only plugin */ plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; - plugin->requires += 0; - - /* what is our DLT value? */ + plugin-> + requires + += 0; + + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_name); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_ieee80211_init; @@ -90,30 +89,28 @@ dlt_ieee80211_register(tcpeditdlt_t *ctx) return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_ieee80211_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + /* allocate memory for our decode extra data */ if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(ieee80211_extra_t)) { ctx->decoded_extra_size = sizeof(ieee80211_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(ieee80211_extra_t); @@ -134,7 +131,7 @@ dlt_ieee80211_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_ieee80211_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_ieee80211_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -160,13 +157,13 @@ dlt_ieee80211_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_ieee80211_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); /* we have none */ - + return TCPEDIT_OK; /* success */ } @@ -180,8 +177,8 @@ dlt_ieee80211_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int l2len; @@ -193,15 +190,17 @@ dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) return TCPEDIT_ERROR; dbgx(3, "Decoding 802.11 packet " COUNTER_SPEC, ctx->tcpedit->runtime.packetnum); - if (! ieee80211_is_data(ctx, packet, pktlen)) { - tcpedit_seterr(ctx->tcpedit, "Packet " COUNTER_SPEC " is not a normal 802.11 data frame", - ctx->tcpedit->runtime.packetnum); + if (!ieee80211_is_data(ctx, packet, pktlen)) { + tcpedit_seterr(ctx->tcpedit, + "Packet " COUNTER_SPEC " is not a normal 802.11 data frame", + ctx->tcpedit->runtime.packetnum); return TCPEDIT_SOFT_ERROR; } - + if (ieee80211_is_encrypted(ctx, packet, pktlen)) { - tcpedit_seterr(ctx->tcpedit, "Packet " COUNTER_SPEC " is encrypted. Unable to decode frame.", - ctx->tcpedit->runtime.packetnum); + tcpedit_seterr(ctx->tcpedit, + "Packet " COUNTER_SPEC " is encrypted. Unable to decode frame.", + ctx->tcpedit->runtime.packetnum); return TCPEDIT_SOFT_ERROR; } @@ -217,13 +216,12 @@ dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_ieee80211_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, - _U_ tcpr_dir_t dir) +int +dlt_ieee80211_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); - + tcpedit_seterr(ctx->tcpedit, "%s", "DLT_IEEE802_11 plugin does not support packet encoding"); return TCPEDIT_ERROR; } @@ -231,8 +229,8 @@ dlt_ieee80211_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int l2len; int hdrlen = 0; @@ -253,28 +251,27 @@ dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* Not all 802.11 frames have data */ if ((fc & ieee80211_FC_TYPE_MASK) != ieee80211_FC_TYPE_DATA) return TCPEDIT_SOFT_ERROR; - - /* Some data frames are QoS and have no data + + /* Some data frames are QoS and have no data if (((fc & ieee80211_FC_SUBTYPE_MASK) & ieee80211_FC_SUBTYPE_QOS) == ieee80211_FC_SUBTYPE_QOS) return TCPEDIT_SOFT_ERROR; */ if ((fc & ieee80211_FC_SUBTYPE_QOS) == ieee80211_FC_SUBTYPE_QOS) { hdrlen += 2; } - + /* figure out the actual header length */ if (ieee80211_USE_4(fc)) { hdrlen += sizeof(ieee80211_addr4_hdr_t); } else { hdrlen += sizeof(ieee80211_hdr_t); } - + hdr = (struct tcpr_802_2snap_hdr *)&packet[hdrlen]; /* verify the header is 802.2SNAP (8 bytes) not 802.2 (3 bytes) */ if (hdr->snap_dsap == 0xAA && hdr->snap_ssap == 0xAA) return hdr->snap_type; - return TCPEDIT_SOFT_ERROR; /* 802.2 has no type field */ } @@ -283,7 +280,7 @@ dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_ieee80211_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_ieee80211_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -305,11 +302,7 @@ dlt_ieee80211_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_ieee80211_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_ieee80211_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); @@ -319,19 +312,19 @@ dlt_ieee80211_merge_layer3(tcpeditdlt_t *ctx, l2len = dlt_ieee80211_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } -/* +/* * return the length of the L2 header of the current packet * based on: http://www.tcpdump.org/lists/workers/2004/07/msg00121.html */ int -dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { uint16_t *frame_control, fc; - int hdrlen = 0; + int hdrlen; assert(ctx); assert(packet); @@ -349,7 +342,7 @@ dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) } else { hdrlen = sizeof(ieee80211_hdr_t); } - + /* if Data/QoS, then L2 len is + 2 bytes */ if ((fc & ieee80211_FC_SUBTYPE_QOS) == ieee80211_FC_SUBTYPE_QOS) { dbgx(2, "total header length (fc %04x) (802.11 + QoS data): %d", fc, hdrlen + 2); @@ -360,7 +353,7 @@ dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) struct tcpr_802_2snap_hdr *hdr; hdr = (struct tcpr_802_2snap_hdr *)&packet[hdrlen]; - + /* verify the header is 802.2SNAP (8 bytes) not 802.2 (3 bytes) */ if (hdr->snap_dsap == 0xAA && hdr->snap_ssap == 0xAA) { hdrlen += (int)sizeof(struct tcpr_802_2snap_hdr); @@ -373,7 +366,7 @@ dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (pktlen < hdrlen) return 0; - + dbgx(2, "header length: %d", hdrlen); return hdrlen; } @@ -381,9 +374,9 @@ dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_ieee80211_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_ieee80211_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -391,30 +384,23 @@ dlt_ieee80211_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char if (pktlen < 14) return NULL; - - switch(mac) { + + switch (mac) { case SRC_MAC: macaddr = ieee80211_get_src(packet); memcpy(ctx->srcmac, macaddr, ETHER_ADDR_LEN); - return(ctx->srcmac); - break; - + return (ctx->srcmac); case DST_MAC: macaddr = ieee80211_get_dst(packet); memcpy(ctx->dstmac, macaddr, ETHER_ADDR_LEN); - return(ctx->dstmac); - break; - + return (ctx->dstmac); default: errx(1, "Invalid tcpeditdlt_mac_type_t: %d", mac); } - return(NULL); } - -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_ieee80211_l2addr_type(void) { return ETHERNET; } - diff --git a/src/tcpedit/plugins/dlt_ieee80211/ieee80211.h b/src/tcpedit/plugins/dlt_ieee80211/ieee80211.h index b2f9c26c1..b983914e8 100644 --- a/src/tcpedit/plugins/dlt_ieee80211/ieee80211.h +++ b/src/tcpedit/plugins/dlt_ieee80211/ieee80211.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,37 +18,29 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_ieee80211_H_ -#define _DLT_ieee80211_H_ +#pragma once -#include "plugins_types.h" #include "ieee80211_types.h" +#include "plugins_types.h" #ifdef __cplusplus extern "C" { #endif - int dlt_ieee80211_register(tcpeditdlt_t *ctx); int dlt_ieee80211_init(tcpeditdlt_t *ctx); int dlt_ieee80211_cleanup(tcpeditdlt_t *ctx); int dlt_ieee80211_parse_opts(tcpeditdlt_t *ctx); -int dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_ieee80211_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_ieee80211_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_ieee80211_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_ieee80211_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_ieee80211_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_ieee80211_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char * +dlt_ieee80211_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_ieee80211_l2addr_type(void); -int dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_ieee80211_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_ieee80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_ieee80211_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.c b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.c index fcc7f9c52..12b238356 100644 --- a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.c +++ b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,23 +18,18 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "ieee80211_hdr.h" #include "dlt_utils.h" #include "tcpedit_stub.h" -#include "ieee80211.h" -#include "ieee80211_hdr.h" +#include +#include /* * Does the given 802.11 header have data? * returns 1 for true & 0 for false */ int -ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, const int pktlen) +ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, int pktlen) { uint16_t *frame_control, fc; struct tcpr_802_2snap_hdr *snap; @@ -49,11 +44,11 @@ ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, const int pktlen) return 0; } - /* + /* * Fields: Version|Type|Subtype|Flags * Bytes: 2|2|4|8 * Types: 00 = Management, 01 = Control, 10 = Data - * Data Subtypes (in binary): + * Data Subtypes (in binary): * 0000 - Data * 0001 - Data + Ack * 0010 - Data + Poll @@ -81,7 +76,7 @@ ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, const int pktlen) return 1; } - /* QoS is set by the high bit, all the lower bits are QoS sub-types + /* QoS is set by the high bit, all the lower bits are QoS sub-types QoS seems to add 2 bytes of data at the end of the 802.11 hdr */ if ((fc & ieee80211_FC_SUBTYPE_MASK) >= ieee80211_FC_SUBTYPE_QOS) { hdrlen += 2; @@ -104,18 +99,18 @@ ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, const int pktlen) if (snap->snap_dsap == 0xAA && snap->snap_ssap == 0xAA) { dbg(2, "packet is 802.2SNAP which I think always has data"); return 1; - } + } warnx("Packet " COUNTER_SPEC " is unknown reason for non-data", ctx->tcpedit->runtime.packetnum); return 0; } -/* +/* * returns 1 if WEP is enabled, 0 if not */ int -ieee80211_is_encrypted(tcpeditdlt_t *ctx, const void *packet, const int pktlen) +ieee80211_is_encrypted(tcpeditdlt_t *ctx, const void *packet, int pktlen) { uint16_t *frame_control, fc; @@ -155,17 +150,16 @@ ieee80211_get_src(const void *header) } else { ieee80211_hdr_t *addr3 = (ieee80211_hdr_t *)header; switch (fc & (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK)) { - case ieee80211_FC_TO_DS_MASK: - return addr3->addr2; - case ieee80211_FC_FROM_DS_MASK: - return addr3->addr3; - case 0: - return addr3->addr2; - default: - err(-1, "Whoops... we shouldn't of gotten here."); + case ieee80211_FC_TO_DS_MASK: + return addr3->addr2; + case ieee80211_FC_FROM_DS_MASK: + return addr3->addr3; + case 0: + return addr3->addr2; + default: + err(-1, "Whoops... we shouldn't of gotten here."); } } - return NULL; } u_char * @@ -184,15 +178,14 @@ ieee80211_get_dst(const void *header) ieee80211_hdr_t *addr3 = (ieee80211_hdr_t *)header; switch (fc & (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK)) { - case ieee80211_FC_TO_DS_MASK: - return addr3->addr3; - case ieee80211_FC_FROM_DS_MASK: - return addr3->addr1; - case 0: - return addr3->addr3; - default: - err(-1, "Whoops... we shouldn't of gotten here."); + case ieee80211_FC_TO_DS_MASK: + return addr3->addr3; + case ieee80211_FC_FROM_DS_MASK: + return addr3->addr1; + case 0: + return addr3->addr3; + default: + err(-1, "Whoops... we shouldn't of gotten here."); } } - return NULL; } diff --git a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.h b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.h index 0dd00794e..77c6c23d1 100644 --- a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.h +++ b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_hdr.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,18 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_ieee80211_hdr_H_ -#define _DLT_ieee80211_hdr_H_ - -#include "plugins_types.h" +#pragma once #include "ieee80211_types.h" +#include "plugins_types.h" #ifdef __cplusplus extern "C" { #endif -int ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, const int pktlen); -int ieee80211_is_encrypted(tcpeditdlt_t *ctx, const void *packet, const int pktlen); +int ieee80211_is_data(tcpeditdlt_t *ctx, const void *packet, int pktlen); +int ieee80211_is_encrypted(tcpeditdlt_t *ctx, const void *packet, int pktlen); u_char *ieee80211_get_src(const void *header); u_char *ieee80211_get_dst(const void *header); @@ -37,6 +35,3 @@ u_char *ieee80211_get_dst(const void *header); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_types.h b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_types.h index 850c53d0c..06f02deeb 100644 --- a/src/tcpedit/plugins/dlt_ieee80211/ieee80211_types.h +++ b/src/tcpedit/plugins/dlt_ieee80211/ieee80211_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_ieee80211_TYPES_H_ -#define _DLT_ieee80211_TYPES_H_ +#pragma once #include "plugins_types.h" @@ -27,35 +26,34 @@ extern "C" { #endif - /* 802.11 packet header w/ 3 addresses (non-WDS) */ typedef struct { u_int16_t frame_control; /* version is first two bytes */ -#define ieee80211_FC_VERSION_MASK 0x0300 +#define ieee80211_FC_VERSION_MASK 0x0300 /* type is second 2 bytes */ -#define ieee80211_FC_TYPE_MASK 0x0F00 -#define ieee80211_FC_TYPE_DATA 0x0800 -#define ieee80211_FC_TYPE_MGMT 0x0000 -#define ieee80211_FC_TYPE_CONTROL 0x0400 +#define ieee80211_FC_TYPE_MASK 0x0F00 +#define ieee80211_FC_TYPE_DATA 0x0800 +#define ieee80211_FC_TYPE_MGMT 0x0000 +#define ieee80211_FC_TYPE_CONTROL 0x0400 /* subtype is the 4 high bytes */ -#define ieee80211_FC_SUBTYPE_MASK 0xF000 -#define ieee80211_FC_SUBTYPE_QOS 0x8000 /* high bit is QoS, but there are sub-sub types for QoS */ -#define ieee80211_FC_SUBTYPE_NULL 0xC000 /* no data */ +#define ieee80211_FC_SUBTYPE_MASK 0xF000 +#define ieee80211_FC_SUBTYPE_QOS 0x8000 /* high bit is QoS, but there are sub-sub types for QoS */ +#define ieee80211_FC_SUBTYPE_NULL 0xC000 /* no data */ /* Direction */ -#define ieee80211_FC_TO_DS_MASK 0x0001 -#define ieee80211_FC_FROM_DS_MASK 0x0002 +#define ieee80211_FC_TO_DS_MASK 0x0001 +#define ieee80211_FC_FROM_DS_MASK 0x0002 /* Flags */ -#define ieee80211_FC_MORE_FRAG 0x0004 -#define ieee80211_FC_RETRY_MASK 0x0008 -#define ieee80211_FC_PWR_MGMT_MASK 0x0010 +#define ieee80211_FC_MORE_FRAG 0x0004 +#define ieee80211_FC_RETRY_MASK 0x0008 +#define ieee80211_FC_PWR_MGMT_MASK 0x0010 #define ieee80211_FC_MORE_DATA_MASK 0x0020 -#define ieee80211_FC_WEP_MASK 0x0040 -#define ieee80211_FC_ORDER_MASK 0x0080 +#define ieee80211_FC_WEP_MASK 0x0040 +#define ieee80211_FC_ORDER_MASK 0x0080 u_int16_t duration; u_char addr1[6]; u_char addr2[6]; @@ -73,10 +71,9 @@ typedef struct { u_int16_t fragid; } ieee80211_addr4_hdr_t; - -#define ieee80211_USE_4(frame_control) \ - (frame_control & (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK)) == \ - (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK) +#define ieee80211_USE_4(frame_control) \ + (frame_control & (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK)) == \ + (ieee80211_FC_TO_DS_MASK + ieee80211_FC_FROM_DS_MASK) /* * FIXME: structure to hold any data parsed from the packet by the decoder. @@ -86,23 +83,20 @@ typedef struct { u_char packet[MAXPACKET]; } ieee80211_extra_t; -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ typedef struct { - /* dummy entry for SunPro compiler which doesn't like empty structs */ + /* dummy entry for SunPro compiler which doesn't like empty structs */ int dummy; } ieee80211_config_t; #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.c b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.c index e282ef489..c53ec2973 100644 --- a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.c +++ b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.c @@ -31,19 +31,14 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include - -#include "defines.h" -#include "common.h" -#include "tcpr.h" -#include "tcpedit.h" -#include "dlt_utils.h" -#include "tcpedit_stub.h" #include "jnpr_ether.h" +#include "dlt_utils.h" #include "jnpr_ether_types.h" -#include "../ethernet.h" -#include "../dlt_en10mb/en10mb.h" +#include "tcpedit.h" +#include "tcpedit_stub.h" +#include +#include +#include static char dlt_name[] = "jnpr_eth"; static uint16_t dlt_value = DLT_JUNIPER_ETHER; @@ -59,7 +54,7 @@ static uint16_t dlt_value = DLT_JUNIPER_ETHER; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_jnpr_ether_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -69,16 +64,18 @@ dlt_jnpr_ether_register(tcpeditdlt_t *ctx) plugin = tcpedit_dlt_newplugin(); plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; - plugin->requires = 0; + plugin-> + requires + = 0; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_name); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_jnpr_ether_init; @@ -98,24 +95,23 @@ dlt_jnpr_ether_register(tcpeditdlt_t *ctx) return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_jnpr_ether_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + /* allocate memory for our config data */ plugin->config_size = sizeof(jnpr_ether_config_t); plugin->config = safe_malloc(plugin->config_size); @@ -127,20 +123,20 @@ dlt_jnpr_ether_init(tcpeditdlt_t *ctx) * Post init function. This function is called only once after init() and parse_opts() * It basically allows decoders to properly initialize sub-plugins. */ -int +int dlt_jnpr_ether_post_init(tcpeditdlt_t *ctx) { jnpr_ether_config_t *config; - + /* do nothing if we're not the decoder */ if (ctx->decoder->dlt != dlt_value) return TCPEDIT_OK; - + /* init our subcontext & decoder of en10mb */ config = (jnpr_ether_config_t *)ctx->encoder->config; if (config->subctx == NULL) config->subctx = tcpedit_dlt_init(ctx->tcpedit, DLT_EN10MB); - + return TCPEDIT_OK; } @@ -149,11 +145,11 @@ dlt_jnpr_ether_post_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_jnpr_ether_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_jnpr_ether_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; - + assert(ctx); if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { @@ -168,7 +164,8 @@ dlt_jnpr_ether_cleanup(tcpeditdlt_t *ctx) jnpr_ether_config_t *config; config = (jnpr_ether_config_t *)ctx->encoder->config; - tcpedit_dlt_cleanup(config->subctx); + if (config->subctx != NULL) + tcpedit_dlt_cleanup(config->subctx); safe_free(plugin->config); plugin->config = NULL; plugin->config_size = 0; @@ -183,7 +180,7 @@ dlt_jnpr_ether_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_jnpr_ether_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -201,14 +198,13 @@ dlt_jnpr_ether_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int jnpr_header_len = 0; const u_char *ethernet = NULL; jnpr_ether_config_t *config; - - + assert(ctx); assert(packet); @@ -218,38 +214,33 @@ dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) config = (jnpr_ether_config_t *)ctx->encoder->config; - /* first, verify magic */ if (memcmp(packet, JUNIPER_ETHER_MAGIC, JUNIPER_ETHER_MAGIC_LEN) != 0) { - tcpedit_seterr(ctx->tcpedit, "Invalid magic 0x%02X%02X%02X", - packet[0], packet[1], packet[2]); + tcpedit_seterr(ctx->tcpedit, "Invalid magic 0x%02X%02X%02X", packet[0], packet[1], packet[2]); return TCPEDIT_ERROR; } - + /* next make sure the L2 header is present */ - if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) - != JUNIPER_ETHER_L2PRESENT) { - tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", - packet[JUNIPER_ETHER_OPTIONS_OFFSET]); + if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) != JUNIPER_ETHER_L2PRESENT) { + tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", packet[JUNIPER_ETHER_OPTIONS_OFFSET]); return TCPEDIT_ERROR; } - + /* then get the Juniper header length */ memcpy(&jnpr_header_len, &packet[JUNIPER_ETHER_EXTLEN_OFFSET], 2); - + jnpr_header_len = ntohs(jnpr_header_len) + JUNIPER_ETHER_HEADER_LEN; dbgx(1, "jnpr header len: %d", jnpr_header_len); /* make sure the packet is big enough to find the Ethernet Header */ if (pktlen < jnpr_header_len + TCPR_ETH_H) { - tcpedit_seterr(ctx->tcpedit, "Frame is too short! %d < %d", - pktlen, (jnpr_header_len + TCPR_ETH_H)); + tcpedit_seterr(ctx->tcpedit, "Frame is too short! %d < %d", pktlen, (jnpr_header_len + TCPR_ETH_H)); return TCPEDIT_ERROR; } - + ctx->l2len = jnpr_header_len; - + /* jump to the appropriate offset */ ethernet = packet + jnpr_header_len; @@ -260,7 +251,7 @@ dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* copy the subdecoder state to our encoder state */ if (tcpedit_dlt_copy_decoder_state(ctx, config->subctx) == TCPEDIT_ERROR) return TCPEDIT_ERROR; - + return TCPEDIT_OK; } @@ -268,7 +259,7 @@ dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int +int dlt_jnpr_ether_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); @@ -277,7 +268,7 @@ dlt_jnpr_ether_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_di /* MAGIC + Static fields + Extension Length */ if (pktlen < JUNIPER_ETHER_HEADER_LEN) return TCPEDIT_ERROR; - + tcpedit_seterr(ctx->tcpedit, "%s", "DLT_JUNIPER_ETHER plugin does not support packet encoding"); return TCPEDIT_ERROR; } @@ -286,8 +277,8 @@ dlt_jnpr_ether_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_di * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error * Make sure you return this value in NETWORK byte order! */ -int -dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int jnpr_hdr_len; const u_char *ethernet; @@ -302,21 +293,18 @@ dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) config = (jnpr_ether_config_t *)ctx->encoder->config; - /* next make sure the L2 header is present */ - if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) - != JUNIPER_ETHER_L2PRESENT) { - tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", - packet[JUNIPER_ETHER_OPTIONS_OFFSET]); + if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) != JUNIPER_ETHER_L2PRESENT) { + tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", packet[JUNIPER_ETHER_OPTIONS_OFFSET]); return TCPEDIT_ERROR; } /* then get the Juniper header length */ memcpy(&jnpr_hdr_len, &packet[JUNIPER_ETHER_EXTLEN_OFFSET], 2); - + jnpr_hdr_len = ntohs(jnpr_hdr_len) + JUNIPER_ETHER_HEADER_LEN; ethernet = packet + jnpr_hdr_len; - + /* let the en10mb plugin do the rest of the work */ return tcpedit_dlt_proto(config->subctx, DLT_EN10MB, ethernet, (pktlen - jnpr_hdr_len)); } @@ -325,17 +313,15 @@ dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_jnpr_ether_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_jnpr_ether_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); assert(packet); /* next make sure the L2 header is present */ - if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) - != JUNIPER_ETHER_L2PRESENT) { - tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", - packet[JUNIPER_ETHER_OPTIONS_OFFSET]); + if ((packet[JUNIPER_ETHER_OPTIONS_OFFSET] & JUNIPER_ETHER_L2PRESENT) != JUNIPER_ETHER_L2PRESENT) { + tcpedit_seterr(ctx->tcpedit, "Frame is missing L2 Header: %x", packet[JUNIPER_ETHER_OPTIONS_OFFSET]); return NULL; } @@ -353,30 +339,26 @@ dlt_jnpr_ether_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_jnpr_ether_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_jnpr_ether_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + l2len = dlt_jnpr_ether_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_jnpr_ether_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_jnpr_ether_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { const u_char *ethernet = NULL; jnpr_ether_config_t *config; @@ -392,19 +374,18 @@ dlt_jnpr_ether_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_cha /* first get the Juniper header length */ memcpy(&jnpr_hdr_len, &packet[JUNIPER_ETHER_EXTLEN_OFFSET], 2); - + jnpr_hdr_len = ntohs(jnpr_hdr_len) + JUNIPER_ETHER_HEADER_LEN; ethernet = packet + jnpr_hdr_len; - + return dlt_en10mb_get_mac(config->subctx, mac, ethernet, (pktlen - jnpr_hdr_len)); } - -/* +/* * return the length of the L2 header of the current packet */ int -dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int len, res; jnpr_ether_config_t *config; @@ -414,15 +395,15 @@ dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (pktlen < JUNIPER_ETHER_EXTLEN_OFFSET + 2) return -1; - + config = (jnpr_ether_config_t *)ctx->encoder->config; /* first get the Juniper header length */ memcpy(&len, &packet[JUNIPER_ETHER_EXTLEN_OFFSET], 2); - + len = ntohs(len) + JUNIPER_ETHER_HEADER_LEN; dbgx(3, "juniper header len: %u", len); - + /* add the 802.3 length */ res = tcpedit_dlt_l2len(config->subctx, DLT_EN10MB, (packet + len), (pktlen - len)); if (res == -1) @@ -430,15 +411,13 @@ dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) len += res; dbgx(3, "total l2len: %u", len); - + /* and return that */ return len; } - -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_jnpr_ether_l2addr_type(void) { return ETHERNET; } - diff --git a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.h b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.h index d7ca2464d..4875350d2 100644 --- a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.h +++ b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_jnpr_ether_H_ -#define _DLT_jnpr_ether_H_ +#pragma once #include "jnpr_ether_types.h" @@ -35,29 +34,21 @@ extern "C" { #define JUNIPER_ETHER_DIRECTION 0x01 #define JUNIPER_ETHER_EXTLEN_OFFSET 4 - int dlt_jnpr_ether_register(tcpeditdlt_t *ctx); int dlt_jnpr_ether_init(tcpeditdlt_t *ctx); int dlt_jnpr_ether_post_init(tcpeditdlt_t *ctx); int dlt_jnpr_ether_cleanup(tcpeditdlt_t *ctx); int dlt_jnpr_ether_parse_opts(tcpeditdlt_t *ctx); -int dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_jnpr_ether_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_jnpr_ether_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_jnpr_ether_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_jnpr_ether_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_jnpr_ether_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_jnpr_ether_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char * +dlt_jnpr_ether_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_jnpr_ether_l2addr_type(void); -int dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_jnpr_ether_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); - +int dlt_jnpr_ether_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_jnpr_ether_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_api.h b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_api.h index 988b064b3..dbfaea8bb 100644 --- a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_api.h +++ b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,21 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_jnpr_ether_API_H_ -#define _DLT_jnpr_ether_API_H_ +#pragma once -#include "tcpedit_types.h" -#include "plugins_types.h" #include "jnpr_ether_types.h" +#include "plugins_types.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { #endif - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_types.h b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_types.h index cad9146c9..95b466f7e 100644 --- a/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_types.h +++ b/src/tcpedit/plugins/dlt_jnpr_ether/jnpr_ether_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_jnpr_ether_TYPES_H_ -#define _DLT_jnpr_ether_TYPES_H_ +#pragma once #include "jnpr_ether_api.h" @@ -33,11 +32,6 @@ typedef struct jnpr_ether_config_s { tcpeditdlt_t *subctx; } jnpr_ether_config_t; - - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_linuxsll/linuxsll.c b/src/tcpedit/plugins/dlt_linuxsll/linuxsll.c index 4c171db76..e6dfeb2f7 100644 --- a/src/tcpedit/plugins/dlt_linuxsll/linuxsll.c +++ b/src/tcpedit/plugins/dlt_linuxsll/linuxsll.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,17 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "linuxsll.h" +#include "../ethernet.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "../ethernet.h" -#include "linuxsll.h" - +#include +#include static char dlt_name[] = "linuxsll"; static char _U_ dlt_prefix[] = "linuxsll"; @@ -45,7 +41,7 @@ static uint16_t dlt_value = DLT_LINUX_SLL; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_linuxsll_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -56,17 +52,18 @@ dlt_linuxsll_register(tcpeditdlt_t *ctx) /* FIXME: set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR; - plugin->requires += 0; + plugin-> + requires + += 0; - - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_linuxsll_init; @@ -85,14 +82,13 @@ dlt_linuxsll_register(tcpeditdlt_t *ctx) return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_linuxsll_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -107,8 +103,7 @@ dlt_linuxsll_init(tcpeditdlt_t *ctx) if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(linuxsll_extra_t)) { ctx->decoded_extra_size = sizeof(linuxsll_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(linuxsll_extra_t); @@ -127,7 +122,7 @@ dlt_linuxsll_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_linuxsll_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_linuxsll_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -153,7 +148,7 @@ dlt_linuxsll_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_linuxsll_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -172,8 +167,8 @@ dlt_linuxsll_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int type; linux_sll_header_t *linux_sll; @@ -187,7 +182,6 @@ dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) ctx->proto = linux_sll->proto; ctx->l2len = sizeof(linux_sll_header_t); - type = ntohs(linux_sll->type); if (type == ARPHRD_ETHER || type == ARPHRD_LOOPBACK) { /* ethernet or loopback */ memcpy(&(ctx->srcaddr), linux_sll->address, ETHER_ADDR_LEN); @@ -203,9 +197,8 @@ dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_linuxsll_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, - _U_ tcpr_dir_t dir) +int +dlt_linuxsll_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); @@ -217,8 +210,8 @@ dlt_linuxsll_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_linuxsll_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_linuxsll_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { linux_sll_header_t *linux_sll; assert(ctx); @@ -236,7 +229,7 @@ dlt_linuxsll_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_linuxsll_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_linuxsll_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -256,11 +249,7 @@ dlt_linuxsll_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_linuxsll_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_linuxsll_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); @@ -274,11 +263,11 @@ dlt_linuxsll_merge_layer3(tcpeditdlt_t *ctx, return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_linuxsll_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_linuxsll_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -294,7 +283,7 @@ dlt_linuxsll_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * return NULL on error/address doesn't exist */ u_char * -dlt_linuxsll_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_linuxsll_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -303,26 +292,20 @@ dlt_linuxsll_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char return NULL; /* FIXME: return a ptr to the source or dest mac address. */ - switch(mac) { + switch (mac) { case SRC_MAC: memcpy(ctx->srcmac, &packet[6], 8); /* linuxssl defines the src mac field to be 8 bytes, not 6 */ - return(ctx->srcmac); - break; - + return (ctx->srcmac); case DST_MAC: - return(NULL); - break; - + return (NULL); default: errx(-1, "Invalid tcpeditdlt_mac_type_t: %d", mac); } - return(NULL); } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_linuxsll_l2addr_type(void) { /* we only support ethernet packets */ return ETHERNET; } - diff --git a/src/tcpedit/plugins/dlt_linuxsll/linuxsll.h b/src/tcpedit/plugins/dlt_linuxsll/linuxsll.h index 42a461c93..eb2b26e34 100644 --- a/src/tcpedit/plugins/dlt_linuxsll/linuxsll.h +++ b/src/tcpedit/plugins/dlt_linuxsll/linuxsll.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_linuxsll_H_ -#define _DLT_linuxsll_H_ +#pragma once #include "plugins_types.h" #include "linuxsll_types.h" @@ -33,22 +32,19 @@ int dlt_linuxsll_register(tcpeditdlt_t *ctx); int dlt_linuxsll_init(tcpeditdlt_t *ctx); int dlt_linuxsll_cleanup(tcpeditdlt_t *ctx); int dlt_linuxsll_parse_opts(tcpeditdlt_t *ctx); -int dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_linuxsll_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_linuxsll_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_linuxsll_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_linuxsll_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); +int dlt_linuxsll_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_linuxsll_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); u_char *dlt_linuxsll_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, - const int pktlen, + int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_linuxsll_l2addr_type(void); -int dlt_linuxsll_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_linuxsll_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_linuxsll_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_linuxsll_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_linuxsll/linuxsll_types.h b/src/tcpedit/plugins/dlt_linuxsll/linuxsll_types.h index 00626db3f..39df13e30 100644 --- a/src/tcpedit/plugins/dlt_linuxsll/linuxsll_types.h +++ b/src/tcpedit/plugins/dlt_linuxsll/linuxsll_types.h @@ -1,11 +1,11 @@ /* $Id$ */ - + /* * Copyright (c) 2001-2010 Aaron Turner * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -17,11 +17,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_linuxsll_TYPES_H_ -#define _DLT_linuxsll_TYPES_H_ +#pragma once -#include "tcpedit_types.h" #include "plugins_types.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { @@ -35,36 +34,31 @@ typedef struct { u_char packet[MAXPACKET]; } linuxsll_extra_t; - -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ -typedef struct { +typedef struct { /* dummy entry for SunPro compiler which doesn't like empty structs */ int dummy; } linuxsll_config_t; - typedef struct { - u_int16_t source; /* values 0-4 determine where the packet came and where it's going */ - u_int16_t type; /* linux ARPHRD_* values for link-layer device type. See: - * http://www.gelato.unsw.edu.au/lxr/source/include/linux/if_arp.h - */ -#define ARPHRD_ETHER 1 /* ethernet */ - u_int16_t length; /* source address length */ - u_char address[8]; /* first 8 bytes of source address (may be truncated) */ - u_int16_t proto; /* Ethernet protocol type */ + u_int16_t source; /* values 0-4 determine where the packet came and where it's going */ + u_int16_t type; /* linux ARPHRD_* values for link-layer device type. See: + * http://www.gelato.unsw.edu.au/lxr/source/include/linux/if_arp.h + */ +#define ARPHRD_ETHER 1 /* ethernet */ + u_int16_t length; /* source address length */ + u_char address[8]; /* first 8 bytes of source address (may be truncated) */ + u_int16_t proto; /* Ethernet protocol type */ } linux_sll_header_t; #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_loop/loop.c b/src/tcpedit/plugins/dlt_loop/loop.c index 0163bd081..70b5fba02 100644 --- a/src/tcpedit/plugins/dlt_loop/loop.c +++ b/src/tcpedit/plugins/dlt_loop/loop.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,20 +18,16 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" -#include "dlt_utils.h" -#include "tcpedit_stub.h" #include "loop.h" #include "../dlt_null/null.h" +#include "dlt_utils.h" +#include "tcpedit.h" +#include "tcpedit_stub.h" +#include -/* +/* * Basically, DLT_LOOP and DLT_NULL are the same thing except that the PF_ value - * in the header is always network byte order in DLT_LOOP and host byte order + * in the header is always network byte order in DLT_LOOP and host byte order * in DLT_NULL. So since DLT_NULL has to handle both big & little endian values * we just send all DLT_LOOP processing over there */ @@ -51,7 +47,7 @@ static uint16_t dlt_value = DLT_LOOP; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_loop_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -62,9 +58,11 @@ dlt_loop_register(tcpeditdlt_t *ctx) /* set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO; - plugin->requires += 0; + plugin-> + requires + += 0; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ @@ -82,28 +80,27 @@ dlt_loop_register(tcpeditdlt_t *ctx) plugin->plugin_get_layer3 = dlt_null_get_layer3; plugin->plugin_merge_layer3 = dlt_null_merge_layer3; plugin->plugin_get_mac = dlt_null_get_mac; - + /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_loop_init(tcpeditdlt_t *ctx) { - tcpeditdlt_plugin_t *plugin; assert(ctx); - - if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { + + if (tcpedit_dlt_getplugin(ctx, dlt_value) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + return TCPEDIT_OK; /* success */ } @@ -112,14 +109,14 @@ dlt_loop_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_loop_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int dlt_loop_cleanup(tcpeditdlt_t *ctx) +int +dlt_loop_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { - tcpedit_seterr(ctx->tcpedit, "Unable to cleanup unregistered plugin %s", - dlt_name); + tcpedit_seterr(ctx->tcpedit, "Unable to cleanup unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } diff --git a/src/tcpedit/plugins/dlt_loop/loop.h b/src/tcpedit/plugins/dlt_loop/loop.h index 5df78e9ae..5ffdcc9cb 100644 --- a/src/tcpedit/plugins/dlt_loop/loop.h +++ b/src/tcpedit/plugins/dlt_loop/loop.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_loop_H_ -#define _DLT_loop_H_ +#pragma once #include "plugins_types.h" @@ -27,7 +26,6 @@ extern "C" { #endif - int dlt_loop_register(tcpeditdlt_t *ctx); int dlt_loop_init(tcpeditdlt_t *ctx); int dlt_loop_cleanup(tcpeditdlt_t *ctx); @@ -37,6 +35,3 @@ int dlt_loop_cleanup(tcpeditdlt_t *ctx); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_null/null.c b/src/tcpedit/plugins/dlt_null/null.c index f33fc9711..cc682aa1d 100644 --- a/src/tcpedit/plugins/dlt_null/null.c +++ b/src/tcpedit/plugins/dlt_null/null.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,16 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "null.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "null.h" - +#include +#include #include // PF_* values static char dlt_name[] = "null"; @@ -42,7 +38,7 @@ static uint16_t dlt_value = DLT_NULL; * * Note that ``host byte order'' is the byte order of the * machine on which the packets are captured, and the PF_ values - * are for the OS of the machine on which the packets are captured; + * are for the OS of the machine on which the packets are captured; * if a live capture is being done, ``host byte order'' * is the byte order of the machine capturing the packets, and * the PF_ values are those of the OS of the machine capturing @@ -62,7 +58,7 @@ static uint16_t dlt_value = DLT_NULL; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_null_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -73,16 +69,18 @@ dlt_null_register(tcpeditdlt_t *ctx) /* set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO; - plugin->requires += 0; + plugin-> + requires + += 0; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_null_init; @@ -100,23 +98,22 @@ dlt_null_register(tcpeditdlt_t *ctx) return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_null_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; - } + } return TCPEDIT_OK; /* success */ } @@ -126,7 +123,7 @@ dlt_null_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_null_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_null_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -152,7 +149,7 @@ dlt_null_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_null_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -171,8 +168,8 @@ dlt_null_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_null_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_null_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int proto; assert(ctx); @@ -191,13 +188,12 @@ dlt_null_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_null_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, - _U_ tcpr_dir_t dir) +int +dlt_null_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); - + tcpedit_seterr(ctx->tcpedit, "%s", "DLT_NULL and DLT_LOOP plugins do not support packet encoding"); return TCPEDIT_ERROR; } @@ -205,17 +201,17 @@ dlt_null_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); - uint32_t *af_type; + uint32_t *af_type; int protocol = 0; if (pktlen < 4) return TCPEDIT_ERROR; - + /* PF_INET is always 2 but PF_INET6 varies based on platform, i.e * Linux - 10 * NetBSD,OpenBSD,BSD/OS - 24 @@ -226,17 +222,15 @@ dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) af_type = (uint32_t *)packet; if (*af_type == PF_INET || SWAPLONG(*af_type) == PF_INET) { protocol = ETHERTYPE_IP; - } else if (*af_type == PF_INET6 || SWAPLONG(*af_type) == PF_INET6 || - *af_type == 10 || SWAPLONG(*af_type) == 10 || - *af_type == 24 || SWAPLONG(*af_type) == 24 || - *af_type == 28 || SWAPLONG(*af_type) == 28 || + } else if (*af_type == PF_INET6 || SWAPLONG(*af_type) == PF_INET6 || *af_type == 10 || SWAPLONG(*af_type) == 10 || + *af_type == 24 || SWAPLONG(*af_type) == 24 || *af_type == 28 || SWAPLONG(*af_type) == 28 || *af_type == 30 || SWAPLONG(*af_type) == 30) { protocol = ETHERTYPE_IP6; } else { tcpedit_seterr(ctx->tcpedit, "Unsupported DLT_NULL/DLT_LOOP PF_ type: 0x%04x", *af_type); return TCPEDIT_ERROR; } - + return htons(protocol); } @@ -244,7 +238,7 @@ dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_null_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_null_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -265,29 +259,25 @@ dlt_null_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_null_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_null_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + l2len = dlt_null_l2len(ctx, packet, pktlen); if (pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_null_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_null_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -302,21 +292,18 @@ dlt_null_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_null_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, - const u_char *packet, _U_ const int pktlen) +dlt_null_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, const u_char *packet, _U_ int pktlen) { assert(ctx); assert(packet); - return(NULL); - + return (NULL); } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_null_l2addr_type(void) { return NONE; } - diff --git a/src/tcpedit/plugins/dlt_null/null.h b/src/tcpedit/plugins/dlt_null/null.h index be1054b20..fe348c515 100644 --- a/src/tcpedit/plugins/dlt_null/null.h +++ b/src/tcpedit/plugins/dlt_null/null.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_null_H_ -#define _DLT_null_H_ +#pragma once #include "plugins_types.h" @@ -31,18 +30,12 @@ int dlt_null_register(tcpeditdlt_t *ctx); int dlt_null_init(tcpeditdlt_t *ctx); int dlt_null_cleanup(tcpeditdlt_t *ctx); int dlt_null_parse_opts(tcpeditdlt_t *ctx); -int dlt_null_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_null_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_null_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_null_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_null_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_null_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_null_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char * +dlt_null_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_null_l2addr_type(void); -int dlt_null_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_null_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); - -#endif - +int dlt_null_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_null_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); diff --git a/src/tcpedit/plugins/dlt_plugins.c b/src/tcpedit/plugins/dlt_plugins.c index eae387444..515853789 100644 --- a/src/tcpedit/plugins/dlt_plugins.c +++ b/src/tcpedit/plugins/dlt_plugins.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,41 +19,37 @@ */ #include "config.h" - -#include - -#include "tcpedit.h" +#include "dlt_utils.h" #include "plugins.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "dlt_utils.h" -#include "common.h" +#include /** * Include plugin header files here... */ #include "dlt_en10mb/en10mb.h" -#include "dlt_user/user.h" #include "dlt_hdlc/hdlc.h" -#include "dlt_raw/raw.h" -#include "dlt_null/null.h" -#include "dlt_loop/loop.h" -#include "dlt_linuxsll/linuxsll.h" #include "dlt_ieee80211/ieee80211.h" -#include "dlt_radiotap/radiotap.h" #include "dlt_jnpr_ether/jnpr_ether.h" +#include "dlt_linuxsll/linuxsll.h" +#include "dlt_loop/loop.h" +#include "dlt_null/null.h" #include "dlt_pppserial/pppserial.h" - +#include "dlt_radiotap/radiotap.h" +#include "dlt_raw/raw.h" +#include "dlt_user/user.h" /** * Everyone writing a DLT plugin, must add their registration function * here. */ -int +int tcpedit_dlt_register(tcpeditdlt_t *ctx) { int retcode = 0; assert(ctx); - + retcode += dlt_en10mb_register(ctx); retcode += dlt_hdlc_register(ctx); retcode += dlt_user_register(ctx); @@ -65,15 +61,13 @@ tcpedit_dlt_register(tcpeditdlt_t *ctx) retcode += dlt_radiotap_register(ctx); retcode += dlt_jnpr_ether_register(ctx); retcode += dlt_pppserial_register(ctx); - + if (retcode < 0) return TCPEDIT_ERROR; - + return TCPEDIT_OK; } - - /******************************************************************** * People writing DLT plugins should stop editing here! * @@ -81,23 +75,17 @@ tcpedit_dlt_register(tcpeditdlt_t *ctx) * a look! ********************************************************************/ -/* +/* * mapping for bit_mask to bit_info. If you're making changes here * then you almost certainly need to modify tcpeditdlt_t in dlt_plugins-int.h */ -const uint32_t tcpeditdlt_bit_map[] = { - PLUGIN_MASK_PROTO, - PLUGIN_MASK_SRCADDR, - PLUGIN_MASK_DSTADDR -}; +const uint32_t tcpeditdlt_bit_map[] = {PLUGIN_MASK_PROTO, PLUGIN_MASK_SRCADDR, PLUGIN_MASK_DSTADDR}; /* Meanings of the above map */ -const char *tcpeditdlt_bit_info[] = { - "Missing required Layer 3 protocol.", - "Missing required Layer 2 source address.", - "Missing required Layer 2 destination address." -}; - +const char *tcpeditdlt_bit_info[] = {"Missing required Layer 3 protocol.", + "Missing required Layer 2 source address.", + "Missing required Layer 2 destination address."}; + /********************************************************************* * Internal functions ********************************************************************/ @@ -105,7 +93,7 @@ const char *tcpeditdlt_bit_info[] = { /********************************************************************* * Public functions ********************************************************************/ - + /** * initialize our plugin library. Pass the DLT of the source pcap handle. * Actions: @@ -119,7 +107,7 @@ const char *tcpeditdlt_bit_info[] = { * - Validate provides/reqiures + user options */ tcpeditdlt_t * -tcpedit_dlt_init(tcpedit_t *tcpedit, const int srcdlt) +tcpedit_dlt_init(tcpedit_t *tcpedit, const int srcdlt) { tcpeditdlt_t *ctx; int rcode; @@ -163,7 +151,6 @@ tcpedit_dlt_init(tcpedit_t *tcpedit, const int srcdlt) return NULL; } - /* we're OK */ return ctx; } @@ -176,45 +163,44 @@ tcpedit_dlt_init(tcpedit_t *tcpedit, const int srcdlt) * you'll need to roll your own! * Returns 0 on success, -1 on error */ -int +int tcpedit_dlt_post_args(tcpedit_t *tcpedit) { tcpeditdlt_t *ctx; const char *dst_dlt_name; - int rcode; - + assert(tcpedit); ctx = tcpedit->dlt_ctx; assert(ctx); - + /* Select the encoder plugin */ dst_dlt_name = OPT_ARG(DLT) ? OPT_ARG(DLT) : ctx->decoder->name; if ((ctx->encoder = tcpedit_dlt_getplugin_byname(ctx, dst_dlt_name)) == NULL) { tcpedit_seterr(tcpedit, "No output DLT plugin available for: %s", dst_dlt_name); return TCPEDIT_ERROR; } - + /* Figure out if we're skipping braodcast & multicast */ if (HAVE_OPT(SKIPL2BROADCAST)) ctx->skip_broadcast = 1; /* init encoder plugin if it's not the decoder plugin */ if (ctx->encoder->dlt != ctx->decoder->dlt) { - if ((rcode = ctx->encoder->plugin_init(ctx)) != TCPEDIT_OK) { + if (ctx->encoder->plugin_init(ctx) != TCPEDIT_OK) { /* plugin should generate the error */ return TCPEDIT_ERROR; } } /* parse the DLT specific options */ - if ((rcode = tcpedit_dlt_parse_opts(ctx)) != TCPEDIT_OK) { + if (tcpedit_dlt_parse_opts(ctx) != TCPEDIT_OK) { /* parser should generate the error */ return TCPEDIT_ERROR; } /* we're OK */ return tcpedit_dlt_post_init(ctx); -} +} /** * This is the recommended method to edit a packet. Returns (new) total packet length @@ -223,16 +209,16 @@ int tcpedit_dlt_process(tcpeditdlt_t *ctx, u_char **packet, int pktlen, tcpr_dir_t direction) { int rcode; - + assert(ctx); assert(packet); assert(direction == TCPR_DIR_C2S || direction == TCPR_DIR_S2C || direction == TCPR_DIR_NOSEND); - + /* nothing to do here */ if (direction == TCPR_DIR_NOSEND) return pktlen; - - /* decode packet */ + + /* decode packet */ if ((rcode = tcpedit_dlt_decode(ctx, *packet, pktlen)) == TCPEDIT_ERROR) { return TCPEDIT_ERROR; } else if (rcode == TCPEDIT_WARN) { @@ -240,51 +226,49 @@ tcpedit_dlt_process(tcpeditdlt_t *ctx, u_char **packet, int pktlen, tcpr_dir_t d } else if (rcode == TCPEDIT_SOFT_ERROR) { return rcode; /* can't edit the packet */ } - + /* encode packet */ if ((rcode = tcpedit_dlt_encode(ctx, *packet, pktlen, direction)) == TCPEDIT_ERROR) { return TCPEDIT_ERROR; } else if (rcode == TCPEDIT_WARN) { warnx("Warning encoding packet: %s", tcpedit_getwarn(ctx->tcpedit)); } - + return rcode; } /** * \brief Call after tcpedit_dlt_post_args() to allow plugins to do special things - * + * * Useful for plugins to initialize sub-plugins and what not. * Returns the standard TCPEDIT_OK|ERROR|WARN */ -int +int tcpedit_dlt_post_init(tcpeditdlt_t *tcpedit) { - /* first init decoder */ if (tcpedit->decoder->plugin_post_init != NULL) if (tcpedit->decoder->plugin_post_init(tcpedit) == TCPEDIT_ERROR) return TCPEDIT_ERROR; - + /* the encoder */ if (tcpedit->encoder->plugin_post_init != NULL) if (tcpedit->encoder->plugin_post_init(tcpedit) == TCPEDIT_ERROR) return TCPEDIT_ERROR; - + return TCPEDIT_OK; } - /** * What is the output DLT type??? */ -int +int tcpedit_dlt_output_dlt(tcpeditdlt_t *ctx) { uint16_t dlt; assert(ctx); - - /* + + /* * usually we just return the DLT value of the decoder, but for DLT_USER0 * we return a user-specified value via --user-dlt */ @@ -309,16 +293,18 @@ tcpedit_dlt_l2len(tcpeditdlt_t *ctx, int dlt, const u_char *packet, const int pk assert(ctx); assert(dlt >= 0); assert(packet); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to find plugin for DLT 0x%04x", dlt); - return -1; + return -1; } res = plugin->plugin_l2len(ctx, packet, pktlen); if (res == -1) { - tcpedit_seterr(ctx->tcpedit, "Packet length %d is to short to contain a layer 2 header for DLT 0x%04x", - pktlen, dlt); + tcpedit_seterr(ctx->tcpedit, + "Packet length %d is to short to contain a layer 2 header for DLT 0x%04x", + pktlen, + dlt); return -1; } @@ -341,7 +327,7 @@ tcpedit_dlt_proto(tcpeditdlt_t *ctx, int dlt, const u_char *packet, const int pk tcpedit_seterr(ctx->tcpedit, "Unable to find plugin for DLT 0x%04x", dlt); return -1; } - + return plugin->plugin_proto(ctx, packet, pktlen); } @@ -357,7 +343,7 @@ tcpedit_dlt_l3data(tcpeditdlt_t *ctx, int dlt, u_char *packet, const int pktlen) assert(ctx); assert(dlt >= 0); assert(packet); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to find plugin for DLT 0x%04x", dlt); return NULL; @@ -365,8 +351,10 @@ tcpedit_dlt_l3data(tcpeditdlt_t *ctx, int dlt, u_char *packet, const int pktlen) res = plugin->plugin_get_layer3(ctx, packet, pktlen); if (res == NULL) - tcpedit_seterr(ctx->tcpedit, "Packet length %d is to short to contain a layer 3 header for DLT 0x%04x", - pktlen, dlt); + tcpedit_seterr(ctx->tcpedit, + "Packet length %d is to short to contain a layer 3 header for DLT 0x%04x", + pktlen, + dlt); return res; } @@ -374,16 +362,16 @@ tcpedit_dlt_l3data(tcpeditdlt_t *ctx, int dlt, u_char *packet, const int pktlen) /** * \brief Merge the Layer 3 data back onto the mainbuffer so it's immediately * after the layer 2 header - * + * * Since some L2 headers aren't strictly aligned, we need to "merge" the packet w/ L2 data * and the L3 buffer. This is basically a NO-OP for things like vlan tagged ethernet (16 byte) header * or Cisco HDLC (4 byte header) but is critical for std ethernet (12 byte header) */ u_char * -tcpedit_dlt_merge_l3data(tcpeditdlt_t *ctx, - int dlt, - u_char *packet, - const int pktlen, +tcpedit_dlt_merge_l3data(tcpeditdlt_t *ctx, + int dlt, + u_char *packet, + const int pktlen, u_char *ipv4_data, u_char *ipv6_data) { @@ -396,7 +384,7 @@ tcpedit_dlt_merge_l3data(tcpeditdlt_t *ctx, if (ipv4_data == NULL && ipv6_data == NULL) return packet; - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to find plugin for DLT 0x%04x", dlt); return NULL; @@ -404,18 +392,15 @@ tcpedit_dlt_merge_l3data(tcpeditdlt_t *ctx, res = plugin->plugin_merge_layer3(ctx, packet, pktlen, ipv4_data, ipv6_data); if (res == NULL) - tcpedit_seterr(ctx->tcpedit, "Packet length %d is to short for layer 3 merge for DLT 0x%04x", - pktlen, dlt); + tcpedit_seterr(ctx->tcpedit, "Packet length %d is to short for layer 3 merge for DLT 0x%04x", pktlen, dlt); return res; } - - /** * Call the specific plugin decode() method */ -int +int tcpedit_dlt_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) { return ctx->decoder->plugin_decode(ctx, packet, pktlen); @@ -424,8 +409,8 @@ tcpedit_dlt_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /** * Call the specific plugin encode() method */ -int -tcpedit_dlt_encode(tcpeditdlt_t* ctx, u_char *packet, int pktlen, tcpr_dir_t direction) +int +tcpedit_dlt_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t direction) { return ctx->encoder->plugin_encode(ctx, packet, pktlen, direction); } @@ -433,7 +418,7 @@ tcpedit_dlt_encode(tcpeditdlt_t* ctx, u_char *packet, int pktlen, tcpr_dir_t dir /** * what is the source (decoder) DLT type? */ -int +int tcpedit_dlt_src(tcpeditdlt_t *ctx) { assert(ctx); @@ -443,14 +428,13 @@ tcpedit_dlt_src(tcpeditdlt_t *ctx) /** * What is the destination (encoder) DLT type */ -int +int tcpedit_dlt_dst(tcpeditdlt_t *ctx) { - assert(ctx); - return ctx->encoder->dlt; + assert(ctx); + return ctx->encoder->dlt; } - /** * cleanup after ourselves: destroys our context and all plugin data */ @@ -460,7 +444,7 @@ tcpedit_dlt_cleanup(tcpeditdlt_t *ctx) tcpeditdlt_plugin_t *plugin; assert(ctx); - + plugin = ctx->plugins; while (plugin != NULL) { plugin->plugin_cleanup(ctx); @@ -486,5 +470,3 @@ tcpedit_dlt_cleanup(tcpeditdlt_t *ctx) safe_free(ctx); } - - diff --git a/src/tcpedit/plugins/dlt_pppserial/pppserial.c b/src/tcpedit/plugins/dlt_pppserial/pppserial.c index 8a983819b..1ac135621 100644 --- a/src/tcpedit/plugins/dlt_pppserial/pppserial.c +++ b/src/tcpedit/plugins/dlt_pppserial/pppserial.c @@ -31,18 +31,12 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - +#include "pppserial.h" +#include "dlt_utils.h" +#include "tcpedit.h" #include #include -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" -#include "dlt_utils.h" -#include "tcpedit_stub.h" -#include "pppserial.h" -#include "pppserial_types.h" - static char dlt_name[] = "pppserial"; static u_int16_t dlt_value = 0x0032; @@ -57,7 +51,7 @@ static u_int16_t dlt_value = 0x0032; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_pppserial_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -70,14 +64,14 @@ dlt_pppserial_register(tcpeditdlt_t *ctx) plugin->provides += PLUGIN_MASK_PROTO; /* plugin->requires += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; */ - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_name); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_pppserial_init; @@ -97,20 +91,18 @@ dlt_pppserial_register(tcpeditdlt_t *ctx) return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_pppserial_init(tcpeditdlt_t *ctx) { - tcpeditdlt_plugin_t *plugin; assert(ctx); - - if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { + + if (tcpedit_dlt_getplugin(ctx, dlt_value) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } @@ -122,22 +114,22 @@ dlt_pppserial_init(tcpeditdlt_t *ctx) * Post init function. This function is called only once after init() and parse_opts() * It basically allows decoders to properly initialize sub-plugins. */ -int +int dlt_pppserial_post_init(tcpeditdlt_t _U_ *ctx) { -/* FIXME: Only needs to do something if we're using a sub-plugin - * See the jnpr_ether_plugin for an example of this - - pppserial_config_t *config; - - // do nothing if we're not the decoder - if (ctx->decoder->dlt != dlt_value) - return TCPEDIT_OK; - - // init our subcontext & decoder - config = (pppserial_config_t *)ctx->encoder->config; - config->subctx = tcpedit_dlt_init(ctx->tcpedit, SUB_PLUGIN_DLT_TYPE); -*/ + /* FIXME: Only needs to do something if we're using a sub-plugin + * See the jnpr_ether_plugin for an example of this + + pppserial_config_t *config; + + // do nothing if we're not the decoder + if (ctx->decoder->dlt != dlt_value) + return TCPEDIT_OK; + + // init our subcontext & decoder + config = (pppserial_config_t *)ctx->encoder->config; + config->subctx = tcpedit_dlt_init(ctx->tcpedit, SUB_PLUGIN_DLT_TYPE); + */ return TCPEDIT_OK; } @@ -146,7 +138,7 @@ dlt_pppserial_post_init(tcpeditdlt_t _U_ *ctx) * Unless you allocated some memory in dlt_pppserial_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_pppserial_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -181,7 +173,7 @@ dlt_pppserial_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_pppserial_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -201,8 +193,8 @@ dlt_pppserial_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { struct tcpr_pppserial_hdr *ppp = NULL; @@ -212,7 +204,7 @@ dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (pktlen < 4) return TCPEDIT_ERROR; - /* + /* * PPP has three fields: address, control and protocol * address should always be 0xff, and control seems pretty meaningless. * protocol field informs you of the following header, but alas does not @@ -220,18 +212,18 @@ dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) */ ppp = (struct tcpr_pppserial_hdr *)packet; switch (ntohs(ppp->protocol)) { - case 0x0021: /* IPv4 */ + case 0x0021: /* IPv4 */ ctx->proto = htons(ETHERTYPE_IP); ctx->l2len = 4; break; - default: - /* + default: + /* * PPP Seems to be using different protocol values then IEEE/802.x * but Wireshark seems to know how to decode them, so rather then - * returning TCPEDIT_SOFT_ERROR and skipping rewrite completely, + * returning TCPEDIT_SOFT_ERROR and skipping rewrite completely, * I just copy the packet payload over and let Wireshark figure it out - */ + */ ctx->l2len = 4; ctx->proto = ppp->protocol; } @@ -243,18 +235,17 @@ dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int +int dlt_pppserial_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); - + if (pktlen < 4) return TCPEDIT_ERROR; /* FIXME: make this function work */ - return pktlen; /* success */ } @@ -262,31 +253,31 @@ dlt_pppserial_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error * Make sure you return this value in NETWORK byte order! */ -int -dlt_pppserial_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_pppserial_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { struct tcpr_pppserial_hdr *ppp = NULL; - int protocol = 0; + int protocol; assert(ctx); assert(packet); if (pktlen < (int)sizeof(*ppp)) return TCPEDIT_ERROR; - + ppp = (struct tcpr_pppserial_hdr *)packet; switch (ntohs(ppp->protocol)) { - case 0x0021: /* IPv4 */ + case 0x0021: /* IPv4 */ protocol = ETHERTYPE_IP; break; - default: - tcpedit_seterr(ctx->tcpedit, "Packet " COUNTER_SPEC - " isn't IP. Skipping packet", - ctx->tcpedit->runtime.packetnum); + default: + tcpedit_seterr(ctx->tcpedit, + "Packet " COUNTER_SPEC " isn't IP. Skipping packet", + ctx->tcpedit->runtime.packetnum); return TCPEDIT_SOFT_ERROR; } - + return protocol; } @@ -294,7 +285,7 @@ dlt_pppserial_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_pppserial_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_pppserial_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -315,31 +306,26 @@ dlt_pppserial_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_pppserial_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_pppserial_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + l2len = dlt_pppserial_l2len(ctx, packet, pktlen); if (l2len == -1 || pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_pppserial_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t UNUSED(mac), - const u_char *packet, _U_ const int pktlen) +dlt_pppserial_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t UNUSED(mac), const u_char *packet, _U_ int pktlen) { assert(ctx); assert(packet); @@ -347,12 +333,11 @@ dlt_pppserial_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t UNUSED(mac), return NULL; } - -/* +/* * return the length of the L2 header of the current packet */ int -dlt_pppserial_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_pppserial_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -363,10 +348,8 @@ dlt_pppserial_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) return 4; } - -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_pppserial_l2addr_type(void) { return NONE; } - diff --git a/src/tcpedit/plugins/dlt_pppserial/pppserial.h b/src/tcpedit/plugins/dlt_pppserial/pppserial.h index 71fb15368..7bea1bed9 100644 --- a/src/tcpedit/plugins/dlt_pppserial/pppserial.h +++ b/src/tcpedit/plugins/dlt_pppserial/pppserial.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_pppserial_H_ -#define _DLT_pppserial_H_ +#pragma once #include "pppserial_types.h" @@ -28,18 +27,12 @@ int dlt_pppserial_init(tcpeditdlt_t *ctx); int dlt_pppserial_post_init(tcpeditdlt_t *ctx); int dlt_pppserial_cleanup(tcpeditdlt_t *ctx); int dlt_pppserial_parse_opts(tcpeditdlt_t *ctx); -int dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_pppserial_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_pppserial_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_pppserial_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_pppserial_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_pppserial_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_pppserial_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_pppserial_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char * +dlt_pppserial_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_pppserial_l2addr_type(void); -int dlt_pppserial_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_pppserial_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); - -#endif - +int dlt_pppserial_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_pppserial_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); diff --git a/src/tcpedit/plugins/dlt_pppserial/pppserial_api.c b/src/tcpedit/plugins/dlt_pppserial/pppserial_api.c index a8f69b44a..a0921074a 100644 --- a/src/tcpedit/plugins/dlt_pppserial/pppserial_api.c +++ b/src/tcpedit/plugins/dlt_pppserial/pppserial_api.c @@ -31,18 +31,17 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /* * FIXME: If you are creating an encoder plugin with any options - * then you need to create API calls for each option so that the + * then you need to create API calls for each option so that the * GUI or other programs using libtcpedit can set those values. * * Just uncomment the following headers, declare your methods in * pppserial_api.h and write them here... - + #include "common.h" -#include "tcpr.h" -#include "tcpedit.h" #include "pppserial_types.h" +#include "tcpedit.h" +#include "tcpr.h" */ diff --git a/src/tcpedit/plugins/dlt_pppserial/pppserial_api.h b/src/tcpedit/plugins/dlt_pppserial/pppserial_api.h index a7f263efb..f37c48003 100644 --- a/src/tcpedit/plugins/dlt_pppserial/pppserial_api.h +++ b/src/tcpedit/plugins/dlt_pppserial/pppserial_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,12 +18,11 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_pppserial_API_H_ -#define _DLT_pppserial_API_H_ +#pragma once -#include "tcpedit_types.h" #include "plugins_types.h" #include "pppserial_types.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { @@ -34,6 +33,3 @@ extern "C" { #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_pppserial/pppserial_types.h b/src/tcpedit/plugins/dlt_pppserial/pppserial_types.h index 5e6f8080e..3b7b33e4a 100644 --- a/src/tcpedit/plugins/dlt_pppserial/pppserial_types.h +++ b/src/tcpedit/plugins/dlt_pppserial/pppserial_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ - -#ifndef _DLT_pppserial_TYPES_H_ -#define _DLT_pppserial_TYPES_H_ +#pragma once #include "plugins_types.h" @@ -28,10 +26,6 @@ extern "C" { #endif - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_radiotap/radiotap.c b/src/tcpedit/plugins/dlt_radiotap/radiotap.c index 42906bf65..9e8754487 100644 --- a/src/tcpedit/plugins/dlt_radiotap/radiotap.c +++ b/src/tcpedit/plugins/dlt_radiotap/radiotap.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,16 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" -#include "dlt_utils.h" -#include "tcpedit_stub.h" #include "radiotap.h" #include "../dlt_ieee80211/ieee80211.h" +#include "dlt_utils.h" +#include "tcpedit.h" +#include "tcpedit_stub.h" +#include +#include /* edit these variables to taste */ static char dlt_name[] = "radiotap"; @@ -36,11 +33,11 @@ static uint16_t dlt_value = DLT_IEEE802_11_RADIO; /* * The Radiotap header plugin utilizes the 802.11 plugin internally to do all the work - * we just eat the radiotap header itself and pass the resulting buffer to the ieee80211 + * we just eat the radiotap header itself and pass the resulting buffer to the ieee80211 * plugin. */ -static u_char *dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen, const int radiolen); +static u_char *dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, int pktlen, int radiolen); /* * Function to register ourselves. This function is always called, regardless @@ -53,7 +50,7 @@ static u_char *dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, c * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_radiotap_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -64,16 +61,18 @@ dlt_radiotap_register(tcpeditdlt_t *ctx) /* we're a decoder only plugin, copy from ieee802.11 */ plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; - plugin->requires += 0; + plugin-> + requires + += 0; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_name); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_radiotap_init; @@ -94,11 +93,11 @@ dlt_radiotap_register(tcpeditdlt_t *ctx) /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_radiotap_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -113,8 +112,7 @@ dlt_radiotap_init(tcpeditdlt_t *ctx) if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(radiotap_extra_t)) { ctx->decoded_extra_size = sizeof(radiotap_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(radiotap_extra_t); @@ -133,7 +131,7 @@ dlt_radiotap_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_radiotap_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_radiotap_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -149,7 +147,7 @@ dlt_radiotap_cleanup(tcpeditdlt_t *ctx) safe_free(plugin->config); plugin->config = NULL; plugin->config_size = 0; - + return TCPEDIT_OK; /* success */ } @@ -159,13 +157,13 @@ dlt_radiotap_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_radiotap_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); /* we have none */ - + return TCPEDIT_OK; /* success */ } @@ -179,8 +177,8 @@ dlt_radiotap_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int radiolen, rcode; u_char *data; @@ -189,7 +187,7 @@ dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if (pktlen < (int)sizeof(radiotap_hdr_t)) return TCPEDIT_ERROR; - + radiolen = dlt_radiotap_l2len(ctx, packet, pktlen); data = dlt_radiotap_get_80211(ctx, packet, pktlen, radiolen); if (!data) @@ -197,7 +195,7 @@ dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) /* ieee80211 decoder fills out everything */ rcode = dlt_ieee80211_decode(ctx, data, pktlen - radiolen); - + /* need to override the ieee802.11 l2 length result */ ctx->l2len = dlt_radiotap_80211_l2len(ctx, packet, pktlen); return (ctx->l2len > 0) ? rcode : TCPEDIT_ERROR; @@ -207,13 +205,12 @@ dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_radiotap_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, - _U_ tcpr_dir_t dir) +int +dlt_radiotap_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); - + tcpedit_seterr(ctx->tcpedit, "%s", "DLT_IEEE802_11_RADIO plugin does not support packet encoding"); return TCPEDIT_ERROR; } @@ -223,8 +220,8 @@ dlt_radiotap_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, * Make sure you return this in host byte order since all the comparisons will be * against the ETHERTYPE_* values which are oddly in host byte order. */ -int -dlt_radiotap_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_radiotap_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int radiolen; u_char *data; @@ -246,14 +243,14 @@ dlt_radiotap_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_radiotap_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_radiotap_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int radiolen, l2len; u_char *data; - + assert(ctx); assert(packet); - + radiolen = dlt_radiotap_l2len(ctx, packet, pktlen); data = dlt_radiotap_get_80211(ctx, packet, pktlen, radiolen); l2len = dlt_ieee80211_l2len(ctx, data, pktlen - radiolen); @@ -267,15 +264,11 @@ dlt_radiotap_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_radiotap_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_radiotap_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int radiolen, l2len; u_char *data; - + assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); @@ -289,13 +282,13 @@ dlt_radiotap_merge_layer3(tcpeditdlt_t *ctx, /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_radiotap_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) +dlt_radiotap_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { int radiolen; u_char *data; - + assert(ctx); assert(packet); @@ -308,13 +301,11 @@ dlt_radiotap_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char return dlt_ieee80211_get_mac(ctx, mac, data, pktlen - radiolen); } - - -/* +/* * return the length of the L2 header of the current packet */ int -dlt_radiotap_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_radiotap_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { uint16_t radiolen; assert(ctx); @@ -329,15 +320,15 @@ dlt_radiotap_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) return (int)radiolen; } -/* +/* * return the length of the L2 header w/ 802.11 header of the current packet */ int -dlt_radiotap_80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +dlt_radiotap_80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int radiolen, res; u_char *data; - + radiolen = dlt_radiotap_l2len(ctx, packet, pktlen); if (radiolen == -1) return TCPEDIT_ERROR; @@ -351,21 +342,20 @@ dlt_radiotap_80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktl return radiolen; } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_radiotap_l2addr_type(void) { /* FIXME: return the tcpeditdlt_l2addr_type_t value that this DLT uses */ return ETHERNET; } -/* +/* * returns a buffer to the 802.11 header in the packet. * This does an optimization of only doing a memcpy() once per packet * since we track which was the last packet # we copied. */ static u_char * -dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, - const int pktlen, const int radiolen) +dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, int pktlen, int radiolen) { radiotap_extra_t *extra; static COUNTER lastpacket = 0; @@ -374,9 +364,8 @@ dlt_radiotap_get_80211(tcpeditdlt_t *ctx, const u_char *packet, return NULL; extra = (radiotap_extra_t *)(ctx->decoded_extra); - if (pktlen >= radiolen && - (size_t)(pktlen - radiolen) >= sizeof(extra->packet) && - lastpacket != ctx->tcpedit->runtime.packetnum) { + if (pktlen >= radiolen && (size_t)(pktlen - radiolen) >= sizeof(extra->packet) && + lastpacket != ctx->tcpedit->runtime.packetnum) { memcpy(extra->packet, &packet[radiolen], pktlen - radiolen); lastpacket = ctx->tcpedit->runtime.packetnum; } diff --git a/src/tcpedit/plugins/dlt_radiotap/radiotap.h b/src/tcpedit/plugins/dlt_radiotap/radiotap.h index f4d3dc0c3..dfd061e98 100644 --- a/src/tcpedit/plugins/dlt_radiotap/radiotap.h +++ b/src/tcpedit/plugins/dlt_radiotap/radiotap.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,9 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ - -#ifndef _DLT_radiotap_H_ -#define _DLT_radiotap_H_ +#pragma once #include "plugins_types.h" @@ -28,19 +26,15 @@ int dlt_radiotap_register(tcpeditdlt_t *ctx); int dlt_radiotap_init(tcpeditdlt_t *ctx); int dlt_radiotap_cleanup(tcpeditdlt_t *ctx); int dlt_radiotap_parse_opts(tcpeditdlt_t *ctx); -int dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_radiotap_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_radiotap_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_radiotap_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_radiotap_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_radiotap_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_radiotap_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_radiotap_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char *dlt_radiotap_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_radiotap_l2addr_type(void); -int dlt_radiotap_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -int dlt_radiotap_80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_radiotap_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_radiotap_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +int dlt_radiotap_80211_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_radiotap_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); /* * FIXME: structure to hold any data parsed from the packet by the decoder. @@ -51,18 +45,17 @@ struct radiotap_extra_s { }; typedef struct radiotap_extra_s radiotap_extra_t; - -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ struct radiotap_config_s { - /* dummy entry for SunPro compiler which doesn't like empty structs */ + /* dummy entry for SunPro compiler which doesn't like empty structs */ int dummy; }; typedef struct radiotap_config_s radiotap_config_t; @@ -75,6 +68,3 @@ struct radiotap_hdr_s { u_int32_t present; /* flags of present headers */ }; typedef struct radiotap_hdr_s radiotap_hdr_t; - -#endif - diff --git a/src/tcpedit/plugins/dlt_raw/raw.c b/src/tcpedit/plugins/dlt_raw/raw.c index e3b46a643..cc801b1a2 100644 --- a/src/tcpedit/plugins/dlt_raw/raw.c +++ b/src/tcpedit/plugins/dlt_raw/raw.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "raw.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "raw.h" +#include +#include static char dlt_name[] = "raw"; static char _U_ dlt_prefix[] = "raw"; @@ -47,7 +44,7 @@ static uint16_t dlt_value = DLT_RAW; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_raw_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -59,14 +56,14 @@ dlt_raw_register(tcpeditdlt_t *ctx) /* set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_raw_init; @@ -80,19 +77,18 @@ dlt_raw_register(tcpeditdlt_t *ctx) plugin->plugin_get_layer3 = dlt_raw_get_layer3; plugin->plugin_merge_layer3 = dlt_raw_merge_layer3; plugin->plugin_get_mac = dlt_raw_get_mac; - + /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_raw_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -107,8 +103,7 @@ dlt_raw_init(tcpeditdlt_t *ctx) if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < sizeof(raw_extra_t)) { ctx->decoded_extra_size = sizeof(raw_extra_t); - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = sizeof(raw_extra_t); @@ -127,7 +122,7 @@ dlt_raw_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_raw_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_raw_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -153,7 +148,7 @@ dlt_raw_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_raw_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -172,8 +167,8 @@ dlt_raw_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { int proto; assert(ctx); @@ -184,7 +179,7 @@ dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) if ((proto = dlt_raw_proto(ctx, packet, pktlen)) == TCPEDIT_ERROR) return TCPEDIT_ERROR; - + ctx->proto = (uint16_t)proto; ctx->l2len = 0; @@ -195,27 +190,26 @@ dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_raw_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, - _U_ tcpr_dir_t dir) +int +dlt_raw_encode(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); - + tcpedit_seterr(ctx->tcpedit, "%s", "DLT_RAW plugin does not support packet encoding"); - return TCPEDIT_ERROR; + return TCPEDIT_ERROR; } /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int +dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { struct tcpr_ipv4_hdr *iphdr; assert(ctx); assert(packet); - int protocol = 0; + int protocol; if (pktlen < (int)sizeof(*iphdr)) return TCPEDIT_ERROR; @@ -229,7 +223,7 @@ dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) tcpedit_seterr(ctx->tcpedit, "%s", "Unsupported DLT_RAW packet: doesn't look like IPv4 or IPv6"); return TCPEDIT_ERROR; } - + return htons(protocol); } @@ -237,11 +231,11 @@ dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_raw_get_layer3(tcpeditdlt_t *ctx, u_char *packet, _U_ const int pktlen) +dlt_raw_get_layer3(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen) { assert(ctx); assert(packet); - + /* raw has a zero byte header, so this is basically a non-op */ return packet; @@ -254,26 +248,22 @@ dlt_raw_get_layer3(tcpeditdlt_t *ctx, u_char *packet, _U_ const int pktlen) * like SPARC */ u_char * -dlt_raw_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, _U_ - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_raw_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, _U_ int pktlen, u_char *ipv4_data, u_char *ipv6_data) { assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + /* raw has a zero byte header, so this is basically a non-op */ - + return packet; } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_raw_l2len(tcpeditdlt_t *ctx, const u_char *packet, _U_ const int pktlen) +dlt_raw_l2len(tcpeditdlt_t *ctx, const u_char *packet, _U_ int pktlen) { assert(ctx); assert(packet); @@ -284,20 +274,18 @@ dlt_raw_l2len(tcpeditdlt_t *ctx, const u_char *packet, _U_ const int pktlen) /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_raw_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, - const u_char *packet, _U_ const int pktlen) +dlt_raw_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, const u_char *packet, _U_ int pktlen) { assert(ctx); assert(packet); - return(NULL); + return (NULL); } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_raw_l2addr_type(void) { return NONE; } - diff --git a/src/tcpedit/plugins/dlt_raw/raw.h b/src/tcpedit/plugins/dlt_raw/raw.h index 41893c5bb..0a7e45d32 100644 --- a/src/tcpedit/plugins/dlt_raw/raw.h +++ b/src/tcpedit/plugins/dlt_raw/raw.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_raw_H_ -#define _DLT_raw_H_ +#pragma once #include "plugins_types.h" @@ -27,18 +26,14 @@ int dlt_raw_register(tcpeditdlt_t *ctx); int dlt_raw_init(tcpeditdlt_t *ctx); int dlt_raw_cleanup(tcpeditdlt_t *ctx); int dlt_raw_parse_opts(tcpeditdlt_t *ctx); -int dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_raw_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_raw_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_raw_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_raw_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_raw_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_raw_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char *dlt_raw_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_raw_l2addr_type(void); -int dlt_raw_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_raw_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_raw_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_raw_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); /* * structure to hold any data parsed from the packet by the decoder. @@ -49,20 +44,17 @@ struct raw_extra_s { }; typedef struct raw_extra_s raw_extra_t; -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ struct raw_config_s { - /* dummy entry for SunPro compiler which doesn't like empty structs */ + /* dummy entry for SunPro compiler which doesn't like empty structs */ int dummy; }; typedef struct raw_config_s raw_config_t; - -#endif - diff --git a/src/tcpedit/plugins/dlt_template/plugin.c.tmpl b/src/tcpedit/plugins/dlt_template/plugin.c.tmpl index 78da4b25f..542d5b4f4 100644 --- a/src/tcpedit/plugins/dlt_template/plugin.c.tmpl +++ b/src/tcpedit/plugins/dlt_template/plugin.c.tmpl @@ -31,15 +31,14 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include -#include - #include "defines.h" #include "common.h" -#include "tcpr.h" -#include "tcpedit.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" +#include "tcpr.h" +#include +#include #include "%{plugin}.h" #include "%{plugin}_types.h" @@ -59,8 +58,7 @@ static u_int16_t dlt_value = 0xFFFF; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_%{plugin}_register(tcpeditdlt_t *ctx) +int dlt_ % {plugin} _register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); @@ -68,67 +66,65 @@ dlt_%{plugin}_register(tcpeditdlt_t *ctx) /* create a new plugin structure */ plugin = tcpedit_dlt_newplugin(); - /* FIXME: set what we provide & require + /* FIXME: set what we provide & require plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; plugin->requires += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; */ - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_name); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ - plugin->plugin_init = dlt_%{plugin}_init; - plugin->plugin_post_init = dlt_%{plugin}_init; - plugin->plugin_cleanup = dlt_%{plugin}_cleanup; - plugin->plugin_parse_opts = dlt_%{plugin}_parse_opts; - plugin->plugin_decode = dlt_%{plugin}_decode; - plugin->plugin_encode = dlt_%{plugin}_encode; - plugin->plugin_proto = dlt_%{plugin}_proto; - plugin->plugin_l2addr_type = dlt_%{plugin}_l2addr_type; - plugin->plugin_l2len = dlt_%{plugin}_l2len; - plugin->plugin_get_layer3 = dlt_%{plugin}_get_layer3; - plugin->plugin_merge_layer3 = dlt_%{plugin}_merge_layer3; - plugin->plugin_get_mac = dlt_%{plugin}_get_mac; + plugin->plugin_init = dlt_ % {plugin} _init; + plugin->plugin_post_init = dlt_ % {plugin} _init; + plugin->plugin_cleanup = dlt_ % {plugin} _cleanup; + plugin->plugin_parse_opts = dlt_ % {plugin} _parse_opts; + plugin->plugin_decode = dlt_ % {plugin} _decode; + plugin->plugin_encode = dlt_ % {plugin} _encode; + plugin->plugin_proto = dlt_ % {plugin} _proto; + plugin->plugin_l2addr_type = dlt_ % {plugin} _l2addr_type; + plugin->plugin_l2len = dlt_ % {plugin} _l2len; + plugin->plugin_get_layer3 = dlt_ % {plugin} _get_layer3; + plugin->plugin_merge_layer3 = dlt_ % {plugin} _merge_layer3; + plugin->plugin_get_mac = dlt_ % {plugin} _get_mac; /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_%{plugin}_init(tcpeditdlt_t *ctx) +int dlt_ % {plugin} _init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; - %{plugin}_config_t *config; + % {plugin} _config_t *config; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + /* allocate memory for our deocde extra data */ - if (sizeof(%{plugin}_extra_t) > 0) - ctx->decoded_extra = safe_malloc(sizeof(%{plugin}_extra_t)); + if (sizeof(% {plugin} _extra_t) > 0) + ctx->decoded_extra = safe_malloc(sizeof(% {plugin} _extra_t)); /* allocate memory for our config data */ - if (sizeof(%{plugin}_config_t) > 0) - plugin->config = safe_malloc(sizeof(%{plugin}_config_t)); - - config = (%{plugin}_config_t *)plugin->config; - + if (sizeof(% {plugin} _config_t) > 0) + plugin->config = safe_malloc(sizeof(% {plugin} _config_t)); + + config = (% {plugin} _config_t *)plugin->config; + /* FIXME: set default config values here */ return TCPEDIT_OK; /* success */ @@ -138,22 +134,21 @@ dlt_%{plugin}_init(tcpeditdlt_t *ctx) * Post init function. This function is called only once after init() and parse_opts() * It basically allows decoders to properly initialize sub-plugins. */ -int -dlt_%{plugin}_post_init(tcpeditdlt_t *ctx) +int dlt_ % {plugin} _post_init(tcpeditdlt_t *ctx) { -/* FIXME: Only needs to do something if we're using a sub-plugin - * See the jnpr_ether_plugin for an example of this - - %{plugin}_config_t *config; - - // do nothing if we're not the decoder - if (ctx->decoder->dlt != dlt_value) - return TCPEDIT_OK; - - // init our subcontext & decoder - config = (%{plugin}_config_t *)ctx->encoder->config; - config->subctx = tcpedit_dlt_init(ctx->tcpedit, SUB_PLUGIN_DLT_TYPE); -*/ + /* FIXME: Only needs to do something if we're using a sub-plugin + * See the jnpr_ether_plugin for an example of this + + %{plugin}_config_t *config; + + // do nothing if we're not the decoder + if (ctx->decoder->dlt != dlt_value) + return TCPEDIT_OK; + + // init our subcontext & decoder + config = (%{plugin}_config_t *)ctx->encoder->config; + config->subctx = tcpedit_dlt_init(ctx->tcpedit, SUB_PLUGIN_DLT_TYPE); + */ return TCPEDIT_OK; } @@ -162,8 +157,7 @@ dlt_%{plugin}_post_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_%{plugin}_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_%{plugin}_cleanup(tcpeditdlt_t *ctx) +int dlt_ % {plugin} _cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; assert(ctx); @@ -178,7 +172,7 @@ dlt_%{plugin}_cleanup(tcpeditdlt_t *ctx) safe_free(ctx->decoded_extra); ctx->decoded_extra = NULL; } - + if (plugin->config != NULL) { safe_free(plugin->config); plugin->config = NULL; @@ -193,8 +187,7 @@ dlt_%{plugin}_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_%{plugin}_parse_opts(tcpeditdlt_t *ctx) +int dlt_ % {plugin} _parse_opts(tcpeditdlt_t *ctx) { assert(ctx); @@ -213,8 +206,7 @@ dlt_%{plugin}_parse_opts(tcpeditdlt_t *ctx) * - ctx->decoded_extra * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int -dlt_%{plugin}_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int dlt_ % {plugin} _decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -231,18 +223,16 @@ dlt_%{plugin}_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int -dlt_%{plugin}_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t dir) +int dlt_ % {plugin} _encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir_t dir) { assert(ctx); assert(packet); if (pktlen < /* FIXME: our L2 length */) return TCPEDIT_ERROR; - + /* FIXME: make this function work */ - return pktlen; /* success */ } @@ -250,33 +240,31 @@ dlt_%{plugin}_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, _U_ tcpr_dir * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error * Make sure you return this value in NETWORK byte order! */ -int -dlt_%{plugin}_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int dlt_ % {plugin} _proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); - int protocol; + int protocol; if (pktlen > /* FIXME: our L2 length */) return TCPEDIT_ERROR; - + /* FIXME: make this function work */ - + return protocol; } /* * Function returns a pointer to the layer 3 protocol header or NULL on error */ -u_char * -dlt_%{plugin}_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +u_char *dlt_ % {plugin} _get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); assert(packet); /* FIXME: Is there anything else we need to do?? */ - l2len = dlt_%{plugin}_l2len(ctx, packet, pktlen); + l2len = dlt_ % {plugin} _l2len(ctx, packet, pktlen); if (pktlen < l2len) return NULL; @@ -290,29 +278,28 @@ dlt_%{plugin}_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * same buffer, otherwise there was a memcpy involved on strictly aligned architectures * like SPARC */ -u_char * -dlt_%{plugin}_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen, u_char *l3data) +u_char *dlt_ % {plugin} _merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *l3data) { int l2len; assert(ctx); assert(packet); assert(l3data); - + /* FIXME: Is there anything else we need to do?? */ - l2len = dlt_%{plugin}_l2len(ctx, packet, pktlen); - - if (pktlen < l2len); - return NULL; - + l2len = dlt_ % {plugin} _l2len(ctx, packet, pktlen); + + if (pktlen < l2len) + ; + return NULL; + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, l3data, l2len); } /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ -u_char * -dlt_%{plugin}_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen) + */ +u_char *dlt_ % {plugin} _get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -321,28 +308,26 @@ dlt_%{plugin}_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char return NULL; /* FIXME: return a ptr to the source or dest mac address. */ - switch(mac) { + switch (mac) { case SRC_MAC: memcpy(ctx->srcmac, packet, length); - return(ctx->srcmac); + return (ctx->srcmac); break; - + case DST_MAC: memcpy(ctx->dstmac, packet, length); - return(ctx->dstmac); + return (ctx->dstmac); break; - + default: errx(-1, "Invalid tcpeditdlt_mac_type_t: %d", mac); } } - -/* +/* * return the length of the L2 header of the current packet */ -int -dlt_%{plugin}_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) +int dlt_ % {plugin} _l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen) { assert(ctx); assert(packet); @@ -354,11 +339,8 @@ dlt_%{plugin}_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen) return 14; } - -tcpeditdlt_l2addr_type_t -dlt_%{plugin}_l2addr_type(void) +tcpeditdlt_l2addr_type_t dlt_ % {plugin} _l2addr_type(void) { /* FIXME: return the tcpeditdlt_l2addr_type_t value that this DLT uses */ return ETHERNET; } - diff --git a/src/tcpedit/plugins/dlt_template/plugin.h b/src/tcpedit/plugins/dlt_template/plugin.h index c269ebe4f..1e69bce7a 100644 --- a/src/tcpedit/plugins/dlt_template/plugin.h +++ b/src/tcpedit/plugins/dlt_template/plugin.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_%{plugin}_H_ -#define _DLT_%{plugin}_H_ +#pragma once #include "%{plugin}_types.h" @@ -28,14 +27,12 @@ int dlt_%{plugin}_init(tcpeditdlt_t *ctx); int dlt_%{plugin}_post_init(tcpeditdlt_t *ctx); int dlt_%{plugin}_cleanup(tcpeditdlt_t *ctx); int dlt_%{plugin}_parse_opts(tcpeditdlt_t *ctx); -int dlt_%{plugin}_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_%{plugin}_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_%{plugin}_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_%{plugin}_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_%{plugin}_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_%{plugin}_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen, u_char *l3data); +int dlt_%{plugin}_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_%{plugin}_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char *dlt_%{plugin}_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *l3data); tcpeditdlt_l2addr_type_t dlt_%{plugin}_l2addr_type(void); -int dlt_%{plugin}_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_%{plugin}_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); - -#endif +int dlt_%{plugin}_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_%{plugin}_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); diff --git a/src/tcpedit/plugins/dlt_template/plugin_api.h b/src/tcpedit/plugins/dlt_template/plugin_api.h index 247ba9af7..bf6d47101 100644 --- a/src/tcpedit/plugins/dlt_template/plugin_api.h +++ b/src/tcpedit/plugins/dlt_template/plugin_api.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_%{plugin}_API_H_ -#define _DLT_%{plugin}_API_H_ +#pragma once #include "tcpedit_types.h" #include "plugins_types.h" @@ -35,5 +34,3 @@ extern "C" { } #endif -#endif - diff --git a/src/tcpedit/plugins/dlt_template/plugin_types.h b/src/tcpedit/plugins/dlt_template/plugin_types.h index 4302ac2f5..e0a6615fc 100644 --- a/src/tcpedit/plugins/dlt_template/plugin_types.h +++ b/src/tcpedit/plugins/dlt_template/plugin_types.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_%{plugin}_TYPES_H_ -#define _DLT_%{plugin}_TYPES_H_ +#pragma once /* any includes go here */ @@ -53,5 +52,3 @@ typedef struct { } #endif -#endif - diff --git a/src/tcpedit/plugins/dlt_user/user.c b/src/tcpedit/plugins/dlt_user/user.c index 07cd0fce2..b086670f5 100644 --- a/src/tcpedit/plugins/dlt_user/user.c +++ b/src/tcpedit/plugins/dlt_user/user.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include - -#include "tcpedit.h" -#include "common.h" -#include "tcpr.h" +#include "user.h" #include "dlt_utils.h" +#include "tcpedit.h" #include "tcpedit_stub.h" -#include "user.h" +#include +#include static char dlt_name[] = "user"; static char _U_ dlt_prefix[] = "user"; @@ -43,7 +40,7 @@ static uint16_t dlt_value = DLT_USER0; * - Add the plugin to the context's plugin chain * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_user_register(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -54,16 +51,18 @@ dlt_user_register(tcpeditdlt_t *ctx) /* FIXME: set what we provide & require */ plugin->provides += PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; - plugin->requires += 0; // PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; + plugin-> + requires + += 0; // PLUGIN_MASK_PROTO + PLUGIN_MASK_SRCADDR + PLUGIN_MASK_DSTADDR; - /* what is our DLT value? */ + /* what is our DLT value? */ plugin->dlt = dlt_value; /* set the prefix name of our plugin. This is also used as the prefix for our options */ plugin->name = safe_strdup(dlt_prefix); - /* - * Point to our functions, note, you need a function for EVERY method. + /* + * Point to our functions, note, you need a function for EVERY method. * Even if it is only an empty stub returning success. */ plugin->plugin_init = dlt_user_init; @@ -77,38 +76,36 @@ dlt_user_register(tcpeditdlt_t *ctx) plugin->plugin_get_layer3 = dlt_user_get_layer3; plugin->plugin_merge_layer3 = dlt_user_merge_layer3; plugin->plugin_get_mac = dlt_user_get_mac; - + /* add it to the available plugin list */ return tcpedit_dlt_addplugin(ctx, plugin); } - /* * Initializer function. This function is called only once, if and only if - * this plugin will be utilized. Remember, if you need to keep track of any state, + * this plugin will be utilized. Remember, if you need to keep track of any state, * store it in your plugin->config, not a global! * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_user_init(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; user_config_t *config; assert(ctx); - + if ((plugin = tcpedit_dlt_getplugin(ctx, dlt_value)) == NULL) { tcpedit_seterr(ctx->tcpedit, "Unable to initialize unregistered plugin %s", dlt_name); return TCPEDIT_ERROR; } - + /* allocate memory for our decode extra data - plus some space for * other DLT decodes */ if (ctx->decoded_extra_size > 0) { if (ctx->decoded_extra_size < USER_L2MAXLEN) { ctx->decoded_extra_size = USER_L2MAXLEN; - ctx->decoded_extra = safe_realloc(ctx->decoded_extra, - ctx->decoded_extra_size); + ctx->decoded_extra = safe_realloc(ctx->decoded_extra, ctx->decoded_extra_size); } } else { ctx->decoded_extra_size = USER_L2MAXLEN; @@ -118,10 +115,10 @@ dlt_user_init(tcpeditdlt_t *ctx) /* allocate memory for our config data */ plugin->config_size = sizeof(user_config_t); plugin->config = safe_malloc(plugin->config_size); - + config = (user_config_t *)plugin->config; config->length = -1; - + /* do nothing */ return TCPEDIT_OK; /* success */ } @@ -131,7 +128,7 @@ dlt_user_init(tcpeditdlt_t *ctx) * Unless you allocated some memory in dlt_user_init(), this is just an stub. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_user_cleanup(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -157,7 +154,7 @@ dlt_user_cleanup(tcpeditdlt_t *ctx) * bit mask. * Returns: TCPEDIT_ERROR | TCPEDIT_OK | TCPEDIT_WARN */ -int +int dlt_user_parse_opts(tcpeditdlt_t *ctx) { tcpeditdlt_plugin_t *plugin; @@ -173,7 +170,7 @@ dlt_user_parse_opts(tcpeditdlt_t *ctx) return TCPEDIT_ERROR; /* - * --user-dlt will override the output DLT type, otherwise we'll use + * --user-dlt will override the output DLT type, otherwise we'll use * the DLT of the decoder */ if (HAVE_OPT(USER_DLT)) { @@ -184,19 +181,18 @@ dlt_user_parse_opts(tcpeditdlt_t *ctx) /* --user-dlink */ if (HAVE_OPT(USER_DLINK)) { - int ct = STACKCT_OPT(USER_DLINK); - char **list = (char**)STACKLST_OPT(USER_DLINK); + int ct = STACKCT_OPT(USER_DLINK); + char **list = (char **)STACKLST_OPT(USER_DLINK); int first = 1; - - do { + + do { char *p = *list++; if (first) { config->length = read_hexstring(p, config->l2server, USER_L2MAXLEN); memcpy(config->l2client, config->l2server, config->length); } else { if (config->length != read_hexstring(p, config->l2client, USER_L2MAXLEN)) { - tcpedit_seterr(ctx->tcpedit, "%s", - "both --dlink's must contain the same number of bytes"); + tcpedit_seterr(ctx->tcpedit, "%s", "both --dlink's must contain the same number of bytes"); return TCPEDIT_ERROR; } } @@ -204,13 +200,13 @@ dlt_user_parse_opts(tcpeditdlt_t *ctx) first = 0; } while (--ct > 0); } - + return TCPEDIT_OK; /* success */ } /* you should never decode packets with this plugin! */ -int -dlt_user_decode(tcpeditdlt_t *ctx, const u_char *packet, const int _U_ pktlen) +int +dlt_user_decode(tcpeditdlt_t *ctx, const u_char *packet, int _U_ pktlen) { assert(ctx); assert(packet); @@ -223,7 +219,7 @@ dlt_user_decode(tcpeditdlt_t *ctx, const u_char *packet, const int _U_ pktlen) * Function to encode the layer 2 header back into the packet. * Returns: total packet len or TCPEDIT_ERROR */ -int +int dlt_user_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) { user_config_t *config; @@ -234,7 +230,7 @@ dlt_user_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) if (pktlen == 0) return TCPEDIT_ERROR; - + plugin = tcpedit_dlt_getplugin(ctx, dlt_value); if (!plugin) return TCPEDIT_ERROR; @@ -255,7 +251,7 @@ dlt_user_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) /* update the total packet length */ pktlen += config->length - ctx->l2len; - + if (dir == TCPR_DIR_C2S) { memcpy(packet, config->l2client, config->length); } else if (dir == TCPR_DIR_S2C) { @@ -264,30 +260,29 @@ dlt_user_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir) tcpedit_seterr(ctx->tcpedit, "%s", "Encoders only support C2S or C2S!"); return TCPEDIT_ERROR; } - - + return pktlen; /* success */ } /* * Function returns the Layer 3 protocol type of the given packet, or TCPEDIT_ERROR on error */ -int -dlt_user_proto(tcpeditdlt_t *ctx, const u_char *packet, const int _U_ pktlen) +int +dlt_user_proto(tcpeditdlt_t *ctx, const u_char *packet, int _U_ pktlen) { assert(ctx); assert(packet); /* calling this for DLT_USER0 is broken */ tcpedit_seterr(ctx->tcpedit, "%s", "Nonsensical calling of dlt_user_proto()"); - return TCPEDIT_ERROR; + return TCPEDIT_ERROR; } /* * Function returns a pointer to the layer 3 protocol header or NULL on error */ u_char * -dlt_user_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) +dlt_user_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen) { int l2len; assert(ctx); @@ -309,30 +304,26 @@ dlt_user_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen) * like SPARC */ u_char * -dlt_user_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data) +dlt_user_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data) { int l2len; assert(ctx); assert(packet); assert(ipv4_data || ipv6_data); - + /* FIXME: Is there anything else we need to do?? */ l2len = dlt_user_l2len(ctx, packet, pktlen); if (l2len == TCPEDIT_ERROR || pktlen < l2len) return NULL; - + return tcpedit_dlt_l3data_merge(ctx, packet, pktlen, ipv4_data ?: ipv6_data, l2len); } -/* +/* * return the length of the L2 header of the current packet */ int -dlt_user_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int _U_ pktlen) +dlt_user_l2len(tcpeditdlt_t *ctx, const u_char *packet, int _U_ pktlen) { tcpeditdlt_plugin_t *plugin; user_config_t *config; @@ -353,19 +344,18 @@ dlt_user_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int _U_ pktlen) /* * return a static pointer to the source/destination MAC address * return NULL on error/address doesn't exist - */ + */ u_char * -dlt_user_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, - const u_char *packet, const int _U_ pktlen) +dlt_user_get_mac(tcpeditdlt_t *ctx, _U_ tcpeditdlt_mac_type_t mac, const u_char *packet, int _U_ pktlen) { assert(ctx); assert(packet); /* we don't know the format of USER DLT, hence always return NULL */ - return(NULL); + return (NULL); } -tcpeditdlt_l2addr_type_t +tcpeditdlt_l2addr_type_t dlt_user_l2addr_type(void) { return NONE; @@ -384,7 +374,5 @@ dlt_user_get_output_dlt(tcpeditdlt_t *ctx) plugin = tcpedit_dlt_getplugin(ctx, dlt_value); config = plugin->config; - return config->dlt; + return config->dlt; } - - diff --git a/src/tcpedit/plugins/dlt_user/user.h b/src/tcpedit/plugins/dlt_user/user.h index 947a2687d..94b5d18ac 100644 --- a/src/tcpedit/plugins/dlt_user/user.h +++ b/src/tcpedit/plugins/dlt_user/user.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_user_H_ -#define _DLT_user_H_ +#pragma once #include "plugins_types.h" #include "user_types.h" @@ -32,18 +31,15 @@ int dlt_user_register(tcpeditdlt_t *ctx); int dlt_user_init(tcpeditdlt_t *ctx); int dlt_user_cleanup(tcpeditdlt_t *ctx); int dlt_user_parse_opts(tcpeditdlt_t *ctx); -int dlt_user_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); +int dlt_user_decode(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); int dlt_user_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t dir); -int dlt_user_proto(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_user_get_layer3(tcpeditdlt_t *ctx, u_char *packet, const int pktlen); -u_char *dlt_user_merge_layer3(tcpeditdlt_t *ctx, - u_char *packet, - const int pktlen, - u_char *ipv4_data, - u_char *ipv6_data); +int dlt_user_proto(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_user_get_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen); +u_char * +dlt_user_merge_layer3(tcpeditdlt_t *ctx, u_char *packet, int pktlen, u_char *ipv4_data, u_char *ipv6_data); tcpeditdlt_l2addr_type_t dlt_user_l2addr_type(void); -int dlt_user_l2len(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -u_char *dlt_user_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, const int pktlen); +int dlt_user_l2len(tcpeditdlt_t *ctx, const u_char *packet, int pktlen); +u_char *dlt_user_get_mac(tcpeditdlt_t *ctx, tcpeditdlt_mac_type_t mac, const u_char *packet, int pktlen); /* extra function called directly by tcpedit_dlt_output_dlt() */ u_int16_t dlt_user_get_output_dlt(tcpeditdlt_t *ctx); @@ -51,6 +47,3 @@ u_int16_t dlt_user_get_output_dlt(tcpeditdlt_t *ctx); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_user/user_api.c b/src/tcpedit/plugins/dlt_user/user_api.c index cf741bad5..eea2544f8 100644 --- a/src/tcpedit/plugins/dlt_user/user_api.c +++ b/src/tcpedit/plugins/dlt_user/user_api.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,21 +18,15 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "user_api.h" +#include "tcpedit.h" #include #include -#include "defines.h" -#include "common.h" - -#include "tcpedit.h" -#include "user.h" - -#include "user_api.h" - /** * \brief Define the libpcap DLT Type value */ -int +int tcpedit_user_set_dlt_type(tcpedit_t *tcpedit, uint16_t type) { tcpeditdlt_t *ctx; @@ -46,7 +40,7 @@ tcpedit_user_set_dlt_type(tcpedit_t *tcpedit, uint16_t type) plugin = ctx->decoder; assert(plugin); config = (user_config_t *)plugin->config; - + config->dlt = type; return TCPEDIT_OK; } @@ -58,10 +52,10 @@ tcpedit_user_set_dlt_type(tcpedit_t *tcpedit, uint16_t type) * BOTH - both directions (or in the case of no tcpprep cache file) * S2C - server to client (primary interface) * C2S - client to server (secondary interface) - * + * * NOTE: the datalen value must be the same between each call. */ -int +int tcpedit_user_set_dlink(tcpedit_t *tcpedit, u_char *data, int datalen, tcpedit_user_dlt_direction direction) { tcpeditdlt_t *ctx; @@ -84,25 +78,25 @@ tcpedit_user_set_dlink(tcpedit_t *tcpedit, u_char *data, int datalen, tcpedit_us tcpedit_seterr(tcpedit, "user datalink length is > %d. Please increase USER_L2MAXLEN", USER_L2MAXLEN); return TCPEDIT_ERROR; } - + if ((config->length > 0) && (config->length != datalen)) { tcpedit_seterr(tcpedit, "%s", "Subsequent calls to tcpedit_user_set_dlink() must use the same datalen"); - return TCPEDIT_ERROR; + return TCPEDIT_ERROR; } else { config->length = datalen; switch (direction) { - case TCPEDIT_USER_DLT_BOTH: - memcpy(config->l2server, data, datalen); - memcpy(config->l2client, data, datalen); - break; - - case TCPEDIT_USER_DLT_S2C: - memcpy(config->l2server, data, datalen); - break; - - case TCPEDIT_USER_DLT_C2S: - memcpy(config->l2client, data, datalen); - break; + case TCPEDIT_USER_DLT_BOTH: + memcpy(config->l2server, data, datalen); + memcpy(config->l2client, data, datalen); + break; + + case TCPEDIT_USER_DLT_S2C: + memcpy(config->l2server, data, datalen); + break; + + case TCPEDIT_USER_DLT_C2S: + memcpy(config->l2client, data, datalen); + break; } } return TCPEDIT_OK; diff --git a/src/tcpedit/plugins/dlt_user/user_api.h b/src/tcpedit/plugins/dlt_user/user_api.h index f9b8579b3..f8df9d382 100644 --- a/src/tcpedit/plugins/dlt_user/user_api.h +++ b/src/tcpedit/plugins/dlt_user/user_api.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_user_API_H_ -#define _DLT_user_API_H_ +#pragma once #include "tcpedit_types.h" #include "plugins_types.h" @@ -45,7 +44,3 @@ int tcpedit_user_set_dlink(tcpedit_t *tcpedit, u_char *data, int datalen, tcpedi #ifdef __cplusplus } #endif - - -#endif - diff --git a/src/tcpedit/plugins/dlt_user/user_types.h b/src/tcpedit/plugins/dlt_user/user_types.h index 65a6c0419..8d78405ce 100644 --- a/src/tcpedit/plugins/dlt_user/user_types.h +++ b/src/tcpedit/plugins/dlt_user/user_types.h @@ -3,9 +3,9 @@ /* * Copyright (c) 2001-2010 Aaron Turner * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -17,18 +17,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _DLT_user_TYPES_H_ -#define _DLT_user_TYPES_H_ +#pragma once -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif -typedef enum { - TCPEDIT_USER_DLT_BOTH, - TCPEDIT_USER_DLT_S2C, - TCPEDIT_USER_DLT_C2S -} tcpedit_user_dlt_direction; +typedef enum { TCPEDIT_USER_DLT_BOTH, TCPEDIT_USER_DLT_S2C, TCPEDIT_USER_DLT_C2S } tcpedit_user_dlt_direction; /* * FIXME: structure to hold any data parsed from the packet by the decoder. @@ -36,18 +31,18 @@ typedef enum { */ typedef struct { /* dummy entry for SunPro compiler which doesn't like empty structs */ - int dummy; + int dummy; } user_extra_t; #define USER_L2MAXLEN 255 -/* - * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config - * Things like: +/* + * FIXME: structure to hold any data in the tcpeditdlt_plugin_t->config + * Things like: * - Parsed user options * - State between packets * - Note, you should only use this for the encoder function, decoder functions should place - * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that + * "extra" data parsed from the packet in the tcpeditdlt_t->decoded_extra buffer since that * is available to any encoder plugin. */ typedef struct { @@ -60,6 +55,3 @@ typedef struct { #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins/dlt_utils.c b/src/tcpedit/plugins/dlt_utils.c index 3bf9cf3ec..29ebf1e05 100644 --- a/src/tcpedit/plugins/dlt_utils.c +++ b/src/tcpedit/plugins/dlt_utils.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,11 +18,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#include - -#include "tcpedit.h" #include "dlt_utils.h" -#include "common.h" +#include "tcpedit.h" +#include /* from dlt_plugins.c */ extern const uint32_t tcpeditdlt_bit_map[]; @@ -31,14 +29,14 @@ extern const char *tcpeditdlt_bit_info[]; /* * Call parse args on src & dst plugins */ -int +int tcpedit_dlt_parse_opts(tcpeditdlt_t *ctx) { assert(ctx); - + if (ctx->decoder->plugin_parse_opts(ctx) != TCPEDIT_OK) return TCPEDIT_ERROR; - + if (ctx->decoder->dlt != ctx->encoder->dlt) { if (ctx->encoder->plugin_parse_opts(ctx) != TCPEDIT_OK) return TCPEDIT_ERROR; @@ -46,7 +44,7 @@ tcpedit_dlt_parse_opts(tcpeditdlt_t *ctx) return TCPEDIT_OK; } - + /* * find a given plugin struct in the context for a given DLT. Returns NULL on failure */ @@ -54,20 +52,20 @@ tcpeditdlt_plugin_t * tcpedit_dlt_getplugin(tcpeditdlt_t *ctx, int dlt) { tcpeditdlt_plugin_t *ptr; - + assert(ctx); ptr = ctx->plugins; if (ptr == NULL) return NULL; - + while (ptr->dlt != dlt && ptr->next != NULL) { ptr = ptr->next; } - + if (ptr->dlt == dlt) return ptr; - + return NULL; } @@ -78,32 +76,32 @@ tcpeditdlt_plugin_t * tcpedit_dlt_getplugin_byname(tcpeditdlt_t *ctx, const char *name) { tcpeditdlt_plugin_t *ptr; - + assert(ctx); assert(name); ptr = ctx->plugins; if (ptr == NULL) return NULL; - + while ((strcmp(ptr->name, name) != 0) && ptr->next != NULL) { ptr = ptr->next; } - + if (strcmp(ptr->name, name) == 0) return ptr; - + return NULL; } -/* +/* * Create a new plugin struct. WILL NOT RETURN ON FAILURE! (out of memory is not recoverable) */ tcpeditdlt_plugin_t * tcpedit_dlt_newplugin(void) { tcpeditdlt_plugin_t *plugin; - + plugin = (tcpeditdlt_plugin_t *)safe_malloc(sizeof(tcpeditdlt_plugin_t)); plugin->dlt = 0xffff; /* zero is a valid plugin, so use 0xffff */ return plugin; @@ -113,26 +111,25 @@ tcpedit_dlt_newplugin(void) * Add a plugin to the plugin chain for the given context. Return 0 on success, * -1 on failure */ -int +int tcpedit_dlt_addplugin(tcpeditdlt_t *ctx, tcpeditdlt_plugin_t *new) { - tcpeditdlt_plugin_t *ptr; assert(ctx); assert(new); /* look for a dupe by DLT */ - if ((ptr = tcpedit_dlt_getplugin(ctx, new->dlt)) != NULL) { + if (tcpedit_dlt_getplugin(ctx, new->dlt) != NULL) { tcpedit_seterr(ctx->tcpedit, "Can only have one DLT plugin registered per-DLT: 0x%x", new->dlt); return TCPEDIT_ERROR; } - + /* dupe by name? */ - if ((ptr = tcpedit_dlt_getplugin_byname(ctx, new->name)) != NULL) { + if (tcpedit_dlt_getplugin_byname(ctx, new->name) != NULL) { tcpedit_seterr(ctx->tcpedit, "Can only have one DLT plugin registered per-name: %s", new->name); return TCPEDIT_ERROR; } - - /* + + /* * check that the plugin is properly constructed, note that the encoder * and decoder are optional! */ @@ -146,23 +143,21 @@ tcpedit_dlt_addplugin(tcpeditdlt_t *ctx, tcpeditdlt_plugin_t *new) assert(new->plugin_get_layer3); assert(new->plugin_merge_layer3); - /* add it to the end of the chain */ if (ctx->plugins == NULL) { ctx->plugins = new; } else { - ptr = ctx->plugins; + tcpeditdlt_plugin_t *ptr = ctx->plugins; while (ptr->next != NULL) ptr = ptr->next; - + ptr->next = new; } - + /* we're done */ return 0; } - /* * validates that the decoder plugin provides all the fields that are required * by then encoding plugin. Returns TCPEDIT_OK | TCPEDIT_ERROR @@ -171,24 +166,21 @@ int tcpedit_dlt_validate(tcpeditdlt_t *ctx) { uint32_t bit; - + /* loops from 1 -> UINT32_MAX by powers of 2 */ for (bit = 1; bit != 0; bit = bit << 2) { if (ctx->encoder->requires & bit && !(ctx->decoder->provides & bit)) { tcpedit_seterr(ctx->tcpedit, "%s", tcpeditdlt_bit_info[tcpeditdlt_bit_map[bit]]); return TCPEDIT_ERROR; - } + } } - dbgx(1, "Input linktype is %s", - pcap_datalink_val_to_description(ctx->decoder->dlt)); - dbgx(1, "Output linktype is %s", - pcap_datalink_val_to_description(ctx->encoder->dlt)); + dbgx(1, "Input linktype is %s", pcap_datalink_val_to_description(ctx->decoder->dlt)); + dbgx(1, "Output linktype is %s", pcap_datalink_val_to_description(ctx->encoder->dlt)); return TCPEDIT_OK; } - /* * Utility function to extract the Layer 3 header and beyond in a single buffer * Since some CPU's like UltraSPARC are strictly aligned, they really don't like @@ -203,12 +195,12 @@ tcpedit_dlt_l3data_copy(tcpeditdlt_t *ctx, u_char *packet, int pktlen, int l2len if (pktlen <= l2len) return NULL; - + #ifdef FORCE_ALIGN - /* + /* * copy layer 3 and up to our temp packet buffer * for now on, we have to edit the packetbuff because - * just before we send the packet, we copy the packetbuff + * just before we send the packet, we copy the packetbuff * back onto the pkt.data + l2len buffer * we do all this work to prevent byte alignment issues */ @@ -220,7 +212,7 @@ tcpedit_dlt_l3data_copy(tcpeditdlt_t *ctx, u_char *packet, int pktlen, int l2len } #else /* - * on non-strict byte align systems, don't need to memcpy(), + * on non-strict byte align systems, don't need to memcpy(), * just point to 14 bytes into the existing buffer */ ptr = (&(packet)[l2len]); @@ -232,7 +224,7 @@ tcpedit_dlt_l3data_copy(tcpeditdlt_t *ctx, u_char *packet, int pktlen, int l2len * reverse of tcpedit_dlt_l3data_copy */ u_char * -tcpedit_dlt_l3data_merge(tcpeditdlt_t *ctx, u_char *packet, int pktlen, const u_char *l3data, const int l2len) +tcpedit_dlt_l3data_merge(tcpeditdlt_t *ctx, u_char *packet, int pktlen, const u_char *l3data, int l2len) { assert(ctx); assert(packet); @@ -240,12 +232,12 @@ tcpedit_dlt_l3data_merge(tcpeditdlt_t *ctx, u_char *packet, int pktlen, const u_ assert(l3data); assert(l2len >= 0); #ifdef FORCE_ALIGN - /* - * put back the layer 3 and above back in the pkt.data buffer + /* + * put back the layer 3 and above back in the pkt.data buffer * we can't edit the packet at layer 3 or above beyond this point */ - if (l2len % 4 != 0) - memcpy((&(packet)[l2len]), l3data, pktlen - l2len); + if (l2len % 4 != 0) + memcpy((&(packet)[l2len]), l3data, pktlen - l2len); #endif return packet; } @@ -265,17 +257,16 @@ tcpedit_dlt_copy_decoder_state(tcpeditdlt_t *ctx, tcpeditdlt_t *subctx) ctx->proto = subctx->proto; memcpy(&ctx->srcmac, &subctx->srcmac, MAX_MAC_LEN); memcpy(&ctx->dstmac, &subctx->dstmac, MAX_MAC_LEN); - + /* just need to copy the ptr */ ctx->decoded_extra = subctx->decoded_extra; ctx->decoded_extra_size = subctx->decoded_extra_size; - /* + /* * the first decoder should of already specified it's l2len, so we need to * add to it the l2len determined by the sub-plugin */ ctx->l2len += subctx->l2len; - + return TCPEDIT_OK; } - diff --git a/src/tcpedit/plugins/dlt_utils.h b/src/tcpedit/plugins/dlt_utils.h index d6bb9fc6d..dcc88c480 100644 --- a/src/tcpedit/plugins/dlt_utils.h +++ b/src/tcpedit/plugins/dlt_utils.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,14 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ - -#ifndef _DLT_UTILS_H_ -#define _DLT_UTILS_H_ +#pragma once #include "plugins_types.h" u_char *tcpedit_dlt_l3data_copy(tcpeditdlt_t *ctx, u_char *packet, int ptklen, int l2len); -u_char *tcpedit_dlt_l3data_merge(tcpeditdlt_t *ctx, u_char *packet, int pktlen, const u_char *l3data, const int l2len); +u_char *tcpedit_dlt_l3data_merge(tcpeditdlt_t *ctx, u_char *packet, int pktlen, const u_char *l3data, int l2len); int tcpedit_dlt_parse_opts(tcpeditdlt_t *ctx); int tcpedit_dlt_validate(tcpeditdlt_t *ctx); @@ -37,5 +35,3 @@ tcpeditdlt_plugin_t *tcpedit_dlt_getplugin_byname(tcpeditdlt_t *ctx, const char int tcpedit_dlt_addplugin(tcpeditdlt_t *ctx, tcpeditdlt_plugin_t *new); int tcpedit_dlt_copy_decoder_state(tcpeditdlt_t *ctx, tcpeditdlt_t *subctx); - -#endif diff --git a/src/tcpedit/plugins/ethernet.c b/src/tcpedit/plugins/ethernet.c index d115741a1..bf85a2c8f 100644 --- a/src/tcpedit/plugins/ethernet.c +++ b/src/tcpedit/plugins/ethernet.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,20 +18,18 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "ethernet.h" #include #include -#include "ethernet.h" - -/* +/* * Takes a ptr to an ethernet address and returns * 1 if it is unicast or 0 if it is multicast or * broadcast. As per RFC7042. */ -int +int is_unicast_ethernet(tcpeditdlt_t *ctx, const u_char *ether) { - assert(ctx); assert(ether); @@ -51,8 +49,7 @@ is_unicast_ethernet(tcpeditdlt_t *ctx, const u_char *ether) * 00:00:5e:(00:01:00 – 00:01:ff) - IPv4 Virtual Router Redundancy Protocol * 00:00:5e:(00:02:00 – 00:02:ff) - IPv6 Virtual Router Redundancy Protocol */ - if (memcmp(ðer[0], IPV4_VRRP, 5) == 0 - || memcmp(ðer[0], IPV6_VRRP, 5) == 0) + if (memcmp(ðer[0], IPV4_VRRP, 5) == 0 || memcmp(ðer[0], IPV6_VRRP, 5) == 0) return 0; /* everything else is unicast */ diff --git a/src/tcpedit/plugins/ethernet.h b/src/tcpedit/plugins/ethernet.h index d1569627e..db38cc2ea 100644 --- a/src/tcpedit/plugins/ethernet.h +++ b/src/tcpedit/plugins/ethernet.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -22,12 +22,8 @@ * Generic functions for ethernet addresses */ -#ifndef _ETHERNET_H_ -#define _ETHERNET_H_ +#pragma once #include "plugins_types.h" int is_unicast_ethernet(tcpeditdlt_t *, const u_char *); - - -#endif diff --git a/src/tcpedit/plugins_api.h b/src/tcpedit/plugins_api.h index 344d1a03c..f22c07d9f 100644 --- a/src/tcpedit/plugins_api.h +++ b/src/tcpedit/plugins_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,22 +18,20 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _PLUGINS_API_H_ -#define _PLUGINS_API_H_ +#pragma once +#include "plugins_types.h" #ifdef __cplusplus extern "C" { #endif - /* Used to parse arguments if you have AutoGen */ int tcpedit_dlt_post_args(tcpedit_t *tcpedit); - -/* +/* * initialize the DLT plugin backend, and return a new context var. - * call this once per pcap to be processed + * call this once per pcap to be processed */ tcpeditdlt_t *tcpedit_dlt_init(tcpedit_t *tcpedit, int srcdlt); @@ -60,7 +58,7 @@ int tcpedit_dlt_process(tcpeditdlt_t *ctx, u_char **packet, int pktlen, tcpr_dir * or you can call them sperately if you want */ int tcpedit_dlt_decode(tcpeditdlt_t *ctx, const u_char *packet, const int pktlen); -int tcpedit_dlt_encode(tcpeditdlt_t* ctx, u_char *packet, int pktlen, tcpr_dir_t direction); +int tcpedit_dlt_encode(tcpeditdlt_t *ctx, u_char *packet, int pktlen, tcpr_dir_t direction); /* * After processing each packet, you can get info about L2/L3 @@ -76,13 +74,9 @@ u_char *tcpedit_dlt_merge_l3data(tcpeditdlt_t *ctx, u_char *ipv4_data, u_char *ipv6_data); - int tcpedit_dlt_src(tcpeditdlt_t *ctx); int tcpedit_dlt_dst(tcpeditdlt_t *ctx); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/plugins_types.h b/src/tcpedit/plugins_types.h index 82e88dfd5..fae43f2cb 100644 --- a/src/tcpedit/plugins_types.h +++ b/src/tcpedit/plugins_types.h @@ -19,8 +19,7 @@ */ -#ifndef _PLUGINS_TYPES_H_ -#define _PLUGINS_TYPES_H_ +#pragma once #include "defines.h" #include "tcpr.h" @@ -95,9 +94,6 @@ struct tcpeditdlt_plugin_s { size_t config_size; }; - -#define L2EXTRA_LEN 255 /* size of buffer to hold any extra L2 data parsed from the decoder */ - /* * internal DLT plugin context */ @@ -140,6 +136,3 @@ struct tcpeditdlt_s { } #endif - -#endif - diff --git a/src/tcpedit/portmap.c b/src/tcpedit/portmap.c index 82dc97006..5fe1779f9 100644 --- a/src/tcpedit/portmap.c +++ b/src/tcpedit/portmap.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -22,21 +22,15 @@ * This file contains routines to manipulate port maps, in which * one port number is mapped to another. */ +#include "portmap.h" #include "config.h" -#include "defines.h" -#include "common.h" - +#include "incremental_checksum.h" +#include "tcpedit.h" #include #include -#include - -#include "tcpreplay.h" -#include "tcpedit.h" -#include "portmap.h" -#include "incremental_checksum.h" /** - * mallocs a new tcpedit_portmap_t structure + * mallocs a new tcpedit_portmap_t structure */ tcpedit_portmap_t * new_portmap() @@ -52,10 +46,10 @@ new_portmap() * * We support the following formats: * : - map a single port to a new port - * -: - map a range of ports to a new port - * ++...: - map a list of ports to a single ports + * -: - map a range of ports to a new port + * ++...: - map a list of ports to a single ports * - * In the case of port ranges or port lists, we actually return a + * In the case of port ranges or port lists, we actually return a * chain of tcpedit_portmap_t's */ static tcpedit_portmap_t * @@ -96,7 +90,7 @@ ports2PORT(char *ports) return NULL; /* - * put the new portmap info into the new node + * put the new portmap info into the new node * while we convert to network-byte order, b/c its better * to do it once now, rather then each time we have to do a lookup */ @@ -161,9 +155,9 @@ ports2PORT(char *ports) /* this is just the old port:port format */ else { /* - * convert the strings to longs: if badchar points to anything - * after, then it was a bad string - */ + * convert the strings to longs: if badchar points to anything + * after, then it was a bad string + */ from_l = strtol(from_s, &badchar, 10); if (strlen(badchar) != 0 || from_l > 65535 || from_l < 0) { safe_free(portmap); @@ -179,11 +173,11 @@ ports2PORT(char *ports) /** * Processes a string (ourstr) containing the portmap ("2000:4000" for - * example) and places the data in **portmapdata and finally returns 1 for + * example) and places the data in **portmapdata and finally returns 1 for * success, 0 for fail. */ int -parse_portmap(tcpedit_portmap_t ** portmap, const char *ourstr) +parse_portmap(tcpedit_portmap_t **portmap, const char *ourstr) { tcpedit_portmap_t *portmap_ptr; char *substr, *ourstrcpy, *token = NULL; @@ -194,7 +188,7 @@ parse_portmap(tcpedit_portmap_t ** portmap, const char *ourstr) /* first iteration of input */ substr = strtok_r(ourstrcpy, ",", &token); - if ((*portmap = ports2PORT(substr)) == NULL) { + if (substr == NULL || (*portmap = ports2PORT(substr)) == NULL) { safe_free(ourstrcpy); return 0; } @@ -223,14 +217,12 @@ parse_portmap(tcpedit_portmap_t ** portmap, const char *ourstr) return 1; } - /** * Free's all the memory associated with the given portmap chain */ void -free_portmap(tcpedit_portmap_t * portmap) +free_portmap(tcpedit_portmap_t *portmap) { - assert(portmap); /* recursively go down the portmaps */ @@ -240,26 +232,6 @@ free_portmap(tcpedit_portmap_t * portmap) safe_free(portmap); } - -/** - * This function takes a pointer to a portmap list and prints each node - */ -void -print_portmap(tcpedit_portmap_t *portmap_data) -{ - tcpedit_portmap_t *portmap_ptr; - - assert(portmap_data); - portmap_ptr = portmap_data; - while (portmap_ptr != NULL) { - printf("from: %ld to: %ld\n", portmap_ptr->from, portmap_ptr->to); - portmap_ptr = portmap_ptr->next; - } - - printf("\n"); -} - - /** * This function takes a portmap and a port, and returns the mapped port, * or the original port if it isn't mapped to anything. @@ -283,7 +255,7 @@ map_port(tcpedit_portmap_t *portmap_data, long port) portmap_ptr = portmap_ptr->next; } - return(newport); + return (newport); } /** @@ -292,8 +264,7 @@ map_port(tcpedit_portmap_t *portmap_data, long port) */ static int -rewrite_ports(tcpedit_t *tcpedit, u_char protocol, u_char *layer4, - const int l4len) +rewrite_ports(tcpedit_t *tcpedit, u_char protocol, u_char *layer4, const int l4len) { tcp_hdr_t *tcp_hdr = NULL; udp_hdr_t *udp_hdr = NULL; @@ -306,8 +277,7 @@ rewrite_ports(tcpedit_t *tcpedit, u_char protocol, u_char *layer4, if (protocol == IPPROTO_TCP) { if (l4len < (int)sizeof(tcp_hdr_t)) { - tcpedit_setwarn(tcpedit, "caplen to small to set TCP port: l4 len=%d", - l4len); + tcpedit_setwarn(tcpedit, "caplen to small to set TCP port: l4 len=%d", l4len); return TCPEDIT_WARN; } @@ -328,8 +298,7 @@ rewrite_ports(tcpedit_t *tcpedit, u_char protocol, u_char *layer4, } } else if (protocol == IPPROTO_UDP) { if (l4len < (int)sizeof(udp_hdr_t)) { - tcpedit_setwarn(tcpedit, "caplen to small to set UDP port: l4 len=%d", - l4len); + tcpedit_setwarn(tcpedit, "caplen to small to set UDP port: l4 len=%d", l4len); return TCPEDIT_WARN; } @@ -360,23 +329,20 @@ rewrite_ports(tcpedit_t *tcpedit, u_char protocol, u_char *layer4, } int -rewrite_ipv4_ports(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, const int l3len) +rewrite_ipv4_ports(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, int l3len) { assert(tcpedit); u_char *l4; if (*ip_hdr == NULL || ip_hdr == NULL) { - tcpedit_seterr(tcpedit, "rewrite_ipv4_ports: NULL IP header: l3 len=%d", - l3len); + tcpedit_seterr(tcpedit, "rewrite_ipv4_ports: NULL IP header: l3 len=%d", l3len); return TCPEDIT_ERROR; } else if ((*ip_hdr)->ip_p == IPPROTO_TCP || (*ip_hdr)->ip_p == IPPROTO_UDP) { - l4 = get_layer4_v4(*ip_hdr, l3len); + l4 = get_layer4_v4(*ip_hdr, (u_char *)ip_hdr + l3len); if (l4) - return rewrite_ports(tcpedit, (*ip_hdr)->ip_p, l4, - l3len - (l4 - (u_char*)*ip_hdr)); + return rewrite_ports(tcpedit, (*ip_hdr)->ip_p, l4, l3len - (l4 - (u_char *)*ip_hdr)); - tcpedit_setwarn(tcpedit, "Unable to rewrite ports on IP header: l3 len=%d", - l3len); + tcpedit_setwarn(tcpedit, "Unable to rewrite ports on IP header: l3 len=%d", l3len); return TCPEDIT_WARN; } @@ -384,23 +350,20 @@ rewrite_ipv4_ports(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, const int l3len) } int -rewrite_ipv6_ports(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, const int l3len) +rewrite_ipv6_ports(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, int l3len) { assert(tcpedit); u_char *l4; if (*ip6_hdr == NULL || ip6_hdr == NULL) { - tcpedit_seterr(tcpedit, "rewrite_ipv6_ports: NULL IPv6 header: l3 len=%d", - l3len); + tcpedit_seterr(tcpedit, "rewrite_ipv6_ports: NULL IPv6 header: l3 len=%d", l3len); return TCPEDIT_ERROR; } else if ((*ip6_hdr)->ip_nh == IPPROTO_TCP || (*ip6_hdr)->ip_nh == IPPROTO_UDP) { - l4 = get_layer4_v6(*ip6_hdr, l3len); + l4 = get_layer4_v6(*ip6_hdr, (u_char *)ip6_hdr + l3len); if (l4) - return rewrite_ports(tcpedit, (*ip6_hdr)->ip_nh, l4, - l3len - (l4 - (u_char*)*ip6_hdr)); + return rewrite_ports(tcpedit, (*ip6_hdr)->ip_nh, l4, l3len - (l4 - (u_char *)*ip6_hdr)); - tcpedit_setwarn(tcpedit, "Unable to rewrite ports on IPv6 header: l3 len=%d", - l3len); + tcpedit_setwarn(tcpedit, "Unable to rewrite ports on IPv6 header: l3 len=%d", l3len); return TCPEDIT_WARN; } diff --git a/src/tcpedit/portmap.h b/src/tcpedit/portmap.h index 43661dd7c..05f90d523 100644 --- a/src/tcpedit/portmap.h +++ b/src/tcpedit/portmap.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,17 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "tcpedit_types.h" +#pragma once -#ifndef __PORTMAP_H__ -#define __PORTMAP_H__ +#include "tcpedit_types.h" tcpedit_portmap_t *new_portmap(); int parse_portmap(tcpedit_portmap_t **portmapdata, const char *ourstr); void free_portmap(tcpedit_portmap_t *portmap); -void print_portmap(tcpedit_portmap_t *portmap); -long map_port(tcpedit_portmap_t *portmap , long port); -int rewrite_ipv4_ports(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, const int l3len); -int rewrite_ipv6_ports(tcpedit_t *tcpedit, ipv6_hdr_t **ip_hdr, const int l3len); - -#endif +long map_port(tcpedit_portmap_t *portmap, long port); +int rewrite_ipv4_ports(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, int l3len); +int rewrite_ipv6_ports(tcpedit_t *tcpedit, ipv6_hdr_t **ip_hdr, int l3len); diff --git a/src/tcpedit/rewrite_sequence.c b/src/tcpedit/rewrite_sequence.c index cd772d9eb..ffa3bb5ac 100644 --- a/src/tcpedit/rewrite_sequence.c +++ b/src/tcpedit/rewrite_sequence.c @@ -5,9 +5,9 @@ * Copyright (c) 2013-2017 Fred Klassen - AppNeta * Copyright (c) 2017 Mario D. Santana - El Orangutan * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -23,19 +23,11 @@ * This file contains routines to manipulate port maps, in which * one port number is mapped to another. */ -#include "config.h" -#include "defines.h" -#include "common.h" - -#include -#include -#include - -#include "tcpreplay.h" -#include "tcpedit.h" #include "rewrite_sequence.h" +#include "config.h" #include "incremental_checksum.h" - +#include "tcpedit.h" +#include /** * rewrites the TCP sequence and ack numbers @@ -61,19 +53,16 @@ rewrite_seqs(tcpedit_t *tcpedit, tcp_hdr_t *tcp_hdr) return 0; } - int -rewrite_ipv4_tcp_sequence(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, - const int l3len) +rewrite_ipv4_tcp_sequence(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, int l3len) { assert(tcpedit); assert(*ip_hdr && ip_hdr); if (*ip_hdr && (*ip_hdr)->ip_p == IPPROTO_TCP) { - tcp_hdr_t *tcp_hdr = (tcp_hdr_t *)get_layer4_v4(*ip_hdr, l3len); + tcp_hdr_t *tcp_hdr = (tcp_hdr_t *)get_layer4_v4(*ip_hdr, (u_char *)ip_hdr + l3len); if (!tcp_hdr) { - tcpedit_setwarn(tcpedit, "caplen to small to set TCP sequence for IP packet: l3 len=%d", - l3len); + tcpedit_setwarn(tcpedit, "caplen to small to set TCP sequence for IP packet: l3 len=%d", l3len); return TCPEDIT_WARN; } @@ -84,17 +73,15 @@ rewrite_ipv4_tcp_sequence(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, } int -rewrite_ipv6_tcp_sequence(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, - const int l3len) +rewrite_ipv6_tcp_sequence(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, int l3len) { assert(tcpedit); assert(*ip6_hdr && ip6_hdr); if (*ip6_hdr && (*ip6_hdr)->ip_nh == IPPROTO_TCP) { - tcp_hdr_t *tcp_hdr = (tcp_hdr_t *)get_layer4_v6(*ip6_hdr, l3len); + tcp_hdr_t *tcp_hdr = (tcp_hdr_t *)get_layer4_v6(*ip6_hdr, (u_char *)ip6_hdr + l3len); if (!tcp_hdr) { - tcpedit_setwarn(tcpedit, "caplen to small to set TCP sequence for IP packet: l3 len=%d", - l3len); + tcpedit_setwarn(tcpedit, "caplen to small to set TCP sequence for IP packet: l3 len=%d", l3len); return TCPEDIT_WARN; } diff --git a/src/tcpedit/rewrite_sequence.h b/src/tcpedit/rewrite_sequence.h index 4eda093be..767e71e7f 100644 --- a/src/tcpedit/rewrite_sequence.h +++ b/src/tcpedit/rewrite_sequence.h @@ -5,9 +5,9 @@ * Copyright (c) 2013-2017 Fred Klassen - AppNeta * Copyright (c) 2017 Mario D. Santana - El Orangutan * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -19,14 +19,9 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "tcpedit_types.h" - -#ifndef __REWRITE_SEQUENCE_H__ -#define __REWRITE_SEQUENCE_H__ +#pragma once -int rewrite_ipv4_tcp_sequence(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, - const int l3len); -int rewrite_ipv6_tcp_sequence(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, - const int l3len); +#include "tcpedit_types.h" -#endif +int rewrite_ipv4_tcp_sequence(tcpedit_t *tcpedit, ipv4_hdr_t **ip_hdr, int l3len); +int rewrite_ipv6_tcp_sequence(tcpedit_t *tcpedit, ipv6_hdr_t **ip6_hdr, int l3len); diff --git a/src/tcpedit/tcpedit.c b/src/tcpedit/tcpedit.c index b67072483..b1af7b057 100644 --- a/src/tcpedit/tcpedit.c +++ b/src/tcpedit/tcpedit.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,57 +18,20 @@ * along with the Tcpreplay Suite. If not, see . */ -#include "config.h" #include "defines.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tcpedit_stub.h" -#include "portmap.h" +#include "config.h" #include "common.h" -#include "incremental_checksum.h" #include "edit_packet.h" -#include "parse_args.h" #include "fuzzing.h" +#include "incremental_checksum.h" +#include "parse_args.h" +#include "portmap.h" #include "rewrite_sequence.h" - -#include "lib/sll.h" -#include "dlt.h" - -extern tOptDesc *const tcpedit_tcpedit_optDesc_p; - -/** - * \brief Checks to see if you should make an edit - * - * Given the packet direction, this lets you know if you should make an edit - * - * packet: C2S & editdir = client == 1 - * packet: C2S & editdir = server == 0 - * packet: S2C & editdir = client == 0 - * packet: S2C & editdir = server == 1 - * packet: S2C & editdir = both == 1 - * packet: C2S & editdir = both == 1 - */ -int -tcpedit_checkdir(tcpedit_t *tcpedit, tcpr_dir_t direction) -{ - - /* Should we edit this packet? */ - if ((tcpedit->editdir == TCPEDIT_EDIT_BOTH) || - (tcpedit->editdir == TCPEDIT_EDIT_C2S && direction == TCPR_DIR_C2S) || - (tcpedit->editdir == TCPEDIT_EDIT_S2C && direction == TCPR_DIR_S2C)) { - return 1; - } - return 0; -} - +#include "tcpedit_stub.h" +#include +#include +#include +#include /** * \brief Edit the given packet @@ -81,8 +44,7 @@ tcpedit_checkdir(tcpedit_t *tcpedit, tcpr_dir_t direction) * 1 on change */ int -tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, - u_char **pktdata, tcpr_dir_t direction) +tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, u_char **pktdata, tcpr_dir_t direction) { bool fuzz_once = tcpedit->fuzz_seed != 0; ipv4_hdr_t *ip_hdr; @@ -90,11 +52,10 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, arp_hdr_t *arp_hdr; int l2len, l2proto, retval; int dst_dlt, src_dlt, pktlen, lendiff; - int ipflags, tclass; - int needtorecalc; /* did the packet change? if so, checksum */ + uint32_t ipflags, tclass; + int needtorecalc; /* did the packet change? if so, checksum */ u_char *packet; - assert(tcpedit); assert(pkthdr); assert(*pkthdr); @@ -106,8 +67,7 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, tcpedit->runtime.packetnum++; - dbgx(3, "packet " COUNTER_SPEC " caplen %d", - tcpedit->runtime.packetnum, (*pkthdr)->caplen); + dbgx(3, "packet " COUNTER_SPEC " caplen %d", tcpedit->runtime.packetnum, (*pkthdr)->caplen); /* * remove the Ethernet FCS (checksum)? @@ -115,7 +75,7 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, * only set this flag IFF the pcap has the FCS. If not, then they * just removed 2 bytes of ACTUAL PACKET DATA. Sucks to be them. */ - if (tcpedit->efcs > 0 &&(*pkthdr)->len > 4) { + if (tcpedit->efcs > 0 && (*pkthdr)->len > 4) { if ((*pkthdr)->caplen == (*pkthdr)->len) { (*pkthdr)->caplen -= 4; } @@ -124,7 +84,7 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, } src_dlt = tcpedit_dlt_src(tcpedit->dlt_ctx); - + needtorecalc = 0; again: ip_hdr = NULL; @@ -132,29 +92,28 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, arp_hdr = NULL; retval = 0; ipflags = 0; - tclass = 0; /* not everything has a L3 header, so check for errors. returns proto in network byte order */ - if ((l2proto = tcpedit_dlt_proto(tcpedit->dlt_ctx, src_dlt, packet, (*pkthdr)->caplen)) < 0) { + if ((l2proto = tcpedit_dlt_proto(tcpedit->dlt_ctx, src_dlt, packet, (int)(*pkthdr)->caplen)) < 0) { dbgx(2, "Packet has no L3+ header: %s", tcpedit_geterr(tcpedit)); return TCPEDIT_SOFT_ERROR; } else { dbgx(2, "Layer 3 protocol type is: 0x%04x", ntohs(l2proto)); } - + /* rewrite Layer 2 */ - if ((pktlen = tcpedit_dlt_process(tcpedit->dlt_ctx, pktdata, (*pkthdr)->caplen, direction)) < 0) { + if ((pktlen = tcpedit_dlt_process(tcpedit->dlt_ctx, pktdata, (int)(*pkthdr)->caplen, direction)) < 0) { /* unable to edit packet, most likely 802.11 management or data QoS frame */ dbgx(3, "Failed to edit DLT: %s", tcpedit_geterr(tcpedit)); return TCPEDIT_SOFT_ERROR; } /* update our packet lengths (real/captured) based on L2 length changes */ - lendiff = pktlen - (*pkthdr)->caplen; + lendiff = pktlen - (int)(*pkthdr)->caplen; (*pkthdr)->caplen += lendiff; (*pkthdr)->len += lendiff; - + dst_dlt = tcpedit_dlt_dst(tcpedit->dlt_ctx); - l2len = tcpedit_dlt_l2len(tcpedit->dlt_ctx, dst_dlt, packet, (*pkthdr)->caplen); + l2len = tcpedit_dlt_l2len(tcpedit->dlt_ctx, dst_dlt, packet, (int)(*pkthdr)->caplen); if (l2len == -1) return TCPEDIT_SOFT_ERROR; @@ -165,19 +124,24 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, u_char *p; if ((*pkthdr)->caplen < l2len + sizeof(*ip_hdr)) { - tcpedit_seterr(tcpedit, "Packet length %d is too short to contain a layer IP header for DLT 0x%04x", - pktlen, dst_dlt); + tcpedit_seterr(tcpedit, + "Packet length %d is too short to contain a layer IP header for DLT 0x%04x", + pktlen, + dst_dlt); return TCPEDIT_SOFT_ERROR; } - ip_hdr = (ipv4_hdr_t *)tcpedit_dlt_l3data(tcpedit->dlt_ctx, dst_dlt, packet, (*pkthdr)->caplen); + ip_hdr = (ipv4_hdr_t *)tcpedit_dlt_l3data(tcpedit->dlt_ctx, dst_dlt, packet, (int)(*pkthdr)->caplen); if (ip_hdr == NULL) return TCPEDIT_SOFT_ERROR; - p = get_layer4_v4(ip_hdr, (*pkthdr)->caplen - l2len); + p = get_layer4_v4(ip_hdr, (u_char *)ip_hdr + (*pkthdr)->caplen - l2len); if (!p) { - tcpedit_seterr(tcpedit, "Packet length %d is too short to contain a layer %d byte IP header for DLT 0x%04x", - pktlen, ip_hdr->ip_hl << 2, dst_dlt); + tcpedit_seterr(tcpedit, + "Packet length %d is too short to contain a layer %d byte IP header for DLT 0x%04x", + pktlen, + ip_hdr->ip_hl << 2, + dst_dlt); return TCPEDIT_SOFT_ERROR; } @@ -186,19 +150,23 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, u_char *p; if ((*pkthdr)->caplen < l2len + sizeof(*ip6_hdr)) { - tcpedit_seterr(tcpedit, "Packet length %d is too short to contain a layer IPv6 header for DLT 0x%04x", - pktlen, dst_dlt); + tcpedit_seterr(tcpedit, + "Packet length %d is too short to contain a layer IPv6 header for DLT 0x%04x", + pktlen, + dst_dlt); return TCPEDIT_SOFT_ERROR; } - ip6_hdr = (ipv6_hdr_t *)tcpedit_dlt_l3data(tcpedit->dlt_ctx, dst_dlt, packet, (*pkthdr)->caplen); + ip6_hdr = (ipv6_hdr_t *)tcpedit_dlt_l3data(tcpedit->dlt_ctx, dst_dlt, packet, (int)(*pkthdr)->caplen); if (ip6_hdr == NULL) return TCPEDIT_SOFT_ERROR; - p = get_layer4_v6(ip6_hdr, (*pkthdr)->caplen - l2len); + p = get_layer4_v6(ip6_hdr, (u_char *)ip6_hdr + (*pkthdr)->caplen - l2len); if (!p) { - tcpedit_seterr(tcpedit, "Packet length %d is too short to contain an IPv6 header for DLT 0x%04x", - pktlen, dst_dlt); + tcpedit_seterr(tcpedit, + "Packet length %d is too short to contain an IPv6 header for DLT 0x%04x", + pktlen, + dst_dlt); return TCPEDIT_SOFT_ERROR; } @@ -212,14 +180,13 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, /* The following edits only apply for IPv4 */ if (ip_hdr != NULL) { - /* set TOS ? */ if (tcpedit->tos > -1) { - volatile uint16_t oldval = *((uint16_t*)ip_hdr); + volatile uint16_t oldval = *((uint16_t *)ip_hdr); volatile uint16_t newval; ip_hdr->ip_tos = tcpedit->tos; - newval = *((uint16_t*)ip_hdr); + newval = *((uint16_t *)ip_hdr); csum_replace2(&ip_hdr->ip_sum, oldval, newval); } @@ -228,15 +195,13 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, /* rewrite TCP/UDP ports */ if (tcpedit->portmap != NULL) { - if ((retval = rewrite_ipv4_ports(tcpedit, &ip_hdr, - (*pkthdr)->caplen - l2len)) < 0) + if ((retval = rewrite_ipv4_ports(tcpedit, &ip_hdr, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; } if (tcpedit->tcp_sequence_enable) - rewrite_ipv4_tcp_sequence(tcpedit, &ip_hdr, - (*pkthdr)->caplen - l2len); + rewrite_ipv4_tcp_sequence(tcpedit, &ip_hdr, (int)(*pkthdr)->caplen - l2len); } /* IPv6 edits */ @@ -248,15 +213,15 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, if (tcpedit->tclass > -1) { /* calculate the bits */ tclass = tcpedit->tclass << 20; - + /* convert our 4 bytes to an int */ memcpy(&ipflags, &ip6_hdr->ip_flags, 4); - + /* strip out the old tclass bits */ ipflags = ntohl(ipflags) & 0xf00fffff; /* add the tclass bits back */ - ipflags += tclass; + ipflags += tclass; ipflags = htonl(ipflags); memcpy(&ip6_hdr->ip_flags, &ipflags, 4); } @@ -272,14 +237,13 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, /* rewrite TCP/UDP ports */ if (tcpedit->portmap != NULL) { - if ((retval = rewrite_ipv6_ports(tcpedit, &ip6_hdr, - (*pkthdr)->caplen - l2len)) < 0) + if ((retval = rewrite_ipv6_ports(tcpedit, &ip6_hdr, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; } if (tcpedit->tcp_sequence_enable) - rewrite_ipv6_tcp_sequence(tcpedit, &ip6_hdr, (*pkthdr)->caplen - l2len); + rewrite_ipv6_tcp_sequence(tcpedit, &ip6_hdr, (int)(*pkthdr)->caplen - l2len); } if (fuzz_once) { @@ -298,18 +262,16 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, return TCPEDIT_ERROR; needtorecalc += retval; } - + /* rewrite IP addresses in IPv4/IPv6 or ARP */ if (tcpedit->rewrite_ip) { /* IP packets */ if (ip_hdr != NULL) { - if ((retval = rewrite_ipv4l3(tcpedit, ip_hdr, direction, - (*pkthdr)->caplen - l2len)) < 0) + if ((retval = rewrite_ipv4l3(tcpedit, ip_hdr, direction, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; } else if (ip6_hdr != NULL) { - if ((retval = rewrite_ipv6l3(tcpedit, ip6_hdr, direction, - (*pkthdr)->caplen - l2len)) < 0) + if ((retval = rewrite_ipv6l3(tcpedit, ip6_hdr, direction, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; } @@ -330,26 +292,24 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, if (tcpedit->seed) { /* IPv4 Packets */ if (ip_hdr != NULL) { - if ((retval = randomize_ipv4(tcpedit, *pkthdr, packet, - ip_hdr, (*pkthdr)->caplen - l2len)) < 0) + if ((retval = randomize_ipv4(tcpedit, *pkthdr, packet, ip_hdr, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; } else if (ip6_hdr != NULL) { - if ((retval = randomize_ipv6(tcpedit, *pkthdr, packet, - ip6_hdr, (*pkthdr)->caplen - l2len)) < 0) + if ((retval = randomize_ipv6(tcpedit, *pkthdr, packet, ip6_hdr, (int)(*pkthdr)->caplen - l2len)) < 0) return TCPEDIT_ERROR; needtorecalc += retval; - /* ARP packets */ + /* ARP packets */ } else if (l2proto == htons(ETHERTYPE_ARP)) { if (direction == TCPR_DIR_C2S) { - if (randomize_iparp(tcpedit, *pkthdr, packet, - tcpedit->runtime.dlt1, (*pkthdr)->caplen - l2len) < 0) + if (randomize_iparp(tcpedit, *pkthdr, packet, tcpedit->runtime.dlt1, (int)(*pkthdr)->caplen - l2len) < + 0) return TCPEDIT_ERROR; } else { - if (randomize_iparp(tcpedit, *pkthdr, packet, - tcpedit->runtime.dlt2, (*pkthdr)->caplen - l2len) < 0) + if (randomize_iparp(tcpedit, *pkthdr, packet, tcpedit->runtime.dlt2, (int)(*pkthdr)->caplen - l2len) < + 0) return TCPEDIT_ERROR; } } @@ -358,6 +318,7 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, /* fixhdrlen option ensure IP header length is correct */ /* do we need to fix checksums? -- must always do this last! */ if (tcpedit->fixhdrlen) { + /* ensure IP header length is correct */ int changed = 0; if (ip_hdr != NULL) { fix_ipv4_length(*pkthdr, ip_hdr, l2len); @@ -391,13 +352,14 @@ tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, } tcpedit_dlt_merge_l3data(tcpedit->dlt_ctx, - dst_dlt, packet, - (*pkthdr)->caplen, - (u_char*)ip_hdr, - (u_char*)ip6_hdr); + dst_dlt, + packet, + (int)(*pkthdr)->caplen, + (u_char *)ip_hdr, + (u_char *)ip6_hdr); tcpedit->runtime.total_bytes += (*pkthdr)->caplen; - tcpedit->runtime.pkts_edited ++; + tcpedit->runtime.pkts_edited++; return retval; } @@ -408,7 +370,7 @@ int tcpedit_init(tcpedit_t **tcpedit_ex, int dlt) { tcpedit_t *tcpedit; - + *tcpedit_ex = safe_malloc(sizeof(tcpedit_t)); tcpedit = *tcpedit_ex; @@ -424,13 +386,12 @@ tcpedit_init(tcpedit_t **tcpedit_ex, int dlt) tcpedit->tclass = -1; tcpedit->flowlabel = -1; tcpedit->editdir = TCPEDIT_EDIT_BOTH; - + memset(&(tcpedit->runtime), 0, sizeof(tcpedit_runtime_t)); tcpedit->runtime.dlt1 = dlt; tcpedit->runtime.dlt2 = dlt; - - dbgx(1, "Input file (1) datalink type is %s", - pcap_datalink_val_to_name(dlt)); + + dbgx(1, "Input file (1) datalink type is %s", pcap_datalink_val_to_name(dlt)); #ifdef FORCE_ALIGN tcpedit->runtime.l3buff = (u_char *)safe_malloc(MAXPACKET); @@ -477,10 +438,8 @@ tcpedit_validate(tcpedit_t *tcpedit) char * tcpedit_geterr(tcpedit_t *tcpedit) { - assert(tcpedit); return tcpedit->runtime.errstr; - } /** @@ -491,11 +450,11 @@ tcpedit_geterr(tcpedit_t *tcpedit) * tcpedit_seterr() which is a macro wrapping this instead. */ void -__tcpedit_seterr(tcpedit_t *tcpedit, const char *func, const int line, const char *file, const char *fmt, ...) +__tcpedit_seterr(tcpedit_t *tcpedit, const char *func, int line, const char *file, const char *fmt, ...) { va_list ap; char errormsg[TCPEDIT_ERRSTR_LEN - 32]; - + assert(tcpedit); va_start(ap, fmt); @@ -504,10 +463,14 @@ __tcpedit_seterr(tcpedit_t *tcpedit, const char *func, const int line, const cha } va_end(ap); - - snprintf(tcpedit->runtime.errstr, sizeof(tcpedit->runtime.errstr), + + snprintf(tcpedit->runtime.errstr, + sizeof(tcpedit->runtime.errstr), "From %s:%s() line %d:\n%s", - file, func, line, errormsg); + file, + func, + line, + errormsg); } /** @@ -533,73 +496,68 @@ tcpedit_setwarn(tcpedit_t *tcpedit, const char *fmt, ...) va_start(ap, fmt); if (fmt != NULL) - (void)vsnprintf(tcpedit->runtime.warnstr, - sizeof(tcpedit->runtime.warnstr), fmt, ap); + (void)vsnprintf(tcpedit->runtime.warnstr, sizeof(tcpedit->runtime.warnstr), fmt, ap); va_end(ap); - } /** * \brief Checks the given error code and does the right thing - * + * * Generic function which checks the TCPEDIT_* error code - * and always returns OK or ERROR. For warnings, prints the + * and always returns OK or ERROR. For warnings, prints the * warning message and returns OK. For any other value, fails with * an assert. * * prefix is a string prepended to the error/warning */ int -tcpedit_checkerror(tcpedit_t *tcpedit, const int rcode, const char *prefix) { +tcpedit_checkerror(tcpedit_t *tcpedit, int rcode, const char *prefix) +{ assert(tcpedit); - + switch (rcode) { - case TCPEDIT_OK: - case TCPEDIT_ERROR: - return rcode; - break; - - case TCPEDIT_SOFT_ERROR: - if (prefix != NULL) { - fprintf(stderr, "Error %s: %s\n", prefix, tcpedit_geterr(tcpedit)); - } else { - fprintf(stderr, "Error: %s\n", tcpedit_geterr(tcpedit)); - } - break; - case TCPEDIT_WARN: - if (prefix != NULL) { - fprintf(stderr, "Warning %s: %s\n", prefix, tcpedit_getwarn(tcpedit)); - } else { - fprintf(stderr, "Warning: %s\n", tcpedit_getwarn(tcpedit)); - } - return TCPEDIT_OK; - break; - - default: - assert(0 == 1); /* this should never happen! */ - break; + case TCPEDIT_OK: + case TCPEDIT_ERROR: + return rcode; + case TCPEDIT_SOFT_ERROR: + if (prefix != NULL) { + fprintf(stderr, "Error %s: %s\n", prefix, tcpedit_geterr(tcpedit)); + } else { + fprintf(stderr, "Error: %s\n", tcpedit_geterr(tcpedit)); + } + break; + case TCPEDIT_WARN: + if (prefix != NULL) { + fprintf(stderr, "Warning %s: %s\n", prefix, tcpedit_getwarn(tcpedit)); + } else { + fprintf(stderr, "Warning: %s\n", tcpedit_getwarn(tcpedit)); + } + return TCPEDIT_OK; + default: + assert(0 == 1); /* this should never happen! */ + break; } return TCPEDIT_ERROR; } /** - * \brief Cleans up after ourselves. Return 0 on success. - * + * \brief Cleans up after ourselves. Return 0 on success. + * * Clean up after ourselves and free the ptr. */ int tcpedit_close(tcpedit_t **tcpedit_ex) { - assert(*tcpedit_ex); tcpedit_t *tcpedit; tcpedit = *tcpedit_ex; - dbgx(1, "tcpedit processed " COUNTER_SPEC " bytes in " COUNTER_SPEC - " packets.", tcpedit->runtime.total_bytes, - tcpedit->runtime.pkts_edited); + dbgx(1, + "tcpedit processed " COUNTER_SPEC " bytes in " COUNTER_SPEC " packets.", + tcpedit->runtime.total_bytes, + tcpedit->runtime.pkts_edited); /* free if required */ if (tcpedit->dlt_ctx) { @@ -665,7 +623,7 @@ tcpedit_close(tcpedit_t **tcpedit_ex) * Return a ptr to the Layer 3 data. Returns TCPEDIT_ERROR on error */ const u_char * -tcpedit_l3data(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, const int pktlen) +tcpedit_l3data(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, int pktlen) { u_char *result = NULL; if (code == BEFORE_PROCESS) { @@ -679,12 +637,12 @@ tcpedit_l3data(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, const int /** * Returns the layer 3 type, often encoded as the layer2.proto field */ -int -tcpedit_l3proto(tcpedit_t *tcpedit, tcpedit_coder code, const u_char *packet, const int pktlen) +int +tcpedit_l3proto(tcpedit_t *tcpedit, tcpedit_coder code, const u_char *packet, int pktlen) { - int result = 0; + int result; if (code == BEFORE_PROCESS) { - result = tcpedit_dlt_proto(tcpedit->dlt_ctx, tcpedit->dlt_ctx->decoder->dlt, packet, pktlen); + result = tcpedit_dlt_proto(tcpedit->dlt_ctx, tcpedit->dlt_ctx->decoder->dlt, packet, pktlen); } else { result = tcpedit_dlt_proto(tcpedit->dlt_ctx, tcpedit->dlt_ctx->encoder->dlt, packet, pktlen); } diff --git a/src/tcpedit/tcpedit.h b/src/tcpedit/tcpedit.h index 33cad5328..af6b18214 100644 --- a/src/tcpedit/tcpedit.h +++ b/src/tcpedit/tcpedit.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,65 +18,51 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TCPEDIT_H_ -#define _TCPEDIT_H_ - +#pragma once #include "defines.h" #include "common.h" - -#include "tcpedit_types.h" -#include "tcpedit_api.h" #include "parse_args.h" #include "plugins.h" +#include "tcpedit_api.h" +#include "tcpedit_types.h" #ifdef __cplusplus extern "C" { #endif /** - * libtcpedit common API + * libtcpedit common API */ int tcpedit_init(tcpedit_t **tcpedit_ex, int dlt); char *tcpedit_geterr(tcpedit_t *tcpedit); char *tcpedit_getwarn(tcpedit_t *tcpedit); -int tcpedit_checkerror(tcpedit_t *tcpedit, const int rcode, const char *prefix); +int tcpedit_checkerror(tcpedit_t *tcpedit, int rcode, const char *prefix); int tcpedit_validate(tcpedit_t *tcpedit); -int tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, - u_char **pktdata, tcpr_dir_t direction); +int tcpedit_packet(tcpedit_t *tcpedit, struct pcap_pkthdr **pkthdr, u_char **pktdata, tcpr_dir_t direction); int tcpedit_close(tcpedit_t **tcpedit_ex); int tcpedit_get_output_dlt(tcpedit_t *tcpedit); -const u_char *tcpedit_l3data(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, const int pktlen); +const u_char *tcpedit_l3data(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, int pktlen); -int tcpedit_l3proto(tcpedit_t *tcpedit, tcpedit_coder code, const u_char *packet, const int pktlen); +int tcpedit_l3proto(tcpedit_t *tcpedit, tcpedit_coder code, const u_char *packet, int pktlen); COUNTER tcpedit_get_total_bytes(tcpedit_t *tcpedit); COUNTER tcpedit_get_pkts_edited(tcpedit_t *tcpedit); -/* -u_char *tcpedit_srcmac(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, const int pktlen); -u_char *tcpedit_dstmac(tcpedit_t *tcpedit, tcpedit_coder code, u_char *packet, const int pktlen); -int tcpedit_maclen(tcpedit_t *tcpedit, tcpedit_coder code); -*/ - - /** * These functions are seen by the outside world, but nobody should ever use them * outside of internal tcpedit functions */ #define tcpedit_seterr(x, y, ...) __tcpedit_seterr(x, __FUNCTION__, __LINE__, __FILE__, y, __VA_ARGS__) -void __tcpedit_seterr(tcpedit_t *tcpedit, const char *func, const int line, const char *file, const char *fmt, ...); +void __tcpedit_seterr(tcpedit_t *tcpedit, const char *func, int line, const char *file, const char *fmt, ...); void tcpedit_setwarn(tcpedit_t *tcpedit, const char *fmt, ...); #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/tcpedit_api.c b/src/tcpedit/tcpedit_api.c index 05fca1029..3f23d6ac5 100644 --- a/src/tcpedit/tcpedit_api.c +++ b/src/tcpedit/tcpedit_api.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,15 +18,12 @@ * along with the Tcpreplay Suite. If not, see . */ -#include -#include -#include - -#include "config.h" #include "defines.h" -#include "tcpedit.h" -#include "portmap.h" +#include "config.h" #include "dlt_utils.h" +#include "portmap.h" +#include "tcpedit.h" +#include /** * Set output DLT plugin by using it's DLT_. Note that the user plugin @@ -106,7 +103,6 @@ tcpedit_set_encoder_dltplugin_byname(tcpedit_t *tcpedit, const char *name) return TCPEDIT_OK; } - /** * Set whether we should edit broadcast & multicast IP addresses */ @@ -154,7 +150,7 @@ tcpedit_set_fixhdrlen(tcpedit_t *tcpedit, bool value) /** * \brief should we remove the EFCS from the frame? */ -int +int tcpedit_set_efcs(tcpedit_t *tcpedit, bool value) { assert(tcpedit); @@ -163,7 +159,7 @@ tcpedit_set_efcs(tcpedit_t *tcpedit, bool value) } /** - * \brief set the IPv4 TTL mode + * \brief set the IPv4 TTL mode */ int tcpedit_set_ttl_mode(tcpedit_t *tcpedit, tcpedit_ttl_mode value) @@ -185,7 +181,7 @@ tcpedit_set_ttl_value(tcpedit_t *tcpedit, uint8_t value) } /** - * \brief set the IPv4 TOS/DiffServ/ECN byte value + * \brief set the IPv4 TOS/DiffServ/ECN byte value */ int tcpedit_set_tos(tcpedit_t *tcpedit, uint8_t value) @@ -196,7 +192,7 @@ tcpedit_set_tos(tcpedit_t *tcpedit, uint8_t value) } /** - * \brief set the IPv6 Traffic Class byte value + * \brief set the IPv6 Traffic Class byte value */ int tcpedit_set_tclass(tcpedit_t *tcpedit, uint8_t value) @@ -207,13 +203,13 @@ tcpedit_set_tclass(tcpedit_t *tcpedit, uint8_t value) } /** - * \brief set the IPv6 Flow Label 20bit value + * \brief set the IPv6 Flow Label 20bit value */ int tcpedit_set_flowlabel(tcpedit_t *tcpedit, uint32_t value) { assert(tcpedit); - tcpedit->flowlabel = value; + tcpedit->flowlabel = (int)value; return TCPEDIT_OK; } @@ -235,7 +231,7 @@ tcpedit_set_seed(tcpedit_t *tcpedit) /** * Set the MTU of the frames */ -int +int tcpedit_set_mtu(tcpedit_t *tcpedit, int value) { assert(tcpedit); @@ -246,7 +242,8 @@ tcpedit_set_mtu(tcpedit_t *tcpedit, int value) /** * Enable truncating packets to the MTU length */ -int tcpedit_set_mtu_truncate(tcpedit_t *tcpedit, bool value) +int +tcpedit_set_mtu_truncate(tcpedit_t *tcpedit, bool value) { assert(tcpedit); tcpedit->mtu_truncate = value; @@ -264,7 +261,6 @@ tcpedit_set_maxpacket(tcpedit_t *tcpedit, int value) return TCPEDIT_OK; } - /** * \brief Set the server to client (primary) CIDR map (Pseudo NAT) * @@ -278,8 +274,8 @@ tcpedit_set_cidrmap_s2c(tcpedit_t *tcpedit, char *value) { assert(tcpedit); - tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->cidrmap1, value)) { + tcpedit->rewrite_ip = true; + if (!parse_cidr_map(&tcpedit->cidrmap1, value)) { tcpedit_seterr(tcpedit, "Unable to parse: %s", value); return TCPEDIT_ERROR; } @@ -300,7 +296,7 @@ tcpedit_set_cidrmap_c2s(tcpedit_t *tcpedit, char *value) assert(tcpedit); tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->cidrmap2, value)) { + if (!parse_cidr_map(&tcpedit->cidrmap2, value)) { tcpedit_seterr(tcpedit, "Unable to parse: %s", value); return TCPEDIT_ERROR; } @@ -308,7 +304,7 @@ tcpedit_set_cidrmap_c2s(tcpedit_t *tcpedit, char *value) } /** - * Rewrite the Source IP of any packet + * Rewrite the Source IP of any packet */ int tcpedit_set_srcip_map(tcpedit_t *tcpedit, char *value) @@ -316,7 +312,7 @@ tcpedit_set_srcip_map(tcpedit_t *tcpedit, char *value) assert(tcpedit); tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->srcipmap, value)) { + if (!parse_cidr_map(&tcpedit->srcipmap, value)) { tcpedit_seterr(tcpedit, "Unable to parse source ip map: %s", value); return TCPEDIT_ERROR; } @@ -324,7 +320,7 @@ tcpedit_set_srcip_map(tcpedit_t *tcpedit, char *value) } /** - * Rewrite the Destination IP of any packet + * Rewrite the Destination IP of any packet */ int tcpedit_set_dstip_map(tcpedit_t *tcpedit, char *value) @@ -333,7 +329,7 @@ tcpedit_set_dstip_map(tcpedit_t *tcpedit, char *value) tcpedit->rewrite_ip = true; - if (! parse_cidr_map(&tcpedit->dstipmap, value)) { + if (!parse_cidr_map(&tcpedit->dstipmap, value)) { tcpedit_seterr(tcpedit, "Unable to parse destination ip map: %s", value); return TCPEDIT_ERROR; } @@ -349,9 +345,8 @@ tcpedit_set_port_map(tcpedit_t *tcpedit, char *value) { assert(tcpedit); - if (! parse_portmap(&tcpedit->portmap, value)) { - tcpedit_seterr(tcpedit, - "Unable to parse portmap: %s", value); + if (!parse_portmap(&tcpedit->portmap, value)) { + tcpedit_seterr(tcpedit, "Unable to parse portmap: %s", value); return TCPEDIT_ERROR; } return TCPEDIT_OK; diff --git a/src/tcpedit/tcpedit_api.h b/src/tcpedit/tcpedit_api.h index 8c92e1f5d..6547f2628 100644 --- a/src/tcpedit/tcpedit_api.h +++ b/src/tcpedit/tcpedit_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TCPEDIT_API_H_ -#define _TCPEDIT_API_H_ +#pragma once #ifdef __cplusplus extern "C" { @@ -33,9 +32,8 @@ extern "C" { int tcpedit_set_encoder_dltplugin_byid(tcpedit_t *, int); int tcpedit_set_encoder_dltplugin_byname(tcpedit_t *, const char *); - /** - * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR + * setters always return TCPEDIT_OK on success or TCPEDIT_ERROR * if there is a problem. You can use tcpedit_geterr() to get the reason * for the failure */ @@ -59,10 +57,6 @@ int tcpedit_set_srcip_map(tcpedit_t *, char *); int tcpedit_set_dstip_map(tcpedit_t *, char *); int tcpedit_set_port_map(tcpedit_t *, char *); - #ifdef __cplusplus } #endif - -#endif - diff --git a/src/tcpedit/tcpedit_types.h b/src/tcpedit/tcpedit_types.h index 028ac4cb2..7085d7376 100644 --- a/src/tcpedit/tcpedit_types.h +++ b/src/tcpedit/tcpedit_types.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TCPEDIT_TYPES_H_ -#define _TCPEDIT_TYPES_H_ +#pragma once #include "defines.h" #include "common.h" @@ -30,35 +29,22 @@ extern "C" { #endif #define TCPEDIT_SOFT_ERROR -2 -#define TCPEDIT_ERROR -1 -#define TCPEDIT_OK 0 -#define TCPEDIT_WARN 1 +#define TCPEDIT_ERROR -1 +#define TCPEDIT_OK 0 +#define TCPEDIT_WARN 1 -typedef enum { - TCPEDIT_FIXLEN_OFF = 0, - TCPEDIT_FIXLEN_PAD, - TCPEDIT_FIXLEN_TRUNC, - TCPEDIT_FIXLEN_DEL -} tcpedit_fixlen; +typedef enum { TCPEDIT_FIXLEN_OFF = 0, TCPEDIT_FIXLEN_PAD, TCPEDIT_FIXLEN_TRUNC, TCPEDIT_FIXLEN_DEL } tcpedit_fixlen; typedef enum { - TCPEDIT_TTL_MODE_OFF = 0, + TCPEDIT_TTL_MODE_OFF = 0, TCPEDIT_TTL_MODE_SET, TCPEDIT_TTL_MODE_ADD, TCPEDIT_TTL_MODE_SUB } tcpedit_ttl_mode; -typedef enum { - TCPEDIT_EDIT_BOTH = 0, - TCPEDIT_EDIT_C2S, - TCPEDIT_EDIT_S2C -} tcpedit_direction; - -typedef enum { - BEFORE_PROCESS, - AFTER_PROCESS -} tcpedit_coder; +typedef enum { TCPEDIT_EDIT_BOTH = 0, TCPEDIT_EDIT_C2S, TCPEDIT_EDIT_S2C } tcpedit_direction; +typedef enum { BEFORE_PROCESS, AFTER_PROCESS } tcpedit_coder; #define TCPEDIT_ERRSTR_LEN 1024 typedef struct { @@ -69,7 +55,7 @@ typedef struct { int dlt2; char errstr[TCPEDIT_ERRSTR_LEN]; char warnstr[TCPEDIT_ERRSTR_LEN]; -#ifdef FORCE_ALIGN +#ifdef FORCE_ALIGN u_char *l3buff; #endif } tcpedit_runtime_t; @@ -103,12 +89,12 @@ typedef struct tcpedit_portmap_s { * all the arguments that the packet editing library supports */ typedef struct { - bool validated; /* have we run tcpedit_validate()? */ + bool validated; /* have we run tcpedit_validate()? */ struct tcpeditdlt_s *dlt_ctx; - + /* runtime variables, don't mess with these */ tcpedit_runtime_t runtime; - + /* skip rewriting IP/MAC's which are broadcast or multicast? */ bool skip_broadcast; @@ -122,7 +108,7 @@ typedef struct { /* rewrite TCP seq/ack numbers? */ u_int32_t tcp_sequence_enable; u_int32_t tcp_sequence_adjust; - + /* fix IP/TCP/UDP checksums */ bool fixcsum; @@ -134,30 +120,30 @@ typedef struct { /* TOS/DiffServ/ECN, -1 is disabled, else copy value */ int tos; - + /* IPv6 FlowLabel, -1 is disabled, else copy value */ int flowlabel; - + /* IPv6 TClass, -1 is disabled, else copy value */ int tclass; - + /* rewrite end-point IP addresses between cidrmap1 & cidrmap2 */ - tcpr_cidrmap_t *cidrmap1; /* tcpprep cache data */ + tcpr_cidrmap_t *cidrmap1; /* tcpprep cache data */ tcpr_cidrmap_t *cidrmap2; - + /* src & dst IP mapping */ tcpr_cidrmap_t *srcipmap; tcpr_cidrmap_t *dstipmap; - + /* pseudo-randomize IP addresses using a seed */ uint32_t seed; - + /* rewrite tcp/udp ports */ tcpedit_portmap_t *portmap; - - int mtu; /* Deal with different MTU's */ - bool mtu_truncate; /* Should we truncate frames > MTU? */ - int maxpacket; /* L2 header + MTU */ + + int mtu; /* Deal with different MTU's */ + bool mtu_truncate; /* Should we truncate frames > MTU? */ + int maxpacket; /* L2 header + MTU */ uint32_t fuzz_seed; uint32_t fuzz_factor; @@ -166,12 +152,6 @@ typedef struct { bool fixhdrlen; } tcpedit_t; - #ifdef __cplusplus } #endif - - - -#endif - diff --git a/src/tcpliveplay.c b/src/tcpliveplay.c index 4a6d95acc..010ba614c 100644 --- a/src/tcpliveplay.c +++ b/src/tcpliveplay.c @@ -1,160 +1,147 @@ /* - * Main Author & Publisher: Yazan H. Siam (tcpliveplay@gmail.com) - * File: tcpliveplay.c + * Main Author & Publisher: Yazan H. Siam (tcpliveplay@gmail.com) + * File: tcpliveplay.c * Started as a Senior Design project @ North Carolina State University * Last Updated Date: September 5, 2012 - * + * */ /** - * Program Description: - * This program, 'tcpliveplay' replays a captured set of packets using new TCP connections with the - * captured TCP payloads against a remote host in order to do comprehensive vulnerability testings. + * Program Description: + * This program, 'tcpliveplay' replays a captured set of packets using new TCP connections with the + * captured TCP payloads against a remote host in order to do comprehensive vulnerability testings. * This program takes in a "*.pcap" file that contains only one tcp flow connection and replays it * against a live host exactly how the captured packets are laid out. At the beginning, the program - * establishes who the 'client' is and the 'server' is based on who initiates the SYN compares each - * packet's source ip against the ip of the 'client' (which is named local in the code) and the 'server' - * (remote) to correctly determine the expected seqs & acks. This also extracts the MACs of both local - * and remote clients. The program is also capable of rewriting the local and remote MAC & IP so that - * the packets are properly replayed when used on live networks. The current state of the program is that - * it takes in a pcap file on command line and writes a new file called "newfile.pcap" which is used thereafter - * for the rest of the program's calculations and set expectations. The program prints out a summary of the - * new file on the command prompt. Once the program is done, "newfile.pcap" is cleaned up. + * establishes who the 'client' is and the 'server' is based on who initiates the SYN compares each + * packet's source ip against the ip of the 'client' (which is named local in the code) and the 'server' + * (remote) to correctly determine the expected seqs & acks. This also extracts the MACs of both local + * and remote clients. The program is also capable of rewriting the local and remote MAC & IP so that + * the packets are properly replayed when used on live networks. The current state of the program is that + * it takes in a pcap file on command line and writes a new file called "newfile.pcap" which is used thereafter + * for the rest of the program's calculations and set expectations. The program prints out a summary of the + * new file on the command prompt. Once the program is done, "newfile.pcap" is cleaned up. * Program Design Overview: - * Before replaying the packets, the program reads in the pcap file that contains one tcp flow, - * and takes the SEQ/ACK #s. - * Based on the number of packets, a struct schedule of events are is set up. Based on - * the SEQ/ACK numbers read in, the schedule is setup to be relative numbers rather than - * absolute. This is done by starting with local packets, subtracting the first SEQ (which - * is that of the first SYN packet) from all the SEQs of the local packets then by subtracting - * the first remote sequence (which is that of the SYN-ACK packet) from all the local packet's - * ACKs. After the local side SEQ/ACK numbers are fixed to relative numbers, 'lseq_adjust' - * the locally generated random number for the SYN packet gets added to all the local SEQs - * to adjust the schedule to absolute number configuration. Then doing the remote side is similar - * except we only fix the remote ACKs based on our locally generated random number because - * we do not yet know the remote random number of the SYN-ACK packet. This means that at this - * point the entire schedule of local packets and remote packets are set in such a way that - * the local packets' SEQ's are absolute, but ACKs are relative and the remote packets' SEQ's are - * relative but ACKs as absolute. Once this is set, the replay starts by sending first SYN packet. + * Before replaying the packets, the program reads in the pcap file that contains one tcp flow, + * and takes the SEQ/ACK #s. + * Based on the number of packets, a struct schedule of events are is set up. Based on + * the SEQ/ACK numbers read in, the schedule is setup to be relative numbers rather than + * absolute. This is done by starting with local packets, subtracting the first SEQ (which + * is that of the first SYN packet) from all the SEQs of the local packets then by subtracting + * the first remote sequence (which is that of the SYN-ACK packet) from all the local packet's + * ACKs. After the local side SEQ/ACK numbers are fixed to relative numbers, 'lseq_adjust' + * the locally generated random number for the SYN packet gets added to all the local SEQs + * to adjust the schedule to absolute number configuration. Then doing the remote side is similar + * except we only fix the remote ACKs based on our locally generated random number because + * we do not yet know the remote random number of the SYN-ACK packet. This means that at this + * point the entire schedule of local packets and remote packets are set in such a way that + * the local packets' SEQ's are absolute, but ACKs are relative and the remote packets' SEQ's are + * relative but ACKs as absolute. Once this is set, the replay starts by sending first SYN packet. * If the remote host's acks with the SYN packet_SEQ+1 then we save their remote SEQ and adjust - * the local ACKs and remote SEQs in the struct schedule to be absolute based this remote SEQ. - * From this point on forward, we know or 'expect' what the remote host's ACKs and SEQs are exactly. - * If the remote host responds correctly as we expect (checking the schedule position expectation - * as packets are received) then we proceed in the schedule whether the next event is to send a local - * packet or wait for a remote packet to arrive. + * the local ACKs and remote SEQs in the struct schedule to be absolute based this remote SEQ. + * From this point on forward, we know or 'expect' what the remote host's ACKs and SEQs are exactly. + * If the remote host responds correctly as we expect (checking the schedule position expectation + * as packets are received) then we proceed in the schedule whether the next event is to send a local + * packet or wait for a remote packet to arrive. * - * Usage: tcpliveplay <'random' dst port OR specify dport #> + * Usage: tcpliveplay <'random' + dst port OR specify dport #> * - * Example: + * Example: * yhsiam@yhsiam-VirtualBox:~$ tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random - * - * NOTE: This program may not completely replay the packets due to the remote host responding in an unexpected - * fashion such as responding with packets never seen in the given *.pcap file or coupling packets together, etc. - * if you have any suggestion on improving this software or if you find any bugs, please let me know at my - * email: tcpliveplay@gmail.com - * - * Past Contributors (Last contributed May 4, 2012): Andrew Leonard & Beau Luck + * + * NOTE: This program may not completely replay the packets due to the remote host responding in an unexpected + * fashion such as responding with packets never seen in the given *.pcap file or coupling packets together, etc. + * if you have any suggestion on improving this software or if you find any bugs, please let me know at my + * email: tcpliveplay@gmail.com + * + * Past Contributors (Last contributed May 4, 2012): Andrew Leonard & Beau Luck * */ +#include "tcpliveplay.h" #include "config.h" -#include "defines.h" -#include "common.h" - +#include "common/sendpacket.h" +#include "common/utils.h" +#include "tcpliveplay_opts.h" +#include +#include +#include #include -#include -#include -#include -#include +#include #include #include #include -#include -#include -#include -#include #include -#include #include -#include -#include -#include -#include -#include -#include - -#include "tcpliveplay.h" -#include "tcpliveplay_opts.h" -#include "common/sendpacket.h" -#include "common/utils.h" -#include "send_packets.h" +#include +#include volatile int didsig; -#ifdef DEBUG /* set -DDEBUG=1 */ +#ifdef DEBUG /* set -DDEBUG=1 */ int debug = 0; #endif -pcap_t *set_live_filter(char *dev, input_addr* hostip, unsigned int port); -pcap_t *set_offline_filter(char* file); -pcap_t *live_handle; -u_char *recvd_pkt_data = NULL; -unsigned int buf_write_index = 0; -unsigned int sched_index = 0; -unsigned int initial_rseq=0; +pcap_t *set_live_filter(char *dev, input_addr *hostip, unsigned int port); +pcap_t *set_offline_filter(char *file); +pcap_t *live_handle; +unsigned int sched_index = 0; +unsigned int initial_rseq = 0; sendpacket_t *sp; unsigned int seed = 0; -const u_char *packet_keeper_rprev = NULL; -ether_hdr *etherhdr_rprev = NULL; /*g for Global header pointers used in pcap_loop callback*/ +/*g for Global header pointers used in pcap_loop callback*/ tcp_hdr *tcphdr_rprev = NULL; -ipv4_hdr *iphdr_rprev = NULL; -unsigned int size_payload_prev = 0; -unsigned int finack_rindex = 0; +unsigned int size_payload_prev = 0; unsigned int acked_index = 0; -unsigned int diff_payload_index = 0; -bool different_payload = false; +unsigned int diff_payload_index = 0; +bool different_payload = false; volatile sig_atomic_t keep_going = 1; int random_port(); -unsigned int pkts_scheduled=0; /* packet counter */ -struct tcp_sched* sched = NULL; +unsigned int pkts_scheduled = 0; /* packet counter */ +struct tcp_sched *sched = NULL; void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); -void catch_alarm (int sig); -int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac); -int extmac(char* new_rmac_ptr, struct mac_addr* new_remotemac); -int extip(char *ip_string, input_addr* new_remoteip); -int rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* myip, struct mac_addr* mymac, char* file, unsigned int new_src_port); -int setup_sched(struct tcp_sched* sched); -int relative_sched(struct tcp_sched* sched, u_int32_t first_rseq, int num_packets); +void catch_alarm(int sig); +int iface_addrs(char *iface, input_addr *ip, struct mac_addr *mac); +int extmac(char *new_rmac_ptr, struct mac_addr *new_remotemac); +int extip(char *ip_string, input_addr *new_remoteip); +int rewrite(input_addr *new_remoteip, + struct mac_addr *new_remotemac, + input_addr *myip, + struct mac_addr *mymac, + char *file, + unsigned int new_src_port); +int setup_sched(struct tcp_sched *schedule); +int relative_sched(struct tcp_sched *schedule, u_int32_t first_rseq, int num_packets); int fix_all_checksum_liveplay(ipv4_hdr *iphdr); -int compip(input_addr* lip, input_addr* rip, input_addr* pkgip); +int compip(input_addr *lip, input_addr *rip, input_addr *pkgip); int do_checksum_liveplay(u_int8_t *data, int proto, int len); int do_checksum_math_liveplay(u_int16_t *data, int len); /** - * This is the main function of the program that handles calling other + * This is the main function of the program that handles calling other * functions to implemented the needed operations of the replay functionaily. */ -int -main(int argc, char **argv) +int +main(int argc, char **argv) { unsigned int k; - int num_packets = 0; + int num_packets; static const char random_strg[] = "random"; - char* iface = argv[1]; - char* new_rmac_ptr; - char* new_rip_ptr; - input_addr new_remoteip; + char *iface = argv[1]; + char *new_rmac_ptr; + char *new_rip_ptr; + input_addr new_remoteip; struct mac_addr new_remotemac; input_addr myip; struct mac_addr mymac; - int new_src_port = 0; - unsigned int retransmissions = 0; + int new_src_port; + unsigned int retransmissions = 0; pcap_t *local_handle; char errbuf[PCAP_ERRBUF_SIZE]; char ebuf[SENDPACKET_ERRBUF_SIZE]; @@ -162,17 +149,18 @@ main(int argc, char **argv) optionProcess(&tcpliveplayOptions, argc, argv); /*Process AutoOpts for manpage options*/ - if((argc < 5) || (argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL) || (argv[4]==NULL) || (argv[5]==NULL)){ - printf("ERROR: Incorrect Usage!\n"); + if ((argc < 5) || (argv[1] == NULL) || (argv[2] == NULL) || (argv[3] == NULL) || (argv[4] == NULL) || + (argv[5] == NULL)) { + printf("ERROR: Incorrect Usage!\n"); printf("Usage: tcpliveplay \n"); - printf("Example:\n yhsiam@yhsiam-VirtualBox:~$ sudo tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random\n\n"); + printf("Example:\n yhsiam@yhsiam-VirtualBox:~$ sudo tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random\n\n"); exit(0); } if (strlen(iface) > IFNAMSIZ - 1) errx(-1, "Invalid interface name %s\n", iface); - if (iface_addrs(iface, &myip, &mymac) < 0) /* Extract MAC of interface replay is being request on */ + if (iface_addrs(iface, &myip, &mymac) < 0) /* Extract MAC of interface replay is being request on */ errx(-1, "Failed to access interface %s\n", iface); /* open send function socket*/ @@ -180,10 +168,10 @@ main(int argc, char **argv) errx(-1, "Can't open %s: %s", argv[1], ebuf); /*for(int i = 0; i<10; i++) tolower(port_mode[i]);*/ - if(strcmp(argv[5], random_strg)==0) + if (strcmp(argv[5], random_strg) == 0) new_src_port = random_port(); else - new_src_port = atoi(argv[5]); + new_src_port = strtol(argv[5], NULL, 10); if (new_src_port < 0 || new_src_port > 65535) errx(new_src_port, "Cannot use source port %d", new_src_port); @@ -192,12 +180,11 @@ main(int argc, char **argv) /* Establish a handler for SIGALRM signals. */ /* This is used as timeout for unresponsive remote hosts */ - signal (SIGALRM, catch_alarm); - + signal(SIGALRM, catch_alarm); /* Extract new Remote MAC & IP inputed at command line */ - new_rmac_ptr= argv[4]; - new_rip_ptr = argv[3]; + new_rmac_ptr = argv[4]; + new_rip_ptr = argv[3]; /* These function setup the MAC & IP addresses in the mac_addr & in_addr structs */ if (extmac(new_rmac_ptr, &new_remotemac) == ERROR) @@ -210,14 +197,14 @@ main(int argc, char **argv) /* that need to be replayed */ num_packets = rewrite(&new_remoteip, &new_remotemac, &myip, &mymac, argv[2], new_src_port); if (num_packets < 2) - errx(-1, "Unable to rewrite PCAP file %s\n",argv[2]); + errx(-1, "Unable to rewrite PCAP file %s\n", argv[2]); /* create schedule & set it up */ - sched = (struct tcp_sched*) malloc(num_packets*sizeof(struct tcp_sched)); + sched = (struct tcp_sched *)malloc(num_packets * sizeof(struct tcp_sched)); if (!sched) err(-1, "out of memory\n"); - pkts_scheduled = setup_sched(sched); /* Returns number of packets in schedule*/ + pkts_scheduled = setup_sched(sched); /* Returns number of packets in schedule*/ /* Set up the schedule struct to be relative numbers rather than absolute*/ for (i = 0; i < num_packets; i++) { @@ -229,24 +216,24 @@ main(int argc, char **argv) printf("Packets Scheduled %u\n", pkts_scheduled); /* Open socket for savedfile traffic to be sent*/ - local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ + local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ if (local_handle == NULL) { - fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); + fprintf(stderr, "Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); free(sched); - return(2); + return (2); } /* Open socket for live traffic to be listed to*/ - live_handle = set_live_filter(iface, &myip, new_src_port); /* returns a pcap_t that filters out traffic other than TCP*/ + live_handle = + set_live_filter(iface, &myip, new_src_port); /* returns a pcap_t that filters out traffic other than TCP*/ if (live_handle == NULL) { - fprintf(stderr,"Error occurred while listing on traffic: %s\n", errbuf); + fprintf(stderr, "Error occurred while listing on traffic: %s\n", errbuf); free(sched); - return(2); + return (2); } - /* Printout when no packets are scheduled */ - if(pkts_scheduled==0){ + if (pkts_scheduled == 0) { printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ ERROR:: There are no TCP packets to send +\n"); printf("+ Closing replay... +\n"); @@ -257,118 +244,110 @@ main(int argc, char **argv) } /* Start replay by sending the first packet, the SYN, from the schedule */ - else if(sched[0].local){ /* Send first packet*/ + else if (sched[0].local) { /* Send first packet*/ sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr); - printf("Sending Local Packet............... [%u]\n",sched_index+1); + printf("Sending Local Packet............... [%u]\n", sched_index + 1); sched_index++; /* Proceed in the schedule */ } /* Main while loop that handles the decision making and the replay oprations */ - while(sched_indexth_flags==TH_RST) || (tcphdr_rprev->th_flags==(TH_RST|TH_ACK))){ - printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - printf("+ ERROR:: Remote host has requested to RESET the connection. +\n"); - printf("+ Closing replay... +\n"); - printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); - break; + if (tcphdr_rprev == NULL) { + // printf("FIRST PASS!\n"); } - /*Check if received earlier FIN-ACK than expected - else if((sched_index-1 < finack_rindex) && (tcphdr_rprev->th_flags==(TH_FIN|TH_ACK))){ + /* Check if received RST or RST-ACK flagged packets*/ + else if ((tcphdr_rprev->th_flags == TH_RST) || (tcphdr_rprev->th_flags == (TH_RST | TH_ACK))) { printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - printf("+ ERROR:: Remote host sent an earlier FIN-ACK than expected. +\n"); + printf("+ ERROR:: Remote host has requested to RESET the connection. +\n"); printf("+ Closing replay... +\n"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); - return; - } */ + break; + } /* Do the following if we receive a packet that ACKs for the same ACKing of next packet */ - else if((tcphdr_rprev->th_seq==htonl(sched[sched_index].exp_rseq)) && (tcphdr_rprev->th_ack==htonl(sched[sched_index].exp_rack)) && (size_payload_prev>0)){ - printf("Received Remote Packet............... [%u]\n",sched_index+1); - printf("Skipping Packet...................... [%u] to Packet [%u]\n",sched_index+1, sched_index+2); + else if ((tcphdr_rprev->th_seq == htonl(sched[sched_index].exp_rseq)) && + (tcphdr_rprev->th_ack == htonl(sched[sched_index].exp_rack)) && (size_payload_prev > 0)) { + printf("Received Remote Packet............... [%u]\n", sched_index + 1); + printf("Skipping Packet...................... [%u] to Packet [%u]\n", + sched_index + 1, + sched_index + 2); printf("Next Remote Packet Expectation met.\nProceeding in replay...\n"); - sched_index++; - } + sched_index++; + } /* Do the following if payload does not meet expectation and re-attempt with the remote host for 3 tries*/ - else if(different_payload){ + else if (different_payload) { printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - printf("+ WARNING: Remote host is not meeting packet size expectations. +\n"); - printf("+ for packet %-u. Application layer data differs from capture being replayed. +\n", diff_payload_index+1); - printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); + printf("+ WARNING: Remote host is not meeting packet size expectations. +\n"); + printf("+ for packet %-u. Application layer data differs from capture being replayed. +\n", + diff_payload_index + 1); + printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); printf("Requesting retransmission.\n Proceeding...\n"); - different_payload = false; + different_payload = false; } /* Local Packets */ - if(sched[sched_index].local) { + if (sched[sched_index].local) { /*Reset alarm timeout*/ - alarm (ALARM_TIMEOUT); + alarm(ALARM_TIMEOUT); printf("Sending Local Packet............... [%u]\n", sched_index + 1); - - /* edit each packet tcphdr before sending based on the schedule*/ - if(sched_index>0){ - sched[sched_index].tcphdr->th_ack = htonl(sched[sched_index].curr_lack); + + /* edit each packet tcphdr before sending based on the schedule*/ + if (sched_index > 0) { + sched[sched_index].tcphdr->th_ack = htonl(sched[sched_index].curr_lack); fix_all_checksum_liveplay(sched[sched_index].iphdr); } /* If 3 attempts of resending was made, then error out to the user */ - if(sched[sched_index].sent_counter==3){ + if (sched[sched_index].sent_counter == 3) { printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - printf("+ ERROR: Re-sent packet [%-u] 3 times, but remote host is not +\n", sched_index+1); + printf("+ ERROR: Re-sent packet [%-u] 3 times, but remote host is not +\n", sched_index + 1); printf("+ responding as expected. 3 resend attempts are a maximum. +\n"); printf("+ Closing replay... +\n"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); - break; + break; } /* If nothing goes wrong, then send the packet scheduled to be sent, then proceed in the schedule */ sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr); sched[sched_index].sent_counter++; /* Keep track of how many times this specific packet was attempted */ - sched_index++; /* proceed */ + sched_index++; /* proceed */ } /* Remote Packets */ - else if(sched[sched_index].remote){ - - alarm (ALARM_TIMEOUT); + else if (sched[sched_index].remote) { + alarm(ALARM_TIMEOUT); printf("Receiving Packets from remote host...\n"); pcap_dispatch(live_handle, 1, got_packet, NULL); /* Listen in on NIC for tcp packets */ - //printf("pcap_loop returned\n"); + // printf("pcap_loop returned\n"); } } /* end of main while loop*/ - - pcap_breakloop(live_handle); + pcap_breakloop(live_handle); pcap_close(live_handle); - sendpacket_close(sp); /* Close Send socket*/ + sendpacket_close(sp); /* Close Send socket*/ remove("newfile.pcap"); /* Remote the rewritten file that was created*/ - for(k=0; kth_seq = htonl(sched[i].curr_lseq); /* Edit the actual packet header data */ - fix_all_checksum_liveplay(sched[i].iphdr); /* Fix the checksum */ - sched[i].exp_rseq = sched[i].exp_rseq - first_rseq; - sched[i].exp_rack = sched[i].exp_rack - first_lseq; - sched[i].exp_rack = sched[i].exp_rack + lseq_adjust; - } - else if(sched[i].remote){ - sched[i].exp_rseq = sched[i].exp_rseq - first_rseq; /* Fix expected remote SEQ to be relative */ - sched[i].exp_rack = sched[i].exp_rack - first_lseq; /* Fix expected remote ACK to be relative*/ - sched[i].exp_rack = sched[i].exp_rack + lseq_adjust; /* Fix expected remote ACK to be absolute */ + for (i = 0; i < num_packets; i++) { + if (schedule[i].local) { + schedule[i].curr_lseq = schedule[i].curr_lseq - first_lseq; /* Fix current local SEQ to relative */ + schedule[i].curr_lseq = schedule[i].curr_lseq + + lseq_adjust; /* Make absolute. lseq_adjust is the locally generated random number */ + schedule[i].curr_lack = schedule[i].curr_lack - first_rseq; /* Fix current local ACK to relative */ + if (schedule[i].tcphdr) + schedule[i].tcphdr->th_seq = htonl(schedule[i].curr_lseq); /* Edit the actual packet header data */ + fix_all_checksum_liveplay(schedule[i].iphdr); /* Fix the checksum */ + schedule[i].exp_rseq = schedule[i].exp_rseq - first_rseq; + schedule[i].exp_rack = schedule[i].exp_rack - first_lseq; + schedule[i].exp_rack = schedule[i].exp_rack + lseq_adjust; + } else if (schedule[i].remote) { + schedule[i].exp_rseq = schedule[i].exp_rseq - first_rseq; /* Fix expected remote SEQ to be relative */ + schedule[i].exp_rack = schedule[i].exp_rack - first_lseq; /* Fix expected remote ACK to be relative*/ + schedule[i].exp_rack = schedule[i].exp_rack + lseq_adjust; /* Fix expected remote ACK to be absolute */ } } return SUCCESS; - } - /** * This function sets up the schedule for the rest of the program * extracting all the needed information from the given pcap file - * and coping into memory (into a struct format) + * and coping into memory (into a struct format) * */ int -setup_sched(struct tcp_sched* sched){ - - input_addr sip, dip; /* Source & Destination IP */ - input_addr local_ip, remote_ip; /* ip address of client and server*/ +setup_sched(struct tcp_sched *schedule) +{ + input_addr sip, dip; /* Source & Destination IP */ + input_addr local_ip, remote_ip; /* ip address of client and server*/ pcap_t *local_handle; - const u_char *packet; /* The actual packet */ - unsigned int flags=0; - struct pcap_pkthdr header; // The header that pcap gives us - unsigned int pkt_counter=0; - bool remote = false; /* flags to test if data is from 'client'=local or 'server'=remote */ + const u_char *packet; /* The actual packet */ + unsigned int flags; + struct pcap_pkthdr header; // The header that pcap gives us + int pkt_counter = 0; + bool remote = false; /* flags to test if data is from 'client'=local or 'server'=remote */ bool local = false; unsigned int i = 0; - local_ip.byte1=0; - local_ip.byte2=0; - local_ip.byte3=0; - local_ip.byte4=0; + local_ip.byte1 = 0; + local_ip.byte2 = 0; + local_ip.byte3 = 0; + local_ip.byte4 = 0; - remote_ip.byte1=0; - remote_ip.byte2=0; - remote_ip.byte3=0; - remote_ip.byte4=0; + remote_ip.byte1 = 0; + remote_ip.byte2 = 0; + remote_ip.byte3 = 0; + remote_ip.byte4 = 0; char errbuf[PCAP_ERRBUF_SIZE]; - - local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ + local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ if (local_handle == NULL) { - fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); - return(2); + fprintf(stderr, "Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); + return (2); } /*Before sending any packet, setup the schedule with the proper parameters*/ - while((packet = safe_pcap_next(local_handle, &header))) { + while ((packet = safe_pcap_next(local_handle, &header))) { /*temporary packet buffers*/ ether_hdr *etherhdr; tcp_hdr *tcphdr; @@ -511,45 +487,44 @@ setup_sched(struct tcp_sched* sched){ pkt_counter++; /*increment number of packets seen*/ - memcpy(&sched[i].pkthdr, &header, sizeof(struct pcap_pkthdr)); - sched[i].packet_ptr = safe_malloc(sched[i].pkthdr.len); - memcpy(sched[i].packet_ptr, packet, sched[i].pkthdr.len); + memcpy(&schedule[i].pkthdr, &header, sizeof(struct pcap_pkthdr)); + schedule[i].packet_ptr = safe_malloc(schedule[i].pkthdr.len); + memcpy(schedule[i].packet_ptr, packet, schedule[i].pkthdr.len); /* extract necessary data */ - etherhdr = (ether_hdr*)(sched[i].packet_ptr); - iphdr = (ipv4_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET); + etherhdr = (ether_hdr *)(schedule[i].packet_ptr); + iphdr = (ipv4_hdr *)(schedule[i].packet_ptr + SIZE_ETHERNET); size_ip = iphdr->ip_hl << 2; if (size_ip < 20) { printf("ERROR: Invalid IP header length: %u bytes\n", size_ip); return 0; } - tcphdr = (tcp_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip); - size_tcp = tcphdr->th_off*4; + tcphdr = (tcp_hdr *)(schedule[i].packet_ptr + SIZE_ETHERNET + size_ip); + size_tcp = tcphdr->th_off * 4; if (size_tcp < 20) { printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp); return 0; } - /* payload = (u_char *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip + size_tcp); */ + /* payload = (u_char *)(schedule[i].packet_ptr + SIZE_ETHERNET + size_ip + size_tcp); */ size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp)); - /* Source IP and Destination IP */ sip = iphdr->ip_src; dip = iphdr->ip_dst; flags = tcphdr->th_flags; - if (flags == TH_SYN){ /* set IPs who's local and who's remote based on the SYN flag */ + if (flags == TH_SYN) { /* set IPs who's local and who's remote based on the SYN flag */ local_ip = sip; remote_ip = dip; } /*Compare IPs to see which packet is this coming from*/ - if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH){ + if (compip(&local_ip, &remote_ip, &sip) == LOCAL_IP_MATCH) { local = true; remote = false; } - if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH){ + if (compip(&local_ip, &remote_ip, &sip) == REMOTE_IP_MATCH) { local = false; remote = true; } @@ -557,88 +532,89 @@ setup_sched(struct tcp_sched* sched){ /* Setup rest of Schedule, parameter by parameter */ /* Refer to header file for details on each of the parameters */ - sched[i].etherhdr = etherhdr; - sched[i].iphdr = iphdr; - sched[i].tcphdr = tcphdr; - sched[i].size_ip = size_ip; - sched[i].size_tcp = size_tcp; - sched[i].size_payload = size_payload; - sched[i].sent_counter = 0; + schedule[i].etherhdr = etherhdr; + schedule[i].iphdr = iphdr; + schedule[i].tcphdr = tcphdr; + schedule[i].size_ip = size_ip; + schedule[i].size_tcp = size_tcp; + schedule[i].size_payload = size_payload; + schedule[i].sent_counter = 0; /* Do the following only for the first packet (SYN)*/ - if(i==0){ - sched[i].length_last_ldata = 0; - sched[i].length_curr_ldata = 0; - sched[i].length_last_rdata = 0; - sched[i].length_curr_rdata = 0; - sched[i].local = true; - sched[i].remote = false; - sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq); - sched[i].curr_lack = 0; - sched[i].exp_rseq = 0; /* Keep track of previous remote seq & ack #s*/ - sched[i].exp_rack = 0; - - } + if (i == 0) { + schedule[i].length_last_ldata = 0; + schedule[i].length_curr_ldata = 0; + schedule[i].length_last_rdata = 0; + schedule[i].length_curr_rdata = 0; + schedule[i].local = true; + schedule[i].remote = false; + schedule[i].curr_lseq = ntohl(schedule[i].tcphdr->th_seq); + schedule[i].curr_lack = 0; + schedule[i].exp_rseq = 0; /* Keep track of previous remote seq & ack #s*/ + schedule[i].exp_rack = 0; + + } /* Local Packet operations */ - else if(local){ - sched[i].length_last_ldata = sched[i-1].length_curr_ldata; - sched[i].length_curr_ldata = size_payload; - sched[i].length_last_rdata = sched[i-1].length_curr_rdata; - sched[i].length_curr_rdata = 0; - sched[i].local = true; - sched[i].remote = false; - sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq); - sched[i].curr_lack = ntohl(sched[i].tcphdr->th_ack); - sched[i].exp_rseq = sched[i-1].exp_rseq; /* Keep track of previous remote seq & ack #s*/ - sched[i].exp_rack = sched[i-1].exp_rack; + else if (local) { + schedule[i].length_last_ldata = schedule[i - 1].length_curr_ldata; + schedule[i].length_curr_ldata = size_payload; + schedule[i].length_last_rdata = schedule[i - 1].length_curr_rdata; + schedule[i].length_curr_rdata = 0; + schedule[i].local = true; + schedule[i].remote = false; + schedule[i].curr_lseq = ntohl(schedule[i].tcphdr->th_seq); + schedule[i].curr_lack = ntohl(schedule[i].tcphdr->th_ack); + schedule[i].exp_rseq = schedule[i - 1].exp_rseq; /* Keep track of previous remote seq & ack #s*/ + schedule[i].exp_rack = schedule[i - 1].exp_rack; } /* Remote Packet operations */ - else if(remote){ - sched[i].length_last_ldata = sched[i-1].length_curr_ldata; - sched[i].length_curr_ldata = 0; - sched[i].length_last_rdata = sched[i-1].length_curr_rdata; - sched[i].length_curr_rdata = size_payload; - sched[i].local = false; - sched[i].remote = true; - sched[i].curr_lseq = sched[i-1].curr_lseq; - sched[i].curr_lack = sched[i-1].curr_lack; - sched[i].exp_rseq = ntohl(sched[i].tcphdr->th_seq); /* Keep track of previous remote seq & ack #s*/ - sched[i].exp_rack = ntohl(sched[i].tcphdr->th_ack); - /* Setup global variable where remote FIN-ACK exists*/ - if(flags == (TH_FIN|TH_ACK)) finack_rindex = i; - //printf("REMOTE --------%d\n",i+1); + else if (remote) { + schedule[i].length_last_ldata = schedule[i - 1].length_curr_ldata; + schedule[i].length_curr_ldata = 0; + schedule[i].length_last_rdata = schedule[i - 1].length_curr_rdata; + schedule[i].length_curr_rdata = size_payload; + schedule[i].local = false; + schedule[i].remote = true; + schedule[i].curr_lseq = schedule[i - 1].curr_lseq; + schedule[i].curr_lack = schedule[i - 1].curr_lack; + schedule[i].exp_rseq = ntohl(schedule[i].tcphdr->th_seq); /* Keep track of previous remote seq & ack #s*/ + schedule[i].exp_rack = ntohl(schedule[i].tcphdr->th_ack); } i++; /* increment schedule index */ } /*end internal loop for reading packets (all in one file)*/ - pcap_close(local_handle); /*close the pcap file*/ + pcap_close(local_handle); /*close the pcap file*/ return pkt_counter; /* Return number of packets scheduled */ } - /** - * This function returns a pcap_t for the live traffic handler which + * This function returns a pcap_t for the live traffic handler which * filters out traffic other than TCP * */ -pcap_t* -set_live_filter(char *dev, input_addr* hostip, unsigned int port) +pcap_t * +set_live_filter(char *dev, input_addr *hostip, unsigned int port) { - pcap_t *handle = NULL; /* Session handle */ - char errbuf[PCAP_ERRBUF_SIZE]; /* Error string buffer */ - struct bpf_program fp; /* The compiled filter */ + pcap_t *handle = NULL; /* Session handle */ + char errbuf[PCAP_ERRBUF_SIZE]; /* Error string buffer */ + struct bpf_program fp; /* The compiled filter */ char filter_exp[52]; - sprintf(filter_exp,"tcp and dst host %d.%d.%d.%d and dst port %u", - hostip->byte1, hostip->byte2, hostip->byte3, hostip->byte4, port); /* The filter expression */ - bpf_u_int32 mask; /* Our network mask */ - bpf_u_int32 net; /* Our IP */ + sprintf(filter_exp, + "tcp and dst host %d.%d.%d.%d and dst port %u", + hostip->byte1, + hostip->byte2, + hostip->byte3, + hostip->byte4, + port); /* The filter expression */ + bpf_u_int32 mask; /* Our network mask */ + bpf_u_int32 net; /* Our IP */ /* Define the device */ if (dev == NULL) { @@ -672,24 +648,22 @@ set_live_filter(char *dev, input_addr* hostip, unsigned int port) return handle; } - /** - * This function returns a pcap_t for the savedfile traffic handler which + * This function returns a pcap_t for the savedfile traffic handler which * filters out traffic other than TCP * */ -pcap_t* -set_offline_filter(char* file) +pcap_t * +set_offline_filter(char *file) { - pcap_t *handle; /* Session handle */ - char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ - struct bpf_program fp; /* The compiled filter */ + pcap_t *handle; /* Session handle */ + char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ + struct bpf_program fp; /* The compiled filter */ char filter_exp[] = "tcp"; - bpf_u_int32 net=0; /* Our IP */ - + bpf_u_int32 net = 0; /* Our IP */ /* Open savedfile */ - handle = pcap_open_offline(file, errbuf); + handle = pcap_open_offline(file, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open file %s\n", errbuf); return handle; @@ -708,24 +682,20 @@ set_offline_filter(char* file) return handle; } - /** * This is the callback function for pcap_loop * This function is called every time we receive a remote packet */ -void -got_packet(_U_ u_char *args, _U_ const struct pcap_pkthdr *header, - const u_char *packet) +void +got_packet(_U_ u_char *args, _U_ const struct pcap_pkthdr *header, const u_char *packet) { - ether_hdr *etherhdr; tcp_hdr *tcphdr; ipv4_hdr *iphdr; unsigned int size_ip, size_tcp, size_payload; - unsigned int flags = 0; + unsigned int flags; /* Extract and examine received packet headers */ - etherhdr = (ether_hdr*)(packet); iphdr = (ipv4_hdr *)(packet + SIZE_ETHERNET); size_ip = iphdr->ip_hl << 2; if (size_ip < 20) { @@ -733,84 +703,83 @@ got_packet(_U_ u_char *args, _U_ const struct pcap_pkthdr *header, return; } tcphdr = (tcp_hdr *)(packet + SIZE_ETHERNET + size_ip); - size_tcp = tcphdr->th_off*4; + size_tcp = tcphdr->th_off * 4; if (size_tcp < 20) { printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp); return; } - size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp)); - + size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp)); flags = tcphdr->th_flags; - /* Check correct SYN-ACK expectation, if so then proceed in fixing entire schedule from relative to absolute SEQs+ACKs */ - if((flags == (TH_SYN|TH_ACK)) && (sched_index==1) && (tcphdr->th_ack==htonl(sched[sched_index-1].curr_lseq + 1))){ + /* Check correct SYN-ACK expectation, if so then proceed in fixing entire schedule from relative to absolute + * SEQs+ACKs */ + if ((flags == (TH_SYN | TH_ACK)) && (sched_index == 1) && + (tcphdr->th_ack == htonl(sched[sched_index - 1].curr_lseq + 1))) { unsigned int j; printf("Received Remote Packet............... [%u]\n", sched_index + 1); - printf("Remote Pakcet Expectation met.\nProceeding in replay....\n"); - //printf("SYN-ACKed Random SEQ set!\n"); - initial_rseq = ntohl(tcphdr->th_seq); - //printf("initial_rseq: %u\n", initial_rseq); + printf("Remote Packet Expectation met.\nProceeding in replay....\n"); + // printf("SYN-ACKed Random SEQ set!\n"); + initial_rseq = ntohl(tcphdr->th_seq); + // printf("initial_rseq: %u\n", initial_rseq); /* After we receiving the first SYN-ACK, then adjust the entire sched to be absolute rather than relative #s*/ sched[1].exp_rseq = sched[1].exp_rseq + initial_rseq; - for(j = 2; jReceived a Remote Packet\n"); printf(">>Checking Expectations\n"); - /* Handle Remote Packet Loss */ - if(sched[sched_index].exp_rack > ntohl(tcphdr->th_ack)) { - //printf("Remote Packet Loss! Resending Lost packet\n"); - sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ - //printf("ACKED Index = %d\n", acked_index); - while(!sched[sched_index].local){ - sched_index++; + if (sched[sched_index].exp_rack > ntohl(tcphdr->th_ack)) { + // printf("Remote Packet Loss! Resending Lost packet\n"); + sched_index = acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ + // printf("ACKED Index = %d\n", acked_index); + while (!sched[sched_index].local) { + sched_index++; } - return; - } + return; + } - /* Handle Local Packet Loss <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<th_seq)) && sched[sched_index].remote){ + /* Handle Local Packet Loss <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<th_seq)) && sched[sched_index].remote) { /* Resend immediate previous LOCAL packet */ printf("Local Packet Loss! Resending Lost packet >> DupACK Issued!\n"); - sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ + sched_index = acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ /*sched[sched_index].sent_counter=0; Reset the re-transmission counter for this ACKed packet?*/ - //printf("ACKED Index = %d\n", acked_index); - while(!sched[sched_index].local){ - sched_index++; + // printf("ACKED Index = %d\n", acked_index); + while (!sched[sched_index].local) { + sched_index++; } - return; - } + return; + } /* No Packet Loss... Proceed Normally (if expectations are met!) */ - else if((tcphdr->th_seq==htonl(sched[sched_index].exp_rseq)) && - (tcphdr->th_ack==htonl(sched[sched_index].exp_rack))){ - printf("Received Remote Packet............... [%d]\n",sched_index+1); + else if ((tcphdr->th_seq == htonl(sched[sched_index].exp_rseq)) && + (tcphdr->th_ack == htonl(sched[sched_index].exp_rack))) { + printf("Received Remote Packet............... [%d]\n", sched_index + 1); /* Handles differing payload size and does not trigger on unnecessary ACK + window update issues*/ - if((sched[sched_index].size_payload!=size_payload) && (size_payload!=0)){ + if ((sched[sched_index].size_payload != size_payload) && (size_payload != 0)) { printf("Payload size of received packet does not meet expectations\n"); /* Resent last local packet, maybe remote host behaves this time*/ - different_payload=true; + different_payload = true; /* Set global variable of where differing payload size is not meeting expectations*/ diff_payload_index = sched_index; /*Treat this as packet loss, and attempt resetting index to resend packets where*/ /* packets were received matching expectation*/ - sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ - //printf("ACKED Index = %d\n", acked_index); - while(!sched[sched_index].local){ + sched_index = acked_index; /* Reset the schedule index back to the last correctly ACKed packet */ + // printf("ACKED Index = %d\n", acked_index); + while (!sched[sched_index].local) { sched_index++; } return; @@ -818,74 +787,40 @@ got_packet(_U_ u_char *args, _U_ const struct pcap_pkthdr *header, printf("Remote Packet Expectation met.\nProceeding in replay....\n"); sched_index++; acked_index = sched_index; /*Keep track correctly ACKed packet index*/ - } + } /* Global variable to keep tack of last received packet info */ - packet_keeper_rprev = packet; - etherhdr_rprev = etherhdr; tcphdr_rprev = tcphdr; - iphdr_rprev = iphdr; size_payload_prev = size_payload; - - - return; } - - /** - * This function prints out the ip address, given an in_addr struct pointer - * - */ -void -printip(input_addr* IP) -{ - - printf("[%d.%d.%d.%d]\n", IP->byte1, IP->byte2, IP->byte3, IP->byte4); - - return; -} - -/** - * This function prints out the mac address, given a mac_addr struct pointer - * - */ -void -printmac(struct mac_addr* MAC) -{ - - printf("[%x:%x:%x:%x:%x:%x]\n", MAC->byte1, MAC->byte2, MAC->byte3, MAC->byte4, MAC->byte5, MAC->byte6); - - return; -} - - -/** - * This function compares two IPs, + * This function compares two IPs, * returns 1 if match with local ip * returns 2 if matches with remote ip * returns 0 if no match * */ -int -compip(input_addr* lip, input_addr* rip, input_addr* pkgip) +int +compip(input_addr *lip, input_addr *rip, input_addr *pkgip) { - - if((lip->byte1==pkgip->byte1)&&(lip->byte2==pkgip->byte2)&&(lip->byte3==pkgip->byte3)&&(lip->byte4==pkgip->byte4)) + if ((lip->byte1 == pkgip->byte1) && (lip->byte2 == pkgip->byte2) && (lip->byte3 == pkgip->byte3) && + (lip->byte4 == pkgip->byte4)) return LOCAL_IP_MATCH; - else if((rip->byte1==pkgip->byte1)&&(rip->byte2==pkgip->byte2)&&(rip->byte3==pkgip->byte3)&&(rip->byte4==pkgip->byte4)) + else if ((rip->byte1 == pkgip->byte1) && (rip->byte2 == pkgip->byte2) && (rip->byte3 == pkgip->byte3) && + (rip->byte4 == pkgip->byte4)) return REMOTE_IP_MATCH; else return NO_MATCH; } - /** * This function sets the IP and MAC of a given interface (i.e. eth0) * into in_addr & mac_addr struct pointers * */ -int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac) +int +iface_addrs(char *iface, input_addr *ip, struct mac_addr *mac) { int s; struct ifreq buffer; @@ -894,23 +829,23 @@ int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac) return -1; memset(&buffer, 0x00, sizeof(buffer)); - strncpy(buffer.ifr_name, iface, sizeof(buffer.ifr_name)-1); + strncpy(buffer.ifr_name, iface, sizeof(buffer.ifr_name) - 1); int res; if ((res = ioctl(s, SIOCGIFADDR, &buffer)) < 0) goto done; struct in_addr localip = ((struct sockaddr_in *)&buffer.ifr_addr)->sin_addr; -#if defined( WORDS_BIGENDIAN ) - ip->byte1 = (localip.s_addr)>>24; - ip->byte2 = ((localip.s_addr)>>16)&255; - ip->byte3 = ((localip.s_addr)>>8)&255; - ip->byte4 = (localip.s_addr)&255; +#if defined(WORDS_BIGENDIAN) + ip->byte1 = (localip.s_addr) >> 24; + ip->byte2 = ((localip.s_addr) >> 16) & 255; + ip->byte3 = ((localip.s_addr) >> 8) & 255; + ip->byte4 = (localip.s_addr) & 255; #else - ip->byte4 = (localip.s_addr)>>24; - ip->byte3 = ((localip.s_addr)>>16)&255; - ip->byte2 = ((localip.s_addr)>>8)&255; - ip->byte1 = (localip.s_addr)&255; + ip->byte4 = (localip.s_addr) >> 24; + ip->byte3 = ((localip.s_addr) >> 16) & 255; + ip->byte2 = ((localip.s_addr) >> 8) & 255; + ip->byte1 = (localip.s_addr) & 255; #endif if ((res = ioctl(s, SIOCGIFHWADDR, &buffer)) < 0) @@ -929,76 +864,77 @@ int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac) return res; } - /** - * This function rewrites the IPs and MACs of a given packet, - * creates a newfile.pcap. It returns the number of packets of the newfile. + * This function rewrites the IPs and MACs of a given packet, + * creates a newfile.pcap. It returns the number of packets of the newfile. * This function only starts rewriting the newfile once it sees the first - * SYN packet. This is so that the first packet in the newfile is always - * the first packet to be sent. + * SYN packet. This is so that the first packet in the newfile is always + * the first packet to be sent. */ int -rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* myip, struct mac_addr* mymac, char* file, unsigned int new_src_port) +rewrite(input_addr *new_remoteip, + struct mac_addr *new_remotemac, + input_addr *myip, + struct mac_addr *mymac, + char *file, + unsigned int new_src_port) { - char *newfile = "newfile.pcap"; - int pkt_counter; - input_addr local_ip; - input_addr remote_ip; + input_addr local_ip; + input_addr remote_ip; const u_char *packet; struct pcap_pkthdr *header; pcap_dumper_t *dumpfile; - input_addr sip; /* Source IP */ + input_addr sip; /* Source IP */ int local_packets = 0; - bool initstep1 = false; /* keep track of successful handshake step */ + bool initstep1 = false; /* keep track of successful handshake step */ bool warned = false; - local_ip.byte1=0; - local_ip.byte2=0; - local_ip.byte3=0; - local_ip.byte4=0; - - remote_ip.byte1=0; - remote_ip.byte2=0; - remote_ip.byte3=0; - remote_ip.byte4=0; - - pcap_t *pcap = set_offline_filter(file); - if (!pcap){ - char ErrBuff [1024]; - fprintf (stderr, "Cannot open PCAP file '%s' for reading\n", file); - fprintf(stderr, "%s\n",ErrBuff); + local_ip.byte1 = 0; + local_ip.byte2 = 0; + local_ip.byte3 = 0; + local_ip.byte4 = 0; + + remote_ip.byte1 = 0; + remote_ip.byte2 = 0; + remote_ip.byte3 = 0; + remote_ip.byte4 = 0; + + pcap_t *pcap = set_offline_filter(file); + if (!pcap) { + char ErrBuff[1024]; + fprintf(stderr, "Cannot open PCAP file '%s' for reading\n", file); + fprintf(stderr, "%s\n", ErrBuff); return PCAP_OPEN_ERROR; } dumpfile = pcap_dump_open(pcap, newfile); if (!dumpfile) { - fprintf (stderr, "Cannot open PCAP file '%s' for writing\n", newfile); + fprintf(stderr, "Cannot open PCAP file '%s' for writing\n", newfile); return PCAP_OPEN_ERROR; } /*Modify each packet's IP & MAC based on the passed args then do a checksum of each packet*/ - for (pkt_counter = 0; safe_pcap_next_ex(pcap, &header, &packet) > 0; pkt_counter++){ + while (safe_pcap_next_ex(pcap, &header, &packet) > 0) { unsigned int flags, size_ip; - ether_hdr* etherhdr; + ether_hdr *etherhdr; ipv4_hdr *iphdr; tcp_hdr *tcphdr; unsigned int size_tcp; if (!warned && header->len > header->caplen) { - fprintf(stderr, "warning: packet capture truncated to %d byte packets\n", - header->caplen); + fprintf(stderr, "warning: packet capture truncated to %d byte packets\n", header->caplen); warned = true; } - etherhdr = (ether_hdr*)(packet); + etherhdr = (ether_hdr *)(packet); iphdr = (ipv4_hdr *)(packet + SIZE_ETHERNET); - size_ip = iphdr->ip_hl << 2; + size_ip = iphdr->ip_hl << 2; if (size_ip < 20) { printf("ERROR: Invalid IP header length: %u bytes\n", size_ip); return ERROR; } tcphdr = (tcp_hdr *)(packet + SIZE_ETHERNET + size_ip); - size_tcp = tcphdr->th_off*4; + size_tcp = tcphdr->th_off * 4; if (size_tcp < 20) { printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp); return ERROR; @@ -1009,13 +945,13 @@ rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* my flags = tcphdr->th_flags; /* set IPs who's local and who's remote based on the SYN flag */ - if(flags == TH_SYN){ - local_ip = iphdr->ip_src; - remote_ip = iphdr->ip_dst; + if (flags == TH_SYN) { + local_ip = iphdr->ip_src; + remote_ip = iphdr->ip_dst; initstep1 = true; /* This flag is set to signify the first encounter of the SYN within the pacp*/ } - if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH){ + if (compip(&local_ip, &remote_ip, &sip) == LOCAL_IP_MATCH) { /* Set the source MAC */ etherhdr->ether_shost[0] = mymac->byte1; etherhdr->ether_shost[1] = mymac->byte2; @@ -1039,9 +975,7 @@ rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* my /* This is to change the source port, whether it is specified as random or as a port # by the user */ tcphdr->th_sport = htons(new_src_port); - } - else if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH){ - + } else if (compip(&local_ip, &remote_ip, &sip) == REMOTE_IP_MATCH) { /* Set the destination MAC */ etherhdr->ether_dhost[0] = mymac->byte1; etherhdr->ether_dhost[1] = mymac->byte2; @@ -1068,29 +1002,35 @@ rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* my /*Calculate & fix checksum for newly edited-packet*/ fix_all_checksum_liveplay(iphdr); - if(initstep1){ /*only start rewriting new pcap with SYN packets on wards*/ - local_packets ++; + if (initstep1) { /*only start rewriting new pcap with SYN packets on wards*/ + local_packets++; pcap_dump((u_char *)dumpfile, header, packet); } } /* end of while loop */ - pcap_close (pcap); + pcap_close(pcap); pcap_dump_close(dumpfile); return local_packets; } /** - * This function extracts the MAC address (from command line format + * This function extracts the MAC address (from command line format * and sets the mac_addr struct) * */ int -extmac(char* new_rmac_ptr, struct mac_addr* new_remotemac) +extmac(char *new_rmac_ptr, struct mac_addr *new_remotemac) { u_int8_t new_rmac[6]; - if (sscanf (new_rmac_ptr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &new_rmac[0], &new_rmac[1], - &new_rmac[2], &new_rmac[3], &new_rmac[4], &new_rmac[5]) != 6) + if (sscanf(new_rmac_ptr, + "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", + &new_rmac[0], + &new_rmac[1], + &new_rmac[2], + &new_rmac[3], + &new_rmac[4], + &new_rmac[5]) != 6) return ERROR; new_remotemac->byte1 = (unsigned char)new_rmac[0]; @@ -1104,19 +1044,19 @@ extmac(char* new_rmac_ptr, struct mac_addr* new_remotemac) } /** - * This function extracts the IP address (from command line format + * This function extracts the IP address (from command line format * and sets the in_addr struct) * */ int -extip(char *ip_string, input_addr* new_remoteip) +extip(char *ip_string, input_addr *new_remoteip) { struct in_addr addr; if (inet_aton(ip_string, &addr) == 0) return ERROR; -#if defined( WORDS_BIGENDIAN ) +#if defined(WORDS_BIGENDIAN) new_remoteip->byte4 = (unsigned char)addr.s_addr & 0xff; new_remoteip->byte3 = (unsigned char)(addr.s_addr >> 8) & 0xff; new_remoteip->byte2 = (unsigned char)(addr.s_addr >> 16) & 0xff; @@ -1131,31 +1071,25 @@ extip(char *ip_string, input_addr* new_remoteip) return SUCCESS; } - /** * This function calls all the checksum function given the IP Header - * and edits the checksums fixing them appropriately + * and edits the checksums fixing them appropriately * */ int -fix_all_checksum_liveplay(ipv4_hdr *iphdr){ - - int ret1 = 0, ret2 = 0; +fix_all_checksum_liveplay(ipv4_hdr *iphdr) +{ + int ret; /*Calculate TCP Checksum*/ - ret2 = do_checksum_liveplay((u_char *) iphdr,iphdr->ip_p, ntohs(iphdr->ip_len) - (iphdr->ip_hl << 2)); - if(ret2==-1){ + ret = do_checksum_liveplay((u_char *)iphdr, iphdr->ip_p, ntohs(iphdr->ip_len) - (iphdr->ip_hl << 2)); + if (ret != TCPEDIT_OK) { printf("*******An Error Occurred calculating TCP Checksum*******\n"); return -1; } /*Calculate IP Checksum*/ - ret1 = do_checksum_liveplay((u_char *) iphdr, IPPROTO_IP, ntohs(iphdr->ip_len)); - if(ret1==-1){ - printf("*******An Error Occurred calculating IP Checksum*******\n"); - return -1; - } - + do_checksum_liveplay((u_char *)iphdr, IPPROTO_IP, ntohs(iphdr->ip_len)); return 0; } @@ -1165,9 +1099,9 @@ fix_all_checksum_liveplay(ipv4_hdr *iphdr){ /*[copied from Aaron Turnor's checksum.c, but omitting tcpedit_t structs] */ /*[The following functions have been slightly modified to be integrated with tcpliveplay code structure] */ -/** +/** * This code re-calcs the IP and Layer 4 checksums - * the IMPORTANT THING is that the Layer 4 header + * the IMPORTANT THING is that the Layer 4 header * is contiguous in memory after *ip_hdr we're actually * writing to the layer 4 header via the ip_hdr ptr. * (Yes, this sucks, but that's the way libnet works, and @@ -1175,16 +1109,16 @@ fix_all_checksum_liveplay(ipv4_hdr *iphdr){ * Returns 0 on success, -1 on error */ - /** * Returns -1 on error and 0 on success, 1 on warn */ int -do_checksum_liveplay(u_int8_t *data, int proto, int len) { +do_checksum_liveplay(u_int8_t *data, int proto, int len) +{ ipv4_hdr *ipv4; tcp_hdr *tcp; int ip_hl; - volatile int sum = 0; // <-- volatile works around a PPC g++ bug + volatile int sum; // <-- volatile works around a PPC g++ bug ipv4 = NULL; @@ -1217,7 +1151,6 @@ do_checksum_liveplay(u_int8_t *data, int proto, int len) { ipv4->ip_sum = CHECKSUM_CARRY(sum); break; - default: printf("Unsupported protocol for checksum:\n"); return TCPEDIT_WARN; @@ -1251,5 +1184,3 @@ do_checksum_math_liveplay(u_int16_t *data, int len) return (sum); } - - diff --git a/src/tcpliveplay.h b/src/tcpliveplay.h index 4f4d814f6..81fac91c0 100644 --- a/src/tcpliveplay.h +++ b/src/tcpliveplay.h @@ -1,123 +1,108 @@ /* - * Main Author & Publisher: Yazan Siam (tcpliveplay@gmail.com) + * Main Author & Publisher: Yazan Siam (tcpliveplay@gmail.com) * File: tcpliveplay.h * Started as a Senior Design project @ North Carolina State University * Last Updated Date: September 5, 2012 * Past Contributors (Last contributed May 4, 2012): Andrew Leonard & Beau Luck -*/ + */ +#pragma once -#ifndef __TCPLIVEPLAY_H__ -#define __TCPLIVEPLAY_H__ +#include "defines.h" +#include "config.h" - -/*defines for the packet type code in an ETHERNET header*/ -#define ETHER_TYPE_IP (0x0800) -#define ETHER_TYPE_8021Q (0x8100) - - -/* Ethernet addresses are 6 bytes */ -//#define ETHER_ADDR_LEN 6 -#define SIZE_ETHERNET 14 -#define LOCAL_IP_MATCH 1 -#define REMOTE_IP_MATCH 2 -#define NO_MATCH 0 -#define REWRITE_ERROR -1 -#define PCAP_OPEN_ERROR -1 -#define PACKET_BUFF 65535 -#define TIMEOUT_ms 10000 -#define PROMISC_OFF 0 -#define BUFSIZ_PLUS BUFSIZ -#define ALARM_TIMEOUT 10 -#define SUCCESS 1 -#define ERROR -1 -#define manpage_cmds (strcmp(argv[1], "-V")==0) || (strcmp(argv[1], "-v")==0) || (strcmp(argv[1], "-H")==0) || (strcmp(argv[1], "-h")==0) +#define SIZE_ETHERNET 14 +#define LOCAL_IP_MATCH 1 +#define REMOTE_IP_MATCH 2 +#define NO_MATCH 0 +#define PCAP_OPEN_ERROR (-1) +#define TIMEOUT_ms 10000 +#define PROMISC_OFF 0 +#define BUFSIZ_PLUS BUFSIZ +#define ALARM_TIMEOUT 10 +#define SUCCESS 1 +#define ERROR (-1) /***********From tcpedit.h*****/ -#define TCPEDIT_SOFT_ERROR -2 -#define TCPEDIT_ERROR -1 -#define TCPEDIT_OK 0 -#define TCPEDIT_WARN 1 +#define TCPEDIT_SOFT_ERROR (-2) +#define TCPEDIT_ERROR (-1) +#define TCPEDIT_OK 0 +#define TCPEDIT_WARN 1 /************From checksum.h******/ -#define CHECKSUM_CARRY(x) \ - (x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff)) +#define CHECKSUM_CARRY(x) (x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff)) #include - // 6 byte MAC Address -struct mac_addr { - unsigned char byte1; - unsigned char byte2; - unsigned char byte3; - unsigned char byte4; - unsigned char byte5; - unsigned char byte6; +struct mac_addr { + unsigned char byte1; + unsigned char byte2; + unsigned char byte3; + unsigned char byte4; + unsigned char byte5; + unsigned char byte6; }; - typedef struct ip_addr input_addr; -// 4 bytes IP address -struct ip_addr{ - unsigned char byte1; - unsigned char byte2; - unsigned char byte3; - unsigned char byte4; -}; - -typedef struct ether_hdr ether_hdr; +// 4 bytes IP address +struct ip_addr { + unsigned char byte1; + unsigned char byte2; + unsigned char byte3; + unsigned char byte4; +}; + +typedef struct ether_hdr ether_hdr; /* Ethernet header */ struct ether_hdr { u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */ u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */ - u_short ether_type; /* IP? ARP? RARP? etc */ + u_short ether_type; /* IP? ARP? RARP? etc */ }; - typedef struct ipv4_hdr ipv4_hdr; -struct ipv4_hdr{ -#if defined( WORDS_BIGENDIAN ) - u_int8_t ip_v:4; - u_int8_t ip_hl:4; +struct ipv4_hdr { +#if defined(WORDS_BIGENDIAN) + u_int8_t ip_v:4; + u_int8_t ip_hl:4; #else - u_int8_t ip_hl:4; - u_int8_t ip_v:4; + u_int8_t ip_hl:4; + u_int8_t ip_v:4; #endif - u_int8_t ip_tos; - u_int16_t ip_len; - u_int16_t ip_id; - u_int16_t ip_off; - u_int8_t ip_ttl; - u_int8_t ip_p; - u_int16_t ip_sum; - input_addr ip_src, ip_dst; + u_int8_t ip_tos; + u_int16_t ip_len; + u_int16_t ip_id; + u_int16_t ip_off; + u_int8_t ip_ttl; + u_int8_t ip_p; + u_int16_t ip_sum; + input_addr ip_src, ip_dst; }; typedef struct tcpheader tcp_hdr; /* for easy reference ************ */ -struct tcpheader{ - u_int16_t th_sport; // source port - u_int16_t th_dport; - u_int32_t th_seq; - u_int32_t th_ack; -#if defined( WORDS_BIGENDIAN ) - u_int8_t th_off:4; - u_int8_t th_x2:4; +struct tcpheader { + u_int16_t th_sport; // source port + u_int16_t th_dport; + u_int32_t th_seq; + u_int32_t th_ack; +#if defined(WORDS_BIGENDIAN) + u_int8_t th_off:4; + u_int8_t th_x2:4; #else - u_int8_t th_x2:4; - u_int8_t th_off:4; + u_int8_t th_x2:4; + u_int8_t th_off:4; #endif - u_int8_t th_flags; - u_int16_t th_win; - u_int16_t th_sum; - u_int16_t th_urp; -}; - + u_int8_t th_flags; + u_int16_t th_win; + u_int16_t th_sum; + u_int16_t th_urp; +}; #define TH_FIN 0x01 #define TH_SYN 0x02 @@ -127,34 +112,29 @@ struct tcpheader{ #define TH_URG 0x20 #define TH_ECE 0x40 #define TH_CWR 0x80 -#define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR) - - -struct tcp_sched{ - u_int32_t exp_rseq; /* Expected Remote SEQ */ - u_int32_t exp_rack; /* Expected Remote ACK */ - u_int32_t calc_curr_rseq; /* Calculated Current Remote SEQ (not used at the moment) */ - u_int32_t calc_curr_rack; /* Calculated Current Remote ACK (not used at the moment) */ - u_int32_t calc_curr_lseq; /* Calculated Current Local SEQ (not used at the moment) */ - u_int32_t calc_curr_lack; /* Calculated Current Local ACK (not used at the moment) */ - u_int32_t curr_lseq; /* Current Local SEQ */ - u_int32_t curr_lack; /* Current Local ACK */ + +struct tcp_sched { + u_int32_t exp_rseq; /* Expected Remote SEQ */ + u_int32_t exp_rack; /* Expected Remote ACK */ + u_int32_t calc_curr_rseq; /* Calculated Current Remote SEQ (not used at the moment) */ + u_int32_t calc_curr_rack; /* Calculated Current Remote ACK (not used at the moment) */ + u_int32_t calc_curr_lseq; /* Calculated Current Local SEQ (not used at the moment) */ + u_int32_t calc_curr_lack; /* Calculated Current Local ACK (not used at the moment) */ + u_int32_t curr_lseq; /* Current Local SEQ */ + u_int32_t curr_lack; /* Current Local ACK */ unsigned int length_curr_ldata; /* Data Length of Currently seen local data */ unsigned int length_last_ldata; /* Data Length of last locally seen data */ unsigned int length_curr_rdata; /* Length of currently seen remote data */ unsigned int length_last_rdata; /* Length of last remote seen data*/ - u_char *packet_ptr; /* The entire packet data to be sent */ - struct pcap_pkthdr pkthdr; /* Packet header */ - ether_hdr *etherhdr; /* Ethernet Header */ - tcp_hdr *tcphdr; /* TCP Header */ - ipv4_hdr *iphdr; /* IP Header */ - unsigned int size_ip; /* Keep track of each packet's IP Size */ - unsigned int size_tcp; /* Keep track of each packet's TCP Size */ - unsigned int size_payload; /* Keep tack of each packet's Payload size, if any */ - unsigned int sent_counter; /* Keep track of each packet's sent attempts*/ - bool remote; /* Flag to signify this is a remote packet */ - bool local; /* Flag to signify this is a local packet */ + u_char *packet_ptr; /* The entire packet data to be sent */ + struct pcap_pkthdr pkthdr; /* Packet header */ + ether_hdr *etherhdr; /* Ethernet Header */ + tcp_hdr *tcphdr; /* TCP Header */ + ipv4_hdr *iphdr; /* IP Header */ + unsigned int size_ip; /* Keep track of each packet's IP Size */ + unsigned int size_tcp; /* Keep track of each packet's TCP Size */ + unsigned int size_payload; /* Keep tack of each packet's Payload size, if any */ + unsigned int sent_counter; /* Keep track of each packet's sent attempts*/ + bool remote; /* Flag to signify this is a remote packet */ + bool local; /* Flag to signify this is a local packet */ }; - - -#endif /* _TCPLIVEPLAY_H_ */ diff --git a/src/tcpprep.c b/src/tcpprep.c index b8de72905..d17014c0b 100644 --- a/src/tcpprep.c +++ b/src/tcpprep.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -31,24 +31,18 @@ * - Auto learning of CIDR block for servers (clients all other) */ -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - +#include "tcpprep_api.h" +#include "tcpprep_opts.h" +#include "tree.h" +#include +#include #include #include #include -#include -#include #include -#include - -#include "tcpprep.h" -#include "tcpprep_api.h" -#include "tcpprep_opts.h" -#include "lib/tree.h" -#include "tree.h" -#include "lib/sll.h" /* * global variables @@ -59,19 +53,17 @@ int debug = 0; tcpprep_t *tcpprep; int info = 0; -char *ourregex = NULL; char *cidr = NULL; tcpr_data_tree_t treeroot; void print_comment(const char *); void print_info(const char *); void print_stats(const char *); -static int check_ipv4_regex(const unsigned long ip); +static int check_ipv4_regex(unsigned long ip); static int check_ipv6_regex(const struct tcpr_in6_addr *addr); -static COUNTER process_raw_packets(pcap_t * pcap); +static COUNTER process_raw_packets(pcap_t *pcap); static int check_dst_port(ipv4_hdr_t *ip_hdr, ipv6_hdr_t *ip6_hdr, int len); - /* * main() */ @@ -79,49 +71,56 @@ int main(int argc, char *argv[]) { int out_file; - COUNTER totpackets = 0; + COUNTER totpackets; char errbuf[PCAP_ERRBUF_SIZE]; tcpprep_opt_t *options; - + tcpprep = tcpprep_init(); options = tcpprep->options; - + optionProcess(&tcpprepOptions, argc, argv); tcpprep_post_args(tcpprep, argc, argv); /* open the cache file */ - if ((out_file = open(OPT_ARG(CACHEFILE), O_WRONLY | O_CREAT | O_TRUNC, - S_IREAD | S_IWRITE | S_IRGRP | S_IWGRP | S_IROTH)) == -1) - errx(-1, "Unable to open cache file %s for writing: %s", - OPT_ARG(CACHEFILE), strerror(errno)); + if ((out_file = open(OPT_ARG(CACHEFILE), + O_WRONLY | O_CREAT | O_TRUNC, + S_IREAD | S_IWRITE | S_IRGRP | S_IWGRP | S_IROTH)) == -1) { + tcpprep_close(tcpprep); + errx(-1, "Unable to open cache file %s for writing: %s", OPT_ARG(CACHEFILE), strerror(errno)); + } - readpcap: +readpcap: /* open the pcap file */ - if ((options->pcap = pcap_open_offline(OPT_ARG(PCAP), errbuf)) == NULL) - errx(-1, "Error opening file: %s", errbuf); + if ((options->pcap = pcap_open_offline(OPT_ARG(PCAP), errbuf)) == NULL) { + close(out_file); + tcpprep_close(tcpprep); + errx(-1, "Error opening libpcap: %s", errbuf); + } #ifdef HAVE_PCAP_SNAPSHOT if (pcap_snapshot(options->pcap) < 65535) warnx("%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", - OPT_ARG(PCAP), pcap_snapshot(options->pcap)); + OPT_ARG(PCAP), + pcap_snapshot(options->pcap)); #endif /* make sure we support the DLT type */ - switch(pcap_datalink(options->pcap)) { - case DLT_EN10MB: - case DLT_LINUX_SLL: - case DLT_RAW: - case DLT_C_HDLC: - case DLT_JUNIPER_ETHER: - case DLT_PPP_SERIAL: - break; /* do nothing because all is good */ - default: - errx(-1, "Unsupported pcap DLT type: 0x%x", pcap_datalink(options->pcap)); + switch (pcap_datalink(options->pcap)) { + case DLT_EN10MB: + case DLT_LINUX_SLL: + case DLT_RAW: + case DLT_C_HDLC: + case DLT_JUNIPER_ETHER: + case DLT_PPP_SERIAL: + break; /* do nothing because all is good */ + default: + errx(-1, "Unsupported pcap DLT type: 0x%x", pcap_datalink(options->pcap)); } /* Can only split based on MAC address for ethernet */ - if ((pcap_datalink(options->pcap) != DLT_EN10MB) && - (options->mode == MAC_MODE)) { + if ((pcap_datalink(options->pcap) != DLT_EN10MB) && (options->mode == MAC_MODE)) { + close(out_file); + tcpprep_close(tcpprep); err(-1, "MAC mode splitting is only supported by DLT_EN10MB packet captures."); } @@ -133,8 +132,10 @@ main(int argc, char *argv[]) /* do we apply a bpf filter? */ if (options->bpf.filter != NULL) { - if (pcap_compile(options->pcap, &options->bpf.program, options->bpf.filter, - options->bpf.optimize, 0) != 0) { + if (pcap_compile(options->pcap, &options->bpf.program, options->bpf.filter, options->bpf.optimize, 0) != 0) { + close(out_file); + tcpprep_close(tcpprep); + return 0; errx(-1, "Error compiling BPF filter: %s", pcap_geterr(options->pcap)); } pcap_setfilter(options->pcap, &options->bpf.program); @@ -142,10 +143,13 @@ main(int argc, char *argv[]) } if ((totpackets = process_raw_packets(options->pcap)) == 0) { - pcap_close(options->pcap); + close(out_file); + tcpprep_close(tcpprep); err(-1, "No packets were processed. Filter too limiting?"); } + pcap_close(options->pcap); + options->pcap = NULL; #ifdef ENABLE_VERBOSE tcpdump_close(&tcpprep->tcpdump); @@ -154,14 +158,13 @@ main(int argc, char *argv[]) /* we need to process the pcap file twice in HASH/AUTO mode */ if (options->mode == AUTO_MODE) { options->mode = options->automode; - if (options->mode == ROUTER_MODE) { /* do we need to convert TREE->CIDR? */ + if (options->mode == ROUTER_MODE) { /* do we need to convert TREE->CIDR? */ if (info) notice("Building network list from pre-cache...\n"); if (!process_tree()) { err(-1, "Error: unable to build a valid list of servers. Aborting."); } - } - else { + } else { /* * in bridge mode we need to calculate client/sever * manually since this is done automatically in @@ -172,9 +175,9 @@ main(int argc, char *argv[]) if (info) notice("Building cache file...\n"); - /* + /* * re-process files, but this time generate - * cache + * cache */ goto readpcap; } @@ -184,24 +187,24 @@ main(int argc, char *argv[]) #endif /* write cache data */ - totpackets = write_cache(options->cachedata, out_file, totpackets, - options->comment); + totpackets = write_cache(options->cachedata, out_file, totpackets, options->comment); if (info) notice("Done.\nCached " COUNTER_SPEC " packets.\n", totpackets); /* close cache file */ close(out_file); + tcpprep_close(tcpprep); + restore_stdin(); return 0; } - /** * checks the dst port to see if this is destined for a server port. * returns 1 for true, 0 for false */ -static int +static int check_dst_port(ipv4_hdr_t *ip_hdr, ipv6_hdr_t *ip6_hdr, int len) { tcp_hdr_t *tcp_hdr = NULL; @@ -215,60 +218,62 @@ check_dst_port(ipv4_hdr_t *ip_hdr, ipv6_hdr_t *ip6_hdr, int len) return 0; /* not enough data in the packet to know */ proto = ip_hdr->ip_p; - l4 = get_layer4_v4(ip_hdr, len); + l4 = get_layer4_v4(ip_hdr, (u_char *)ip_hdr + len); } else if (ip6_hdr) { if (len < (TCPR_IPV6_H + 4)) return 0; /* not enough data in the packet to know */ - proto = get_ipv6_l4proto(ip6_hdr, len); + proto = get_ipv6_l4proto(ip6_hdr, (u_char *)ip6_hdr + len); dbgx(3, "Our layer4 proto is 0x%hhu", proto); - if ((l4 = get_layer4_v6(ip6_hdr, len)) == NULL) + if ((l4 = get_layer4_v6(ip6_hdr, (u_char *)ip6_hdr + len)) == NULL) return 0; - dbgx(3, "Found proto %u at offset %p. base %p (%p)", proto, (void *)l4, (void *)ip6_hdr, (void*)(l4 - (u_char *)ip6_hdr)); + dbgx(3, + "Found proto %u at offset %p. base %p (%p)", + proto, + (void *)l4, + (void *)ip6_hdr, + (void *)(l4 - (u_char *)ip6_hdr)); } else { assert(0); } dbg(3, "Checking the destination port..."); - switch(proto) { - case IPPROTO_TCP: - tcp_hdr = (tcp_hdr_t *)l4; + switch (proto) { + case IPPROTO_TCP: + tcp_hdr = (tcp_hdr_t *)l4; - /* is a service? */ - if (options->services.tcp[ntohs(tcp_hdr->th_dport)]) { - dbgx(1, "TCP packet is destined for a server port: %d", ntohs(tcp_hdr->th_dport)); - return 1; - } + /* is a service? */ + if (options->services.tcp[ntohs(tcp_hdr->th_dport)]) { + dbgx(1, "TCP packet is destined for a server port: %d", ntohs(tcp_hdr->th_dport)); + return 1; + } - /* nope */ - dbgx(1, "TCP packet is NOT destined for a server port: %d", ntohs(tcp_hdr->th_dport)); - return 0; - break; + /* nope */ + dbgx(1, "TCP packet is NOT destined for a server port: %d", ntohs(tcp_hdr->th_dport)); + return 0; - case IPPROTO_UDP: - udp_hdr = (udp_hdr_t *)l4; + case IPPROTO_UDP: + udp_hdr = (udp_hdr_t *)l4; - /* is a service? */ - if (options->services.udp[ntohs(udp_hdr->uh_dport)]) { - dbgx(1, "UDP packet is destined for a server port: %d", ntohs(udp_hdr->uh_dport)); - return 1; - } + /* is a service? */ + if (options->services.udp[ntohs(udp_hdr->uh_dport)]) { + dbgx(1, "UDP packet is destined for a server port: %d", ntohs(udp_hdr->uh_dport)); + return 1; + } - /* nope */ - dbgx(1, "UDP packet is NOT destined for a server port: %d", ntohs(udp_hdr->uh_dport)); - return 0; - break; + /* nope */ + dbgx(1, "UDP packet is NOT destined for a server port: %d", ntohs(udp_hdr->uh_dport)); + return 0; - default: - /* not a TCP or UDP packet... return as non_ip */ - dbg(1, "Packet isn't a UDP or TCP packet... no port to process."); - return options->nonip; + default: + /* not a TCP or UDP packet... return as non_ip */ + dbg(1, "Packet isn't a UDP or TCP packet... no port to process."); + return options->nonip; } } - /** * checks to see if an ip address matches a regex. Returns 1 for true * 0 for false @@ -282,8 +287,7 @@ check_ipv4_regex(const unsigned long ip) tcpprep_opt_t *options = tcpprep->options; memset(src_ip, '\0', sizeof(src_ip)); - strlcpy((char *)src_ip, (char *)get_addr2name4(ip, RESOLVE), - sizeof(src_ip)); + strlcpy((char *)src_ip, (char *)get_addr2name4(ip, RESOLVE), sizeof(src_ip)); if (regexec(&options->preg, (char *)src_ip, nmatch, NULL, eflags) == 0) { return 1; } else { @@ -300,8 +304,7 @@ check_ipv6_regex(const struct tcpr_in6_addr *addr) tcpprep_opt_t *options = tcpprep->options; memset(src_ip, '\0', sizeof(src_ip)); - strlcpy((char *)src_ip, (char *)get_addr2name6(addr, RESOLVE), - sizeof(src_ip)); + strlcpy((char *)src_ip, (char *)get_addr2name6(addr, RESOLVE), sizeof(src_ip)); if (regexec(&options->preg, (char *)src_ip, nmatch, NULL, eflags) == 0) { return 1; } else { @@ -314,7 +317,7 @@ check_ipv6_regex(const struct tcpr_in6_addr *addr) * the cache file. */ static COUNTER -process_raw_packets(pcap_t * pcap) +process_raw_packets(pcap_t *pcap) { struct pcap_pkthdr pkthdr; const u_char *pktdata = NULL; @@ -325,7 +328,7 @@ process_raw_packets(pcap_t * pcap) tcpprep_opt_t *options = tcpprep->options; assert(pcap); - + ipbuff = safe_malloc(MAXPACKET); while ((pktdata = safe_pcap_next(pcap, &pkthdr)) != NULL) { @@ -360,18 +363,17 @@ process_raw_packets(pcap_t * pcap) */ if (options->mode != MAC_MODE) { dbg(3, "Looking for IPv4/v6 header in non-MAC mode"); - + /* get the IP header (if any) */ buffptr = ipbuff; - + /* first look for IPv4 */ - if ((ip_hdr = (ipv4_hdr_t *)get_ipv4(pktdata, pkthdr.caplen, - pcap_datalink(pcap), &buffptr)) != NULL) { + if ((ip_hdr = (ipv4_hdr_t *)get_ipv4(pktdata, (int)pkthdr.caplen, pcap_datalink(pcap), &buffptr)) != NULL) { dbg(2, "Packet is IPv4"); - } else if ((ip6_hdr = (ipv6_hdr_t *)get_ipv6(pktdata, pkthdr.caplen, - pcap_datalink(pcap), &buffptr)) != NULL) { + } else if ((ip6_hdr = (ipv6_hdr_t *)get_ipv6(pktdata, (int)pkthdr.caplen, pcap_datalink(pcap), &buffptr)) != + NULL) { /* IPv6 */ - dbg(2, "Packet is IPv6"); + dbg(2, "Packet is IPv6"); } else { /* we're something else... */ dbg(2, "Packet isn't IPv4/v6"); @@ -385,8 +387,8 @@ process_raw_packets(pcap_t * pcap) /* go to next packet */ continue; } - - l2len = get_l2len(pktdata, pkthdr.caplen, pcap_datalink(pcap)); + + l2len = get_l2len(pktdata, (int)pkthdr.caplen, pcap_datalink(pcap)); if (l2len < 0) { /* go to next packet */ continue; @@ -461,41 +463,29 @@ process_raw_packets(pcap_t * pcap) /* first run through in auto mode: create tree */ if (options->automode != FIRST_MODE) { if (ip_hdr) { - add_tree_ipv4(ip_hdr->ip_src.s_addr, - pktdata, - pkthdr.caplen, - pcap_datalink(pcap)); + add_tree_ipv4(ip_hdr->ip_src.s_addr, pktdata, (int)pkthdr.caplen, pcap_datalink(pcap)); } else if (ip6_hdr) { - add_tree_ipv6(&ip6_hdr->ip_src, - pktdata, - pkthdr.caplen, - pcap_datalink(pcap)); + add_tree_ipv6(&ip6_hdr->ip_src, pktdata, (int)pkthdr.caplen, pcap_datalink(pcap)); } } else { if (ip_hdr) { - add_tree_first_ipv4(pktdata, - pkthdr.caplen, - pcap_datalink(pcap)); + add_tree_first_ipv4(pktdata, (int)pkthdr.caplen, pcap_datalink(pcap)); } else if (ip6_hdr) { - add_tree_first_ipv6(pktdata, - pkthdr.caplen, - pcap_datalink(pcap)); + add_tree_first_ipv6(pktdata, (int)pkthdr.caplen, pcap_datalink(pcap)); } - } + } break; case ROUTER_MODE: - /* + /* * second run through in auto mode: create route * based cache */ dbg(2, "processing second pass of auto: router mode..."); if (ip_hdr) { - add_cache(&options->cachedata, SEND, - check_ip_tree(options->nonip, ip_hdr->ip_src.s_addr)); + add_cache(&options->cachedata, SEND, check_ip_tree(options->nonip, ip_hdr->ip_src.s_addr)); } else { - add_cache(&options->cachedata, SEND, - check_ip6_tree(options->nonip, &ip6_hdr->ip_src)); + add_cache(&options->cachedata, SEND, check_ip6_tree(options->nonip, &ip6_hdr->ip_src)); } break; @@ -506,41 +496,35 @@ process_raw_packets(pcap_t * pcap) */ dbg(2, "processing second pass of auto: bridge mode..."); if (ip_hdr) { - add_cache(&options->cachedata, SEND, - check_ip_tree(DIR_UNKNOWN, ip_hdr->ip_src.s_addr)); + add_cache(&options->cachedata, SEND, check_ip_tree(DIR_UNKNOWN, ip_hdr->ip_src.s_addr)); } else { - add_cache(&options->cachedata, SEND, - check_ip6_tree(DIR_UNKNOWN, &ip6_hdr->ip_src)); + add_cache(&options->cachedata, SEND, check_ip6_tree(DIR_UNKNOWN, &ip6_hdr->ip_src)); } break; case SERVER_MODE: - /* + /* * second run through in auto mode: create bridge * where unknowns are servers */ dbg(2, "processing second pass of auto: server mode..."); if (ip_hdr) { - add_cache(&options->cachedata, SEND, - check_ip_tree(DIR_SERVER, ip_hdr->ip_src.s_addr)); + add_cache(&options->cachedata, SEND, check_ip_tree(DIR_SERVER, ip_hdr->ip_src.s_addr)); } else { - add_cache(&options->cachedata, SEND, - check_ip6_tree(DIR_SERVER, &ip6_hdr->ip_src)); + add_cache(&options->cachedata, SEND, check_ip6_tree(DIR_SERVER, &ip6_hdr->ip_src)); } break; case CLIENT_MODE: - /* + /* * second run through in auto mode: create bridge * where unknowns are clients */ dbg(2, "processing second pass of auto: client mode..."); if (ip_hdr) { - add_cache(&options->cachedata, SEND, - check_ip_tree(DIR_CLIENT, ip_hdr->ip_src.s_addr)); + add_cache(&options->cachedata, SEND, check_ip_tree(DIR_CLIENT, ip_hdr->ip_src.s_addr)); } else { - add_cache(&options->cachedata, SEND, - check_ip6_tree(DIR_CLIENT, &ip6_hdr->ip_src)); + add_cache(&options->cachedata, SEND, check_ip6_tree(DIR_CLIENT, &ip6_hdr->ip_src)); } break; @@ -549,8 +533,7 @@ process_raw_packets(pcap_t * pcap) * process ports based on their destination port */ dbg(2, "processing port mode..."); - add_cache(&options->cachedata, SEND, - check_dst_port(ip_hdr, ip6_hdr, (pkthdr.caplen - l2len))); + add_cache(&options->cachedata, SEND, check_dst_port(ip_hdr, ip6_hdr, (int)pkthdr.caplen - l2len)); break; case FIRST_MODE: @@ -560,14 +543,12 @@ process_raw_packets(pcap_t * pcap) */ dbg(2, "processing second pass of auto: first packet mode..."); if (ip_hdr) { - add_cache(&options->cachedata, SEND, - check_ip_tree(DIR_UNKNOWN, ip_hdr->ip_src.s_addr)); + add_cache(&options->cachedata, SEND, check_ip_tree(DIR_UNKNOWN, ip_hdr->ip_src.s_addr)); } else { - add_cache(&options->cachedata, SEND, - check_ip6_tree(DIR_UNKNOWN, &ip6_hdr->ip_src)); + add_cache(&options->cachedata, SEND, check_ip6_tree(DIR_UNKNOWN, &ip6_hdr->ip_src)); } break; - + default: errx(-1, "Whoops! What mode are we in anyways? %d", options->mode); } @@ -582,7 +563,6 @@ process_raw_packets(pcap_t * pcap) return packetnum; } - /** * print the tcpprep cache file comment */ @@ -591,7 +571,7 @@ print_comment(const char *file) { char *cachedata = NULL; char *comment = NULL; - COUNTER count = 0; + COUNTER count; count = read_cache(&cachedata, file, &comment); printf("tcpprep args: %s\n", comment); @@ -608,14 +588,13 @@ print_info(const char *file) { char *cachedata = NULL; char *comment = NULL; - COUNTER count = 0, i; + COUNTER count, i; count = read_cache(&cachedata, file, &comment); if (count > 65535) exit(-1); - for (i = 1; i <= count; i ++) { - + for (i = 1; i <= count; i++) { switch (check_cache(cachedata, i)) { case TCPR_DIR_C2S: printf("Packet " COUNTER_SPEC " -> Primary\n", i); @@ -628,9 +607,7 @@ print_info(const char *file) break; default: err(-1, "Invalid cachedata value!"); - break; } - } exit(0); } @@ -643,24 +620,24 @@ print_stats(const char *file) { char *cachedata = NULL; char *comment = NULL; - COUNTER i, count = 0; + COUNTER i, count; COUNTER pri = 0, sec = 0, nosend = 0; - + count = read_cache(&cachedata, file, &comment); - for (i = 1; i <= count; i ++) { + for (i = 1; i <= count; i++) { int cacheval = check_cache(cachedata, i); switch (cacheval) { - case TCPR_DIR_C2S: - pri ++; - break; - case TCPR_DIR_S2C: - sec ++; - break; - case TCPR_DIR_NOSEND: - nosend ++; - break; - default: - errx(-1, "Unknown cache value: %d", cacheval); + case TCPR_DIR_C2S: + pri++; + break; + case TCPR_DIR_S2C: + sec++; + break; + case TCPR_DIR_NOSEND: + nosend++; + break; + default: + errx(-1, "Unknown cache value: %d", cacheval); } } printf("Primary packets:\t" COUNTER_SPEC "\n", pri); diff --git a/src/tcpprep.h b/src/tcpprep.h index 2c1d91cf0..0a8c4f357 100644 --- a/src/tcpprep.h +++ b/src/tcpprep.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,18 +18,13 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TCPPREP_H__ -#define __TCPPREP_H__ +#pragma once -#include "config.h" #include "defines.h" +#include "config.h" #include "common.h" - #include - #ifdef ENABLE_DMALLOC #include #endif - -#endif diff --git a/src/tcpprep_api.c b/src/tcpprep_api.c index f489795ef..2a9709ebd 100644 --- a/src/tcpprep_api.c +++ b/src/tcpprep_api.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,29 +18,18 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "tcpprep_api.h" #include "config.h" -#include "defines.h" #include "common.h" - -#include -#include +#include "tcpprep_opts.h" #include #include #include -#include -#include -#include -#include - -#include "tcpprep_api.h" - -#include "tcpprep_opts.h" extern void print_comment(const char *); extern void print_info(const char *); extern void print_stats(const char *); - /** * \brief Initialize a new tcpprep context * @@ -109,253 +98,6 @@ tcpprep_close(tcpprep_t *ctx) safe_free(ctx); } -/** - * Specify the pcap file to process - */ -int -tcpprep_set_pcap_file(tcpprep_t *ctx, char *value) -{ - assert(ctx); - assert(value); - ctx->pcapfile = safe_strdup(value); - return 0; -} - -/** - * Specify the tcpprep cache file to generate - */ -int -tcpprep_set_output_file(tcpprep_t *ctx, char *value) -{ - assert(ctx); - assert(value); - ctx->outfile = safe_strdup(value); - return 0; -} - -/** - * Specify a cache file comment - */ -int -tcpprep_set_comment(tcpprep_t *ctx, char *value) -{ - assert(ctx); - assert(value); - ctx->options->comment = safe_strdup(value); - return 0; -} - -/** - * \brief Disable comments in the tcpprep cachefile - * - * Indicate that there should not be any comment or option info - * embedded in the generated tcpprep cache file - */ -int -tcpprep_set_nocomment(tcpprep_t *ctx, bool value) -{ - assert(ctx); - ctx->options->nocomment = value; - return 0; -} - -/** - * Specify the tcpprep main mode - */ -int -tcpprep_set_mode(tcpprep_t *ctx, tcpprep_mode_t value) -{ - assert(ctx); - ctx->options->mode = value; - return 0; -} - -/** - * Specify the submode for automode - */ -int -tcpprep_set_automode(tcpprep_t *ctx, tcpprep_mode_t value) -{ - assert(ctx); - ctx->options->automode = value; - return 0; -} - -/** - * Set the minimum CIDR mask length for auto modes - */ -int -tcpprep_set_min_mask(tcpprep_t *ctx, int value) -{ - assert(ctx); - ctx->options->min_mask = value; - return 0; -} - -/** - * Set the maximum CIDR mask length for auto modes - */ -int -tcpprep_set_max_mask(tcpprep_t *ctx, int value) -{ - assert(ctx); - ctx->options->max_mask = value; - return 0; -} - -/** - * Set the client/server ratio for auto modes - */ -int -tcpprep_set_ratio(tcpprep_t *ctx, double value) -{ - assert(ctx); - ctx->options->ratio = value; - return 0; -} - -/** - * Specify the regex for regex mode - */ -int -tcpprep_set_regex(tcpprep_t *ctx, char *value) -{ - int regex_error; - - assert(ctx); - - if ((regex_error = regcomp(&ctx->options->preg, value, - REG_EXTENDED|REG_NOSUB))) { - char ebuf[EBUF_SIZE]; - regerror(regex_error, &ctx->options->preg, ebuf, EBUF_SIZE); - tcpprep_seterr(ctx, "Unable to compile regex (%s): %s", value, regex_error); - return -1; - } - - return 0; -} - -/** - * Override default: Send all non-IP traffic out the secondary interface - */ -int -tcpprep_set_nonip_is_secondary(tcpprep_t *ctx, bool value) -{ - assert(ctx); - ctx->options->nonip = value; - return 0; -} - -#ifdef ENABLE_VERBOSE -/** - * Enable verbose (tcpdump) - */ -int -tcpprep_set_verbose(tcpprep_t *ctx, bool value) -{ - assert(ctx); - ctx->options->verbose = value; - return 0; -} - -/** - * Specify tcpdump args for verbose = ON - */ -int -tcpprep_set_tcpdump_args(tcpprep_t *ctx, char *value) -{ - assert(ctx); - ctx->options->tcpdump_args = safe_strdup(value); - return 0; -} - -/** - * Specify path to tcpdump binary - */ -int -tcpprep_set_tcpdump(tcpprep_t *ctx, tcpdump_t *value) -{ - assert(ctx); - memcpy(&ctx->tcpdump, value, sizeof(tcpdump_t)); - return 0; -} -#endif - -/** - * \brief Returns a string describing the last error. - * - * Value when the last call does not result in an error is undefined - * (may be NULL, may be garbage) - */ -char * -tcpprep_geterr(tcpprep_t *ctx) -{ - assert(ctx); - return(ctx->errstr); -} - -/** - * \brief Returns a string describing the last warning. - * - * Value when the last call does not result in an warning is undefined - * (may be NULL, may be garbage) - */ -char * -tcpprep_getwarn(tcpprep_t *ctx) -{ - assert(ctx); - return(ctx->warnstr); -} - - -/** - * \brief Internal function to set the tcpprep error string - * - * Used to set the error string when there is an error, result is retrieved - * using tcpedit_geterr(). You shouldn't ever actually call this, but use - * tcpreplay_seterr() which is a macro wrapping this instead. - */ -void -__tcpprep_seterr(tcpprep_t *ctx, const char *func, const int line, - const char *file, const char *fmt, ...) -{ - va_list ap; - char errormsg[TCPREPLAY_ERRSTR_LEN - 32]; - - assert(ctx); - - va_start(ap, fmt); - if (fmt != NULL) { - (void)vsnprintf(errormsg, sizeof(errormsg), fmt, ap); - } - - va_end(ap); - - snprintf(ctx->errstr, sizeof(ctx->errstr), "From %s:%s() line %d:\n%s", - file, func, line, errormsg); -} - -/** - * \brief Internal function to set the tcpedit warning string - * - * Used to set the warning string when there is an non-fatal issue, result is - * retrieved using tcpedit_getwarn(). - */ -void -tcpprep_setwarn(tcpprep_t *ctx, const char *fmt, ...) -{ - va_list ap; - assert(ctx); - - va_start(ap, fmt); - if (fmt != NULL) - (void)vsnprintf(ctx->warnstr, sizeof(ctx->warnstr), fmt, ap); - - va_end(ap); -} - - - /** * \brief When using AutoOpts, call to do post argument processing * Used to process the autoopts arguments @@ -364,7 +106,8 @@ int tcpprep_post_args(tcpprep_t *ctx, int argc, char *argv[]) { char myargs[MYARGS_LEN]; - int bufsize; + size_t bufsize; + char *endptr; char *tempstr; memset(myargs, 0, MYARGS_LEN); @@ -379,10 +122,10 @@ tcpprep_post_args(tcpprep_t *ctx, int argc, char *argv[]) if (HAVE_OPT(PRINT_STATS)) print_stats(OPT_ARG(PRINT_STATS)); - if (! HAVE_OPT(CACHEFILE) && ! HAVE_OPT(PCAP)) + if (!HAVE_OPT(CACHEFILE) && !HAVE_OPT(PCAP)) err(-1, "Must specify an output cachefile (-o) and input pcap (-i)"); - if (! ctx->options->mode) + if (!ctx->options->mode) err(-1, "Must specify a processing mode: -a, -c, -r, -p"); #ifdef DEBUG @@ -399,16 +142,15 @@ tcpprep_post_args(tcpprep_t *ctx, int argc, char *argv[]) ctx->tcpdump.args = safe_strdup(OPT_ARG(DECODE)); #endif - - /* + /* * if we are to include the cli args, then prep it for the * cache file header */ - if (! ctx->options->nocomment) { + if (!ctx->options->nocomment) { int i; /* copy all of our args to myargs */ - for (i = 1; i < argc; i ++) { + for (i = 1; i < argc; i++) { /* skip the -C */ if (strcmp(argv[i], "-C") == 0) { i += 2; @@ -425,12 +167,11 @@ tcpprep_post_args(tcpprep_t *ctx, int argc, char *argv[]) dbgx(1, "Comment args length: %zu", strlen(myargs)); } - /* setup or options.comment buffer so that that we get args\ncomment */ + /* setup or options.comment buffer so that we get args\ncomment */ if (ctx->options->comment != NULL) { strlcat(myargs, "\n", MYARGS_LEN); bufsize = strlen(ctx->options->comment) + strlen(myargs) + 1; - ctx->options->comment = (char *)safe_realloc(ctx->options->comment, - bufsize); + ctx->options->comment = (char *)safe_realloc(ctx->options->comment, bufsize); tempstr = strdup(ctx->options->comment); strlcpy(ctx->options->comment, myargs, bufsize); @@ -449,11 +190,16 @@ tcpprep_post_args(tcpprep_t *ctx, int argc, char *argv[]) ctx->options->max_mask = OPT_VALUE_MAXMASK; - if (!(ctx->options->min_mask > ctx->options->max_mask)) - errx(-1, "Min network mask len (%d) must be less then max network mask len (%d)", - ctx->options->min_mask, ctx->options->max_mask); + if (ctx->options->min_mask <= ctx->options->max_mask) + errx(-1, + "Min network mask len (%d) must be less then max network mask len (%d)", + ctx->options->min_mask, + ctx->options->max_mask); + + ctx->options->ratio = strtod(OPT_ARG(RATIO), &endptr); + if (endptr == OPT_ARG(RATIO)) + err(-1, "Ratio supplied is not a number."); - ctx->options->ratio = atof(OPT_ARG(RATIO)); if (ctx->options->ratio < 0) err(-1, "Ratio must be a non-negative number."); diff --git a/src/tcpprep_api.h b/src/tcpprep_api.h index fb0d45301..279de7493 100644 --- a/src/tcpprep_api.h +++ b/src/tcpprep_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,22 +18,17 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TCPPREP_API_H_ -#define _TCPPREP_API_H_ +#pragma once -#include "config.h" #include "defines.h" +#include "config.h" #include "tcpreplay_api.h" - #include #ifdef __cplusplus extern "C" { #endif - - - /* default ports used for servers */ #define DEFAULT_LOW_SERVER_PORT 0 #define DEFAULT_HIGH_SERVER_PORT 1023 @@ -51,10 +46,10 @@ typedef struct tcpprep_opt_s { tcpr_xX_t xX; tcpr_bpf_t bpf; tcpr_services_t services; - char *comment; /* cache file comment */ - bool nocomment; /* don't include the cli in the comment */ - tcpprep_mode_t mode; /* our overall mode */ - tcpprep_mode_t automode; /* our auto mode */ + char *comment; /* cache file comment */ + bool nocomment; /* don't include the cli in the comment */ + tcpprep_mode_t mode; /* our overall mode */ + tcpprep_mode_t automode; /* our auto mode */ int min_mask; int max_mask; double ratio; @@ -74,46 +69,14 @@ typedef struct tcpprep_s { } tcpprep_t; - -char *tcpprep_geterr(tcpprep_t *); -char *tcpprep_getwarn(tcpprep_t *); +_U_ char *tcpprep_geterr(tcpprep_t *); +_U_ char *tcpprep_getwarn(tcpprep_t *); tcpprep_t *tcpprep_init(); void tcpprep_close(tcpprep_t *); int tcpprep_post_args(tcpprep_t *, int, char *[]); - -/* all these functions return 0 on success and < 0 on error. */ -int tcpprep_set_pcap_file(tcpprep_t *, char *); -int tcpprep_set_output_file(tcpprep_t *, char *); -int tcpprep_set_comment(tcpprep_t *, char *); -int tcpprep_set_nocomment(tcpprep_t *, bool); -int tcpprep_set_mode(tcpprep_t *, tcpprep_mode_t); -int tcpprep_set_min_mask(tcpprep_t *, int); -int tcpprep_set_max_mask(tcpprep_t *, int); -int tcpprep_set_ratio(tcpprep_t *, double); -int tcpprep_set_regex(tcpprep_t *, char *); -int tcpprep_set_nonip_is_secondary(tcpprep_t *, bool); - -#ifdef ENABLE_VERBOSE -int tcpprep_set_verbose(tcpprep_t *, bool); -int tcpprep_set_tcpdump_args(tcpprep_t *, char *); -int tcpprep_set_tcpdump(tcpprep_t *, tcpdump_t *); -#endif - - -/** - * These functions are seen by the outside world, but nobody should ever use them - * outside of internal tcpprep API functions - */ - -#define tcpprep_seterr(x, y, ...) __tcpprep_seterr(x, __FUNCTION__, __LINE__, __FILE__, y, __VA_ARGS__) -void __tcpprep_seterr(tcpprep_t *ctx, const char *func, const int line, const char *file, const char *fmt, ...); -void tcpprep_setwarn(tcpprep_t *ctx, const char *fmt, ...); - #ifdef __cplusplus } #endif - -#endif //_TCPREPLAY_API_H_ diff --git a/src/tcpr.h b/src/tcpr.h index 3ac542b08..5554a2962 100644 --- a/src/tcpr.h +++ b/src/tcpr.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -23,11 +23,9 @@ * libnet 1.1.3's libnet-headers.h. Many thanks to Mike D. Schiffman for doing * all this work so I basically just needed to do a search and replace to get * things to work. -*/ - + */ -#ifndef _TCPR_H_ -#define _TCPR_H_ +#pragma once #ifdef HAVE_SYS_TYPES_H #include @@ -65,106 +63,105 @@ #define TOKEN_RING_ADDR_LEN 0x6 #define TCPR_ORG_CODE_SIZE 0x3 - /** * Libnet defines header sizes for every builder function exported. */ -#define TCPR_802_1Q_H 0x12 /**< 802.1Q header: 18 bytes */ -#define TCPR_802_1X_H 0x04 /**< 802.1X header: 4 bytes */ -#define TCPR_802_2_H 0x03 /**< 802.2 LLC header: 3 bytes */ -#define TCPR_802_2SNAP_H 0x08 /**< 802.2 LLC/SNAP header:8 bytes */ -#define TCPR_802_3_H 0x0e /**< 802.3 header: 14 bytes */ -#define TCPR_ARP_H 0x08 /**< ARP header w/o addrs: 8 bytes */ -#define TCPR_ARP_ETH_IP_H 0x1c /**< ARP w/ ETH and IP: 28 bytes */ -#define TCPR_BGP4_HEADER_H 0x13 /**< BGP header: 19 bytes */ -#define TCPR_BGP4_OPEN_H 0x0a /**< BGP open header: 10 bytes */ -#define TCPR_BGP4_UPDATE_H 0x04 /**< BGP open header: 4 bytes */ +#define TCPR_802_1Q_H 0x12 /**< 802.1Q header: 18 bytes */ +#define TCPR_802_1X_H 0x04 /**< 802.1X header: 4 bytes */ +#define TCPR_802_2_H 0x03 /**< 802.2 LLC header: 3 bytes */ +#define TCPR_802_2SNAP_H 0x08 /**< 802.2 LLC/SNAP header:8 bytes */ +#define TCPR_802_3_H 0x0e /**< 802.3 header: 14 bytes */ +#define TCPR_ARP_H 0x08 /**< ARP header w/o addrs: 8 bytes */ +#define TCPR_ARP_ETH_IP_H 0x1c /**< ARP w/ ETH and IP: 28 bytes */ +#define TCPR_BGP4_HEADER_H 0x13 /**< BGP header: 19 bytes */ +#define TCPR_BGP4_OPEN_H 0x0a /**< BGP open header: 10 bytes */ +#define TCPR_BGP4_UPDATE_H 0x04 /**< BGP open header: 4 bytes */ #define TCPR_BGP4_NOTIFICATION_H 0x02 /**< BGP notif. header: 2 bytes */ -#define TCPR_CDP_H 0x08 /**< CDP header base: 8 bytes */ -#define TCPR_DHCPV4_H 0xf0 /**< DHCP v4 header: 240 bytes */ -#define TCPR_UDP_DNSV4_H 0x0c /**< UDP DNS v4 header: 12 bytes */ -#define TCPR_TCP_DNSV4_H 0x0e /**< TCP DNS v4 header: 14 bytes */ -#define TCPR_ETH_H 0x0e /**< Ethernet header: 14 bytes */ -#define TCPR_ETH_MTU 1500 /**< Ethernet MTU size: 1500 bytes */ -#define TCPR_FDDI_H 0x15 /**< FDDI header: 21 bytes */ -#define TCPR_ICMPV4_H 0x04 /**< ICMP header base: 4 bytes */ -#define TCPR_ICMPV4_ECHO_H 0x08 /**< ICMP_ECHO header: 8 bytes */ -#define TCPR_ICMPV4_MASK_H 0x0c /**< ICMP_MASK header: 12 bytes */ -#define TCPR_ICMPV4_UNREACH_H 0x08 /**< ICMP_UNREACH header: 8 bytes */ +#define TCPR_CDP_H 0x08 /**< CDP header base: 8 bytes */ +#define TCPR_DHCPV4_H 0xf0 /**< DHCP v4 header: 240 bytes */ +#define TCPR_UDP_DNSV4_H 0x0c /**< UDP DNS v4 header: 12 bytes */ +#define TCPR_TCP_DNSV4_H 0x0e /**< TCP DNS v4 header: 14 bytes */ +#define TCPR_ETH_H 0x0e /**< Ethernet header: 14 bytes */ +#define TCPR_ETH_MTU 1500 /**< Ethernet MTU size: 1500 bytes */ +#define TCPR_FDDI_H 0x15 /**< FDDI header: 21 bytes */ +#define TCPR_ICMPV4_H 0x04 /**< ICMP header base: 4 bytes */ +#define TCPR_ICMPV4_ECHO_H 0x08 /**< ICMP_ECHO header: 8 bytes */ +#define TCPR_ICMPV4_MASK_H 0x0c /**< ICMP_MASK header: 12 bytes */ +#define TCPR_ICMPV4_UNREACH_H 0x08 /**< ICMP_UNREACH header: 8 bytes */ #define TCPR_ICMPV4_TIMXCEED_H 0x08 /**< ICMP_TIMXCEED header: 8 bytes */ #define TCPR_ICMPV4_REDIRECT_H 0x08 /**< ICMP_REDIRECT header: 8 bytes */ -#define TCPR_ICMPV4_TS_H 0x14 /**< ICMP_TIMESTAMP headr:20 bytes */ -#define TCPR_ICMPV6_H 0x08 /**< ICMP6 header base: 8 bytes */ -#define TCPR_IGMP_H 0x08 /**< IGMP header: 8 bytes */ -#define TCPR_IPV4_H 0x14 /**< IPv4 header: 20 bytes */ -#define TCPR_IPV6_H 0x28 /**< IPv6 header: 40 bytes */ -#define TCPR_IPV6_FRAG_H 0x08 /**< IPv6 frag header: 8 bytes */ -#define TCPR_IPV6_ROUTING_H 0x04 /**< IPv6 frag header base:4 bytes */ -#define TCPR_IPV6_DESTOPTS_H 0x02 /**< IPv6 dest opts base: 2 bytes */ -#define TCPR_IPV6_HBHOPTS_H 0x02 /**< IPv6 hop/hop opt base:2 bytes */ -#define TCPR_IPSEC_ESP_HDR_H 0x0c /**< IPSEC ESP header: 12 bytes */ -#define TCPR_IPSEC_ESP_FTR_H 0x02 /**< IPSEC ESP footer: 2 bytes */ -#define TCPR_IPSEC_AH_H 0x10 /**< IPSEC AH header: 16 bytes */ -#define TCPR_ISL_H 0x1a /**< ISL header: 26 bytes */ -#define TCPR_GRE_H 0x04 /**< GRE header: 4 bytes */ -#define TCPR_GRE_SRE_H 0x04 /**< GRE SRE header: 4 bytes */ -#define TCPR_MPLS_H 0x04 /**< MPLS header: 4 bytes */ -#define TCPR_OSPF_H 0x10 /**< OSPF header: 16 bytes */ -#define TCPR_OSPF_HELLO_H 0x18 /**< OSPF hello header: 24 bytes */ -#define TCPR_OSPF_DBD_H 0x08 /**< OSPF DBD header: 8 bytes */ -#define TCPR_OSPF_LSR_H 0x0c /**< OSPF LSR header: 12 bytes */ -#define TCPR_OSPF_LSU_H 0x04 /**< OSPF LSU header: 4 bytes */ -#define TCPR_OSPF_LSA_H 0x14 /**< OSPF LSA header: 20 bytes */ -#define TCPR_OSPF_AUTH_H 0x08 /**< OSPF AUTH header: 8 bytes */ -#define TCPR_OSPF_CKSUM 0x10 /**< OSPF CKSUM header: 16 bytes */ -#define TCPR_OSPF_LS_RTR_H 0x10 /**< OSPF LS RTR header: 16 bytes */ -#define TCPR_OSPF_LS_NET_H 0x08 /**< OSPF LS NET header: 8 bytes */ -#define TCPR_OSPF_LS_SUM_H 0x0c /**< OSPF LS SUM header: 12 bytes */ +#define TCPR_ICMPV4_TS_H 0x14 /**< ICMP_TIMESTAMP headr:20 bytes */ +#define TCPR_ICMPV6_H 0x08 /**< ICMP6 header base: 8 bytes */ +#define TCPR_IGMP_H 0x08 /**< IGMP header: 8 bytes */ +#define TCPR_IPV4_H 0x14 /**< IPv4 header: 20 bytes */ +#define TCPR_IPV6_H 0x28 /**< IPv6 header: 40 bytes */ +#define TCPR_IPV6_FRAG_H 0x08 /**< IPv6 frag header: 8 bytes */ +#define TCPR_IPV6_ROUTING_H 0x04 /**< IPv6 frag header base:4 bytes */ +#define TCPR_IPV6_DESTOPTS_H 0x02 /**< IPv6 dest opts base: 2 bytes */ +#define TCPR_IPV6_HBHOPTS_H 0x02 /**< IPv6 hop/hop opt base:2 bytes */ +#define TCPR_IPSEC_ESP_HDR_H 0x0c /**< IPSEC ESP header: 12 bytes */ +#define TCPR_IPSEC_ESP_FTR_H 0x02 /**< IPSEC ESP footer: 2 bytes */ +#define TCPR_IPSEC_AH_H 0x10 /**< IPSEC AH header: 16 bytes */ +#define TCPR_ISL_H 0x1a /**< ISL header: 26 bytes */ +#define TCPR_GRE_H 0x04 /**< GRE header: 4 bytes */ +#define TCPR_GRE_SRE_H 0x04 /**< GRE SRE header: 4 bytes */ +#define TCPR_MPLS_H 0x04 /**< MPLS header: 4 bytes */ +#define TCPR_OSPF_H 0x10 /**< OSPF header: 16 bytes */ +#define TCPR_OSPF_HELLO_H 0x18 /**< OSPF hello header: 24 bytes */ +#define TCPR_OSPF_DBD_H 0x08 /**< OSPF DBD header: 8 bytes */ +#define TCPR_OSPF_LSR_H 0x0c /**< OSPF LSR header: 12 bytes */ +#define TCPR_OSPF_LSU_H 0x04 /**< OSPF LSU header: 4 bytes */ +#define TCPR_OSPF_LSA_H 0x14 /**< OSPF LSA header: 20 bytes */ +#define TCPR_OSPF_AUTH_H 0x08 /**< OSPF AUTH header: 8 bytes */ +#define TCPR_OSPF_CKSUM 0x10 /**< OSPF CKSUM header: 16 bytes */ +#define TCPR_OSPF_LS_RTR_H 0x10 /**< OSPF LS RTR header: 16 bytes */ +#define TCPR_OSPF_LS_NET_H 0x08 /**< OSPF LS NET header: 8 bytes */ +#define TCPR_OSPF_LS_SUM_H 0x0c /**< OSPF LS SUM header: 12 bytes */ #define TCPR_OSPF_LS_AS_EXT_H 0x10 /**< OSPF LS AS header: 16 bytes */ -#define TCPR_NTP_H 0x30 /**< NTP header: 48 bytes */ -#define TCPR_RIP_H 0x18 /**< RIP header base: 24 bytes */ -#define TCPR_RPC_CALL_H 0x28 /**< RPC header: 40 bytes - * (assuming 8 byte auth header) - */ -#define TCPR_RPC_CALL_TCP_H 0x2c /**< RPC header: 44 bytes - * (with record marking) - */ -#define TCPR_SEBEK_H 0x30 /* sebek header: 48 bytes */ -#define TCPR_STP_CONF_H 0x23 /**< STP conf header: 35 bytes */ -#define TCPR_STP_TCN_H 0x04 /**< STP tcn header: 4 bytes */ -#define TCPR_TOKEN_RING_H 0x16 /**< Token Ring header: 22 bytes */ -#define TCPR_TCP_H 0x14 /**< TCP header: 20 bytes */ -#define TCPR_UDP_H 0x08 /**< UDP header: 8 bytes */ -#define TCPR_VRRP_H 0x08 /**< VRRP header: 8 bytes */ -#define TCPR_HSRP_H 0x14 /**< HSRP header: 8 bytes */ +#define TCPR_NTP_H 0x30 /**< NTP header: 48 bytes */ +#define TCPR_RIP_H 0x18 /**< RIP header base: 24 bytes */ +#define TCPR_RPC_CALL_H \ + 0x28 /**< RPC header: 40 bytes \ + * (assuming 8 byte auth header) \ + */ +#define TCPR_RPC_CALL_TCP_H \ + 0x2c /**< RPC header: 44 bytes \ + * (with record marking) \ + */ +#define TCPR_SEBEK_H 0x30 /* sebek header: 48 bytes */ +#define TCPR_STP_CONF_H 0x23 /**< STP conf header: 35 bytes */ +#define TCPR_STP_TCN_H 0x04 /**< STP tcn header: 4 bytes */ +#define TCPR_TOKEN_RING_H 0x16 /**< Token Ring header: 22 bytes */ +#define TCPR_TCP_H 0x14 /**< TCP header: 20 bytes */ +#define TCPR_UDP_H 0x08 /**< UDP header: 8 bytes */ +#define TCPR_VRRP_H 0x08 /**< VRRP header: 8 bytes */ +#define TCPR_HSRP_H 0x14 /**< HSRP header: 8 bytes */ /** * IEEE 802.1Q (Virtual Local Area Network) VLAN headr * size: 8 bytes */ -struct tcpr_802_1q_hdr -{ - uint16_t vlan_tci; /* VLAN TCI */ - uint16_t vlan_tpid; /* Next ETH_TYPE */ -#define TCPR_802_1Q_PRIMASK 0xe000 /**< priority mask */ -#define TCPR_802_1Q_CFIMASK 0x1000 /**< CFI mask */ -#define TCPR_802_1Q_VIDMASK 0x0fff /**< vid mask */ +struct tcpr_802_1q_hdr { + uint16_t vlan_tci; /* VLAN TCI */ + uint16_t vlan_tpid; /* Next ETH_TYPE */ +#define TCPR_802_1Q_PRIMASK 0xe000 /**< priority mask */ +#define TCPR_802_1Q_CFIMASK 0x1000 /**< CFI mask */ +#define TCPR_802_1Q_VIDMASK 0x0fff /**< vid mask */ }; /** * IEEE 802.1X EAP (Extensible Authentication Protocol) header, static header * size: 4 bytes */ -struct tcpr_802_1x_hdr -{ - uint8_t dot1x_version; /**< protocol version */ - uint8_t dot1x_type; /**< frame type */ -#define TCPR_802_1X_PACKET 0x00 /**< 802.1x packet */ -#define TCPR_802_1X_START 0x01 /**< 802.1x start */ -#define TCPR_802_1X_LOGOFF 0x02 /**< 802.1x logoff */ -#define TCPR_802_1X_KEY 0x03 /**< 802.1x key */ -#define TCPR_802_1X_ENCASFAL 0x04 /**< 802.1x encasfal */ - uint16_t dot1x_length; /**< total frame length */ +struct tcpr_802_1x_hdr { + uint8_t dot1x_version; /**< protocol version */ + uint8_t dot1x_type; /**< frame type */ +#define TCPR_802_1X_PACKET 0x00 /**< 802.1x packet */ +#define TCPR_802_1X_START 0x01 /**< 802.1x start */ +#define TCPR_802_1X_LOGOFF 0x02 /**< 802.1x logoff */ +#define TCPR_802_1X_KEY 0x03 /**< 802.1x key */ +#define TCPR_802_1X_ENCASFAL 0x04 /**< 802.1x encasfal */ + uint16_t dot1x_length; /**< total frame length */ }; /* @@ -172,77 +169,70 @@ struct tcpr_802_1x_hdr * Link Layer Control * static header size: 4 bytes */ -struct tcpr_802_2_hdr -{ - uint8_t llc_dsap; /* destination service access point */ - uint8_t llc_ssap; /* source service access point */ -#define TCPR_SAP_STP 0x42 -#define TCPR_SAP_SNAP 0xaa - uint16_t llc_control; /* control field */ +struct tcpr_802_2_hdr { + uint8_t llc_dsap; /* destination service access point */ + uint8_t llc_ssap; /* source service access point */ +#define TCPR_SAP_STP 0x42 +#define TCPR_SAP_SNAP 0xaa + uint16_t llc_control; /* control field */ }; - /* * IEEE 802.2 LLC/SNAP header * SubNetwork Attachment Point * static header size: 8 bytes */ -struct tcpr_802_2snap_hdr -{ - uint8_t snap_dsap; /* destination service access point */ - uint8_t snap_ssap; /* destination service access point */ - uint8_t snap_control; /* control field */ - uint8_t snap_oui[3]; /* OUI */ - uint16_t snap_type; /* type */ +struct tcpr_802_2snap_hdr { + uint8_t snap_dsap; /* destination service access point */ + uint8_t snap_ssap; /* destination service access point */ + uint8_t snap_control; /* control field */ + uint8_t snap_oui[3]; /* OUI */ + uint16_t snap_type; /* type */ }; - /* * 802.3 header * IEEE Ethernet * Static header size: 14 bytes */ -struct tcpr_802_3_hdr -{ - uint8_t _802_3_dhost[ETHER_ADDR_LEN];/* destination ethernet address */ - uint8_t _802_3_shost[ETHER_ADDR_LEN];/* source ethernet address */ - uint16_t _802_3_len; /* packet type ID */ +struct tcpr_802_3_hdr { + uint8_t _802_3_dhost[ETHER_ADDR_LEN]; /* destination ethernet address */ + uint8_t _802_3_shost[ETHER_ADDR_LEN]; /* source ethernet address */ + uint16_t _802_3_len; /* packet type ID */ }; - /* * ARP header * Address Resolution Protocol * Base header size: 8 bytes */ -struct tcpr_arp_hdr -{ - uint16_t ar_hrd; /* format of hardware address */ -#define ARPHRD_NETROM 0 /* from KA9Q: NET/ROM pseudo */ -#define ARPHRD_ETHER 1 /* Ethernet 10Mbps */ -#define ARPHRD_EETHER 2 /* Experimental Ethernet */ -#define ARPHRD_AX25 3 /* AX.25 Level 2 */ -#define ARPHRD_PRONET 4 /* PROnet token ring */ -#define ARPHRD_CHAOS 5 /* Chaosnet */ -#define ARPHRD_IEEE802 6 /* IEEE 802.2 Ethernet/TR/TB */ -#define ARPHRD_ARCNET 7 /* ARCnet */ +struct tcpr_arp_hdr { + uint16_t ar_hrd; /* format of hardware address */ +#define ARPHRD_NETROM 0 /* from KA9Q: NET/ROM pseudo */ +#define ARPHRD_ETHER 1 /* Ethernet 10Mbps */ +#define ARPHRD_EETHER 2 /* Experimental Ethernet */ +#define ARPHRD_AX25 3 /* AX.25 Level 2 */ +#define ARPHRD_PRONET 4 /* PROnet token ring */ +#define ARPHRD_CHAOS 5 /* Chaosnet */ +#define ARPHRD_IEEE802 6 /* IEEE 802.2 Ethernet/TR/TB */ +#define ARPHRD_ARCNET 7 /* ARCnet */ #define ARPHRD_APPLETLK 8 /* APPLEtalk */ -#define ARPHRD_LANSTAR 9 /* Lanstar */ -#define ARPHRD_DLCI 15 /* Frame Relay DLCI */ -#define ARPHRD_ATM 19 /* ATM */ +#define ARPHRD_LANSTAR 9 /* Lanstar */ +#define ARPHRD_DLCI 15 /* Frame Relay DLCI */ +#define ARPHRD_ATM 19 /* ATM */ #define ARPHRD_METRICOM 23 /* Metricom STRIP (new IANA id) */ -#define ARPHRD_IPSEC 31 /* IPsec tunnel */ +#define ARPHRD_IPSEC 31 /* IPsec tunnel */ #define ARPHRD_LOOPBACK 772 /* Loopback device */ - uint16_t ar_pro; /* format of protocol address */ - uint8_t ar_hln; /* length of hardware address */ - uint8_t ar_pln; /* length of protocol address */ - uint16_t ar_op; /* operation type */ -#define ARPOP_REQUEST 1 /* req to resolve address */ -#define ARPOP_REPLY 2 /* resp to previous request */ + uint16_t ar_pro; /* format of protocol address */ + uint8_t ar_hln; /* length of hardware address */ + uint8_t ar_pln; /* length of protocol address */ + uint16_t ar_op; /* operation type */ +#define ARPOP_REQUEST 1 /* req to resolve address */ +#define ARPOP_REPLY 2 /* resp to previous request */ #define ARPOP_REVREQUEST 3 /* req protocol address given hardware */ -#define ARPOP_REVREPLY 4 /* resp giving protocol address */ +#define ARPOP_REVREPLY 4 /* resp giving protocol address */ #define ARPOP_INVREQUEST 8 /* req to identify peer */ -#define ARPOP_INVREPLY 9 /* resp identifying peer */ +#define ARPOP_INVREPLY 9 /* resp identifying peer */ /* address information allocated dynamically */ }; @@ -251,16 +241,15 @@ struct tcpr_arp_hdr * Border Gateway Protocol 4 * Base header size : 19 bytes */ -struct tcpr_bgp4_header_hdr -{ -#define TCPR_BGP4_MARKER_SIZE 16 +struct tcpr_bgp4_header_hdr { +#define TCPR_BGP4_MARKER_SIZE 16 uint8_t marker[TCPR_BGP4_MARKER_SIZE]; uint16_t len; uint8_t type; -#define TCPR_BGP4_OPEN 1 -#define TCPR_BGP4_UPDATE 2 -#define TCPR_BGP4_NOTIFICATION 3 -#define TCPR_BGP4_KEEPALIVE 4 +#define TCPR_BGP4_OPEN 1 +#define TCPR_BGP4_UPDATE 2 +#define TCPR_BGP4_NOTIFICATION 3 +#define TCPR_BGP4_KEEPALIVE 4 }; /* @@ -268,8 +257,7 @@ struct tcpr_bgp4_header_hdr * Border Gateway Protocol 4 * Base header size : 10 bytes */ -struct tcpr_bgp4_open_hdr -{ +struct tcpr_bgp4_open_hdr { uint8_t version; uint16_t src_as; uint16_t hold_time; @@ -285,27 +273,26 @@ struct tcpr_bgp4_open_hdr * * Use payload if you need data */ -struct tcpr_bgp4_notification_hdr -{ -#define TCPR_BGP4_MESSAGE_HEADER_ERROR 1 -#define TCPR_BGP4_OPEN_MESSAGE_ERROR 2 -#define TCPR_BGP4_UPDATE_MESSAGE_ERROR 3 -#define TCPR_BGP4_HOLD_TIMER_EXPIRED 4 -#define TCPR_BGP4_FINITE_STATE__ERROR 5 -#define TCPR_BGP4_CEASE 6 +struct tcpr_bgp4_notification_hdr { +#define TCPR_BGP4_MESSAGE_HEADER_ERROR 1 +#define TCPR_BGP4_OPEN_MESSAGE_ERROR 2 +#define TCPR_BGP4_UPDATE_MESSAGE_ERROR 3 +#define TCPR_BGP4_HOLD_TIMER_EXPIRED 4 +#define TCPR_BGP4_FINITE_STATE__ERROR 5 +#define TCPR_BGP4_CEASE 6 uint8_t err_code; /* Message Header Error subcodes */ -#define TCPR_BGP4_CONNECTION_NOT_SYNCHRONIZED 1 -#define TCPR_BGP4_BAD_MESSAGE_LENGTH 2 -#define TCPR_BGP4_BAD_MESSAGE_TYPE 3 +#define TCPR_BGP4_CONNECTION_NOT_SYNCHRONIZED 1 +#define TCPR_BGP4_BAD_MESSAGE_LENGTH 2 +#define TCPR_BGP4_BAD_MESSAGE_TYPE 3 /* OPEN Message Error subcodes */ -#define TCPR_BGP4_UNSUPPORTED_VERSION_NUMBER 1 -#define TCPR_BGP4_BAD_PEER_AS 2 -#define TCPR_BGP4_BAD_BGP_IDENTIFIER 3 +#define TCPR_BGP4_UNSUPPORTED_VERSION_NUMBER 1 +#define TCPR_BGP4_BAD_PEER_AS 2 +#define TCPR_BGP4_BAD_BGP_IDENTIFIER 3 #define TCPR_BGP4_UNSUPPORTED_OPTIONAL_PARAMETER 4 -#define TCPR_BGP4_AUTHENTICATION_FAILURE 5 -#define TCPR_BGP4_UNACCEPTABLE_HOLD_TIME 6 +#define TCPR_BGP4_AUTHENTICATION_FAILURE 5 +#define TCPR_BGP4_UNACCEPTABLE_HOLD_TIME 6 /* UPDATE Message Error subcodes */ #define TCPR_BGP4_MALFORMED_ATTRIBUTE_LIST #define TCPR_BGP4_UNRECOGNIZED_WELL_KNOWN_ATTRIBUTE @@ -321,8 +308,6 @@ struct tcpr_bgp4_notification_hdr uint8_t err_subcode; }; - - /* * CDP header * Cisco Discovery Protocol @@ -333,190 +318,181 @@ struct tcpr_bgp4_notification_hdr * For checksum stuff -- IANA says 135-254 is "unassigned" as of 12.2001. * Let's hope this one stays that way for a while! */ -#define TCPR_PROTO_CDP 200 -struct tcpr_cdp_hdr -{ - uint8_t cdp_version; /* version (should always be 0x01) */ - uint8_t cdp_ttl; /* time receiver should hold info in this packet */ - uint16_t cdp_sum; /* checksum */ - uint16_t cdp_type; /* type */ -#define TCPR_CDP_DEVID 0x1 /* device id */ -#define TCPR_CDP_ADDRESS 0x2 /* address */ -#define TCPR_CDP_PORTID 0x3 /* port id */ -#define TCPR_CDP_CAPABIL 0x4 /* capabilities */ -#define TCPR_CDP_VERSION 0x5 /* version */ +#define TCPR_PROTO_CDP 200 +struct tcpr_cdp_hdr { + uint8_t cdp_version; /* version (should always be 0x01) */ + uint8_t cdp_ttl; /* time receiver should hold info in this packet */ + uint16_t cdp_sum; /* checksum */ + uint16_t cdp_type; /* type */ +#define TCPR_CDP_DEVID 0x1 /* device id */ +#define TCPR_CDP_ADDRESS 0x2 /* address */ +#define TCPR_CDP_PORTID 0x3 /* port id */ +#define TCPR_CDP_CAPABIL 0x4 /* capabilities */ +#define TCPR_CDP_VERSION 0x5 /* version */ #define TCPR_CDP_PLATFORM 0x6 /* platform */ #define TCPR_CDP_IPPREFIX 0x7 /* ip prefix */ - uint16_t cdp_len; /* type + length + value */ + uint16_t cdp_len; /* type + length + value */ /* value information done dynamically */ /* CDP capabilities */ -#define TCPR_CDP_CAP_L3R 0x01/* performs level 3 routing */ -#define TCPR_CDP_CAP_L2B 0x02/* performs level 2 transparent bridging */ -#define TCPR_CDP_CAP_L2SRB 0x04/* performs level 2 sourceroute bridging */ -#define TCPR_CDP_CAP_L2S 0x08/* performs level 2 switching */ -#define TCPR_CDP_CAP_SR 0x10/* sends and receives packets on a network */ -#define TCPR_CDP_CAP_NOI 0x20/* does not forward IGMP on non-router ports */ -#define TCPR_CDP_CAP_L1F 0x40/* provides level 1 functionality */ +#define TCPR_CDP_CAP_L3R 0x01 /* performs level 3 routing */ +#define TCPR_CDP_CAP_L2B 0x02 /* performs level 2 transparent bridging */ +#define TCPR_CDP_CAP_L2SRB 0x04 /* performs level 2 sourceroute bridging */ +#define TCPR_CDP_CAP_L2S 0x08 /* performs level 2 switching */ +#define TCPR_CDP_CAP_SR 0x10 /* sends and receives packets on a network */ +#define TCPR_CDP_CAP_NOI 0x20 /* does not forward IGMP on non-router ports */ +#define TCPR_CDP_CAP_L1F 0x40 /* provides level 1 functionality */ }; - /* * Used as an overlay for type/len/values */ -struct tcpr_cdp_value_hdr -{ +struct tcpr_cdp_value_hdr { uint16_t cdp_type; uint16_t cdp_len; }; - /* * DHCP header * Dynamic Host Configuration Protocol * Static header size: f0 bytes */ -struct tcpr_dhcpv4_hdr -{ - uint8_t dhcp_opcode; /* opcode */ +struct tcpr_dhcpv4_hdr { + uint8_t dhcp_opcode; /* opcode */ #define TCPR_DHCP_REQUEST 0x1 -#define TCPR_DHCP_REPLY 0x2 +#define TCPR_DHCP_REPLY 0x2 uint8_t dhcp_htype; /* hardware address type */ uint8_t dhcp_hlen; /* hardware address length */ uint8_t dhcp_hopcount; /* used by proxy servers */ - uint32_t dhcp_xid; /* transaction ID */ + uint32_t dhcp_xid; /* transaction ID */ uint16_t dhcp_secs; /* number of seconds since trying to bootstrap */ uint16_t dhcp_flags; /* flags for DHCP, unused for BOOTP */ - uint32_t dhcp_cip; /* client's IP */ - uint32_t dhcp_yip; /* your IP */ - uint32_t dhcp_sip; /* server's IP */ - uint32_t dhcp_gip; /* gateway IP */ + uint32_t dhcp_cip; /* client's IP */ + uint32_t dhcp_yip; /* your IP */ + uint32_t dhcp_sip; /* server's IP */ + uint32_t dhcp_gip; /* gateway IP */ uint8_t dhcp_chaddr[16]; /* client hardware address */ uint8_t dhcp_sname[64]; /* server host name */ uint8_t dhcp_file[128]; /* boot file name */ - uint32_t dhcp_magic; /* BOOTP magic header */ -#define DHCP_MAGIC 0x63825363 -#define TCPR_BOOTP_MIN_LEN 0x12c -#define TCPR_DHCP_PAD 0x00 -#define TCPR_DHCP_SUBNETMASK 0x01 -#define TCPR_DHCP_TIMEOFFSET 0x02 -#define TCPR_DHCP_ROUTER 0x03 -#define TCPR_DHCP_TIMESERVER 0x04 -#define TCPR_DHCP_NAMESERVER 0x05 -#define TCPR_DHCP_DNS 0x06 -#define TCPR_DHCP_LOGSERV 0x07 -#define TCPR_DHCP_COOKIESERV 0x08 -#define TCPR_DHCP_LPRSERV 0x09 -#define TCPR_DHCP_IMPSERV 0x0a -#define TCPR_DHCP_RESSERV 0x0b -#define TCPR_DHCP_HOSTNAME 0x0c -#define TCPR_DHCP_BOOTFILESIZE 0x0d -#define TCPR_DHCP_DUMPFILE 0x0e -#define TCPR_DHCP_DOMAINNAME 0x0f -#define TCPR_DHCP_SWAPSERV 0x10 -#define TCPR_DHCP_ROOTPATH 0x11 -#define TCPR_DHCP_EXTENPATH 0x12 -#define TCPR_DHCP_IPFORWARD 0x13 -#define TCPR_DHCP_SRCROUTE 0x14 -#define TCPR_DHCP_POLICYFILTER 0x15 -#define TCPR_DHCP_MAXASMSIZE 0x16 -#define TCPR_DHCP_IPTTL 0x17 -#define TCPR_DHCP_MTUTIMEOUT 0x18 -#define TCPR_DHCP_MTUTABLE 0x19 -#define TCPR_DHCP_MTUSIZE 0x1a -#define TCPR_DHCP_LOCALSUBNETS 0x1b -#define TCPR_DHCP_BROADCASTADDR 0x1c -#define TCPR_DHCP_DOMASKDISCOV 0x1d -#define TCPR_DHCP_MASKSUPPLY 0x1e -#define TCPR_DHCP_DOROUTEDISC 0x1f -#define TCPR_DHCP_ROUTERSOLICIT 0x20 -#define TCPR_DHCP_STATICROUTE 0x21 -#define TCPR_DHCP_TRAILERENCAP 0x22 -#define TCPR_DHCP_ARPTIMEOUT 0x23 -#define TCPR_DHCP_ETHERENCAP 0x24 -#define TCPR_DHCP_TCPTTL 0x25 -#define TCPR_DHCP_TCPKEEPALIVE 0x26 + uint32_t dhcp_magic; /* BOOTP magic header */ +#define DHCP_MAGIC 0x63825363 +#define TCPR_BOOTP_MIN_LEN 0x12c +#define TCPR_DHCP_PAD 0x00 +#define TCPR_DHCP_SUBNETMASK 0x01 +#define TCPR_DHCP_TIMEOFFSET 0x02 +#define TCPR_DHCP_ROUTER 0x03 +#define TCPR_DHCP_TIMESERVER 0x04 +#define TCPR_DHCP_NAMESERVER 0x05 +#define TCPR_DHCP_DNS 0x06 +#define TCPR_DHCP_LOGSERV 0x07 +#define TCPR_DHCP_COOKIESERV 0x08 +#define TCPR_DHCP_LPRSERV 0x09 +#define TCPR_DHCP_IMPSERV 0x0a +#define TCPR_DHCP_RESSERV 0x0b +#define TCPR_DHCP_HOSTNAME 0x0c +#define TCPR_DHCP_BOOTFILESIZE 0x0d +#define TCPR_DHCP_DUMPFILE 0x0e +#define TCPR_DHCP_DOMAINNAME 0x0f +#define TCPR_DHCP_SWAPSERV 0x10 +#define TCPR_DHCP_ROOTPATH 0x11 +#define TCPR_DHCP_EXTENPATH 0x12 +#define TCPR_DHCP_IPFORWARD 0x13 +#define TCPR_DHCP_SRCROUTE 0x14 +#define TCPR_DHCP_POLICYFILTER 0x15 +#define TCPR_DHCP_MAXASMSIZE 0x16 +#define TCPR_DHCP_IPTTL 0x17 +#define TCPR_DHCP_MTUTIMEOUT 0x18 +#define TCPR_DHCP_MTUTABLE 0x19 +#define TCPR_DHCP_MTUSIZE 0x1a +#define TCPR_DHCP_LOCALSUBNETS 0x1b +#define TCPR_DHCP_BROADCASTADDR 0x1c +#define TCPR_DHCP_DOMASKDISCOV 0x1d +#define TCPR_DHCP_MASKSUPPLY 0x1e +#define TCPR_DHCP_DOROUTEDISC 0x1f +#define TCPR_DHCP_ROUTERSOLICIT 0x20 +#define TCPR_DHCP_STATICROUTE 0x21 +#define TCPR_DHCP_TRAILERENCAP 0x22 +#define TCPR_DHCP_ARPTIMEOUT 0x23 +#define TCPR_DHCP_ETHERENCAP 0x24 +#define TCPR_DHCP_TCPTTL 0x25 +#define TCPR_DHCP_TCPKEEPALIVE 0x26 #define TCPR_DHCP_TCPALIVEGARBAGE 0x27 -#define TCPR_DHCP_NISDOMAIN 0x28 -#define TCPR_DHCP_NISSERVERS 0x29 -#define TCPR_DHCP_NISTIMESERV 0x2a -#define TCPR_DHCP_VENDSPECIFIC 0x2b -#define TCPR_DHCP_NBNS 0x2c -#define TCPR_DHCP_NBDD 0x2d -#define TCPR_DHCP_NBTCPIP 0x2e -#define TCPR_DHCP_NBTCPSCOPE 0x2f -#define TCPR_DHCP_XFONT 0x30 -#define TCPR_DHCP_XDISPLAYMGR 0x31 -#define TCPR_DHCP_DISCOVERADDR 0x32 -#define TCPR_DHCP_LEASETIME 0x33 -#define TCPR_DHCP_OPTIONOVERLOAD 0x34 -#define TCPR_DHCP_MESSAGETYPE 0x35 -#define TCPR_DHCP_SERVIDENT 0x36 -#define TCPR_DHCP_PARAMREQUEST 0x37 -#define TCPR_DHCP_MESSAGE 0x38 -#define TCPR_DHCP_MAXMSGSIZE 0x39 -#define TCPR_DHCP_RENEWTIME 0x3a -#define TCPR_DHCP_REBINDTIME 0x3b -#define TCPR_DHCP_CLASSSID 0x3c -#define TCPR_DHCP_CLIENTID 0x3d -#define TCPR_DHCP_NISPLUSDOMAIN 0x40 -#define TCPR_DHCP_NISPLUSSERVERS 0x41 -#define TCPR_DHCP_MOBILEIPAGENT 0x44 -#define TCPR_DHCP_SMTPSERVER 0x45 -#define TCPR_DHCP_POP3SERVER 0x46 -#define TCPR_DHCP_NNTPSERVER 0x47 -#define TCPR_DHCP_WWWSERVER 0x48 -#define TCPR_DHCP_FINGERSERVER 0x49 -#define TCPR_DHCP_IRCSERVER 0x4a -#define TCPR_DHCP_STSERVER 0x4b -#define TCPR_DHCP_STDASERVER 0x4c -#define TCPR_DHCP_END 0xff - -#define TCPR_DHCP_MSGDISCOVER 0x01 -#define TCPR_DHCP_MSGOFFER 0x02 -#define TCPR_DHCP_MSGREQUEST 0x03 -#define TCPR_DHCP_MSGDECLINE 0x04 -#define TCPR_DHCP_MSGACK 0x05 -#define TCPR_DHCP_MSGNACK 0x06 -#define TCPR_DHCP_MSGRELEASE 0x07 -#define TCPR_DHCP_MSGINFORM 0x08 +#define TCPR_DHCP_NISDOMAIN 0x28 +#define TCPR_DHCP_NISSERVERS 0x29 +#define TCPR_DHCP_NISTIMESERV 0x2a +#define TCPR_DHCP_VENDSPECIFIC 0x2b +#define TCPR_DHCP_NBNS 0x2c +#define TCPR_DHCP_NBDD 0x2d +#define TCPR_DHCP_NBTCPIP 0x2e +#define TCPR_DHCP_NBTCPSCOPE 0x2f +#define TCPR_DHCP_XFONT 0x30 +#define TCPR_DHCP_XDISPLAYMGR 0x31 +#define TCPR_DHCP_DISCOVERADDR 0x32 +#define TCPR_DHCP_LEASETIME 0x33 +#define TCPR_DHCP_OPTIONOVERLOAD 0x34 +#define TCPR_DHCP_MESSAGETYPE 0x35 +#define TCPR_DHCP_SERVIDENT 0x36 +#define TCPR_DHCP_PARAMREQUEST 0x37 +#define TCPR_DHCP_MESSAGE 0x38 +#define TCPR_DHCP_MAXMSGSIZE 0x39 +#define TCPR_DHCP_RENEWTIME 0x3a +#define TCPR_DHCP_REBINDTIME 0x3b +#define TCPR_DHCP_CLASSSID 0x3c +#define TCPR_DHCP_CLIENTID 0x3d +#define TCPR_DHCP_NISPLUSDOMAIN 0x40 +#define TCPR_DHCP_NISPLUSSERVERS 0x41 +#define TCPR_DHCP_MOBILEIPAGENT 0x44 +#define TCPR_DHCP_SMTPSERVER 0x45 +#define TCPR_DHCP_POP3SERVER 0x46 +#define TCPR_DHCP_NNTPSERVER 0x47 +#define TCPR_DHCP_WWWSERVER 0x48 +#define TCPR_DHCP_FINGERSERVER 0x49 +#define TCPR_DHCP_IRCSERVER 0x4a +#define TCPR_DHCP_STSERVER 0x4b +#define TCPR_DHCP_STDASERVER 0x4c +#define TCPR_DHCP_END 0xff + +#define TCPR_DHCP_MSGDISCOVER 0x01 +#define TCPR_DHCP_MSGOFFER 0x02 +#define TCPR_DHCP_MSGREQUEST 0x03 +#define TCPR_DHCP_MSGDECLINE 0x04 +#define TCPR_DHCP_MSGACK 0x05 +#define TCPR_DHCP_MSGNACK 0x06 +#define TCPR_DHCP_MSGRELEASE 0x07 +#define TCPR_DHCP_MSGINFORM 0x08 }; - /* * Base DNSv4 header * Domain Name System * Base header size: 12/14 bytes */ -struct tcpr_dnsv4_hdr -{ - uint16_t h_len; /* length of the packet - only used with TCP */ - uint16_t id; /* DNS packet ID */ - uint16_t flags; /* DNS flags */ - uint16_t num_q; /* Number of questions */ - uint16_t num_answ_rr; /* Number of answer resource records */ - uint16_t num_auth_rr; /* Number of authority resource records */ - uint16_t num_addi_rr; /* Number of additional resource records */ +struct tcpr_dnsv4_hdr { + uint16_t h_len; /* length of the packet - only used with TCP */ + uint16_t id; /* DNS packet ID */ + uint16_t flags; /* DNS flags */ + uint16_t num_q; /* Number of questions */ + uint16_t num_answ_rr; /* Number of answer resource records */ + uint16_t num_auth_rr; /* Number of authority resource records */ + uint16_t num_addi_rr; /* Number of additional resource records */ }; #define TCPR_DNS_H TCPR_UDP_DNSV4_H -struct tcpr_dnsv4udp_hdr -{ - uint16_t id; /* DNS packet ID */ - uint16_t flags; /* DNS flags */ - uint16_t num_q; /* Number of questions */ - uint16_t num_answ_rr; /* Number of answer resource records */ - uint16_t num_auth_rr; /* Number of authority resource records */ - uint16_t num_addi_rr; /* Number of additional resource records */ +struct tcpr_dnsv4udp_hdr { + uint16_t id; /* DNS packet ID */ + uint16_t flags; /* DNS flags */ + uint16_t num_q; /* Number of questions */ + uint16_t num_answ_rr; /* Number of answer resource records */ + uint16_t num_auth_rr; /* Number of authority resource records */ + uint16_t num_addi_rr; /* Number of additional resource records */ }; /* * PPP over Serial with HDLC encapsulation for NetBSD */ -struct tcpr_pppserial_hdr -{ - uint8_t address; - uint8_t control; +struct tcpr_pppserial_hdr { + uint8_t address; + uint8_t control; uint16_t protocol; }; @@ -524,53 +500,51 @@ struct tcpr_pppserial_hdr * Ethernet II header * Static header size: 14 bytes */ -struct tcpr_ethernet_hdr -{ - uint8_t ether_dhost[ETHER_ADDR_LEN];/* destination ethernet address */ - uint8_t ether_shost[ETHER_ADDR_LEN];/* source ethernet address */ +struct tcpr_ethernet_hdr { + uint8_t ether_dhost[ETHER_ADDR_LEN]; /* destination ethernet address */ + uint8_t ether_shost[ETHER_ADDR_LEN]; /* source ethernet address */ uint16_t ether_type; /* protocol */ }; #ifndef ETHERTYPE_PUP -#define ETHERTYPE_PUP 0x0200 /* PUP protocol */ +#define ETHERTYPE_PUP 0x0200 /* PUP protocol */ #endif #ifndef ETHERTYPE_IP -#define ETHERTYPE_IP 0x0800 /* IP protocol */ +#define ETHERTYPE_IP 0x0800 /* IP protocol */ #endif #ifndef ETHERTYPE_ARP -#define ETHERTYPE_ARP 0x0806 /* addr. resolution protocol */ +#define ETHERTYPE_ARP 0x0806 /* addr. resolution protocol */ #endif #ifndef ETHERTYPE_REVARP -#define ETHERTYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ +#define ETHERTYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ #endif #ifndef ETHERTYPE_VLAN -#define ETHERTYPE_VLAN 0x8100 /* IEEE 802.1Q VLAN tagging */ +#define ETHERTYPE_VLAN 0x8100 /* IEEE 802.1Q VLAN tagging */ #endif #ifndef ETHERTYPE_EAP -#define ETHERTYPE_EAP 0x888e /* IEEE 802.1X EAP authentication */ +#define ETHERTYPE_EAP 0x888e /* IEEE 802.1X EAP authentication */ #endif #ifndef ETHERTYPE_MPLS -#define ETHERTYPE_MPLS 0x8847 /* MPLS */ +#define ETHERTYPE_MPLS 0x8847 /* MPLS */ #endif #ifndef ETHERTYPE_LOOPBACK -#define ETHERTYPE_LOOPBACK 0x9000 /* used to test interfaces */ +#define ETHERTYPE_LOOPBACK 0x9000 /* used to test interfaces */ #endif #ifndef ETHERTYPE_IP6 -#define ETHERTYPE_IP6 0x86DD /* IPv6 */ +#define ETHERTYPE_IP6 0x86DD /* IPv6 */ #endif #ifndef ETHERTYPE_Q_IN_Q -#define ETHERTYPE_Q_IN_Q 0x88A8 /* 802.1ad Service VLAN */ +#define ETHERTYPE_Q_IN_Q 0x88A8 /* 802.1ad Service VLAN */ #endif #ifndef ETHERTYPE_8021QINQ -#define ETHERTYPE_8021QINQ 0x9100 /* 802.1Q in Q VLAN */ +#define ETHERTYPE_8021QINQ 0x9100 /* 802.1Q in Q VLAN */ #endif #ifndef ETHERTYPE_MPLS_MULTI -#define ETHERTYPE_MPLS_MULTI 0x8848 /* MPLS multicast packet */ +#define ETHERTYPE_MPLS_MULTI 0x8848 /* MPLS multicast packet */ #endif -struct tcpr_ether_addr -{ - uint8_t ether_addr_octet[6]; /* Ethernet address */ +struct tcpr_ether_addr { + uint8_t ether_addr_octet[6]; /* Ethernet address */ }; /* @@ -582,92 +556,87 @@ struct tcpr_ether_addr * alignment of type. Therefore fddi_type (19 bytes in) * is specified as two uint8_ts. */ -struct tcpr_fddi_hdr -{ - uint8_t fddi_frame_control; /* Class/Format/Priority */ -#define TCPR_FDDI_LLC_FRAME 0x10 +struct tcpr_fddi_hdr { + uint8_t fddi_frame_control; /* Class/Format/Priority */ +#define TCPR_FDDI_LLC_FRAME 0x10 #define TCPR_FDDI_48BIT_ADDR 0x40 -#define TCPR_FDDI_FC_REQD TCPR_FDDI_LLC_FRAME | TCPR_FDDI_48BIT_ADDR - uint8_t fddi_dhost[FDDI_ADDR_LEN]; /* destination fddi address */ - uint8_t fddi_shost[FDDI_ADDR_LEN]; /* source fddi address */ - uint8_t fddi_llc_dsap; /* DSAP */ - uint8_t fddi_llc_ssap; /* SSAP */ - uint8_t fddi_llc_control_field; /* Class/Format/Priority */ - uint8_t fddi_llc_org_code[TCPR_ORG_CODE_SIZE]; /* Organization Code 3-bytes */ - uint8_t fddi_type; /* Protocol Type */ - uint8_t fddi_type1; /* see note above. */ -#define FDDI_TYPE_IP 0x0800 /* IP protocol */ -#define FDDI_TYPE_ARP 0x0806 /* addr. resolution protocol */ -#define FDDI_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ -}; - - -struct tcpr_fddi_addr -{ - uint8_t fddi_addr_octet[6]; /* FDDI address */ +#define TCPR_FDDI_FC_REQD TCPR_FDDI_LLC_FRAME | TCPR_FDDI_48BIT_ADDR + uint8_t fddi_dhost[FDDI_ADDR_LEN]; /* destination fddi address */ + uint8_t fddi_shost[FDDI_ADDR_LEN]; /* source fddi address */ + uint8_t fddi_llc_dsap; /* DSAP */ + uint8_t fddi_llc_ssap; /* SSAP */ + uint8_t fddi_llc_control_field; /* Class/Format/Priority */ + uint8_t fddi_llc_org_code[TCPR_ORG_CODE_SIZE]; /* Organization Code 3-bytes */ + uint8_t fddi_type; /* Protocol Type */ + uint8_t fddi_type1; /* see note above. */ +#define FDDI_TYPE_IP 0x0800 /* IP protocol */ +#define FDDI_TYPE_ARP 0x0806 /* addr. resolution protocol */ +#define FDDI_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ }; +struct tcpr_fddi_addr { + uint8_t fddi_addr_octet[6]; /* FDDI address */ +}; /* * GRE header - RFC 1701 & 2637 * Generic Routing Encapsulation (GRE) * Base header size: 4 bytes */ -struct tcpr_gre_hdr -{ +struct tcpr_gre_hdr { uint16_t flags_ver; -#define GRE_CSUM 0x8000 -#define GRE_ROUTING 0x4000 -#define GRE_KEY 0x2000 -#define GRE_SEQ 0x1000 -#define GRE_STRICT 0x0800 -#define GRE_REC 0x0700 -#define GRE_ACK 0x0080 +#define GRE_CSUM 0x8000 +#define GRE_ROUTING 0x4000 +#define GRE_KEY 0x2000 +#define GRE_SEQ 0x1000 +#define GRE_STRICT 0x0800 +#define GRE_REC 0x0700 +#define GRE_ACK 0x0080 -#define GRE_FLAGS_MASK 0x00F8 -#define GRE_VERSION_MASK 0x0007 +#define GRE_FLAGS_MASK 0x00F8 +#define GRE_VERSION_MASK 0x0007 -#define GRE_VERSION_0 0x0000 -#define GRE_VERSION_1 0x0001 +#define GRE_VERSION_0 0x0000 +#define GRE_VERSION_1 0x0001 uint16_t type; -#define GRE_SNA 0x0004 -#define GRE_OSI_NETWORK_LAYER 0x00FE -#define GRE_PUP 0x0200 -#define GRE_XNS 0x0600 -#define GRE_IP 0x0800 -#define GRE_CHAOS 0x0804 -#define GRE_RFC_826_ARP 0x0806 -#define GRE_FRAME_RELAY_ARP 0x0808 -#define GRE_VINES 0x0BAD -#define GRE_VINES_ECHO 0x0BAE -#define GRE_VINES_LOOPBACK 0x0BAF -#define GRE_DECNET 0x6003 -#define GRE_TRANSPARENT_ETHERNET_BRIDGING 0x6558 -#define GRE_RAW_FRAME_RELAY 0x6559 -#define GRE_APOLLO_DOMAIN 0x8019 -#define GRE_ETHERTALK 0x809B -#define GRE_NOVELL_IPX 0x8137 -#define GRE_RFC_1144_TCP_IP_COMPRESSION 0x876B -#define GRE_IP_AUTONOMOUS_SYSTEMS 0x876C -#define GRE_SECURE_DATA 0x876D -#define GRE_PPP 0x880b /* taken from RFC 2637 */ +#define GRE_SNA 0x0004 +#define GRE_OSI_NETWORK_LAYER 0x00FE +#define GRE_PUP 0x0200 +#define GRE_XNS 0x0600 +#define GRE_IP 0x0800 +#define GRE_CHAOS 0x0804 +#define GRE_RFC_826_ARP 0x0806 +#define GRE_FRAME_RELAY_ARP 0x0808 +#define GRE_VINES 0x0BAD +#define GRE_VINES_ECHO 0x0BAE +#define GRE_VINES_LOOPBACK 0x0BAF +#define GRE_DECNET 0x6003 +#define GRE_TRANSPARENT_ETHERNET_BRIDGING 0x6558 +#define GRE_RAW_FRAME_RELAY 0x6559 +#define GRE_APOLLO_DOMAIN 0x8019 +#define GRE_ETHERTALK 0x809B +#define GRE_NOVELL_IPX 0x8137 +#define GRE_RFC_1144_TCP_IP_COMPRESSION 0x876B +#define GRE_IP_AUTONOMOUS_SYSTEMS 0x876C +#define GRE_SECURE_DATA 0x876D +#define GRE_PPP 0x880b /* taken from RFC 2637 */ union { - struct { - uint16_t sum; /* optional */ - uint16_t offset; /* optional */ - uint32_t key; /* optional */ - uint32_t seq; /* optional */ - } _gre; - - struct { - uint16_t payload_s; /* optional */ - uint16_t callID; /* optional */ - uint32_t seq; /* optional */ - uint32_t ack; /* optional */ - } _egre; - }_data; + struct { + uint16_t sum; /* optional */ + uint16_t offset; /* optional */ + uint32_t key; /* optional */ + uint32_t seq; /* optional */ + } _gre; + + struct { + uint16_t payload_s; /* optional */ + uint16_t callID; /* optional */ + uint32_t seq; /* optional */ + uint32_t ack; /* optional */ + } _egre; + } _data; #define gre_sum _data._gre.sum #define gre_offset _data._gre.offset @@ -680,7 +649,6 @@ struct tcpr_gre_hdr #define egre_ack _data._egre.ack }; - #ifndef IPPROTO_GRE #define IPPROTO_GRE 47 #endif @@ -690,60 +658,57 @@ struct tcpr_gre_hdr * This is used for GRE as the Routing field is a list of SREs - RFC 1701 * Base header size: 4 bytes */ -struct tcpr_gre_sre_hdr -{ - uint16_t af; /* address family */ +struct tcpr_gre_sre_hdr { + uint16_t af; /* address family */ uint8_t sre_offset; uint8_t sre_length; uint8_t *routing; }; - /* * IPv4 header * Internet Protocol, version 4 * Static header size: 20 bytes */ -struct tcpr_ipv4_hdr -{ +struct tcpr_ipv4_hdr { #ifdef WORDS_BIGENDIAN - uint8_t ip_v:4, /* version */ - ip_hl:4; /* header length */ + uint8_t ip_v:4, /* version */ + ip_hl:4; /* header length */ #else - uint8_t ip_hl:4, /* header length */ - ip_v:4; /* version */ + uint8_t ip_hl:4, /* header length */ + ip_v:4; /* version */ #endif - uint8_t ip_tos; /* type of service */ + uint8_t ip_tos; /* type of service */ #ifndef IPTOS_LOWDELAY -#define IPTOS_LOWDELAY 0x10 +#define IPTOS_LOWDELAY 0x10 #endif #ifndef IPTOS_THROUGHPUT -#define IPTOS_THROUGHPUT 0x08 +#define IPTOS_THROUGHPUT 0x08 #endif #ifndef IPTOS_RELIABILITY -#define IPTOS_RELIABILITY 0x04 +#define IPTOS_RELIABILITY 0x04 #endif #ifndef IPTOS_LOWCOST -#define IPTOS_LOWCOST 0x02 +#define IPTOS_LOWCOST 0x02 #endif - uint16_t ip_len; /* total length */ - uint16_t ip_id; /* identification */ + uint16_t ip_len; /* total length */ + uint16_t ip_id; /* identification */ uint16_t ip_off; #ifndef IP_RF -#define IP_RF 0x8000 /* reserved fragment flag */ +#define IP_RF 0x8000 /* reserved fragment flag */ #endif #ifndef IP_DF -#define IP_DF 0x4000 /* don't fragment flag */ +#define IP_DF 0x4000 /* don't fragment flag */ #endif #ifndef IP_MF -#define IP_MF 0x2000 /* more fragments flag */ +#define IP_MF 0x2000 /* more fragments flag */ #endif #ifndef IP_OFFMASK -#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ +#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ #endif - uint8_t ip_ttl; /* time to live */ - uint8_t ip_p; /* protocol */ - uint16_t ip_sum; /* checksum */ + uint8_t ip_ttl; /* time to live */ + uint8_t ip_p; /* protocol */ + uint16_t ip_sum; /* checksum */ struct in_addr ip_src, ip_dst; /* source and dest address */ }; @@ -751,38 +716,36 @@ struct tcpr_ipv4_hdr * IP options */ #ifndef IPOPT_EOL -#define IPOPT_EOL 0 /* end of option list */ +#define IPOPT_EOL 0 /* end of option list */ #endif #ifndef IPOPT_NOP -#define IPOPT_NOP 1 /* no operation */ +#define IPOPT_NOP 1 /* no operation */ #endif #ifndef IPOPT_RR -#define IPOPT_RR 7 /* record packet route */ +#define IPOPT_RR 7 /* record packet route */ #endif #ifndef IPOPT_TS -#define IPOPT_TS 68 /* timestamp */ +#define IPOPT_TS 68 /* timestamp */ #endif #ifndef IPOPT_SECURITY -#define IPOPT_SECURITY 130 /* provide s,c,h,tcc */ +#define IPOPT_SECURITY 130 /* provide s,c,h,tcc */ #endif #ifndef IPOPT_LSRR -#define IPOPT_LSRR 131 /* loose source route */ +#define IPOPT_LSRR 131 /* loose source route */ #endif #ifndef IPOPT_SATID -#define IPOPT_SATID 136 /* satnet id */ +#define IPOPT_SATID 136 /* satnet id */ #endif #ifndef IPOPT_SSRR -#define IPOPT_SSRR 137 /* strict source route */ +#define IPOPT_SSRR 137 /* strict source route */ #endif -struct tcpr_in6_addr -{ - union - { - u_int8_t __u6_addr8[16]; - u_int16_t __u6_addr16[8]; - u_int32_t __u6_addr32[4]; - } __u6_addr; /* 128-bit IP6 address */ +struct tcpr_in6_addr { + union { + u_int8_t __u6_addr8[16]; + u_int16_t __u6_addr16[8]; + u_int32_t __u6_addr32[4]; + } __u6_addr; /* 128-bit IP6 address */ }; #define tcpr_s6_addr __u6_addr.__u6_addr8 #define tcpr_s6_addr8 __u6_addr.__u6_addr8 @@ -794,26 +757,24 @@ struct tcpr_in6_addr * Internet Protocol, version 6 * Static header size: 40 bytes */ -struct tcpr_ipv6_hdr -{ - uint8_t ip_flags[4]; /* version, traffic class, flow label */ - uint16_t ip_len; /* total length */ - uint8_t ip_nh; /* next header */ - uint8_t ip_hl; /* hop limit */ +struct tcpr_ipv6_hdr { + uint8_t ip_flags[4]; /* version, traffic class, flow label */ + uint16_t ip_len; /* total length */ + uint8_t ip_nh; /* next header */ + uint8_t ip_hl; /* hop limit */ struct tcpr_in6_addr ip_src, ip_dst; /* source and dest address */ }; -struct tcpr_ipv6_ext_hdr_base -{ - uint8_t ip_nh; /* next header */ - uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ +struct tcpr_ipv6_ext_hdr_base { + uint8_t ip_nh; /* next header */ + uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ /* some more bytes are always here, but we don't know what kind */ }; #define TCPR_IPV6_NH_NO_NEXT 59 -#define TCPR_IPV6_NH_IPV6 41 -#define TCPR_IPV6_NH_ESP 50 -#define TCPR_IPV6_NH_AH 51 +#define TCPR_IPV6_NH_IPV6 41 +#define TCPR_IPV6_NH_ESP 50 +#define TCPR_IPV6_NH_AH 51 /* * IPv6 frag header @@ -821,12 +782,11 @@ struct tcpr_ipv6_ext_hdr_base * Static header size: 8 bytes */ #define TCPR_IPV6_NH_FRAGMENT 44 -struct tcpr_ipv6_frag_hdr -{ - uint8_t ip_nh; /* next header */ - uint8_t ip_reserved; /* reserved */ - uint16_t ip_frag; /* fragmentation stuff */ - uint32_t ip_id; /* id */ +struct tcpr_ipv6_frag_hdr { + uint8_t ip_nh; /* next header */ + uint8_t ip_reserved; /* reserved */ + uint16_t ip_frag; /* fragmentation stuff */ + uint32_t ip_id; /* id */ }; /* @@ -834,13 +794,12 @@ struct tcpr_ipv6_frag_hdr * Internet Protocol, version 6 * Base header size: 4 bytes */ -#define TCPR_IPV6_NH_ROUTING 43 -struct tcpr_ipv6_routing_hdr -{ - uint8_t ip_nh; /* next header */ - uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ - uint8_t ip_rtype; /* routing type */ - uint8_t ip_segments; /* segments left */ +#define TCPR_IPV6_NH_ROUTING 43 +struct tcpr_ipv6_routing_hdr { + uint8_t ip_nh; /* next header */ + uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ + uint8_t ip_rtype; /* routing type */ + uint8_t ip_segments; /* segments left */ /* routing information allocated dynamically */ }; @@ -850,10 +809,9 @@ struct tcpr_ipv6_routing_hdr * Base header size: 2 bytes */ #define TCPR_IPV6_NH_DESTOPTS 60 -struct tcpr_ipv6_destopts_hdr -{ - uint8_t ip_nh; /* next header */ - uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ +struct tcpr_ipv6_destopts_hdr { + uint8_t ip_nh; /* next header */ + uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ /* destination options information allocated dynamically */ }; @@ -862,11 +820,10 @@ struct tcpr_ipv6_destopts_hdr * Internet Protocol, version 6 * Base header size: 2 bytes */ -#define TCPR_IPV6_NH_HBH 0 -struct tcpr_ipv6_hbhopts_hdr -{ - uint8_t ip_nh; /* next header */ - uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ +#define TCPR_IPV6_NH_HBH 0 +struct tcpr_ipv6_hbhopts_hdr { + uint8_t ip_nh; /* next header */ + uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ /* destination options information allocated dynamically */ }; @@ -876,193 +833,183 @@ struct tcpr_ipv6_hbhopts_hdr * Base header size: 8 bytes */ #ifndef IPPROTO_ICMP6 -#define IPPROTO_ICMP6 0x3a +#define IPPROTO_ICMP6 0x3a #endif -struct tcpr_icmpv6_hdr -{ - uint8_t icmp_type; /* ICMP type */ +struct tcpr_icmpv6_hdr { + uint8_t icmp_type; /* ICMP type */ #ifndef ICMP6_ECHO -#define ICMP6_ECHO 128 +#define ICMP6_ECHO 128 #endif #ifndef ICMP6_ECHOREPLY -#define ICMP6_ECHOREPLY 129 +#define ICMP6_ECHOREPLY 129 #endif #ifndef ICMP6_UNREACH -#define ICMP6_UNREACH 1 +#define ICMP6_UNREACH 1 #endif #ifndef ICMP6_PKTTOOBIG -#define ICMP6_PKTTOOBIG 2 +#define ICMP6_PKTTOOBIG 2 #endif #ifndef ICMP6_TIMXCEED -#define ICMP6_TIMXCEED 3 +#define ICMP6_TIMXCEED 3 #endif #ifndef ICMP6_PARAMPROB -#define ICMP6_PARAMPROB 4 +#define ICMP6_PARAMPROB 4 #endif - uint8_t icmp_code; /* ICMP code */ - uint16_t icmp_sum; /* ICMP Checksum */ - uint16_t id; /* ICMP id */ - uint16_t seq; /* ICMP sequence number */ + uint8_t icmp_code; /* ICMP code */ + uint16_t icmp_sum; /* ICMP Checksum */ + uint16_t id; /* ICMP id */ + uint16_t seq; /* ICMP sequence number */ }; - - /* * ICMP header * Internet Control Message Protocol * Base header size: 4 bytes */ -struct tcpr_icmpv4_hdr -{ - uint8_t icmp_type; /* ICMP type */ -#ifndef ICMP_ECHOREPLY -#define ICMP_ECHOREPLY 0 +struct tcpr_icmpv4_hdr { + uint8_t icmp_type; /* ICMP type */ +#ifndef ICMP_ECHOREPLY +#define ICMP_ECHOREPLY 0 #endif -#ifndef ICMP_UNREACH -#define ICMP_UNREACH 3 +#ifndef ICMP_UNREACH +#define ICMP_UNREACH 3 #endif -#ifndef ICMP_SOURCEQUENCH -#define ICMP_SOURCEQUENCH 4 +#ifndef ICMP_SOURCEQUENCH +#define ICMP_SOURCEQUENCH 4 #endif -#ifndef ICMP_REDIRECT -#define ICMP_REDIRECT 5 +#ifndef ICMP_REDIRECT +#define ICMP_REDIRECT 5 #endif -#ifndef ICMP_ECHO -#define ICMP_ECHO 8 +#ifndef ICMP_ECHO +#define ICMP_ECHO 8 #endif -#ifndef ICMP_ROUTERADVERT -#define ICMP_ROUTERADVERT 9 +#ifndef ICMP_ROUTERADVERT +#define ICMP_ROUTERADVERT 9 #endif -#ifndef ICMP_ROUTERSOLICIT -#define ICMP_ROUTERSOLICIT 10 +#ifndef ICMP_ROUTERSOLICIT +#define ICMP_ROUTERSOLICIT 10 #endif -#ifndef ICMP_TIMXCEED -#define ICMP_TIMXCEED 11 +#ifndef ICMP_TIMXCEED +#define ICMP_TIMXCEED 11 #endif -#ifndef ICMP_PARAMPROB -#define ICMP_PARAMPROB 12 +#ifndef ICMP_PARAMPROB +#define ICMP_PARAMPROB 12 #endif -#ifndef ICMP_TSTAMP -#define ICMP_TSTAMP 13 +#ifndef ICMP_TSTAMP +#define ICMP_TSTAMP 13 #endif -#ifndef ICMP_TSTAMPREPLY -#define ICMP_TSTAMPREPLY 14 +#ifndef ICMP_TSTAMPREPLY +#define ICMP_TSTAMPREPLY 14 #endif -#ifndef ICMP_IREQ -#define ICMP_IREQ 15 +#ifndef ICMP_IREQ +#define ICMP_IREQ 15 #endif -#ifndef ICMP_IREQREPLY -#define ICMP_IREQREPLY 16 +#ifndef ICMP_IREQREPLY +#define ICMP_IREQREPLY 16 #endif -#ifndef ICMP_MASKREQ -#define ICMP_MASKREQ 17 +#ifndef ICMP_MASKREQ +#define ICMP_MASKREQ 17 #endif -#ifndef ICMP_MASKREPLY -#define ICMP_MASKREPLY 18 +#ifndef ICMP_MASKREPLY +#define ICMP_MASKREPLY 18 #endif - uint8_t icmp_code; /* ICMP code */ -#ifndef ICMP_UNREACH_NET -#define ICMP_UNREACH_NET 0 + uint8_t icmp_code; /* ICMP code */ +#ifndef ICMP_UNREACH_NET +#define ICMP_UNREACH_NET 0 #endif -#ifndef ICMP_UNREACH_HOST -#define ICMP_UNREACH_HOST 1 +#ifndef ICMP_UNREACH_HOST +#define ICMP_UNREACH_HOST 1 #endif -#ifndef ICMP_UNREACH_PROTOCOL -#define ICMP_UNREACH_PROTOCOL 2 +#ifndef ICMP_UNREACH_PROTOCOL +#define ICMP_UNREACH_PROTOCOL 2 #endif -#ifndef ICMP_UNREACH_PORT -#define ICMP_UNREACH_PORT 3 +#ifndef ICMP_UNREACH_PORT +#define ICMP_UNREACH_PORT 3 #endif -#ifndef ICMP_UNREACH_NEEDFRAG -#define ICMP_UNREACH_NEEDFRAG 4 +#ifndef ICMP_UNREACH_NEEDFRAG +#define ICMP_UNREACH_NEEDFRAG 4 #endif -#ifndef ICMP_UNREACH_SRCFAIL -#define ICMP_UNREACH_SRCFAIL 5 +#ifndef ICMP_UNREACH_SRCFAIL +#define ICMP_UNREACH_SRCFAIL 5 #endif -#ifndef ICMP_UNREACH_NET_UNKNOWN -#define ICMP_UNREACH_NET_UNKNOWN 6 +#ifndef ICMP_UNREACH_NET_UNKNOWN +#define ICMP_UNREACH_NET_UNKNOWN 6 #endif -#ifndef ICMP_UNREACH_HOST_UNKNOWN -#define ICMP_UNREACH_HOST_UNKNOWN 7 +#ifndef ICMP_UNREACH_HOST_UNKNOWN +#define ICMP_UNREACH_HOST_UNKNOWN 7 #endif -#ifndef ICMP_UNREACH_ISOLATED -#define ICMP_UNREACH_ISOLATED 8 +#ifndef ICMP_UNREACH_ISOLATED +#define ICMP_UNREACH_ISOLATED 8 #endif -#ifndef ICMP_UNREACH_NET_PROHIB -#define ICMP_UNREACH_NET_PROHIB 9 +#ifndef ICMP_UNREACH_NET_PROHIB +#define ICMP_UNREACH_NET_PROHIB 9 #endif -#ifndef ICMP_UNREACH_HOST_PROHIB -#define ICMP_UNREACH_HOST_PROHIB 10 +#ifndef ICMP_UNREACH_HOST_PROHIB +#define ICMP_UNREACH_HOST_PROHIB 10 #endif -#ifndef ICMP_UNREACH_TOSNET -#define ICMP_UNREACH_TOSNET 11 +#ifndef ICMP_UNREACH_TOSNET +#define ICMP_UNREACH_TOSNET 11 #endif -#ifndef ICMP_UNREACH_TOSHOST -#define ICMP_UNREACH_TOSHOST 12 +#ifndef ICMP_UNREACH_TOSHOST +#define ICMP_UNREACH_TOSHOST 12 #endif -#ifndef ICMP_UNREACH_FILTER_PROHIB -#define ICMP_UNREACH_FILTER_PROHIB 13 +#ifndef ICMP_UNREACH_FILTER_PROHIB +#define ICMP_UNREACH_FILTER_PROHIB 13 #endif -#ifndef ICMP_UNREACH_HOST_PRECEDENCE -#define ICMP_UNREACH_HOST_PRECEDENCE 14 +#ifndef ICMP_UNREACH_HOST_PRECEDENCE +#define ICMP_UNREACH_HOST_PRECEDENCE 14 #endif -#ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF -#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 +#ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF +#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 #endif -#ifndef ICMP_REDIRECT_NET -#define ICMP_REDIRECT_NET 0 +#ifndef ICMP_REDIRECT_NET +#define ICMP_REDIRECT_NET 0 #endif -#ifndef ICMP_REDIRECT_HOST -#define ICMP_REDIRECT_HOST 1 +#ifndef ICMP_REDIRECT_HOST +#define ICMP_REDIRECT_HOST 1 #endif -#ifndef ICMP_REDIRECT_TOSNET -#define ICMP_REDIRECT_TOSNET 2 +#ifndef ICMP_REDIRECT_TOSNET +#define ICMP_REDIRECT_TOSNET 2 #endif -#ifndef ICMP_REDIRECT_TOSHOST -#define ICMP_REDIRECT_TOSHOST 3 +#ifndef ICMP_REDIRECT_TOSHOST +#define ICMP_REDIRECT_TOSHOST 3 #endif -#ifndef ICMP_TIMXCEED_INTRANS -#define ICMP_TIMXCEED_INTRANS 0 +#ifndef ICMP_TIMXCEED_INTRANS +#define ICMP_TIMXCEED_INTRANS 0 #endif -#ifndef ICMP_TIMXCEED_REASS -#define ICMP_TIMXCEED_REASS 1 +#ifndef ICMP_TIMXCEED_REASS +#define ICMP_TIMXCEED_REASS 1 #endif -#ifndef ICMP_PARAMPROB_OPTABSENT -#define ICMP_PARAMPROB_OPTABSENT 1 +#ifndef ICMP_PARAMPROB_OPTABSENT +#define ICMP_PARAMPROB_OPTABSENT 1 #endif - uint16_t icmp_sum; /* ICMP Checksum */ + uint16_t icmp_sum; /* ICMP Checksum */ - union - { - struct - { - uint16_t id; /* ICMP id */ - uint16_t seq;/* ICMP sequence number */ + union { + struct { + uint16_t id; /* ICMP id */ + uint16_t seq; /* ICMP sequence number */ } echo; #undef icmp_id #undef icmp_seq -#define icmp_id hun.echo.id -#define icmp_seq hun.echo.seq +#define icmp_id hun.echo.id +#define icmp_seq hun.echo.seq uint32_t gateway; /* gateway host */ - struct - { - uint16_t pad;/* padding */ - uint16_t mtu;/* MTU size */ + struct { + uint16_t pad; /* padding */ + uint16_t mtu; /* MTU size */ } frag; } hun; - union - { - struct - { + union { + struct { uint32_t its_otime; uint32_t its_rtime; uint32_t its_ttime; } ts; - struct - { + struct { struct tcpr_ipv4_hdr idi_ip; /* options and then 64 bits of data */ } ip; @@ -1070,46 +1017,43 @@ struct tcpr_icmpv4_hdr int8_t data[1]; #undef icmp_mask -#define icmp_mask dun.mask +#define icmp_mask dun.mask #undef icmp_data -#define icmp_data dun.data +#define icmp_data dun.data #undef icmp_otime -#define icmp_otime dun.ts.its_otime +#define icmp_otime dun.ts.its_otime #undef icmp_rtime -#define icmp_rtime dun.ts.its_rtime +#define icmp_rtime dun.ts.its_rtime #undef icmp_ttime -#define icmp_ttime dun.ts.its_ttime - }dun; +#define icmp_ttime dun.ts.its_ttime + } dun; }; - /* * IGMP header * Internet Group Message Protocol * Static header size: 8 bytes */ -struct tcpr_igmp_hdr -{ - uint8_t igmp_type; /* IGMP type */ +struct tcpr_igmp_hdr { + uint8_t igmp_type; /* IGMP type */ #ifndef IGMP_MEMBERSHIP_QUERY -#define IGMP_MEMBERSHIP_QUERY 0x11 /* membership query */ +#define IGMP_MEMBERSHIP_QUERY 0x11 /* membership query */ #endif #ifndef IGMP_V1_MEMBERSHIP_REPORT -#define IGMP_V1_MEMBERSHIP_REPORT 0x12 /* Ver. 1 membership report */ +#define IGMP_V1_MEMBERSHIP_REPORT 0x12 /* Ver. 1 membership report */ #endif #ifndef IGMP_V2_MEMBERSHIP_REPORT -#define IGMP_V2_MEMBERSHIP_REPORT 0x16 /* Ver. 2 membership report */ +#define IGMP_V2_MEMBERSHIP_REPORT 0x16 /* Ver. 2 membership report */ #endif #ifndef IGMP_LEAVE_GROUP -#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ +#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ #endif - uint8_t igmp_code; /* IGMP code */ - uint16_t igmp_sum; /* IGMP checksum */ - struct in_addr igmp_group;/* IGMP host IP */ + uint8_t igmp_code; /* IGMP code */ + uint16_t igmp_sum; /* IGMP checksum */ + struct in_addr igmp_group; /* IGMP host IP */ }; - /* * IPSEC header * Internet Protocol Security Protocol @@ -1118,36 +1062,32 @@ struct tcpr_igmp_hdr * Authentication Header Static Size: 16 bytes */ #ifndef IPPROTO_ESP -#define IPPROTO_ESP 50 /* not everyone's got this */ +#define IPPROTO_ESP 50 /* not everyone's got this */ #endif -struct tcpr_esp_hdr -{ - uint32_t esp_spi; /* security parameter index */ - uint32_t esp_seq; /* ESP sequence number */ - uint32_t esp_iv; /* initialization vector */ +struct tcpr_esp_hdr { + uint32_t esp_spi; /* security parameter index */ + uint32_t esp_seq; /* ESP sequence number */ + uint32_t esp_iv; /* initialization vector */ }; -struct tcpr_esp_ftr -{ - uint8_t esp_pad_len; /* padding length */ - uint8_t esp_nh; /* next header pointer */ - int8_t *esp_auth; /* authentication data */ +struct tcpr_esp_ftr { + uint8_t esp_pad_len; /* padding length */ + uint8_t esp_nh; /* next header pointer */ + int8_t *esp_auth; /* authentication data */ }; #ifndef IPPROTO_AH -#define IPPROTO_AH 51 /* not everyone's got this */ +#define IPPROTO_AH 51 /* not everyone's got this */ #endif -struct tcpr_ah_hdr -{ - uint8_t ah_nh; /* next header */ - uint8_t ah_len; /* payload length */ - uint16_t ah_res; /* reserved */ - uint32_t ah_spi; /* security parameter index */ - uint32_t ah_seq; /* AH sequence number */ - uint32_t ah_auth; /* authentication data */ +struct tcpr_ah_hdr { + uint8_t ah_nh; /* next header */ + uint8_t ah_len; /* payload length */ + uint16_t ah_res; /* reserved */ + uint32_t ah_spi; /* security parameter index */ + uint32_t ah_seq; /* AH sequence number */ + uint32_t ah_auth; /* authentication data */ }; - /* * ISL header * Cisco Inter-Switch Link @@ -1157,53 +1097,50 @@ struct tcpr_ah_hdr * For checksum stuff -- IANA says 135-254 is "unassigned" as of 12.2001. * Let's hope this one stays that way for a while! */ -#define TCPR_PROTO_ISL 201 -struct tcpr_isl_hdr -{ - uint8_t isl_dhost[5]; /* destination address "01:00:0c:00:00" */ +#define TCPR_PROTO_ISL 201 +struct tcpr_isl_hdr { + uint8_t isl_dhost[5]; /* destination address "01:00:0c:00:00" */ #ifdef WORDS_BIGENDIAN - uint8_t isl_user:4, /* user defined bits */ - isl_type:4; /* type of frame */ + uint8_t isl_user:4, /* user defined bits */ + isl_type:4; /* type of frame */ #else - uint8_t isl_type:4, /* type of frame */ - isl_user:4; /* user defined bits */ -#endif - uint8_t isl_shost[6]; /* source address */ - uint16_t isl_len; /* total length of packet - 18 bytes */ - uint8_t isl_snap[6]; /* 0xaaaa03 + vendor code */ - uint16_t isl_vid; /* 15 bit VLAN ID, 1 bit BPDU / CDP indicator */ - uint16_t isl_index; /* port index */ - uint16_t isl_reserved; /* used for FDDI and token ring */ + uint8_t isl_type:4, /* type of frame */ + isl_user:4; /* user defined bits */ +#endif + uint8_t isl_shost[6]; /* source address */ + uint16_t isl_len; /* total length of packet - 18 bytes */ + uint8_t isl_snap[6]; /* 0xaaaa03 + vendor code */ + uint16_t isl_vid; /* 15 bit VLAN ID, 1 bit BPDU / CDP indicator */ + uint16_t isl_index; /* port index */ + uint16_t isl_reserved; /* used for FDDI and token ring */ /* ethernet frame and 4 byte isl crc */ }; #ifndef IPPROTO_OSPF -#define IPPROTO_OSPF 89 /* not everyone's got this */ +#define IPPROTO_OSPF 89 /* not everyone's got this */ #endif -#define IPPROTO_OSPF_LSA 890 /* made this up. Hope it's unused */ -#define TCPR_MODX 4102 /* used in LSA checksum */ +#define IPPROTO_OSPF_LSA 890 /* made this up. Hope it's unused */ +#define TCPR_MODX 4102 /* used in LSA checksum */ /* * Options used in multiple OSPF packets * More info can be found in section A.2 of RFC 2328. */ -#define TCPR_OPT_EBIT 0x02 /* describes the way AS-external-LSAs are flooded */ +#define TCPR_OPT_EBIT 0x02 /* describes the way AS-external-LSAs are flooded */ #define TCPR_OPT_MCBIT 0x04 /* whether or not IP multicast dgrams are fwdd */ #define TCPR_OPT_NPBIT 0x08 /* describes handling of type-7 LSAs */ #define TCPR_OPT_EABIT 0x10 /* rtr's willingness to send/recv EA-LSAs */ #define TCPR_OPT_DCBIT 0x20 /* describes handling of demand circuits */ - /* * MPLS header * Multi-Protocol Label Switching * Static header size: 4 bytes */ -struct tcpr_mpls_hdr -{ - uint32_t mpls_les; /* 20 bits label, 3 bits exp, 1 bit bos, ttl */ -#define TCPR_MPLS_BOS_ON 1 -#define TCPR_MPLS_BOS_OFF 0 +struct tcpr_mpls_hdr { + uint32_t mpls_les; /* 20 bits label, 3 bits exp, 1 bit bos, ttl */ +#define TCPR_MPLS_BOS_ON 1 +#define TCPR_MPLS_BOS_OFF 0 }; /* @@ -1211,315 +1148,287 @@ struct tcpr_mpls_hdr * Network Time Protocol * Static header size: 48 bytes */ -struct tcpr_ntp_hdr_l_fp /* int32_t floating point (64-bit) */ -{ - uint32_t integer; /* integer */ - uint32_t fraction; /* fraction */ -}; - -struct tcpr_ntp_hdr_s_fp /* int16_t floating point (32-bit) */ -{ - uint16_t integer; /* integer */ - uint16_t fraction; /* fraction */ +struct tcpr_ntp_hdr_l_fp /* int32_t floating point (64-bit) */ +{ + uint32_t integer; /* integer */ + uint32_t fraction; /* fraction */ +}; + +struct tcpr_ntp_hdr_s_fp /* int16_t floating point (32-bit) */ +{ + uint16_t integer; /* integer */ + uint16_t fraction; /* fraction */ +}; + +struct tcpr_ntp_hdr { + uint8_t ntp_li_vn_mode; /* leap indicator, version, mode */ +#define TCPR_NTP_LI_NW 0x0 /* no warning */ +#define TCPR_NTP_LI_AS 0x1 /* last minute has 61 seconds */ +#define TCPR_NTP_LI_DS 0x2 /* last minute has 59 seconds */ +#define TCPR_NTP_LI_AC 0x3 /* alarm condition */ + +#define TCPR_NTP_VN_2 0x2 /* version 2 */ +#define TCPR_NTP_VN_3 0x3 /* version 3 */ +#define TCPR_NTP_VN_4 0x4 /* version 4 */ + +#define TCPR_NTP_MODE_R 0x0 /* reserved */ +#define TCPR_NTP_MODE_A 0x1 /* symmetric active */ +#define TCPR_NTP_MODE_P 0x2 /* symmetric passive */ +#define TCPR_NTP_MODE_C 0x3 /* client */ +#define TCPR_NTP_MODE_S 0x4 /* server */ +#define TCPR_NTP_MODE_B 0x5 /* broadcast */ +#define TCPR_NTP_MODE_RC 0x6 /* reserved for NTP control message */ +#define TCPR_NTP_MODE_RP 0x7 /* reserved for private use */ + uint8_t ntp_stratum; /* stratum */ +#define TCPR_NTP_STRATUM_UNAVAIL 0x0 /* unspecified or unavailable */ +#define TCPR_NTP_STRATUM_PRIMARY 0x1 /* primary reference (radio clock) */ + /* 2 - 15 is secondary */ + /* 16 - 255 is reserved */ + uint8_t ntp_poll; /* poll interval (should be 4 - 12) */ + uint8_t ntp_precision; /* local clock precision */ + struct tcpr_ntp_hdr_s_fp ntp_delay; /* roundtrip delay */ + struct tcpr_ntp_hdr_s_fp ntp_dispersion; /* nominal error */ + uint32_t ntp_reference_id; /* reference source id */ +#define TCPR_NTP_REF_LOCAL 0x4c4f434c /* uncalibrated local clock */ +#define TCPR_NTP_REF_PPS 0x50505300 /* atomic / pulse-per-second clock */ +#define TCPR_NTP_REF_ACTS 0x41435453 /* NIST dialup modem */ +#define TCPR_NTP_REF_USNO 0x55534e4f /* USNO modem service */ +#define TCPR_NTP_REF_PTB 0x50544200 /* PTB (German) modem service */ +#define TCPR_NTP_REF_TDF 0x54444600 /* Allouis (French) radio */ +#define TCPR_NTP_REF_DCF 0x44434600 /* Mainflingen (German) radio */ +#define TCPR_NTP_REF_MSF 0x4d534600 /* Rugby (UK) radio */ +#define TCPR_NTP_REF_WWV 0x57575600 /* Ft Collins (US) radio */ +#define TCPR_NTP_REF_WWVB 0x57575642 /* Boulder (US) radio */ +#define TCPR_NTP_REF_WWVH 0x57575648 /* Kaui Hawaii (US) radio */ +#define TCPR_NTP_REF_CHU 0x43485500 /* Ottaha (Canada) radio */ +#define TCPR_NTP_REF_LORC 0x4c4f5243 /* LORAN-C radionavigation */ +#define TCPR_NTP_REF_OMEG 0x4f4d4547 /* OMEGA radionavigation */ +#define TCPR_NTP_REF_GPS 0x47505300 /* global positioning system */ +#define TCPR_NTP_REF_GOES 0x474f4553 /* geostationary orbit env satellite */ + struct tcpr_ntp_hdr_l_fp ntp_ref_ts; /* reference timestamp */ + struct tcpr_ntp_hdr_l_fp ntp_orig_ts; /* originate timestamp */ + struct tcpr_ntp_hdr_l_fp ntp_rec_ts; /* receive timestamp */ + struct tcpr_ntp_hdr_l_fp ntp_xmt_ts; /* transmit timestamp */ }; - -struct tcpr_ntp_hdr -{ - uint8_t ntp_li_vn_mode; /* leap indicator, version, mode */ -#define TCPR_NTP_LI_NW 0x0 /* no warning */ -#define TCPR_NTP_LI_AS 0x1 /* last minute has 61 seconds */ -#define TCPR_NTP_LI_DS 0x2 /* last minute has 59 seconds */ -#define TCPR_NTP_LI_AC 0x3 /* alarm condition */ - -#define TCPR_NTP_VN_2 0x2 /* version 2 */ -#define TCPR_NTP_VN_3 0x3 /* version 3 */ -#define TCPR_NTP_VN_4 0x4 /* version 4 */ - -#define TCPR_NTP_MODE_R 0x0 /* reserved */ -#define TCPR_NTP_MODE_A 0x1 /* symmetric active */ -#define TCPR_NTP_MODE_P 0x2 /* symmetric passive */ -#define TCPR_NTP_MODE_C 0x3 /* client */ -#define TCPR_NTP_MODE_S 0x4 /* server */ -#define TCPR_NTP_MODE_B 0x5 /* broadcast */ -#define TCPR_NTP_MODE_RC 0x6 /* reserved for NTP control message */ -#define TCPR_NTP_MODE_RP 0x7 /* reserved for private use */ - uint8_t ntp_stratum; /* stratum */ -#define TCPR_NTP_STRATUM_UNAVAIL 0x0 /* unspecified or unavailable */ -#define TCPR_NTP_STRATUM_PRIMARY 0x1 /* primary reference (radio clock) */ - /* 2 - 15 is secondary */ - /* 16 - 255 is reserved */ - uint8_t ntp_poll; /* poll interval (should be 4 - 12) */ - uint8_t ntp_precision; /* local clock precision */ - struct tcpr_ntp_hdr_s_fp ntp_delay; /* roundtrip delay */ - struct tcpr_ntp_hdr_s_fp ntp_dispersion; /* nominal error */ - uint32_t ntp_reference_id; /* reference source id */ -#define TCPR_NTP_REF_LOCAL 0x4c4f434c /* uncalibrated local clock */ -#define TCPR_NTP_REF_PPS 0x50505300 /* atomic / pulse-per-second clock */ -#define TCPR_NTP_REF_ACTS 0x41435453 /* NIST dialup modem */ -#define TCPR_NTP_REF_USNO 0x55534e4f /* USNO modem service */ -#define TCPR_NTP_REF_PTB 0x50544200 /* PTB (German) modem service */ -#define TCPR_NTP_REF_TDF 0x54444600 /* Allouis (French) radio */ -#define TCPR_NTP_REF_DCF 0x44434600 /* Mainflingen (German) radio */ -#define TCPR_NTP_REF_MSF 0x4d534600 /* Rugby (UK) radio */ -#define TCPR_NTP_REF_WWV 0x57575600 /* Ft Collins (US) radio */ -#define TCPR_NTP_REF_WWVB 0x57575642 /* Boulder (US) radio */ -#define TCPR_NTP_REF_WWVH 0x57575648 /* Kaui Hawaii (US) radio */ -#define TCPR_NTP_REF_CHU 0x43485500 /* Ottaha (Canada) radio */ -#define TCPR_NTP_REF_LORC 0x4c4f5243 /* LORAN-C radionavigation */ -#define TCPR_NTP_REF_OMEG 0x4f4d4547 /* OMEGA radionavigation */ -#define TCPR_NTP_REF_GPS 0x47505300 /* global positioning system */ -#define TCPR_NTP_REF_GOES 0x474f4553 /* geostationary orbit env satellite */ - struct tcpr_ntp_hdr_l_fp ntp_ref_ts; /* reference timestamp */ - struct tcpr_ntp_hdr_l_fp ntp_orig_ts; /* originate timestamp */ - struct tcpr_ntp_hdr_l_fp ntp_rec_ts; /* receive timestamp */ - struct tcpr_ntp_hdr_l_fp ntp_xmt_ts; /* transmit timestamp */ -}; - - /* * OSPFv2 header * Open Shortest Path First * Static header size: 16 bytes */ -struct tcpr_ospf_hdr -{ - uint8_t ospf_v; /* version */ -#define OSPFVERSION 2 - uint8_t ospf_type; /* type */ -#define TCPR_OSPF_UMD 0 /* UMd monitoring packet */ -#define TCPR_OSPF_HELLO 1 /* HELLO packet */ -#define TCPR_OSPF_DBD 2 /* dataBase description packet */ -#define TCPR_OSPF_LSR 3 /* link state request packet */ -#define TCPR_OSPF_LSU 4 /* link state Update Packet */ -#define TCPR_OSPF_LSA 5 /* link state acknowledgement packet */ - uint16_t ospf_len; /* length */ - struct in_addr ospf_rtr_id; /* source router ID */ - struct in_addr ospf_area_id;/* roam ID */ - uint16_t ospf_sum; /* checksum */ +struct tcpr_ospf_hdr { + uint8_t ospf_v; /* version */ +#define OSPFVERSION 2 + uint8_t ospf_type; /* type */ +#define TCPR_OSPF_UMD 0 /* UMd monitoring packet */ +#define TCPR_OSPF_HELLO 1 /* HELLO packet */ +#define TCPR_OSPF_DBD 2 /* dataBase description packet */ +#define TCPR_OSPF_LSR 3 /* link state request packet */ +#define TCPR_OSPF_LSU 4 /* link state Update Packet */ +#define TCPR_OSPF_LSA 5 /* link state acknowledgement packet */ + uint16_t ospf_len; /* length */ + struct in_addr ospf_rtr_id; /* source router ID */ + struct in_addr ospf_area_id; /* roam ID */ + uint16_t ospf_sum; /* checksum */ uint16_t ospf_auth_type; /* authentication type */ -#define TCPR_OSPF_AUTH_NULL 0 /* null password */ -#define TCPR_OSPF_AUTH_SIMPLE 1 /* simple, plaintext, 8 int8_t password */ -#define TCPR_OSPF_AUTH_MD5 2 /* MD5 */ +#define TCPR_OSPF_AUTH_NULL 0 /* null password */ +#define TCPR_OSPF_AUTH_SIMPLE 1 /* simple, plaintext, 8 int8_t password */ +#define TCPR_OSPF_AUTH_MD5 2 /* MD5 */ }; - /* * OSPF authentication header * Open Shortest Path First * Static header size: 8 bytes */ -struct tcpr_auth_hdr -{ +struct tcpr_auth_hdr { uint16_t ospf_auth_null; /* NULL */ uint8_t ospf_auth_keyid; /* authentication key ID */ uint8_t ospf_auth_len; /* auth data length */ - uint32_t ospf_auth_seq; /* cryptographic sequence number */ + uint32_t ospf_auth_seq; /* cryptographic sequence number */ }; - /* * OSPF hello header * Open Shortest Path First * Static header size: 28 bytes */ -struct tcpr_ospf_hello_hdr -{ - struct in_addr hello_nmask; /* netmask associated with the interface */ - uint16_t hello_intrvl; /* num of seconds between routers last packet */ - uint8_t hello_opts; /* Options for HELLO packets (look above) */ - uint8_t hello_rtr_pri; /* router's priority (if 0, can't be backup) */ +struct tcpr_ospf_hello_hdr { + struct in_addr hello_nmask; /* netmask associated with the interface */ + uint16_t hello_intrvl; /* num of seconds between routers last packet */ + uint8_t hello_opts; /* Options for HELLO packets (look above) */ + uint8_t hello_rtr_pri; /* router's priority (if 0, can't be backup) */ uint32_t hello_dead_intvl; /* # of secs a router is silent till deemed down */ - struct in_addr hello_des_rtr; /* Designated router on the network */ - struct in_addr hello_bkup_rtr; /* Backup router */ - struct in_addr hello_nbr; /* neighbor router, memcpy more as needed */ + struct in_addr hello_des_rtr; /* Designated router on the network */ + struct in_addr hello_bkup_rtr; /* Backup router */ + struct in_addr hello_nbr; /* neighbor router, memcpy more as needed */ }; - /* * Database Description header. */ -struct tcpr_dbd_hdr -{ - uint16_t dbd_mtu_len; /* max length of IP dgram that this 'if' can use */ - uint8_t dbd_opts; /* DBD packet options (from above) */ - uint8_t dbd_type; /* type of exchange occurring */ -#define TCPR_DBD_IBI 0x01 /* init */ -#define TCPR_DBD_MBIT 0x02 /* more DBD packets are to come */ -#define TCPR_DBD_MSBIT 0x04 /* If 1, sender is the master in the exchange */ - uint32_t dbd_seq; /* DBD sequence number */ +struct tcpr_dbd_hdr { + uint16_t dbd_mtu_len; /* max length of IP dgram that this 'if' can use */ + uint8_t dbd_opts; /* DBD packet options (from above) */ + uint8_t dbd_type; /* type of exchange occurring */ +#define TCPR_DBD_IBI 0x01 /* init */ +#define TCPR_DBD_MBIT 0x02 /* more DBD packets are to come */ +#define TCPR_DBD_MSBIT 0x04 /* If 1, sender is the master in the exchange */ + uint32_t dbd_seq; /* DBD sequence number */ }; - /* * used for the LS type field in all LS* headers */ -#define TCPR_LS_TYPE_RTR 1 /* router-LSA */ -#define TCPR_LS_TYPE_NET 2 /* network-LSA */ -#define TCPR_LS_TYPE_IP 3 /* summary-LSA (IP Network) */ -#define TCPR_LS_TYPE_ASBR 4 /* summary-LSA (ASBR) */ -#define TCPR_LS_TYPE_ASEXT 5 /* AS-external-LSA */ - +#define TCPR_LS_TYPE_RTR 1 /* router-LSA */ +#define TCPR_LS_TYPE_NET 2 /* network-LSA */ +#define TCPR_LS_TYPE_IP 3 /* summary-LSA (IP Network) */ +#define TCPR_LS_TYPE_ASBR 4 /* summary-LSA (ASBR) */ +#define TCPR_LS_TYPE_ASEXT 5 /* AS-external-LSA */ /* * Link State Request header */ -struct tcpr_lsr_hdr -{ - uint32_t lsr_type; /* type of LS being requested */ - uint32_t lsr_lsid; /* link state ID */ - struct in_addr lsr_adrtr; /* advertising router (memcpy more as needed) */ +struct tcpr_lsr_hdr { + uint32_t lsr_type; /* type of LS being requested */ + uint32_t lsr_lsid; /* link state ID */ + struct in_addr lsr_adrtr; /* advertising router (memcpy more as needed) */ }; - /* * Link State Update header */ -struct tcpr_lsu_hdr -{ - uint32_t lsu_num; /* number of LSAs that will be broadcasted */ +struct tcpr_lsu_hdr { + uint32_t lsu_num; /* number of LSAs that will be broadcasted */ }; - /* * Link State Acknowledgement header. */ -struct tcpr_lsa_hdr -{ - uint16_t lsa_age; /* time in seconds since the LSA was originated */ - uint8_t lsa_opts; /* look above for OPTS_* */ - uint8_t lsa_type; /* look below for LS_TYPE_* */ - uint32_t lsa_id; /* link State ID */ +struct tcpr_lsa_hdr { + uint16_t lsa_age; /* time in seconds since the LSA was originated */ + uint8_t lsa_opts; /* look above for OPTS_* */ + uint8_t lsa_type; /* look below for LS_TYPE_* */ + uint32_t lsa_id; /* link State ID */ struct in_addr lsa_adv; /* router ID of Advertising router */ - uint32_t lsa_seq; /* LSA sequence number to detect old/bad ones */ - uint16_t lsa_sum; /* "Fletcher Checksum" of all fields minus age */ - uint16_t lsa_len; /* length in bytes including the 20 byte header */ + uint32_t lsa_seq; /* LSA sequence number to detect old/bad ones */ + uint16_t lsa_sum; /* "Fletcher Checksum" of all fields minus age */ + uint16_t lsa_len; /* length in bytes including the 20 byte header */ }; - /* * Router LSA data format * * Other stuff for TOS can be added for backward compatibility, for this * version, only OSPFv2 is being FULLY supported. */ -struct tcpr_rtr_lsa_hdr -{ - uint16_t rtr_flags; /* set to help describe packet */ -#define TCPR_RTR_FLAGS_W 0x0100 /* W bit */ -#define TCPR_RTR_FLAGS_E 0x0200 /* E bit */ -#define TCPR_RTR_FLAGS_B 0x0400 /* B bit */ - uint16_t rtr_num; /* number of links within that packet */ - uint32_t rtr_link_id; /* describes link_data (look below) */ -#define TCPR_LINK_ID_NBR_ID 1 /* Neighbors router ID, also can be 4 */ -#define TCPR_LINK_ID_IP_DES 2 /* IP address of designated router */ -#define TCPR_LINK_ID_SUB 3 /* IP subnet number */ - uint32_t rtr_link_data; /* Depending on link_id, info is here */ - uint8_t rtr_type; /* Description of router link */ -#define TCPR_RTR_TYPE_PTP 1 /* Point-To-Point */ -#define TCPR_RTR_TYPE_TRANS 2 /* Connection to a "transit network" */ -#define TCPR_RTR_TYPE_STUB 3 /* Connectin to a "stub network" */ -#define RTR_TYPE_VRTL 4 /* connects to a "virtual link" */ - uint8_t rtr_tos_num; /* number of different TOS metrics for this link */ - uint16_t rtr_metric; /* the "cost" of using this link */ +struct tcpr_rtr_lsa_hdr { + uint16_t rtr_flags; /* set to help describe packet */ +#define TCPR_RTR_FLAGS_W 0x0100 /* W bit */ +#define TCPR_RTR_FLAGS_E 0x0200 /* E bit */ +#define TCPR_RTR_FLAGS_B 0x0400 /* B bit */ + uint16_t rtr_num; /* number of links within that packet */ + uint32_t rtr_link_id; /* describes link_data (look below) */ +#define TCPR_LINK_ID_NBR_ID 1 /* Neighbors router ID, also can be 4 */ +#define TCPR_LINK_ID_IP_DES 2 /* IP address of designated router */ +#define TCPR_LINK_ID_SUB 3 /* IP subnet number */ + uint32_t rtr_link_data; /* Depending on link_id, info is here */ + uint8_t rtr_type; /* Description of router link */ +#define TCPR_RTR_TYPE_PTP 1 /* Point-To-Point */ +#define TCPR_RTR_TYPE_TRANS 2 /* Connection to a "transit network" */ +#define TCPR_RTR_TYPE_STUB 3 /* Connectin to a "stub network" */ +#define RTR_TYPE_VRTL 4 /* connects to a "virtual link" */ + uint8_t rtr_tos_num; /* number of different TOS metrics for this link */ + uint16_t rtr_metric; /* the "cost" of using this link */ }; - /* * Network LSA data format. */ -struct tcpr_net_lsa_hdr -{ - struct in_addr net_nmask; /* Netmask for that network */ - uint32_t net_rtr_id; /* ID of router attached to that network */ +struct tcpr_net_lsa_hdr { + struct in_addr net_nmask; /* Netmask for that network */ + uint32_t net_rtr_id; /* ID of router attached to that network */ }; - /* * Summary LSA data format. */ -struct tcpr_sum_lsa_hdr -{ - struct in_addr sum_nmask; /* Netmask of destination IP address */ - uint32_t sum_metric; /* Same as in rtr_lsa (&0xfff to use last 24bit */ - uint32_t sum_tos_metric; /* first 8bits are TOS, 24bits are TOS Metric */ +struct tcpr_sum_lsa_hdr { + struct in_addr sum_nmask; /* Netmask of destination IP address */ + uint32_t sum_metric; /* Same as in rtr_lsa (&0xfff to use last 24bit */ + uint32_t sum_tos_metric; /* first 8bits are TOS, 24bits are TOS Metric */ }; - /* * AS External LSA data format. * & 0xfff logic operator for as_metric to get last 24bits. */ -struct tcpr_as_lsa_hdr -{ - struct in_addr as_nmask; /* Netmask for advertised destination */ - uint32_t as_metric; /* May have to set E bit in first 8bits */ -#define TCPR_AS_E_BIT_ON 0x80000000 /* as_metric */ - struct in_addr as_fwd_addr; /* Forwarding address */ - uint32_t as_rte_tag; /* External route tag */ +struct tcpr_as_lsa_hdr { + struct in_addr as_nmask; /* Netmask for advertised destination */ + uint32_t as_metric; /* May have to set E bit in first 8bits */ +#define TCPR_AS_E_BIT_ON 0x80000000 /* as_metric */ + struct in_addr as_fwd_addr; /* Forwarding address */ + uint32_t as_rte_tag; /* External route tag */ }; - /* * Base RIP header * Routing Information Protocol * Base header size: 24 bytes */ -struct tcpr_rip_hdr -{ - uint8_t rip_cmd; /* RIP command */ -#define RIPCMD_REQUEST 1 /* want info */ -#define RIPCMD_RESPONSE 2 /* responding to request */ -#define RIPCMD_TRACEON 3 /* turn tracing on */ -#define RIPCMD_TRACEOFF 4 /* turn it off */ -#define RIPCMD_POLL 5 /* like request, but anyone answers */ -#define RIPCMD_POLLENTRY 6 /* like poll, but for entire entry */ -#define RIPCMD_MAX 7 /* ? command */ - uint8_t rip_ver; /* RIP version */ -#define RIPVER_0 0 -#define RIPVER_1 1 -#define RIPVER_2 2 - uint16_t rip_rd; /* Zero (v1) or Routing Domain (v2) */ - uint16_t rip_af; /* Address family */ - uint16_t rip_rt; /* Zero (v1) or Route Tag (v2) */ - uint32_t rip_addr; /* IP address */ - uint32_t rip_mask; /* Zero (v1) or Subnet Mask (v2) */ - uint32_t rip_next_hop; /* Zero (v1) or Next hop IP address (v2) */ - uint32_t rip_metric; /* Metric */ +struct tcpr_rip_hdr { + uint8_t rip_cmd; /* RIP command */ +#define RIPCMD_REQUEST 1 /* want info */ +#define RIPCMD_RESPONSE 2 /* responding to request */ +#define RIPCMD_TRACEON 3 /* turn tracing on */ +#define RIPCMD_TRACEOFF 4 /* turn it off */ +#define RIPCMD_POLL 5 /* like request, but anyone answers */ +#define RIPCMD_POLLENTRY 6 /* like poll, but for entire entry */ +#define RIPCMD_MAX 7 /* ? command */ + uint8_t rip_ver; /* RIP version */ +#define RIPVER_0 0 +#define RIPVER_1 1 +#define RIPVER_2 2 + uint16_t rip_rd; /* Zero (v1) or Routing Domain (v2) */ + uint16_t rip_af; /* Address family */ + uint16_t rip_rt; /* Zero (v1) or Route Tag (v2) */ + uint32_t rip_addr; /* IP address */ + uint32_t rip_mask; /* Zero (v1) or Subnet Mask (v2) */ + uint32_t rip_next_hop; /* Zero (v1) or Next hop IP address (v2) */ + uint32_t rip_metric; /* Metric */ }; /* * RPC headers * Remote Procedure Call */ -#define TCPR_RPC_CALL 0 +#define TCPR_RPC_CALL 0 #define TCPR_RPC_REPLY 1 -#define TCPR_RPC_VERS 2 +#define TCPR_RPC_VERS 2 #define TCPR_RPC_LAST_FRAG 0x80000000 /* * Portmap defines */ -#define TCPR_PMAP_PROGRAM 100000 -#define TCPR_PMAP_PROC_NULL 0 -#define TCPR_PMAP_PROC_SET 1 -#define TCPR_PMAP_PROC_UNSET 2 -#define TCPR_PMAP_PROC_GETADDR 3 -#define TCPR_PMAP_PROC_DUMP 4 -#define TCPR_PMAP_PROC_CALLIT 5 -#define TCPR_PMAP_PROC_BCAST 5 /* Not a typo */ -#define TCPR_PMAP_PROC_GETTIME 6 +#define TCPR_PMAP_PROGRAM 100000 +#define TCPR_PMAP_PROC_NULL 0 +#define TCPR_PMAP_PROC_SET 1 +#define TCPR_PMAP_PROC_UNSET 2 +#define TCPR_PMAP_PROC_GETADDR 3 +#define TCPR_PMAP_PROC_DUMP 4 +#define TCPR_PMAP_PROC_CALLIT 5 +#define TCPR_PMAP_PROC_BCAST 5 /* Not a typo */ +#define TCPR_PMAP_PROC_GETTIME 6 #define TCPR_PMAP_PROC_UADDR2TADDR 7 #define TCPR_PMAP_PROC_TADDR2UADDR 8 #define TCPR_PMAP_PROC_GETVERSADDR 9 -#define TCPR_PMAP_PROC_INDIRECT 10 +#define TCPR_PMAP_PROC_INDIRECT 10 #define TCPR_PMAP_PROC_GETADDRLIST 11 -#define TCPR_PMAP_PROC_GETSTAT 12 +#define TCPR_PMAP_PROC_GETSTAT 12 /* There will be more to add... */ -struct tcpr_rpc_opaque_auth -{ +struct tcpr_rpc_opaque_auth { uint32_t rpc_auth_flavor; uint32_t rpc_auth_length; #if 0 @@ -1527,8 +1436,7 @@ struct tcpr_rpc_opaque_auth #endif }; -struct tcpr_rpc_call -{ +struct tcpr_rpc_call { uint32_t rpc_rpcvers; /* RPC version - must be 2 */ uint32_t rpc_prognum; /* Program Number */ uint32_t rpc_vers; /* Program Version */ @@ -1537,15 +1445,13 @@ struct tcpr_rpc_call struct tcpr_rpc_opaque_auth rpc_verifier; }; -struct tcpr_rpc_call_hdr -{ - uint32_t rpc_xid; /* xid (transaction identifier) */ +struct tcpr_rpc_call_hdr { + uint32_t rpc_xid; /* xid (transaction identifier) */ uint32_t rpc_type; - struct tcpr_rpc_call rpc_call; + struct tcpr_rpc_call rpc_call; }; -struct tcpr_rpc_call_tcp_hdr -{ +struct tcpr_rpc_call_tcp_hdr { uint32_t rpc_record_marking; /* used with byte stream protocols */ struct tcpr_rpc_call_hdr rpc_common; }; @@ -1555,14 +1461,13 @@ struct tcpr_rpc_call_tcp_hdr * Spanning Tree Protocol * Static header size: 35 bytes */ -struct tcpr_stp_conf_hdr -{ +struct tcpr_stp_conf_hdr { uint16_t stp_id; /* protocol id */ uint8_t stp_version; /* protocol version */ uint8_t stp_bpdu_type; /* bridge protocol data unit type */ uint8_t stp_flags; /* control flags */ uint8_t stp_rootid[8]; /* root id */ - uint32_t stp_rootpc; /* root path cost */ + uint32_t stp_rootpc; /* root path cost */ uint8_t stp_bridgeid[8]; /* bridge id */ uint16_t stp_portid; /* port id */ uint16_t stp_mage; /* message age */ @@ -1571,94 +1476,87 @@ struct tcpr_stp_conf_hdr uint16_t stp_fdelay; /* forward delay */ }; - /* * STP topology change notification header * Spanning Tree Protocol * Static header size: 4 bytes */ -struct tcpr_stp_tcn_hdr -{ - uint16_t stp_id; /* protocol id */ - uint8_t stp_version; /* protocol version */ - uint8_t stp_bpdu_type; /* bridge protocol data unit type */ +struct tcpr_stp_tcn_hdr { + uint16_t stp_id; /* protocol id */ + uint8_t stp_version; /* protocol version */ + uint8_t stp_bpdu_type; /* bridge protocol data unit type */ }; - /* * TCP header * Transmission Control Protocol * Static header size: 20 bytes */ -struct tcpr_tcp_hdr -{ - uint16_t th_sport; /* source port */ - uint16_t th_dport; /* destination port */ - uint32_t th_seq; /* sequence number */ - uint32_t th_ack; /* acknowledgement number */ +struct tcpr_tcp_hdr { + uint16_t th_sport; /* source port */ + uint16_t th_dport; /* destination port */ + uint32_t th_seq; /* sequence number */ + uint32_t th_ack; /* acknowledgement number */ #ifdef WORDS_BIGENDIAN - uint8_t th_off:4, /* data offset */ - th_x2:4; /* (unused) */ + uint8_t th_off:4, /* data offset */ + th_x2:4; /* (unused) */ #else - uint8_t th_x2:4, /* (unused) */ - th_off:4; /* data offset */ + uint8_t th_x2:4, /* (unused) */ + th_off:4; /* data offset */ #endif - uint8_t th_flags; /* control flags */ + uint8_t th_flags; /* control flags */ #ifndef TH_FIN -#define TH_FIN 0x01 /* finished send data */ +#define TH_FIN 0x01 /* finished send data */ #endif #ifndef TH_SYN -#define TH_SYN 0x02 /* synchronize sequence numbers */ +#define TH_SYN 0x02 /* synchronize sequence numbers */ #endif #ifndef TH_RST -#define TH_RST 0x04 /* reset the connection */ +#define TH_RST 0x04 /* reset the connection */ #endif #ifndef TH_PUSH -#define TH_PUSH 0x08 /* push data to the app layer */ +#define TH_PUSH 0x08 /* push data to the app layer */ #endif #ifndef TH_ACK -#define TH_ACK 0x10 /* acknowledge */ +#define TH_ACK 0x10 /* acknowledge */ #endif #ifndef TH_URG -#define TH_URG 0x20 /* urgent! */ +#define TH_URG 0x20 /* urgent! */ #endif #ifndef TH_ECE -#define TH_ECE 0x40 +#define TH_ECE 0x40 #endif #ifndef TH_CWR -#define TH_CWR 0x80 +#define TH_CWR 0x80 #endif - uint16_t th_win; /* window */ - uint16_t th_sum; /* checksum */ - uint16_t th_urp; /* urgent pointer */ + uint16_t th_win; /* window */ + uint16_t th_sum; /* checksum */ + uint16_t th_urp; /* urgent pointer */ }; - /* * Token Ring Header */ -struct tcpr_token_ring_hdr -{ - uint8_t token_ring_access_control; -#define TCPR_TOKEN_RING_FRAME 0x10 - uint8_t token_ring_frame_control; -#define TCPR_TOKEN_RING_LLC_FRAME 0x40 - uint8_t token_ring_dhost[TOKEN_RING_ADDR_LEN]; - uint8_t token_ring_shost[TOKEN_RING_ADDR_LEN]; - uint8_t token_ring_llc_dsap; - uint8_t token_ring_llc_ssap; - uint8_t token_ring_llc_control_field; - uint8_t token_ring_llc_org_code[TCPR_ORG_CODE_SIZE]; +struct tcpr_token_ring_hdr { + uint8_t token_ring_access_control; +#define TCPR_TOKEN_RING_FRAME 0x10 + uint8_t token_ring_frame_control; +#define TCPR_TOKEN_RING_LLC_FRAME 0x40 + uint8_t token_ring_dhost[TOKEN_RING_ADDR_LEN]; + uint8_t token_ring_shost[TOKEN_RING_ADDR_LEN]; + uint8_t token_ring_llc_dsap; + uint8_t token_ring_llc_ssap; + uint8_t token_ring_llc_control_field; + uint8_t token_ring_llc_org_code[TCPR_ORG_CODE_SIZE]; uint16_t token_ring_type; -#define TOKEN_RING_TYPE_IP 0x0800 /* IP protocol */ -#define TOKEN_RING_TYPE_ARP 0x0806 /* addr. resolution protocol */ -#define TOKEN_RING_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ +#define TOKEN_RING_TYPE_IP 0x0800 /* IP protocol */ +#define TOKEN_RING_TYPE_ARP 0x0806 /* addr. resolution protocol */ +#define TOKEN_RING_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ }; -struct tcpr_token_ring_addr -{ - uint8_t token_ring_addr_octet[6]; /* Token Ring address */ +struct tcpr_token_ring_addr { + uint8_t token_ring_addr_octet[6]; /* Token Ring address */ }; /* @@ -1666,102 +1564,95 @@ struct tcpr_token_ring_addr * User Data Protocol * Static header size: 8 bytes */ -struct tcpr_udp_hdr -{ - uint16_t uh_sport; /* source port */ - uint16_t uh_dport; /* destination port */ - uint16_t uh_ulen; /* length */ - uint16_t uh_sum; /* checksum */ +struct tcpr_udp_hdr { + uint16_t uh_sport; /* source port */ + uint16_t uh_dport; /* destination port */ + uint16_t uh_ulen; /* length */ + uint16_t uh_sum; /* checksum */ }; /* * Sebek header * Static header size: 48 bytes */ -struct tcpr_sebek_hdr -{ - uint32_t magic; /* identify packets that should be hidden */ - uint16_t version; /* protocol version, currently 1 */ +struct tcpr_sebek_hdr { + uint32_t magic; /* identify packets that should be hidden */ + uint16_t version; /* protocol version, currently 1 */ #define SEBEK_PROTO_VERSION 1 - uint16_t type; /* type of record (read data is type 0, write data is type 1) */ -#define SEBEK_TYPE_READ 0 /* Currently, only read is supported */ -#define SEBEK_TYPE_WRITE 1 - uint32_t counter; /* PDU counter used to identify when packet are lost */ - uint32_t time_sec; /* seconds since EPOCH according to the honeypot */ - uint32_t time_usec; /* residual microseconds */ - uint32_t pid; /* PID */ - uint32_t uid; /* UID */ - uint32_t fd; /* FD */ -#define SEBEK_CMD_LENGTH 12 + uint16_t type; /* type of record (read data is type 0, write data is type 1) */ +#define SEBEK_TYPE_READ 0 /* Currently, only read is supported */ +#define SEBEK_TYPE_WRITE 1 + uint32_t counter; /* PDU counter used to identify when packet are lost */ + uint32_t time_sec; /* seconds since EPOCH according to the honeypot */ + uint32_t time_usec; /* residual microseconds */ + uint32_t pid; /* PID */ + uint32_t uid; /* UID */ + uint32_t fd; /* FD */ +#define SEBEK_CMD_LENGTH 12 uint8_t cmd[SEBEK_CMD_LENGTH]; /* 12 first characters of the command */ - uint32_t length; /* length in bytes of the PDU's body */ + uint32_t length; /* length in bytes of the PDU's body */ }; - /* * VRRP header * Virtual Router Redundancy Protocol * Static header size: 8 bytes */ #ifndef IPPROTO_VRRP -#define IPPROTO_VRRP 112 /* not everyone's got this */ +#define IPPROTO_VRRP 112 /* not everyone's got this */ #endif -struct tcpr_vrrp_hdr -{ +struct tcpr_vrrp_hdr { #ifdef WORDS_BIGENDIAN - uint8_t vrrp_t:4, /* packet type */ - vrrp_v:4; /* protocol version */ + uint8_t vrrp_t:4, /* packet type */ + vrrp_v:4; /* protocol version */ #else - uint8_t vrrp_v:4, /* protocol version */ - vrrp_t:4; /* packet type */ + uint8_t vrrp_v:4, /* protocol version */ + vrrp_t:4; /* packet type */ #endif -#define TCPR_VRRP_VERSION_01 0x1 -#define TCPR_VRRP_VERSION_02 0x2 +#define TCPR_VRRP_VERSION_01 0x1 +#define TCPR_VRRP_VERSION_02 0x2 #define TCPR_VRRP_TYPE_ADVERT 0x1 uint8_t vrrp_vrouter_id; /* virtual router id */ uint8_t vrrp_priority; /* priority */ uint8_t vrrp_ip_count; /* number of IP addresses */ uint8_t vrrp_auth_type; /* authorization type */ -#define TCPR_VRRP_AUTH_NONE 0x1 +#define TCPR_VRRP_AUTH_NONE 0x1 #define TCPR_VRRP_AUTH_PASSWD 0x2 -#define TCPR_VRRP_AUTH_IPAH 0x3 +#define TCPR_VRRP_AUTH_IPAH 0x3 uint8_t vrrp_advert_int; /* advertisement interval */ uint16_t vrrp_sum; /* checksum */ /* additional addresses */ /* authentication info */ }; - /* * HSRP header * Static header size: 20 bytes */ -struct tcpr_hsrp_hdr -{ +struct tcpr_hsrp_hdr { #define TCPR_HSRP_VERSION 0x0 - uint8_t version; /* Version of the HSRP messages */ + uint8_t version; /* Version of the HSRP messages */ #define TCPR_HSRP_TYPE_HELLO 0x0 #define TCPR_HSRP_TYPE_COUP 0x1 #define TCPR_HSRP_TYPE_RESIGN 0x2 - uint8_t opcode; /* Type of message */ + uint8_t opcode; /* Type of message */ #define TCPR_HSRP_STATE_INITIAL 0x0 -#define TCPR_HSRP_STATE_LEARN 0x1 -#define TCPR_HSRP_STATE_LISTEN 0x2 -#define TCPR_HSRP_STATE_SPEAK 0x4 +#define TCPR_HSRP_STATE_LEARN 0x1 +#define TCPR_HSRP_STATE_LISTEN 0x2 +#define TCPR_HSRP_STATE_SPEAK 0x4 #define TCPR_HSRP_STATE_STANDBY 0x8 -#define TCPR_HSRP_STATE_ACTIVE 0x10 - uint8_t state; /* Current state of the router */ - uint8_t hello_time; /* Period in seconds between hello messages */ - uint8_t hold_time; /* Seconds that the current hello message is valid */ - uint8_t priority; /* Priority for the election process */ - uint8_t group; /* Standby group */ - uint8_t reserved; /* Reserved field */ -#define HSRP_AUTHDATA_LENGTH 8 +#define TCPR_HSRP_STATE_ACTIVE 0x10 + uint8_t state; /* Current state of the router */ + uint8_t hello_time; /* Period in seconds between hello messages */ + uint8_t hold_time; /* Seconds that the current hello message is valid */ + uint8_t priority; /* Priority for the election process */ + uint8_t group; /* Standby group */ + uint8_t reserved; /* Reserved field */ +#define HSRP_AUTHDATA_LENGTH 8 uint8_t authdata[HSRP_AUTHDATA_LENGTH]; /* Password */ - uint32_t virtual_ip; /* Virtual IP address */ + uint32_t virtual_ip; /* Virtual IP address */ }; - /* MPLS label:: RFC 5462, RFC 3032 * * 0 1 2 3 @@ -1778,32 +1669,30 @@ struct tcpr_hsrp_hdr struct tcpr_mpls_label { uint32_t entry; -#define MPLS_LABEL_GACH 13 +#define MPLS_LABEL_GACH 13 }; #ifndef MPLS_LS_LABEL_MASK -#define MPLS_LS_LABEL_MASK 0xFFFFF000 +#define MPLS_LS_LABEL_MASK 0xFFFFF000 #endif #ifndef MPLS_LS_LABEL_SHIFT -#define MPLS_LS_LABEL_SHIFT 12 +#define MPLS_LS_LABEL_SHIFT 12 #endif #ifndef MPLS_LS_TC_MASK -#define MPLS_LS_TC_MASK 0x00000E00 +#define MPLS_LS_TC_MASK 0x00000E00 #endif #ifndef MPLS_LS_TC_SHIFT -#define MPLS_LS_TC_SHIFT 9 +#define MPLS_LS_TC_SHIFT 9 #endif #ifndef MPLS_LS_S_MASK -#define MPLS_LS_S_MASK 0x00000100 +#define MPLS_LS_S_MASK 0x00000100 #endif #ifndef MPLS_LS_S_SHIFT -#define MPLS_LS_S_SHIFT 8 +#define MPLS_LS_S_SHIFT 8 #endif #ifndef MPLS_LS_TTL_MASK -#define MPLS_LS_TTL_MASK 0x000000FF +#define MPLS_LS_TTL_MASK 0x000000FF #endif #ifndef MPLS_LS_TTL_SHIFT -#define MPLS_LS_TTL_SHIFT 0 +#define MPLS_LS_TTL_SHIFT 0 #endif - -#endif /* _TCPR_H_ */ diff --git a/src/tcpreplay.c b/src/tcpreplay.c index 1517a8ad7..8e1b84c38 100644 --- a/src/tcpreplay.c +++ b/src/tcpreplay.c @@ -22,7 +22,6 @@ #include "defines.h" #include "common.h" -#include #include #include #include @@ -30,12 +29,10 @@ #ifdef HAVE_FTS_H #include #endif -#include #include #include "tcpreplay.h" #include "tcpreplay_api.h" -#include "timestamp_trace.h" #ifdef TCPREPLAY_EDIT #include "tcpreplay_edit_opts.h" @@ -47,7 +44,6 @@ tcpedit_t *tcpedit; #endif #include "send_packets.h" -#include "replay.h" #include "signal_handler.h" #ifdef DEBUG @@ -56,22 +52,18 @@ int debug = 0; tcpreplay_t *ctx; -static void flow_stats(const tcpreplay_t *ctx); +static void flow_stats(const tcpreplay_t *tcpr_ctx); int main(int argc, char *argv[]) { - int i, optct = 0; + int i, optct; int rcode; fflush(NULL); ctx = tcpreplay_init(); -#ifdef TCPREPLAY optct = optionProcess(&tcpreplayOptions, argc, argv); -#elif defined TCPREPLAY_EDIT - optct = optionProcess(&tcpreplay_editOptions, argc, argv); -#endif argc -= optct; argv += optct; @@ -222,49 +214,52 @@ main(int argc, char *argv[]) /** * Print various flow statistics */ -static void flow_stats(const tcpreplay_t *ctx) +static void flow_stats(const tcpreplay_t *tcpr_ctx) { struct timeval diff; COUNTER diff_us; - const tcpreplay_stats_t *stats = &ctx->stats; - const tcpreplay_opt_t *options = ctx->options; + const tcpreplay_stats_t *stats = &tcpr_ctx->stats; + const tcpreplay_opt_t *options = tcpr_ctx->options; COUNTER flows_total = stats->flows; COUNTER flows_unique = stats->flows_unique; COUNTER flows_expired = stats->flows_expired; - COUNTER flow_packets; - COUNTER flow_non_flow_packets; + COUNTER flow_packets = stats->flow_packets; + COUNTER flow_non_flow_packets = stats->flow_non_flow_packets; COUNTER flows_sec = 0; u_int32_t flows_sec_100ths = 0; timersub(&stats->end_time, &stats->start_time, &diff); diff_us = TIMEVAL_TO_MICROSEC(&diff); - if (!flows_total || !ctx->iteration) + if (!flows_total || !tcpr_ctx->iteration) return; /* - * When packets are read into cache, flows + * When packets are read into cache, flows * are only counted in first iteration * If flows are unique from one loop iteration * to the next then multiply by the number of * successful iterations. */ - if (options->preload_pcap) { - if (ctx->options->unique_ip) { - flows_total *= ctx->last_unique_iteration; - flows_unique *= ctx->last_unique_iteration; - flows_expired *= ctx->last_unique_iteration; -#ifdef TCPREPLAY_EDIT - } else if (tcpedit->seed) { - flows_total *= ctx->iteration; - flows_unique *= ctx->iteration; - flows_expired *= ctx->iteration; -#endif - } + if (options->preload_pcap && tcpr_ctx->last_unique_iteration) { + flows_total *= tcpr_ctx->last_unique_iteration; + flows_unique *= tcpr_ctx->last_unique_iteration; + flows_expired *= tcpr_ctx->last_unique_iteration; + flow_packets *= tcpr_ctx->last_unique_iteration; + flow_non_flow_packets *= tcpr_ctx->last_unique_iteration; + } else { + /* adjust for --unique-ip-loops */ + flow_packets = (flow_packets * (tcpr_ctx->last_unique_iteration ?: tcpr_ctx->iteration)) / tcpr_ctx->iteration; } - flow_packets = stats->flow_packets * ctx->iteration; - flow_non_flow_packets = stats->flow_non_flow_packets * ctx->iteration; +#ifdef TCPREPLAY_EDIT + if (tcpedit->seed) { + flow_non_flow_packets *= tcpr_ctx->iteration; + flows_total *= tcpr_ctx->iteration; + flows_unique *= tcpr_ctx->iteration; + flows_expired *= tcpr_ctx->iteration; + } +#endif if (diff_us) { COUNTER flows_sec_X100; @@ -274,12 +269,12 @@ static void flow_stats(const tcpreplay_t *ctx) flows_sec_100ths = flows_sec_X100 % 100; } - if (ctx->options->flow_expiry) - printf("Flows: " COUNTER_SPEC " flows, " COUNTER_SPEC " unique, "COUNTER_SPEC " expired, %llu.%02u fps, " COUNTER_SPEC " flow packets, " COUNTER_SPEC " non-flow\n", + if (tcpr_ctx->options->flow_expiry) + printf("Flows: " COUNTER_SPEC " flows, " COUNTER_SPEC " unique, "COUNTER_SPEC " expired, %llu.%02u fps, " COUNTER_SPEC " unique flow packets, " COUNTER_SPEC " unique non-flow packets\n", flows_total, flows_unique, flows_expired, flows_sec, flows_sec_100ths, flow_packets, flow_non_flow_packets); else - printf("Flows: " COUNTER_SPEC " flows, %llu.%02u fps, " COUNTER_SPEC " flow packets, " COUNTER_SPEC " non-flow\n", + printf("Flows: " COUNTER_SPEC " flows, %llu.%02u fps, " COUNTER_SPEC " unique flow packets, " COUNTER_SPEC " unique non-flow packets\n", flows_total, flows_sec, flows_sec_100ths, flow_packets, flow_non_flow_packets); } diff --git a/src/tcpreplay.h b/src/tcpreplay.h index 404dafd46..ddfaea8ce 100644 --- a/src/tcpreplay.h +++ b/src/tcpreplay.h @@ -18,8 +18,7 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TCPREPLAY_H__ -#define __TCPREPLAY_H__ +#pragma once #include "config.h" #include "defines.h" @@ -30,5 +29,3 @@ #ifdef ENABLE_DMALLOC #include #endif - -#endif diff --git a/src/tcpreplay_api.c b/src/tcpreplay_api.c index 0c0b9683e..d429b91b1 100644 --- a/src/tcpreplay_api.c +++ b/src/tcpreplay_api.c @@ -227,6 +227,16 @@ tcpreplay_post_args(tcpreplay_t *ctx, int argc) options->preload_pcap = true; } +#ifdef TCPREPLAY_EDIT + if (HAVE_OPT(PRELOAD_PCAP) && OPT_VALUE_LOOP > 1) { + tcpreplay_seterr(ctx, + "%s", + "tcpreplay_edit --loop (-l) and --preload_pcap (-K) options are mutually exclusive"); + ret = -1; + goto out; + } +#endif + /* Dual file mode */ if (HAVE_OPT(DUALFILE)) { options->dualfile = true; diff --git a/src/tcpreplay_api.h b/src/tcpreplay_api.h index e34120387..a4b5bd897 100644 --- a/src/tcpreplay_api.h +++ b/src/tcpreplay_api.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,24 +18,22 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef _TCPREPLAY_API_H_ -#define _TCPREPLAY_API_H_ +#pragma once -#include "config.h" #include "defines.h" -#include "common/sendpacket.h" -#include "common/tcpdump.h" - -#include -#include +#include "config.h" +#include +#include +#include +#include #include +#include +#include #ifdef ENABLE_DMALLOC #include #endif - - #ifdef __cplusplus extern "C" { #endif @@ -84,11 +82,7 @@ typedef enum { accurate_ioport, } tcpreplay_accurate; -typedef enum { - source_filename = 1, - source_fd = 2, - source_cache = 3 -} tcpreplay_source_type; +typedef enum { source_filename = 1, source_fd = 2, source_cache = 3 } tcpreplay_source_type; typedef struct { tcpreplay_source_type type; @@ -158,12 +152,8 @@ typedef struct tcpreplay_opt_s { float unique_loops; } tcpreplay_opt_t; - /* interface */ -typedef enum { - intf1 = 1, - intf2 -} tcpreplay_intf; +typedef enum { intf1 = 1, intf2 } tcpreplay_intf; /* tcpreplay context variable */ #define TCPREPLAY_ERRSTR_LEN 1024 @@ -181,8 +171,6 @@ typedef struct tcpreplay_s { char errstr[TCPREPLAY_ERRSTR_LEN]; char warnstr[TCPREPLAY_ERRSTR_LEN]; /* status trackers */ - int cache_bit; - int cache_byte; int current_source; /* current source input being replayed */ /* sleep helpers */ @@ -206,20 +194,18 @@ typedef struct tcpreplay_s { bool running; } tcpreplay_t; - /* * manual callback definition: * ctx = tcpreplay context - * interface = name of interface current packet will be sent out - * current_packet = packet number to be sent out + * interface = name of interface current packet will be sent out + * current_packet = packet number to be sent out * * Returns number of packets to send. 0 == send all remaining packets - * Note: Your callback method is BLOCKING the main tcpreplay loop. If you - * call tcpreplay_abort() from inside of your callback, you still need to + * Note: Your callback method is BLOCKING the main tcpreplay loop. If you + * call tcpreplay_abort() from inside of your callback, you still need to * return (any value) so that the main loop is released and can abort. */ -typedef u_int32_t(*tcpreplay_manual_callback) (tcpreplay_t *ctx, char *interface, COUNTER current_packet); - +typedef u_int32_t (*tcpreplay_manual_callback)(tcpreplay_t *ctx, char *interface, COUNTER current_packet); char *tcpreplay_geterr(tcpreplay_t *); char *tcpreplay_getwarn(tcpreplay_t *); @@ -252,7 +238,7 @@ int tcpreplay_set_preload_pcap(tcpreplay_t *, bool); int tcpreplay_get_source_count(tcpreplay_t *); int tcpreplay_get_current_source(tcpreplay_t *); int tcpreplay_set_flow_stats(tcpreplay_t *, bool); -int tcpreplay_set_flow_expiry(tcpreplay_t *,int); +int tcpreplay_set_flow_expiry(tcpreplay_t *, int); bool tcpreplay_get_flow_stats(tcpreplay_t *); int tcpreplay_get_flow_expiry(tcpreplay_t *); @@ -292,5 +278,3 @@ void tcpreplay_setwarn(tcpreplay_t *ctx, const char *fmt, ...); #ifdef __cplusplus } #endif - -#endif //_TCPREPLAY_API_H_ diff --git a/src/tcprewrite.c b/src/tcprewrite.c index 8a3f36e74..c9aa52c8c 100644 --- a/src/tcprewrite.c +++ b/src/tcprewrite.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -20,28 +20,23 @@ /* * Purpose: Modify packets in a pcap file based on rules provided by the - * user to offload work from tcpreplay and provide a easier means of + * user to offload work from tcpreplay and provide an easier means of * reproducing traffic for testing purposes. */ - +#include "tcprewrite.h" #include "config.h" -#include "defines.h" #include "common.h" - -#include +#include "tcpedit/fuzzing.h" +#include "tcpedit/tcpedit.h" +#include "tcprewrite_opts.h" +#include #include #include #include #include #include #include -#include - -#include "tcprewrite.h" -#include "tcprewrite_opts.h" -#include "tcpedit/tcpedit.h" -#include "tcpedit/fuzzing.h" #ifdef DEBUG int debug; @@ -58,9 +53,9 @@ tcpedit_t *tcpedit; /* local functions */ void tcprewrite_init(void); void post_args(int argc, char *argv[]); -int rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout); +int rewrite_packets(tcpedit_t *tcpedit_ctx, pcap_t *pin, pcap_dumper_t *pout); -int +int main(int argc, char *argv[]) { int optct, rcode; @@ -96,8 +91,7 @@ main(int argc, char *argv[]) } if (tcpedit_validate(tcpedit) < 0) { - err_no_exitx("Unable to edit packets given options:\n%s", - tcpedit_geterr(tcpedit)); + err_no_exitx("Unable to edit packets given options:\n%s", tcpedit_geterr(tcpedit)); tcpedit_close(&tcpedit); exit(-1); } @@ -105,17 +99,15 @@ main(int argc, char *argv[]) /* fuzzing init */ fuzzing_init(tcpedit->fuzz_seed, tcpedit->fuzz_factor); - /* open up the output file */ + /* open up the output file */ options.outfile = safe_strdup(OPT_ARG(OUTFILE)); - dbgx(1, "Rewriting DLT to %s", - pcap_datalink_val_to_name(tcpedit_get_output_dlt(tcpedit))); + dbgx(1, "Rewriting DLT to %s", pcap_datalink_val_to_name(tcpedit_get_output_dlt(tcpedit))); if ((dlt_pcap = pcap_open_dead(tcpedit_get_output_dlt(tcpedit), 65535)) == NULL) { tcpedit_close(&tcpedit); err(-1, "Unable to open dead pcap handle."); } - dbgx(1, "DLT of dlt_pcap is %s", - pcap_datalink_val_to_name(pcap_datalink(dlt_pcap))); + dbgx(1, "DLT of dlt_pcap is %s", pcap_datalink_val_to_name(pcap_datalink(dlt_pcap))); #ifdef ENABLE_FRAGROUTE if (options.fragroute_args) { @@ -171,10 +163,9 @@ main(int argc, char *argv[]) return 0; } -void +void tcprewrite_init(void) { - memset(&options, 0, sizeof(options)); #ifdef ENABLE_VERBOSE @@ -189,7 +180,7 @@ tcprewrite_init(void) /** * post AutoGen argument processing */ -void +void post_args(_U_ int argc, _U_ char *argv[]) { char ebuf[PCAP_ERRBUF_SIZE]; @@ -202,7 +193,6 @@ post_args(_U_ int argc, _U_ char *argv[]) warn("not configured with --enable-debug. Debugging disabled."); #endif - #ifdef ENABLE_VERBOSE if (HAVE_OPT(VERBOSE)) options.verbose = 1; @@ -211,7 +201,6 @@ post_args(_U_ int argc, _U_ char *argv[]) tcpdump.args = safe_strdup(OPT_ARG(DECODE)); #endif - #ifdef ENABLE_FRAGROUTE if (HAVE_OPT(FRAGROUTE)) options.fragroute_args = safe_strdup(OPT_ARG(FRAGROUTE)); @@ -238,20 +227,20 @@ post_args(_U_ int argc, _U_ char *argv[]) #ifdef HAVE_PCAP_SNAPSHOT if (pcap_snapshot(options.pin) < 65535) warnx("%s was captured using a snaplen of %d bytes. This may mean you have truncated packets.", - options.infile, pcap_snapshot(options.pin)); + options.infile, + pcap_snapshot(options.pin)); #endif - } -/** +/** * Main loop to rewrite packets */ int -rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) +rewrite_packets(tcpedit_t *tcpedit_ctx, pcap_t *pin, pcap_dumper_t *pout) { - tcpr_dir_t cache_result = TCPR_DIR_C2S; /* default to primary */ - struct pcap_pkthdr pkthdr, *pkthdr_ptr; /* packet header */ - const u_char *pktconst = NULL; /* packet from libpcap */ + tcpr_dir_t cache_result = TCPR_DIR_C2S; /* default to primary */ + struct pcap_pkthdr pkthdr, *pkthdr_ptr; /* packet header */ + const u_char *pktconst = NULL; /* packet from libpcap */ u_char **pktdata = NULL; static u_char *pktdata_buff; static char *frag = NULL; @@ -271,7 +260,7 @@ rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) if (frag == NULL) frag = (char *)safe_malloc(MAXPACKET); - /* MAIN LOOP + /* MAIN LOOP * Keep sending while we have packets or until * we've sent enough packets */ @@ -281,7 +270,7 @@ rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) if (pkthdr.caplen > MAX_SNAPLEN) errx(-1, "Frame too big, caplen %d exceeds %d", pkthdr.caplen, MAX_SNAPLEN); - /* + /* * copy over the packet so we can pad it out if necessary and * because pcap_next() returns a const ptr */ @@ -295,13 +284,13 @@ rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) /* sometimes we should not send the packet, in such cases * no point in editing this packet at all, just write it to the * output file (note, we can't just remove it, or the tcpprep cache - * file will loose it's indexing + * file will lose it's indexing */ if (cache_result == TCPR_DIR_NOSEND) goto WRITE_PACKET; /* still need to write it so cache stays in sync */ - if ((rcode = tcpedit_packet(tcpedit, &pkthdr_ptr, pktdata, cache_result)) == TCPEDIT_ERROR) { + if ((rcode = tcpedit_packet(tcpedit_ctx, &pkthdr_ptr, pktdata, cache_result)) == TCPEDIT_ERROR) { return rcode; } else if ((rcode == TCPEDIT_SOFT_ERROR) && HAVE_OPT(SKIP_SOFT_ERRORS)) { /* don't write packet */ @@ -322,13 +311,13 @@ rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) pcap_dump((u_char *)pout, pkthdr_ptr, *pktdata); } else { /* get the L3 protocol of the packet */ - proto = tcpedit_l3proto(tcpedit, AFTER_PROCESS, *pktdata, pkthdr_ptr->caplen); + proto = tcpedit_l3proto(tcpedit_ctx, AFTER_PROCESS, *pktdata, pkthdr_ptr->caplen); /* packet is IPv4/IPv6 AND needs to be fragmented */ - if ((proto == ETHERTYPE_IP || proto == ETHERTYPE_IP6) && - ((options.fragroute_dir == FRAGROUTE_DIR_BOTH) || - (cache_result == TCPR_DIR_C2S && options.fragroute_dir == FRAGROUTE_DIR_C2S) || - (cache_result == TCPR_DIR_S2C && options.fragroute_dir == FRAGROUTE_DIR_S2C))) { + if ((proto == ETHERTYPE_IP || proto == ETHERTYPE_IP6) && + ((options.fragroute_dir == FRAGROUTE_DIR_BOTH) || + (cache_result == TCPR_DIR_C2S && options.fragroute_dir == FRAGROUTE_DIR_C2S) || + (cache_result == TCPR_DIR_S2C && options.fragroute_dir == FRAGROUTE_DIR_S2C))) { #ifdef DEBUG int i = 0; #endif @@ -350,9 +339,9 @@ rewrite_packets(tcpedit_t *tcpedit, pcap_t *pin, pcap_dumper_t *pout) } } #else - /* write the packet when there's no fragrouting to be done */ - if (pkthdr_ptr->caplen) - pcap_dump((u_char *)pout, pkthdr_ptr, *pktdata); + /* write the packet when there's no fragrouting to be done */ + if (pkthdr_ptr->caplen) + pcap_dump((u_char *)pout, pkthdr_ptr, *pktdata); #endif } /* while() */ diff --git a/src/tcprewrite.h b/src/tcprewrite.h index 1b517abea..b88eb860c 100644 --- a/src/tcprewrite.h +++ b/src/tcprewrite.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,11 +18,10 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TCPREWRITE_H__ -#define __TCPREWRITE_H__ +#pragma once -#include "config.h" #include "defines.h" +#include "config.h" #include "tcpedit/tcpedit.h" #ifdef ENABLE_DMALLOC @@ -44,9 +43,9 @@ struct tcprewrite_opt_s { /* tcpprep cache data */ COUNTER cache_packets; char *cachedata; - + /* tcpprep cache file comment */ - char *comment; + char *comment; #ifdef ENABLE_VERBOSE /* tcpdump verbose printing */ @@ -57,8 +56,8 @@ struct tcprewrite_opt_s { #ifdef ENABLE_FRAGROUTE char *fragroute_args; fragroute_t *frag_ctx; -#define FRAGROUTE_DIR_C2S 1 -#define FRAGROUTE_DIR_S2C 2 +#define FRAGROUTE_DIR_C2S 1 +#define FRAGROUTE_DIR_S2C 2 #define FRAGROUTE_DIR_BOTH 4 int fragroute_dir; #endif @@ -66,5 +65,3 @@ struct tcprewrite_opt_s { }; typedef struct tcprewrite_opt_s tcprewrite_opt_t; - -#endif /* __TCPREWRITE_H__ */ diff --git a/src/timestamp_trace.h b/src/timestamp_trace.h index 2d19336d1..3aaa46af0 100644 --- a/src/timestamp_trace.h +++ b/src/timestamp_trace.h @@ -2,9 +2,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -16,12 +16,10 @@ * along with the Tcpreplay Suite. If not, see . */ +#pragma once -#ifndef TIMESTAMP_TRACE_H_ -#define TIMESTAMP_TRACE_H_ - -#include "config.h" #include "defines.h" +#include "config.h" #define TRACE_MAX_ENTRIES 15000 @@ -41,8 +39,8 @@ typedef struct timestamp_trace_entry timestamp_trace_entry_t; uint32_t trace_num; timestamp_trace_entry_t timestamp_trace_entry_array[TRACE_MAX_ENTRIES]; -static inline void update_current_timestamp_trace_entry(COUNTER bytes_sent, - COUNTER now_us, COUNTER tx_us, COUNTER next_tx_us) +static inline void +update_current_timestamp_trace_entry(COUNTER bytes_sent, COUNTER now_us, COUNTER tx_us, COUNTER next_tx_us) { if (trace_num >= TRACE_MAX_ENTRIES) return; @@ -59,8 +57,8 @@ static inline void update_current_timestamp_trace_entry(COUNTER bytes_sent, timestamp_trace_entry_array[trace_num].next_tx_us = next_tx_us; } -static inline void add_timestamp_trace_entry(COUNTER size, - struct timeval *timestamp, COUNTER skip_length) +static inline void +add_timestamp_trace_entry(COUNTER size, struct timeval *timestamp, COUNTER skip_length) { if (trace_num >= TRACE_MAX_ENTRIES) return; @@ -72,40 +70,48 @@ static inline void add_timestamp_trace_entry(COUNTER size, ++trace_num; } -static inline void dump_timestamp_trace_array(const struct timeval *start, - const struct timeval *stop, const COUNTER bps) +static inline void +dump_timestamp_trace_array(const struct timeval *start, const struct timeval *stop, const COUNTER bps) { uint32_t i; COUNTER start_us = TIMEVAL_TO_MICROSEC(start); printf("dump_timestamp_trace_array: start=%zd.%06zd stop=%zd.%06zd start_us=%llu traces=%u bps=%llu\n", - start->tv_sec, start->tv_usec, - stop->tv_sec, stop->tv_usec, - start_us, - trace_num, bps); + start->tv_sec, + start->tv_usec, + stop->tv_sec, + stop->tv_usec, + start_us, + trace_num, + bps); for (i = 0; i < trace_num; ++i) { - long long int delta = timestamp_trace_entry_array[i].tx_us - - timestamp_trace_entry_array[i].next_tx_us; + long long int delta = timestamp_trace_entry_array[i].tx_us - timestamp_trace_entry_array[i].next_tx_us; printf("timestamp=%zd.%zd, size=%llu now_us=%llu tx_us=%llu next_tx_us=%llu delta=%lld bytes_sent=%llu skip=%llu\n", - timestamp_trace_entry_array[i].timestamp.tv_sec, - timestamp_trace_entry_array[i].timestamp.tv_usec, - timestamp_trace_entry_array[i].size, - timestamp_trace_entry_array[i].now_us, - timestamp_trace_entry_array[i].tx_us, - timestamp_trace_entry_array[i].next_tx_us, - delta, - timestamp_trace_entry_array[i].bytes_sent, - timestamp_trace_entry_array[i].skip_length); + timestamp_trace_entry_array[i].timestamp.tv_sec, + timestamp_trace_entry_array[i].timestamp.tv_usec, + timestamp_trace_entry_array[i].size, + timestamp_trace_entry_array[i].now_us, + timestamp_trace_entry_array[i].tx_us, + timestamp_trace_entry_array[i].next_tx_us, + delta, + timestamp_trace_entry_array[i].bytes_sent, + timestamp_trace_entry_array[i].skip_length); } } #else -static inline void update_current_timestamp_trace_entry(COUNTER UNUSED(bytes_sent), COUNTER UNUSED(now_us), - COUNTER UNUSED(tx_us), COUNTER UNUSED(next_tx_us)) { } -static inline void add_timestamp_trace_entry(COUNTER UNUSED(size), struct timeval *UNUSED(timestamp), - COUNTER UNUSED(skip_length)) { } -static inline void dump_timestamp_trace_array(const struct timeval *UNUSED(start), - const struct timeval *UNUSED(stop), const COUNTER UNUSED(bps)) { } +static inline void +update_current_timestamp_trace_entry(COUNTER UNUSED(bytes_sent), + COUNTER UNUSED(now_us), + COUNTER UNUSED(tx_us), + COUNTER UNUSED(next_tx_us)) +{} +static inline void +add_timestamp_trace_entry(COUNTER UNUSED(size), struct timeval *UNUSED(timestamp), COUNTER UNUSED(skip_length)) +{} +static inline void +dump_timestamp_trace_array(const struct timeval *UNUSED(start), + const struct timeval *UNUSED(stop), + const COUNTER UNUSED(bps)) +{} #endif /* TIMESTAMP_TRACE */ - -#endif /* TIMESTAMP_TRACE_H_ */ diff --git a/src/tree.c b/src/tree.c index 19a6bd71e..414458167 100644 --- a/src/tree.c +++ b/src/tree.c @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,31 +18,24 @@ * along with the Tcpreplay Suite. If not, see . */ +#include "tree.h" #include "config.h" -#include "defines.h" #include "common.h" - +#include "tcpprep_api.h" +#include "tcpprep_opts.h" #include #include #include -#include "tree.h" -#include "tcpprep.h" -#include "tcpprep_opts.h" -#include "tcpprep_api.h" - extern tcpr_data_tree_t treeroot; extern tcpprep_t *tcpprep; -#ifdef DEBUG -extern int debug; -#endif /* static buffer used by tree_print*() functions */ -char tree_print_buff[TREEPRINTBUFFLEN]; +char tree_print_buff[TREEPRINTBUFFLEN]; static tcpr_tree_t *new_tree(); -static tcpr_tree_t *packet2tree(const u_char *, const int, const int); -#ifdef DEBUG /* prevent compile warnings */ +static tcpr_tree_t *packet2tree(const u_char *, int, int); +#ifdef DEBUG /* prevent compile warnings */ static char *tree_print(tcpr_data_tree_t *); static char *tree_printnode(const char *, const tcpr_tree_t *); #endif /* DEBUG */ @@ -59,22 +52,22 @@ RB_GENERATE(tcpr_data_tree_s, tcpr_tree_s, node, tree_comp) * is smart enough to prevent dupes. void * arg is cast to bulidcidr_t */ void -tree_buildcidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) +tree_buildcidr(tcpr_data_tree_t *tree_root, tcpr_buildcidr_t *bcdata) { tcpr_tree_t *node = NULL; tcpr_cidr_t *newcidr = NULL; - unsigned long network = 0; + unsigned long network; struct tcpr_in6_addr network6; - unsigned long mask = ~0; /* turn on all bits */ + unsigned long mask = ~0; /* turn on all bits */ tcpprep_opt_t *options = tcpprep->options; uint32_t i, j, k; dbg(1, "Running: tree_buildcidr()"); - RB_FOREACH(node, tcpr_data_tree_s, treeroot) { - + RB_FOREACH(node, tcpr_data_tree_s, tree_root) + { /* we only check types that are valid */ - if (bcdata->type != DIR_ANY) /* don't check if we're adding ANY */ + if (bcdata->type != DIR_ANY) /* don't check if we're adding ANY */ if (bcdata->type != node->type) /* no match, exit early */ return; /* @@ -83,9 +76,8 @@ tree_buildcidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) */ dbgx(4, "Checking if %s exists in cidrdata...", get_addr2name4(node->u.ip, RESOLVE)); if (node->family == AF_INET) { - if (! check_ip_cidr(options->cidrdata, node->u.ip)) { /* if we exist, abort */ - dbgx(3, "Node %s doesn't exist... creating.", - get_addr2name4(node->u.ip, RESOLVE)); + if (!check_ip_cidr(options->cidrdata, node->u.ip)) { /* if we exist, abort */ + dbgx(3, "Node %s doesn't exist... creating.", get_addr2name4(node->u.ip, RESOLVE)); newcidr = new_cidr(); newcidr->masklen = bcdata->masklen; network = node->u.ip & (mask << (32 - bcdata->masklen)); @@ -93,12 +85,11 @@ tree_buildcidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) newcidr->u.network = network; add_cidr(&options->cidrdata, &newcidr); } - } + } /* Check IPv6 Address */ else if (node->family == AF_INET6) { - if (! check_ip6_cidr(options->cidrdata, &node->u.ip6)) { /* if we exist, abort */ - dbgx(3, "Node %s doesn't exist... creating.", - get_addr2name6(&node->u.ip6, RESOLVE)); + if (!check_ip6_cidr(options->cidrdata, &node->u.ip6)) { /* if we exist, abort */ + dbgx(3, "Node %s doesn't exist... creating.", get_addr2name6(&node->u.ip6, RESOLVE)); newcidr = new_cidr(); newcidr->masklen = bcdata->masklen; @@ -126,22 +117,20 @@ tree_buildcidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) } } - /** * uses rbwalk to check to see if a given ip address of a given type in the * tree is inside any of the cidrdata */ static int -tree_checkincidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) +tree_checkincidr(tcpr_data_tree_t *tree_root, tcpr_buildcidr_t *bcdata) { tcpr_tree_t *node = NULL; tcpprep_opt_t *options = tcpprep->options; - - RB_FOREACH(node, tcpr_data_tree_s, treeroot) { - + RB_FOREACH(node, tcpr_data_tree_s, tree_root) + { /* we only check types that are valid */ - if (bcdata->type != DIR_ANY) /* don't check if we're adding ANY */ + if (bcdata->type != DIR_ANY) /* don't check if we're adding ANY */ if (bcdata->type != node->type) /* no match, exit early */ return 0; @@ -149,11 +138,10 @@ tree_checkincidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) * in cases of leaves and last visit add to cidrdata if * necessary */ - if (node->family == AF_INET && check_ip_cidr(options->cidrdata, node->u.ip)) /* if we exist, abort */ + if (node->family == AF_INET && check_ip_cidr(options->cidrdata, node->u.ip)) /* if we exist, abort */ return 1; if (node->family == AF_INET6 && check_ip6_cidr(options->cidrdata, &node->u.ip6)) return 1; - } return 0; } @@ -167,11 +155,10 @@ tree_checkincidr(tcpr_data_tree_t *treeroot, tcpr_buildcidr_t * bcdata) int process_tree(void) { - int mymask = 0; + int mymask; tcpr_buildcidr_t *bcdata; tcpprep_opt_t *options = tcpprep->options; - dbg(1, "Running: process_tree()"); bcdata = (tcpr_buildcidr_t *)safe_malloc(sizeof(tcpr_buildcidr_t)); @@ -192,11 +179,10 @@ process_tree(void) /* try to find clients in cidrdata */ bcdata->type = DIR_CLIENT; - if (! tree_checkincidr(&treeroot, bcdata)) { /* didn't find any clients in cidrdata */ + if (!tree_checkincidr(&treeroot, bcdata)) { /* didn't find any clients in cidrdata */ safe_free(bcdata); - return (mymask); /* success! */ - } - else { + return (mymask); /* success! */ + } else { destroy_cidr(options->cidrdata); /* clean up after our mess */ options->cidrdata = NULL; } @@ -216,7 +202,7 @@ process_tree(void) * is smart enough to prevent dupes void -tcpr_tree_to_cidr(const int masklen, const int type) +tcpr_tree_to_cidr(int masklen, int type) { } @@ -230,7 +216,7 @@ tcpr_tree_to_cidr(const int masklen, const int type) * if mode = SERVER, then unknowns become servers */ tcpr_dir_t -check_ip_tree(const int mode, const unsigned long ip) +check_ip_tree(int mode, unsigned long ip) { tcpr_tree_t *node, *finder; @@ -242,9 +228,11 @@ check_ip_tree(const int mode, const unsigned long ip) if (node == NULL && mode == DIR_UNKNOWN) { safe_free(finder); - errx(-1, "%s (%lu) is an unknown system... aborting.!\n" + errx(-1, + "%s (%lu) is an unknown system... aborting.!\n" "Try a different auto mode (-n router|client|server)", - get_addr2name4(ip, RESOLVE), ip); + get_addr2name4(ip, RESOLVE), + ip); } /* return node type if we found the node, else return the default (mode) */ @@ -254,40 +242,36 @@ check_ip_tree(const int mode, const unsigned long ip) dbgx(1, "DIR_SERVER: %s", get_addr2name4(ip, RESOLVE)); safe_free(finder); return TCPR_DIR_S2C; - break; case DIR_CLIENT: dbgx(1, "DIR_CLIENT: %s", get_addr2name4(ip, RESOLVE)); safe_free(finder); return TCPR_DIR_C2S; - break; case DIR_UNKNOWN: dbgx(1, "DIR_UNKNOWN: %s", get_addr2name4(ip, RESOLVE)); /* use our current mode to determine return code */ goto return_unknown; case DIR_ANY: dbgx(1, "DIR_ANY: %s", get_addr2name4(ip, RESOLVE)); - goto return_unknown; + goto return_unknown; default: errx(-1, "Node for %s has invalid type: %d", get_addr2name4(ip, RESOLVE), node->type); } } - + return_unknown: safe_free(finder); switch (mode) { case DIR_SERVER: return TCPR_DIR_S2C; - break; case DIR_CLIENT: return TCPR_DIR_C2S; - break; default: return -1; } } tcpr_dir_t -check_ip6_tree(const int mode, const struct tcpr_in6_addr *addr) +check_ip6_tree(int mode, const struct tcpr_in6_addr *addr) { tcpr_tree_t *node, *finder; @@ -299,7 +283,8 @@ check_ip6_tree(const int mode, const struct tcpr_in6_addr *addr) if (node == NULL && mode == DIR_UNKNOWN) { safe_free(finder); - errx(-1, "%s is an unknown system... aborting.!\n" + errx(-1, + "%s is an unknown system... aborting.!\n" "Try a different auto mode (-n router|client|server)", get_addr2name6(addr, RESOLVE)); } @@ -311,12 +296,10 @@ check_ip6_tree(const int mode, const struct tcpr_in6_addr *addr) dbgx(1, "DIR_SERVER: %s", get_addr2name6(addr, RESOLVE)); safe_free(finder); return TCPR_DIR_S2C; - break; case DIR_CLIENT: dbgx(1, "DIR_CLIENT: %s", get_addr2name6(addr, RESOLVE)); safe_free(finder); return TCPR_DIR_C2S; - break; case DIR_UNKNOWN: dbgx(1, "DIR_UNKNOWN: %s", get_addr2name6(addr, RESOLVE)); /* use our current mode to determine return code */ @@ -334,22 +317,20 @@ check_ip6_tree(const int mode, const struct tcpr_in6_addr *addr) switch (mode) { case DIR_SERVER: return TCPR_DIR_S2C; - break; case DIR_CLIENT: return TCPR_DIR_C2S; - break; default: return -1; } } /** - * Parses the IP header of the given packet (data) to get the SRC/DST IP + * Parses the IP header of the given packet (data) to get the SRC/DST IP * addresses. If the SRC IP doesn't exist in the TREE, we add it as a * client, if the DST IP doesn't exist in the TREE, we add it as a server */ void -add_tree_first_ipv4(const u_char *data, const int len, const int datalink) +add_tree_first_ipv4(const u_char *data, int len, int datalink) { tcpr_tree_t *newnode, *findnode; uint32_t _U_ vlan_offset; @@ -362,21 +343,14 @@ add_tree_first_ipv4(const u_char *data, const int len, const int datalink) assert(data); - res = get_l2len_protocol(data, - pkt_len, - datalink, - ðer_type, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(data, pkt_len, datalink, ðer_type, &l2len, &l2offset, &vlan_offset); if (res == -1 || len < (int)(l2len + TCPR_IPV4_H)) { errx(-1, "Capture length %d too small for IPv4 parsing", len); - return; } - /* - * first add/find the source IP/client + /* + * first add/find the source IP/client */ newnode = new_tree(); @@ -417,7 +391,7 @@ add_tree_first_ipv4(const u_char *data, const int len, const int datalink) } void -add_tree_first_ipv6(const u_char *data, const int len, const int datalink) +add_tree_first_ipv6(const u_char *data, int len, int datalink) { tcpr_tree_t *newnode, *findnode; uint32_t _U_ vlan_offset; @@ -430,24 +404,16 @@ add_tree_first_ipv6(const u_char *data, const int len, const int datalink) assert(data); - res = get_l2len_protocol(data, - pkt_len, - datalink, - ðer_type, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(data, pkt_len, datalink, ðer_type, &l2len, &l2offset, &vlan_offset); - if (res == -1 || len < (int)(l2len + TCPR_IPV6_H)) { + if (res == -1 || len < (int)(l2len + TCPR_IPV6_H)) errx(-1, "Capture length %d too small for IPv6 parsing", len); - return; - } /* * first add/find the source IP/client */ newnode = new_tree(); - + /* prevent issues with byte alignment, must memcpy */ memcpy(&ip6_hdr, data + l2len, TCPR_IPV6_H); @@ -499,27 +465,24 @@ add_tree_node(tcpr_tree_t *newnode) /* increment counters */ if (newnode->type == DIR_SERVER) { newnode->server_cnt++; - } - else if (newnode->type == DIR_CLIENT) { + } else if (newnode->type == DIR_CLIENT) { newnode->client_cnt++; } /* insert it in */ RB_INSERT(tcpr_data_tree_s, &treeroot, newnode); - } - else { + } else { /* we found something, so update it */ dbgx(2, " node: %p\nnewnode: %p", node, newnode); dbgx(3, "%s", tree_printnode("update node", node)); /* increment counter */ if (newnode->type == DIR_SERVER) { node->server_cnt++; - } - else if (newnode->type == DIR_CLIENT) { + } else if (newnode->type == DIR_CLIENT) { /* temp debug code */ node->client_cnt++; } - + /* didn't insert it, so free it */ safe_free(newnode); } @@ -534,84 +497,68 @@ add_tree_node(tcpr_tree_t *newnode) * - number of times each host acts as a client or server * - the way the host acted the first time we saw it (client or server) */ -void add_tree_ipv4(const unsigned long ip, - const u_char *data, - const int len, - const int datalink) +void +add_tree_ipv4(unsigned long ip, const u_char *data, int len, int datalink) { tcpr_tree_t *newnode; assert(data); newnode = packet2tree(data, len, datalink); - if (newnode) { - assert(ip == newnode->u.ip); - - if (newnode->type == DIR_UNKNOWN) { - /* couldn't figure out if packet was client or server */ + assert(newnode); + assert(ip == newnode->u.ip); + if (newnode->type == DIR_UNKNOWN) { + /* couldn't figure out if packet was client or server */ - dbgx(2, "%s (%lu) unknown client/server", - get_addr2name4(newnode->u.ip, RESOLVE), - newnode->u.ip); - - } - - add_tree_node(newnode); + dbgx(2, "%s (%lu) unknown client/server", get_addr2name4(newnode->u.ip, RESOLVE), newnode->u.ip); } + + add_tree_node(newnode); } -void add_tree_ipv6(const struct tcpr_in6_addr *addr, - const u_char *data, - const int len, - const int datalink) +void +add_tree_ipv6(const struct tcpr_in6_addr *addr, const u_char *data, int len, int datalink) { tcpr_tree_t *newnode; assert(data); newnode = packet2tree(data, len, datalink); - if (newnode) { - assert(ipv6_cmp(addr, &newnode->u.ip6) == 0); - - if (newnode->type == DIR_UNKNOWN) { - /* couldn't figure out if packet was client or server */ - - dbgx(2, "%s unknown client/server", - get_addr2name6(&newnode->u.ip6, RESOLVE)); - } + assert(newnode); + assert(ipv6_cmp(addr, &newnode->u.ip6) == 0); + if (newnode->type == DIR_UNKNOWN) { + /* couldn't figure out if packet was client or server */ - add_tree_node(newnode); + dbgx(2, "%s unknown client/server", get_addr2name6(&newnode->u.ip6, RESOLVE)); } + + add_tree_node(newnode); } /** * calculates whether each node in the tree is a client, server, or unknown for each node in the tree */ void -tree_calculate(tcpr_data_tree_t *treeroot) +tree_calculate(tcpr_data_tree_t *tree_root) { tcpr_tree_t *node; tcpprep_opt_t *options = tcpprep->options; dbg(1, "Running tree_calculate()"); - RB_FOREACH(node, tcpr_data_tree_s, treeroot) { + RB_FOREACH(node, tcpr_data_tree_s, tree_root) + { dbgx(4, "Processing %s", get_addr2name4(node->u.ip, RESOLVE)); if ((node->server_cnt > 0) || (node->client_cnt > 0)) { /* type based on: server >= (client*ratio) */ if ((double)node->server_cnt >= (double)node->client_cnt * options->ratio) { node->type = DIR_SERVER; - dbgx(3, "Setting %s to server", - get_addr2name4(node->u.ip, RESOLVE)); - } - else { + dbgx(3, "Setting %s to server", get_addr2name4(node->u.ip, RESOLVE)); + } else { node->type = DIR_CLIENT; - dbgx(3, "Setting %s to client", - get_addr2name4(node->u.ip, RESOLVE)); + dbgx(3, "Setting %s to client", get_addr2name4(node->u.ip, RESOLVE)); } - } - else { /* IP had no client or server connections */ + } else { /* IP had no client or server connections */ node->type = DIR_UNKNOWN; - dbgx(3, "Setting %s to unknown", - get_addr2name4(node->u.ip, RESOLVE)); + dbgx(3, "Setting %s to unknown", get_addr2name4(node->u.ip, RESOLVE)); } } } @@ -623,7 +570,7 @@ ipv6_cmp(const struct tcpr_in6_addr *a, const struct tcpr_in6_addr *b) for (i = 0; i < 4; i++) { int k; - if ((k = (a->tcpr_s6_addr32[i] - b->tcpr_s6_addr32[i]))) { + if ((k = ((int)a->tcpr_s6_addr32[i] - (int)b->tcpr_s6_addr32[i]))) { return (k > 0) ? 1 : -1; } } @@ -654,27 +601,23 @@ tree_comp(tcpr_tree_t *t1, tcpr_tree_t *t2) if (t1->family == AF_INET) { if (t1->u.ip > t2->u.ip) { - dbgx(2, "%s > %s", get_addr2name4(t1->u.ip, RESOLVE), - get_addr2name4(t2->u.ip, RESOLVE)); + dbgx(2, "%s > %s", get_addr2name4(t1->u.ip, RESOLVE), get_addr2name4(t2->u.ip, RESOLVE)); return 1; } if (t1->u.ip < t2->u.ip) { - dbgx(2, "%s < %s", get_addr2name4(t1->u.ip, RESOLVE), - get_addr2name4(t2->u.ip, RESOLVE)); + dbgx(2, "%s < %s", get_addr2name4(t1->u.ip, RESOLVE), get_addr2name4(t2->u.ip, RESOLVE)); return -1; } - dbgx(2, "%s = %s", get_addr2name4(t1->u.ip, RESOLVE), - get_addr2name4(t2->u.ip, RESOLVE)); + dbgx(2, "%s = %s", get_addr2name4(t1->u.ip, RESOLVE), get_addr2name4(t2->u.ip, RESOLVE)); return 0; } if (t1->family == AF_INET6) { int ret = ipv6_cmp(&t1->u.ip6, &t1->u.ip6); - dbgx(2, "cmp(%s, %s) = %d", get_addr2name6(&t1->u.ip6, RESOLVE), - get_addr2name6(&t2->u.ip6, RESOLVE), ret); + dbgx(2, "cmp(%s, %s) = %d", get_addr2name6(&t1->u.ip6, RESOLVE), get_addr2name6(&t2->u.ip6, RESOLVE), ret); return ret; } @@ -700,7 +643,6 @@ new_tree() return (node); } - /** * returns a struct of TREE * from a packet header * and sets the type to be SERVER or CLIENT or UNKNOWN @@ -708,7 +650,7 @@ new_tree() * the u_char * data should be the data that is passed by pcap_dispatch() */ static tcpr_tree_t * -packet2tree(const u_char * data, const int len, int datalink) +packet2tree(const u_char *data, int len, int datalink) { uint32_t _U_ vlan_offset; ssize_t pkt_len = len; @@ -730,23 +672,15 @@ packet2tree(const u_char * data, const int len, int datalink) char srcip[INET6_ADDRSTRLEN]; #endif - res = get_l2len_protocol(data, - pkt_len, - datalink, - ðer_type, - &l2len, - &l2offset, - &vlan_offset); + res = get_l2len_protocol(data, pkt_len, datalink, ðer_type, &l2len, &l2offset, &vlan_offset); if (res == -1) goto len_error; node = new_tree(); - assert(l2len > 0); - if (ether_type == ETHERTYPE_IP) { - if (pkt_len < (ssize_t)(l2len + TCPR_IPV4_H + hl)) + if (pkt_len < (ssize_t)l2len + TCPR_IPV4_H + hl) goto len_error; memcpy(&ip_hdr, data + l2len + hl, TCPR_IPV4_H); @@ -760,7 +694,7 @@ packet2tree(const u_char * data, const int len, int datalink) strlcpy(srcip, get_addr2name4(ip_hdr.ip_src.s_addr, RESOLVE), 16); #endif } else if (ether_type == ETHERTYPE_IP6) { - if (pkt_len < (ssize_t)(l2len + TCPR_IPV6_H + hl)) { + if (pkt_len < (ssize_t)l2len + TCPR_IPV6_H + hl) { goto len_error; } @@ -772,23 +706,21 @@ packet2tree(const u_char * data, const int len, int datalink) hl += TCPR_IPV6_H; #ifdef DEBUG - strlcpy(srcip, get_addr2name6(&ip6_hdr.ip_src, RESOLVE), - INET6_ADDRSTRLEN); + strlcpy(srcip, get_addr2name6(&ip6_hdr.ip_src, RESOLVE), INET6_ADDRSTRLEN); #endif } else { - dbgx(2,"Unrecognized ether_type (%x)", ether_type); + dbgx(2, "Unrecognized ether_type (%x)", ether_type); } - /* - * TCP + /* + * TCP */ if (proto == IPPROTO_TCP) { - #ifdef DEBUG dbgx(3, "%s uses TCP... ", srcip); #endif - if (pkt_len < (ssize_t)(l2len + TCPR_TCP_H + hl)) + if (pkt_len < (ssize_t)l2len + TCPR_TCP_H + hl) goto len_error; /* memcpy it over to prevent alignment issues */ @@ -802,20 +734,18 @@ packet2tree(const u_char * data, const int len, int datalink) if (tcp_hdr.th_flags == TH_SYN) { node->type = DIR_CLIENT; dbg(3, "is a client"); - } - else if (tcp_hdr.th_flags == (TH_SYN | TH_ACK)) { + } else if (tcp_hdr.th_flags == (TH_SYN | TH_ACK)) { node->type = DIR_SERVER; dbg(3, "is a server"); - } - else { + } else { dbg(3, "is an unknown"); } } - /* - * UDP + /* + * UDP */ else if (proto == IPPROTO_UDP) { - if (pkt_len < (ssize_t)(l2len + TCPR_UDP_H + hl)) + if (pkt_len < (ssize_t)l2len + TCPR_UDP_H + hl) goto len_error; /* memcpy over to prevent alignment issues */ @@ -825,8 +755,8 @@ packet2tree(const u_char * data, const int len, int datalink) #endif switch (ntohs(udp_hdr.uh_dport)) { - case 0x0035: /* dns */ - if (pkt_len < (ssize_t)(l2len + TCPR_UDP_H + TCPR_DNS_H + hl)) + case 0x0035: /* dns */ + if (pkt_len < (ssize_t)l2len + TCPR_UDP_H + TCPR_DNS_H + hl) goto len_error; /* prevent memory alignment issues */ @@ -838,22 +768,20 @@ packet2tree(const u_char * data, const int len, int datalink) dbg(3, "is a dns server"); - } - else { + } else { /* bit not set, query */ node->type = DIR_CLIENT; dbg(3, "is a dns client"); } return (node); - break; default: break; } switch (ntohs(udp_hdr.uh_sport)) { - case 0x0035: /* dns */ - if (pkt_len < (ssize_t)(l2len + TCPR_UDP_H + TCPR_DNS_H + hl)) + case 0x0035: /* dns */ + if (pkt_len < (ssize_t)l2len + TCPR_UDP_H + TCPR_DNS_H + hl) goto len_error; /* prevent memory alignment issues */ @@ -863,26 +791,23 @@ packet2tree(const u_char * data, const int len, int datalink) /* bit set, response */ node->type = DIR_SERVER; dbg(3, "is a dns server"); - } - else { + } else { /* bit not set, query */ node->type = DIR_CLIENT; dbg(3, "is a dns client"); } return (node); - break; default: - dbgx(3, "unknown UDP protocol: %hu->%hu", udp_hdr.uh_sport, - udp_hdr.uh_dport); + dbgx(3, "unknown UDP protocol: %hu->%hu", udp_hdr.uh_sport, udp_hdr.uh_dport); break; } } - /* - * ICMP + /* + * ICMP */ else if (proto == IPPROTO_ICMP) { - if (pkt_len < (ssize_t)(l2len + TCPR_ICMPV4_H + hl)) + if (pkt_len < (ssize_t)l2len + TCPR_ICMPV4_H + hl) goto len_error; /* prevent alignment issues */ @@ -893,14 +818,12 @@ packet2tree(const u_char * data, const int len, int datalink) #endif /* - * if port unreachable, then source == server, dst == client + * if port unreachable, then source == server, dst == client */ - if ((icmp_hdr.icmp_type == ICMP_UNREACH) && - (icmp_hdr.icmp_code == ICMP_UNREACH_PORT)) { + if ((icmp_hdr.icmp_type == ICMP_UNREACH) && (icmp_hdr.icmp_code == ICMP_UNREACH_PORT)) { node->type = DIR_SERVER; dbg(3, "is a server with a closed port"); } - } return (node); @@ -908,7 +831,6 @@ packet2tree(const u_char * data, const int len, int datalink) len_error: safe_free(node); errx(-1, "packet capture length %d too small to process", len); - return NULL; } #ifdef DEBUG @@ -918,26 +840,26 @@ packet2tree(const u_char * data, const int len, int datalink) static char * tree_printnode(const char *name, const tcpr_tree_t *node) { - memset(&tree_print_buff, '\0', TREEPRINTBUFFLEN); if (node == NULL) { snprintf(tree_print_buff, TREEPRINTBUFFLEN, "%s node is null", name); } else { - snprintf(tree_print_buff, TREEPRINTBUFFLEN, - "-- %s: %p\nIP: %s\nMask: %d\nSrvr: %d\nClnt: %d\n", - name, (void *)node, node->family == AF_INET ? - get_addr2name4(node->u.ip, RESOLVE) : - get_addr2name6(&node->u.ip6, RESOLVE), - node->masklen, node->server_cnt, node->client_cnt); + snprintf(tree_print_buff, + TREEPRINTBUFFLEN, + "-- %s: %p\nIP: %s\nMask: %d\nSrvr: %d\nClnt: %d\n", + name, + (void *)node, + node->family == AF_INET ? get_addr2name4(node->u.ip, RESOLVE) : get_addr2name6(&node->u.ip6, RESOLVE), + node->masklen, + node->server_cnt, + node->client_cnt); if (node->type == DIR_SERVER) { strlcat(tree_print_buff, "Type: Server\n--\n", TREEPRINTBUFFLEN); - } - else { + } else { strlcat(tree_print_buff, "Type: Client\n--", TREEPRINTBUFFLEN); } - } return (tree_print_buff); } @@ -946,14 +868,14 @@ tree_printnode(const char *name, const tcpr_tree_t *node) * prints out the entire tree */ static char * -tree_print(tcpr_data_tree_t *treeroot) +tree_print(tcpr_data_tree_t *tree_root) { tcpr_tree_t *node = NULL; memset(&tree_print_buff, '\0', TREEPRINTBUFFLEN); - RB_FOREACH(node, tcpr_data_tree_s, treeroot) { + RB_FOREACH(node, tcpr_data_tree_s, tree_root) + { tree_printnode("my node", node); } return (tree_print_buff); - } #endif /* DEBUG */ diff --git a/src/tree.h b/src/tree.h index faecfea8f..9c6ff1b46 100644 --- a/src/tree.h +++ b/src/tree.h @@ -4,9 +4,9 @@ * Copyright (c) 2001-2010 Aaron Turner * Copyright (c) 2013-2022 Fred Klassen - AppNeta * - * The Tcpreplay Suite of tools is free software: you can redistribute it - * and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the + * The Tcpreplay Suite of tools is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the * License, or with the authors permission any later version. * * The Tcpreplay Suite is distributed in the hope that it will be useful, @@ -18,10 +18,11 @@ * along with the Tcpreplay Suite. If not, see . */ -#ifndef __TREE_H__ -#define __TREE_H__ +#pragma once -#include "lib/tree.h" +#include "defines.h" +#include "tcpr.h" +#include #define TREEPRINTBUFFLEN 2048 @@ -29,13 +30,13 @@ typedef struct tcpr_tree_s { RB_ENTRY(tcpr_tree_s) node; int family; union { - unsigned long ip; /* ip/network address in network byte order */ + unsigned long ip; /* ip/network address in network byte order */ struct tcpr_in6_addr ip6; } u; - int masklen; /* CIDR network mask length */ - int server_cnt; /* count # of times this entry was flagged server */ - int client_cnt; /* flagged client */ - int type; /* 1 = server, 0 = client, -1 = undefined */ + int masklen; /* CIDR network mask length */ + int server_cnt; /* count # of times this entry was flagged server */ + int client_cnt; /* flagged client */ + int type; /* 1 = server, 0 = client, -1 = undefined */ } tcpr_tree_t; /* @@ -46,23 +47,18 @@ typedef struct tcpr_data_tree_s { } tcpr_data_tree_t; typedef struct tcpr_buildcidr_s { - int type; /* SERVER|CLIENT|UNKNOWN|ANY */ - int masklen; /* mask size to use to build the CIDR */ + int type; /* SERVER|CLIENT|UNKNOWN|ANY */ + int masklen; /* mask size to use to build the CIDR */ } tcpr_buildcidr_t; #define DNS_QUERY_FLAG 0x8000 -void add_tree_ipv4(const unsigned long, const u_char*, const int, const int); -void add_tree_ipv6(const struct tcpr_in6_addr*, - const u_char*, - const int, - const int); -void add_tree_first_ipv4(const u_char *, const int, const int); -void add_tree_first_ipv6(const u_char *, const int, const int); -tcpr_dir_t check_ip_tree(const int, const unsigned long); -tcpr_dir_t check_ip6_tree(const int, const struct tcpr_in6_addr *); +void add_tree_ipv4(unsigned long, const u_char *, int, int); +void add_tree_ipv6(const struct tcpr_in6_addr *, const u_char *, int, int); +void add_tree_first_ipv4(const u_char *, int, int); +void add_tree_first_ipv6(const u_char *, int, int); +tcpr_dir_t check_ip_tree(int, unsigned long); +tcpr_dir_t check_ip6_tree(int, const struct tcpr_in6_addr *); int process_tree(); void tree_calculate(tcpr_data_tree_t *); int tree_comp(tcpr_tree_t *, tcpr_tree_t *); - -#endif diff --git a/test/Makefile.am b/test/Makefile.am index 299e4aa23..405438aac 100644 --- a/test/Makefile.am +++ b/test/Makefile.am @@ -68,7 +68,7 @@ standard_prep: $(TCPPREP) -i $(TEST_PCAP) -o test.auto_bridge -a bridge $(TCPPREP) -i $(TEST_PCAP) -o test.auto_client -a client $(TCPPREP) -i $(TEST_PCAP) -o test.auto_server -a server - $(TCPPREP) -i test.pcap -o test.auto_first -a first + $(TCPPREP) -i $(TEST_PCAP) -o test.auto_first -a first $(TCPPREP) --load-opts config -o test.prep_config $(TCPPREP) -i $(TEST_PCAP) -o test.port -p $(TCPPREP) -i $(TEST_PCAP) -o test.mac -e 00:1f:f3:3c:e1:13 @@ -313,29 +313,29 @@ mac_reverse: exclude_packets: $(PRINTF) "%s" "[tcpprep] exclude packets test: " $(PRINTF) "%s\n" "*** [tcpprep] exclude packets test: " >> test.log - $(TCPPREP) $(ENABLE_DEBUG) -i test.pcap -o test.$@1 -c '96.17.211.0/24' --exclude 'P:61-65,88-91' >> test.log 2>&1 - diff test.$@ test.$@1 >> test.log 2>&1 + $(TCPPREP) $(ENABLE_DEBUG) -i $(TEST_PCAP) -o test.$@1 -c '96.17.211.0/24' --exclude 'P:61-65,88-91' >> test.log 2>&1 + diff $(srcdir)/test.$@ test.$@1 >> test.log 2>&1 if [ $? ] ; then $(PRINTF) "\t\t%s\n" "FAILED"; else $(PRINTF) "\t\t%s\n" "OK"; fi include_packets: $(PRINTF) "%s" "[tcpprep] include packets test: " $(PRINTF) "%s\n" "*** [tcpprep] include packets test: " >> test.log - $(TCPPREP) $(ENABLE_DEBUG) -i test.pcap -o test.$@1 -c '96.17.211.0/24' --include 'P:61-65,88-91' >> test.log 2>&1 - diff test.$@ test.$@1 >> test.log 2>&1 + $(TCPPREP) $(ENABLE_DEBUG) -i $(TEST_PCAP) -o test.$@1 -c '96.17.211.0/24' --include 'P:61-65,88-91' >> test.log 2>&1 + diff $(srcdir)/test.$@ test.$@1 >> test.log 2>&1 if [ $? ] ; then $(PRINTF) "\t\t\t%s\n" "FAILED"; else $(PRINTF) "\t\t%s\n" "OK"; fi include_source: $(PRINTF) "%s" "[tcpprep] include source test: " $(PRINTF) "%s\n" "*** [tcpprep] include source test: " >> test.log - $(TCPPREP) $(ENABLE_DEBUG) -i test.pcap -o test.$@1 -c '96.17.211.0/24' --include 'S:96.0.0.0/8' >> test.log 2>&1 - diff test.$@ test.$@1 >> test.log 2>&1 + $(TCPPREP) $(ENABLE_DEBUG) -i $(TEST_PCAP) -o test.$@1 -c '96.17.211.0/24' --include 'S:96.0.0.0/8' >> test.log 2>&1 + diff $(srcdir)/test.$@ test.$@1 >> test.log 2>&1 if [ $? ] ; then $(PRINTF) "\t\t%s\n" "FAILED"; else $(PRINTF) "\t\t\t%s\n" "OK"; fi include_dest: $(PRINTF) "%s" "[tcpprep] include destination test: " $(PRINTF) "%s\n" "*** [tcpprep] include destination test: " >> test.log - $(TCPPREP) $(ENABLE_DEBUG) -i test.pcap -o test.$@1 -c '96.17.211.0/24' --include 'D:96.0.0.0/8' >> test.log 2>&1 - diff test.$@ test.$@1 >> test.log 2>&1 + $(TCPPREP) $(ENABLE_DEBUG) -i $(TEST_PCAP) -o test.$@1 -c '96.17.211.0/24' --include 'D:96.0.0.0/8' >> test.log 2>&1 + diff $(srcdir)/test.$@ test.$@1 >> test.log 2>&1 if [ $? ] ; then $(PRINTF) "\t\t%s\n" "FAILED"; else $(PRINTF) "\t\t%s\n" "OK"; fi replay_basic: diff --git a/test/config.in b/test/config.in index b5ce8a2ae..6b3162f58 100644 --- a/test/config.in +++ b/test/config.in @@ -1,24 +1,23 @@ # tcpreplay - Replay network traffic stored in pcap files # preset/initialization file -# Mon Jan 10 15:19:55 2005 # [TCPREPLAY] -cachefile test.auto_bridge +cachefile @srcdir@/test.auto_bridge intf1 @nic1@ intf2 @nic2@ topspeed [TCPREWRITE] -infile test.pcap -outfile test.rewrite_config1 -cachefile test.auto_bridge +infile @srcdir@/test.pcap +outfile test.rewrite_config1 +cachefile @srcdir@/test.auto_bridge enet-vlan add enet-vlan-tag 45 enet-vlan-cfi 1 enet-vlan-pri 5 [TCPPREP] -pcap test.pcap +pcap @srcdir@/test.pcap auto bridge minmask 31 maxmask 16 diff --git a/test/test.rewrite_1ttl b/test/test.rewrite_1ttl index 8ed279a1b..678358545 100644 Binary files a/test/test.rewrite_1ttl and b/test/test.rewrite_1ttl differ diff --git a/test/test.rewrite_2ttl b/test/test.rewrite_2ttl index 9427e3a03..8ad459994 100644 Binary files a/test/test.rewrite_2ttl and b/test/test.rewrite_2ttl differ diff --git a/test/test.rewrite_3ttl b/test/test.rewrite_3ttl index 7205a082f..66662c01b 100644 Binary files a/test/test.rewrite_3ttl and b/test/test.rewrite_3ttl differ diff --git a/test/test.rewrite_config b/test/test.rewrite_config index 89fdedccc..164e13b33 100644 Binary files a/test/test.rewrite_config and b/test/test.rewrite_config differ diff --git a/test/test.rewrite_efcs b/test/test.rewrite_efcs index da4fa0d3c..470dc3778 100644 Binary files a/test/test.rewrite_efcs and b/test/test.rewrite_efcs differ diff --git a/test/test.rewrite_endpoint b/test/test.rewrite_endpoint index 5fab44704..5121e5cfc 100644 Binary files a/test/test.rewrite_endpoint and b/test/test.rewrite_endpoint differ diff --git a/test/test.rewrite_enet_subsmac b/test/test.rewrite_enet_subsmac index cc6af5a5f..4f49673d9 100644 Binary files a/test/test.rewrite_enet_subsmac and b/test/test.rewrite_enet_subsmac differ diff --git a/test/test.rewrite_fixcsum b/test/test.rewrite_fixcsum index b116ffba4..f82948553 100644 Binary files a/test/test.rewrite_fixcsum and b/test/test.rewrite_fixcsum differ diff --git a/test/test.rewrite_fixlen_del b/test/test.rewrite_fixlen_del index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_fixlen_del and b/test/test.rewrite_fixlen_del differ diff --git a/test/test.rewrite_fixlen_pad b/test/test.rewrite_fixlen_pad index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_fixlen_pad and b/test/test.rewrite_fixlen_pad differ diff --git a/test/test.rewrite_fixlen_trunc b/test/test.rewrite_fixlen_trunc index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_fixlen_trunc and b/test/test.rewrite_fixlen_trunc differ diff --git a/test/test.rewrite_l7fuzzing b/test/test.rewrite_l7fuzzing index d4bdc9e85..d6e022462 100644 Binary files a/test/test.rewrite_l7fuzzing and b/test/test.rewrite_l7fuzzing differ diff --git a/test/test.rewrite_mac b/test/test.rewrite_mac index 1a0bee42d..15aa507f9 100644 Binary files a/test/test.rewrite_mac and b/test/test.rewrite_mac differ diff --git a/test/test.rewrite_mac_seed b/test/test.rewrite_mac_seed index 79b8fc813..88e78b200 100644 Binary files a/test/test.rewrite_mac_seed and b/test/test.rewrite_mac_seed differ diff --git a/test/test.rewrite_mac_seed_keep b/test/test.rewrite_mac_seed_keep index 2d0d903ca..365140c7d 100644 Binary files a/test/test.rewrite_mac_seed_keep and b/test/test.rewrite_mac_seed_keep differ diff --git a/test/test.rewrite_mtutrunc b/test/test.rewrite_mtutrunc index 5a873dd98..f373dd01f 100644 Binary files a/test/test.rewrite_mtutrunc and b/test/test.rewrite_mtutrunc differ diff --git a/test/test.rewrite_pad b/test/test.rewrite_pad index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_pad and b/test/test.rewrite_pad differ diff --git a/test/test.rewrite_pnat b/test/test.rewrite_pnat index 277d3d4bf..1a8d42fac 100644 Binary files a/test/test.rewrite_pnat and b/test/test.rewrite_pnat differ diff --git a/test/test.rewrite_portmap b/test/test.rewrite_portmap index 472036112..b519c2589 100644 Binary files a/test/test.rewrite_portmap and b/test/test.rewrite_portmap differ diff --git a/test/test.rewrite_range_portmap b/test/test.rewrite_range_portmap index 8dd0189bc..c9a1c82ad 100644 Binary files a/test/test.rewrite_range_portmap and b/test/test.rewrite_range_portmap differ diff --git a/test/test.rewrite_seed b/test/test.rewrite_seed index b2e473925..6204f570f 100644 Binary files a/test/test.rewrite_seed and b/test/test.rewrite_seed differ diff --git a/test/test.rewrite_sequence b/test/test.rewrite_sequence index 70b365751..d19f23f41 100644 Binary files a/test/test.rewrite_sequence and b/test/test.rewrite_sequence differ diff --git a/test/test.rewrite_skip b/test/test.rewrite_skip index 378e930b2..d4e348cbd 100644 Binary files a/test/test.rewrite_skip and b/test/test.rewrite_skip differ diff --git a/test/test.rewrite_tos b/test/test.rewrite_tos index 2c8ce6f35..fb56b6761 100644 Binary files a/test/test.rewrite_tos and b/test/test.rewrite_tos differ diff --git a/test/test.rewrite_trunc b/test/test.rewrite_trunc index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_trunc and b/test/test.rewrite_trunc differ diff --git a/test/test.rewrite_vlan802.1ad b/test/test.rewrite_vlan802.1ad index 6948826c7..f3fcc1bee 100644 Binary files a/test/test.rewrite_vlan802.1ad and b/test/test.rewrite_vlan802.1ad differ diff --git a/test/test.rewrite_vlandel b/test/test.rewrite_vlandel index fb3578d70..7c40ec511 100644 Binary files a/test/test.rewrite_vlandel and b/test/test.rewrite_vlandel differ diff --git a/test/test2.rewrite_1ttl b/test/test2.rewrite_1ttl index be3383b16..f1d77f940 100644 Binary files a/test/test2.rewrite_1ttl and b/test/test2.rewrite_1ttl differ diff --git a/test/test2.rewrite_2ttl b/test/test2.rewrite_2ttl index 1cfe16b04..a96794836 100644 Binary files a/test/test2.rewrite_2ttl and b/test/test2.rewrite_2ttl differ diff --git a/test/test2.rewrite_3ttl b/test/test2.rewrite_3ttl index 42e2b5564..e820d35ea 100644 Binary files a/test/test2.rewrite_3ttl and b/test/test2.rewrite_3ttl differ diff --git a/test/test2.rewrite_config b/test/test2.rewrite_config index 4bfab287c..a6a834fec 100644 Binary files a/test/test2.rewrite_config and b/test/test2.rewrite_config differ diff --git a/test/test2.rewrite_efcs b/test/test2.rewrite_efcs index d9e23a208..fd74a0a24 100644 Binary files a/test/test2.rewrite_efcs and b/test/test2.rewrite_efcs differ diff --git a/test/test2.rewrite_endpoint b/test/test2.rewrite_endpoint index c927c4530..ba365c740 100644 Binary files a/test/test2.rewrite_endpoint and b/test/test2.rewrite_endpoint differ diff --git a/test/test2.rewrite_enet_subsmac b/test/test2.rewrite_enet_subsmac index e53bfb443..987bfa6dd 100644 Binary files a/test/test2.rewrite_enet_subsmac and b/test/test2.rewrite_enet_subsmac differ diff --git a/test/test2.rewrite_fixcsum b/test/test2.rewrite_fixcsum index e00892878..d28557726 100644 Binary files a/test/test2.rewrite_fixcsum and b/test/test2.rewrite_fixcsum differ diff --git a/test/test2.rewrite_fixlen_del b/test/test2.rewrite_fixlen_del index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_fixlen_del and b/test/test2.rewrite_fixlen_del differ diff --git a/test/test2.rewrite_fixlen_pad b/test/test2.rewrite_fixlen_pad index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_fixlen_pad and b/test/test2.rewrite_fixlen_pad differ diff --git a/test/test2.rewrite_fixlen_trunc b/test/test2.rewrite_fixlen_trunc index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_fixlen_trunc and b/test/test2.rewrite_fixlen_trunc differ diff --git a/test/test2.rewrite_l7fuzzing b/test/test2.rewrite_l7fuzzing index aa6fc64be..4af63622d 100644 Binary files a/test/test2.rewrite_l7fuzzing and b/test/test2.rewrite_l7fuzzing differ diff --git a/test/test2.rewrite_mac b/test/test2.rewrite_mac index cdf805b9e..da59e7cec 100644 Binary files a/test/test2.rewrite_mac and b/test/test2.rewrite_mac differ diff --git a/test/test2.rewrite_mac_seed b/test/test2.rewrite_mac_seed index dffc054a8..c5b9a34a1 100644 Binary files a/test/test2.rewrite_mac_seed and b/test/test2.rewrite_mac_seed differ diff --git a/test/test2.rewrite_mac_seed_keep b/test/test2.rewrite_mac_seed_keep index 116428969..92c9bb2ee 100644 Binary files a/test/test2.rewrite_mac_seed_keep and b/test/test2.rewrite_mac_seed_keep differ diff --git a/test/test2.rewrite_mtutrunc b/test/test2.rewrite_mtutrunc index ede5109d3..22621728b 100644 Binary files a/test/test2.rewrite_mtutrunc and b/test/test2.rewrite_mtutrunc differ diff --git a/test/test2.rewrite_pad b/test/test2.rewrite_pad index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_pad and b/test/test2.rewrite_pad differ diff --git a/test/test2.rewrite_pnat b/test/test2.rewrite_pnat index 8e3cba778..8e6473c48 100644 Binary files a/test/test2.rewrite_pnat and b/test/test2.rewrite_pnat differ diff --git a/test/test2.rewrite_portmap b/test/test2.rewrite_portmap index 90f905972..a3883cc2e 100644 Binary files a/test/test2.rewrite_portmap and b/test/test2.rewrite_portmap differ diff --git a/test/test2.rewrite_range_portmap b/test/test2.rewrite_range_portmap index 71787ce3f..391756ff8 100644 Binary files a/test/test2.rewrite_range_portmap and b/test/test2.rewrite_range_portmap differ diff --git a/test/test2.rewrite_seed b/test/test2.rewrite_seed index 2b0a53690..acd725e24 100644 Binary files a/test/test2.rewrite_seed and b/test/test2.rewrite_seed differ diff --git a/test/test2.rewrite_sequence b/test/test2.rewrite_sequence index 9142f53c6..93524b169 100644 Binary files a/test/test2.rewrite_sequence and b/test/test2.rewrite_sequence differ diff --git a/test/test2.rewrite_skip b/test/test2.rewrite_skip index 5dec89610..ec290c989 100644 Binary files a/test/test2.rewrite_skip and b/test/test2.rewrite_skip differ diff --git a/test/test2.rewrite_tos b/test/test2.rewrite_tos index 1b72e48eb..e3554d982 100644 Binary files a/test/test2.rewrite_tos and b/test/test2.rewrite_tos differ diff --git a/test/test2.rewrite_trunc b/test/test2.rewrite_trunc index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_trunc and b/test/test2.rewrite_trunc differ diff --git a/test/test2.rewrite_vlan802.1ad b/test/test2.rewrite_vlan802.1ad index f2a2d96a4..d91c095aa 100644 Binary files a/test/test2.rewrite_vlan802.1ad and b/test/test2.rewrite_vlan802.1ad differ diff --git a/test/test2.rewrite_vlandel b/test/test2.rewrite_vlandel index c0f39d75c..cae178213 100644 Binary files a/test/test2.rewrite_vlandel and b/test/test2.rewrite_vlandel differ