diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..b1cd379 --- /dev/null +++ b/.clang-format @@ -0,0 +1,115 @@ +--- +Language: Cpp + +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentPPDirectives: AfterHash +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +RawStringFormats: + - Delimiter: pb + Language: TextProto + BasedOnStyle: google +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 4 +UseTab: Never +... + diff --git a/.gitignore b/.gitignore index 52fb503..ee3da06 100644 --- a/.gitignore +++ b/.gitignore @@ -3,24 +3,26 @@ config.h config.h.in~ config.log config.status -compile autom4te.cache/ bin/ lib/ +src/siggen/siggen +src/tripwire/tripwire +src/twadmin/twadmin +src/twprint/twprint +src/twtest/twtest +src/test-harness/twtest **/Makefile **/*.o **/*.dylib **/*.a **/*.so **/*.dll -**/siggen -**/tripwire -**/twadmin -**/twprint -**/twtest -**/siggen.exe -**/tripwire.exe -**/twadmin.exe -**/twprint.exe -**/twtest.exe +**/*.exe +**/*~ +**/*# +**/*.bak +**/.DS_Store +**/*.gcno +**/*.gcda releases/ diff --git a/COMMERCIAL b/COMMERCIAL index 5bfad07..5b7d3fc 100644 --- a/COMMERCIAL +++ b/COMMERCIAL @@ -1,6 +1,10 @@ -If you desire enterprise capable software with commercial support, check out -Tripwire, Inc. at http://www.tripwire.com. +Tripwire, Inc also offers several commercial, supported security and compliance solutions: + +* Tripwire for Servers is most similar to Open Source Tripwire (OST was forked from it in 2000), with additional features such as native Windows support, audit event correlation, and Tripwire Manager, a central management console. http://www.tripwire.com/it-security-software/scm/tripwire-for-servers/ + +* Tripwire Enterprise is an enterprise-grade product with features such as real-time file and registry change detection; change monitoring for databases, directory servers, and network devices; and policy compliance monitoring for standards including PCI, HIPAA, and NERC. http://www.tripwire.com/it-security-software/scm/tripwire-enterprise/ + +* Tripwire Configuration Compliance Manager is an agentless solution with some features similar to Tripwire Enterprise, as well as advanced asset discovery capabilities. http://www.tripwire.com/it-security-software/scm/ccm/ + -For a more detailed comparison of the Open Source Tripwire software and -commercial Tripwire(R) product(s) please visit http://www.tripwire.org. diff --git a/ChangeLog b/ChangeLog index 3b1b589..dcda8da 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,70 @@ +2018-03-24 Brian Cox + * Update version to 2.4.3.7 + * Provide a useful README.md (Github issue #17). + * Document return codes in man pages (Github issue #28). + * Update install script after testing on additional platforms. + * Provide default policies for more operating systems, and update some existing policies + * Usability tweaks to twtest. + * Fix email reporting on Syllable + * Update copyright dates to 2018 + * Clean up code style with clang-format, & add a custom style that approximates existing OST usage. + * Add -t / --output-level option to print-db mode, for consistency w/ print-report mode. + * Add object list support to print-report mode, for consistency w/ print-db mode. + +2017-10-01 Brian Cox + * Update version to 2.4.3.6 + * Fix & expand tests in Perl acceptance test framework + * Fix & expand twtest unit tests, & rework unit test mini-framework so they’re referenced by name, not some numeric ID, and list tests as “skipped" if they don’t make any test assertions. + * Add configure options to enable coverage, profiling, & use /dev/urandom as RNG (all off by default) + * Add a ‘list’ make target to list all make targets + * Remove dead code & add test coverage per gcov+lcov results + * Fix various memory issues pointed out by valgrind + * In examine-encryption mode, better reporting (& nonzero exit) if we can't find a keyfile for the examined file. + * More exception handling around individual objects & init/IC as a whole, since there have been occasional reports of uncaught exceptions during init or check, and so far haven’t been able to repro or figure out what circumstances it occurs under. (e.g. Github issue #25) + * Tweak install.sh so it can be run directly, not just thru 'make install' if you want. (Github issue #26) + * Improve native (non-Posixy) path handling on platforms that need it (DOS, AROS, RISC OS, Redox) + * New platforms: MirOS BSD, Bitrig, LibertyBSD, RISC OS, Redox + * Add default policies for HP-UX & various BSDs + +2017-03-30 Brian Cox + * Bump version to 2.4.3.5 + * Fix ‘install-strip’, ‘check’, ‘uninstall’, and ‘distcheck’ make targets. + * Fix GCC 7.0.x warnings; use std::unique_ptr instead of deprecated std::auto_ptr where available. + * Add ‘--disable-extrawarnings’ configure option, for old compilers that don’t support the ’-Wextra’ compile option. + * Clean up unit tests & enable disabled tests. + * Address more static analyzer warnings, including from CppCheck & Flawfinder + +2017-03-05 Brian Cox + * Bump version to 2.4.3.4 + * Fix issue with printing level 2 reports, introduced by fixing a Clang static analyzer quibble in 2.4.3.3. Sigh. + * 'make install-strip' actually strips binaries now. + +2017-02-21 Brian Cox + * Bump version to 2.4.3.3 + * Run Clang static analyzer & fix some of its quibbles + * Fix compilation error on Alpine Linux 3.x + * Fix file permissions on a couple of source files + * Fix some errors w/ make install/uninstall/dist + +2017-01-15 Brian Cox + * Bump version to 2.4.3.2 + * DOS/DJGPP platform support. + * Use posix_fadvise() to reduce disk cache impact (where available). + * Use O_NOATIME where available, so scans don't update file access times. + * Optional HASH_DIRECT_IO (Linux only) to access files via direct i/o when hashing, per user request. + * Optional support for iconv character conversion, for db/report file portability. + * Improved display of multibyte characters in reports. + * On OSX, use builtin CommonCrypto hashes instead of impls provided with OST. + * Update build system to automake 1.15 + * Cross compiling can use OpenSSL now. + * 'make dist' now creates a buildable source bundle. + * Can use build dir outside of source tree + * Include 'what'-style version strings. + * AROS: Correctly hide passphrases & delete temp files. + * Remove dead code & unused files. + * Optional RESOLVE_IDS_TO_NAMES option to disable uid/gid to name resolution, if needed. + * New --key-size option to twadmin --generate-keys, to generate 1024 (default) or 2048 bit El Gamal keys. + 2016-04-20 Brian Cox * Bump version to 2.4.3.1 * Revive old 'twtest' unit test suite (such as it is); move _t.cpp files into twtest dir. @@ -26,7 +93,7 @@ * Add MAILFROMADDRESS config param (see twconfig man page) * Use O_NONBLOCK, to avoid blocking on fifos & mandatory-locked files * Report Solaris door & event port file types correctly - + 2014-01-01 Barry Allard * Bumping version to 2.4.2.3 @@ -59,24 +126,21 @@ * Fixed bug in install script when sendmail isn't installed target system. * Removed some non-existent files from installer - + 2005-08-18 Ron Forrester * Wow, has it been 4+ years? :) - * Starting fresh with Paul's autoconf'ed code base - * Bumped version number, misc cleanup, etc. - 2001-02-25 Ron Forrester * Bumped version to 2.3.1. - + * BSD support, thanks to Paul Herman . The support was added for FreeBSD 4.2, your mileage may vary on other BSD's. - + * Fixed long standing bug with recurse=3 * If TEMPDIRECTORY was missing trailing /, bad things could @@ -88,8 +152,7 @@ file. Additionally, reports were being sliced to global recipients, despite the fact that global recipients should get the full report. - - + 2001-02-03 Ron Forrester * Fixed possible security problem with the handling of temp diff --git a/Makefile.am b/Makefile.am index a68876b..47de316 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,8 +1,25 @@ AUTOMAKE_OPTIONS = foreign no-dependencies SUBDIRS = man src -EXTRA_DIST = COMMERCIAL MAINTAINERS TRADEMARK touchconfig.sh contrib policy +EXTRA_DIST = COMMERCIAL MAINTAINERS TRADEMARK LICENSE Packaging ReadMe-2.4.3 README.md autogen.sh autogen.sh.README touchconfig.sh contrib policy installer install-data-hook: + INSTALL_STRIP_FLAG="$(INSTALL_STRIP_FLAG)" \ prefix="$(prefix)" sysconfdir="$(sysconfdir)" \ - path_to_vi="$(path_to_vi)" path_to_sendmail="$(path_to_sendmail)" \ - ./install/install.sh + path_to_vi="$(path_to_vi)" path_to_sendmail="$(path_to_sendmail)" \ + $(top_srcdir)/installer/install.sh + +uninstall-hook: + rm -f ${prefix}/sbin/tripwire $(prefix)/sbin/twadmin $(prefix)/sbin/twprint $(prefix)/sbin/siggen + rm -Rf $(prefix)/doc + +check: + rm -Rf $(top_srcdir)/src/test-harness/twtest + rm -Rf $(top_srcdir)/bin/TWTestData + cd $(top_srcdir)/src/test-harness && perl ./twtest.pl + cd $(top_srcdir)/bin && ./twtest all + +test: check + +.PHONY: targets +targets: + @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs diff --git a/Makefile.in b/Makefile.in index 342ff95..96a26f8 100644 --- a/Makefile.in +++ b/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = . +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,50 +85,131 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ -DIST_COMMON = $(am__configure_deps) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in $(srcdir)/config.h.in \ - $(top_srcdir)/configure COPYING ChangeLog config.guess \ - config.sub install-sh missing mkinstalldirs +target_triplet = @target@ subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ + $(am__configure_deps) $(am__DIST_COMMON) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ - configure.lineno configure.status.lineno + configure.lineno config.status.lineno mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = -RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ - html-recursive info-recursive install-data-recursive \ - install-exec-recursive install-info-recursive \ - install-recursive installcheck-recursive installdirs-recursive \ - pdf-recursive ps-recursive uninstall-info-recursive \ - uninstall-recursive +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + cscope distdir dist dist-all distcheck +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ + $(LISP)config.h.in +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +CSCOPE = cscope DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in COPYING \ + ChangeLog compile config.guess config.sub install-sh missing \ + mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ - { test ! -d $(distdir) \ - || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ - && rm -fr $(distdir); }; } + if test -d "$(distdir)"; then \ + find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -rf "$(distdir)" \ + || { sleep 5 && rm -rf "$(distdir)"; }; \ + else :; fi +am__post_remove_distdir = $(am__remove_distdir) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best +DIST_TARGETS = dist-gzip distuninstallcheck_listfiles = find . -type f -print +am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ + | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -100,6 +233,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -111,6 +245,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -127,21 +262,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -171,35 +309,38 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies SUBDIRS = man src -EXTRA_DIST = COMMERCIAL MAINTAINERS TRADEMARK touchconfig.sh contrib policy +EXTRA_DIST = COMMERCIAL MAINTAINERS TRADEMARK LICENSE Packaging ReadMe-2.4.3 README.md autogen.sh autogen.sh.README touchconfig.sh contrib policy installer all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: -am--refresh: +am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - echo ' cd $(srcdir) && $(AUTOMAKE) --foreign '; \ - cd $(srcdir) && $(AUTOMAKE) --foreign \ + echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ + $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -214,39 +355,46 @@ $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENC $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) - cd $(srcdir) && $(AUTOCONF) + $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) - cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) + $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +$(am__aclocal_m4_deps): config.h: stamp-h1 - @if test ! -f $@; then \ - rm -f stamp-h1; \ - $(MAKE) stamp-h1; \ - else :; fi + @test -f $@ || rm -f stamp-h1 + @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) - cd $(top_srcdir) && $(AUTOHEADER) + ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 -uninstall-info-am: # This directory's subdirectories are mostly independent; you can cd -# into them and run `make' without going through this Makefile. -# To change the values of `make' variables: instead of editing Makefiles, -# (1) if the variable is set in `config.status', edit `config.status' -# (which will cause the Makefiles to be regenerated when you run `make'); -# (2) otherwise, pass the desired values on the `make' command line. -$(RECURSIVE_TARGETS): - @set fnord $$MAKEFLAGS; amf=$$2; \ +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ - list='$(SUBDIRS)'; for subdir in $$list; do \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ @@ -254,60 +402,20 @@ $(RECURSIVE_TARGETS): else \ local_target="$$target"; \ fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" -mostlyclean-recursive clean-recursive distclean-recursive \ -maintainer-clean-recursive: - @set fnord $$MAKEFLAGS; amf=$$2; \ - dot_seen=no; \ - case "$@" in \ - distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ - *) list='$(SUBDIRS)' ;; \ - esac; \ - rev=''; for subdir in $$list; do \ - if test "$$subdir" = "."; then :; else \ - rev="$$subdir $$rev"; \ - fi; \ - done; \ - rev="$$rev ."; \ - target=`echo $@ | sed s/-recursive//`; \ - for subdir in $$rev; do \ - echo "Making $$target in $$subdir"; \ - if test "$$subdir" = "."; then \ - local_target="$$target-am"; \ - else \ - local_target="$$target"; \ - fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ - done && test -z "$$fail" -tags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ - done -ctags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ - done +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ @@ -319,114 +427,162 @@ TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ - tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ - list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscope: cscope.files + test ! -s cscope.files \ + || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) +clean-cscope: + -rm -f cscope.files +cscope.files: clean-cscope cscopelist +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + -rm -f cscope.out cscope.in.out cscope.po.out cscope.files distdir: $(DISTFILES) $(am__remove_distdir) - mkdir $(distdir) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + test -d "$(distdir)" || mkdir "$(distdir)" + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done - list='$(SUBDIRS)'; for subdir in $$list; do \ + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ - test -d "$(distdir)/$$subdir" \ - || mkdir "$(distdir)/$$subdir" \ - || exit 1; \ - (cd $$subdir && \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ - top_distdir="../$(top_distdir)" \ - distdir="../$(distdir)/$$subdir" \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done - -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ + -test -n "$(am__skip_mode_fix)" \ + || find "$(distdir)" -type d ! -perm -755 \ + -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ - ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \ - || chmod -R a+r $(distdir) + ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r "$(distdir)" dist-gzip: distdir - $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz - $(am__remove_distdir) + tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz + $(am__post_remove_distdir) dist-bzip2: distdir - $(AMTAR) chof - $(distdir) | bzip2 -9 -c >$(distdir).tar.bz2 - $(am__remove_distdir) + tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 + $(am__post_remove_distdir) + +dist-lzip: distdir + tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz + $(am__post_remove_distdir) + +dist-xz: distdir + tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz + $(am__post_remove_distdir) dist-tarZ: distdir - $(AMTAR) chof - $(distdir) | compress -c >$(distdir).tar.Z - $(am__remove_distdir) + @echo WARNING: "Support for distribution archives compressed with" \ + "legacy program 'compress' is deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z + $(am__post_remove_distdir) dist-shar: distdir - shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz - $(am__remove_distdir) + @echo WARNING: "Support for shar distribution archives is" \ + "deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz + $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) - $(am__remove_distdir) + $(am__post_remove_distdir) -dist dist-all: distdir - $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz - $(am__remove_distdir) +dist dist-all: + $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' + $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another @@ -434,25 +590,33 @@ dist dist-all: distdir distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ - GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(AMTAR) xf - ;;\ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ - bunzip2 -c $(distdir).tar.bz2 | $(AMTAR) xf - ;;\ + bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.lz*) \ + lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ + *.tar.xz*) \ + xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ - uncompress -c $(distdir).tar.Z | $(AMTAR) xf - ;;\ + uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ - GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac - chmod -R a-w $(distdir); chmod a+w $(distdir) - mkdir $(distdir)/_build - mkdir $(distdir)/_inst + chmod -R a-w $(distdir) + chmod u+w $(distdir) + mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst chmod a-w $(distdir) + test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ - && cd $(distdir)/_build \ - && ../configure --srcdir=.. --prefix="$$dc_install_base" \ + && am__cwd=`pwd` \ + && $(am__cd) $(distdir)/_build/sub \ + && ../../configure \ + $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ + --srcdir=../.. --prefix="$$dc_install_base" \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ @@ -472,14 +636,24 @@ distcheck: dist && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ - && $(MAKE) $(AM_MAKEFLAGS) distcleancheck - $(am__remove_distdir) + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ + && cd "$$am__cwd" \ + || exit 1 + $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ - sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}' + sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: - @cd $(distuninstallcheck_dir) \ - && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ + @test -n '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: trying to run $@ with an empty' \ + '$$(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + $(am__cd) '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ @@ -510,16 +684,22 @@ install-am: all-am installcheck: installcheck-recursive install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -539,6 +719,8 @@ dvi-am: html: html-recursive +html-am: + info: info-recursive info-am: @@ -546,13 +728,30 @@ info-am: install-data-am: @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook +install-dvi: install-dvi-recursive + +install-dvi-am: install-exec-am: +install-html: install-html-recursive + +install-html-am: + install-info: install-info-recursive +install-info-am: + install-man: +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-recursive @@ -573,30 +772,53 @@ ps: ps-recursive ps-am: -uninstall-am: uninstall-info-am - -uninstall-info: uninstall-info-recursive +uninstall-am: + @$(NORMAL_INSTALL) + $(MAKE) $(AM_MAKEFLAGS) uninstall-hook +.MAKE: $(am__recursive_targets) all install-am install-data-am \ + install-strip uninstall-am + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ + am--refresh check check-am clean clean-cscope clean-generic \ + cscope cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \ + dist-gzip dist-lzip dist-shar dist-tarZ dist-xz dist-zip \ + distcheck distclean distclean-generic distclean-hdr \ + distclean-tags distcleancheck distdir distuninstallcheck dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-data-hook install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic pdf pdf-am ps ps-am tags \ + tags-am uninstall uninstall-am uninstall-hook -.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \ - check-am clean clean-generic clean-recursive ctags \ - ctags-recursive dist dist-all dist-bzip2 dist-gzip dist-shar \ - dist-tarZ dist-zip distcheck distclean distclean-generic \ - distclean-hdr distclean-recursive distclean-tags \ - distcleancheck distdir distuninstallcheck dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs installdirs-am maintainer-clean \ - maintainer-clean-generic maintainer-clean-recursive \ - mostlyclean mostlyclean-generic mostlyclean-recursive pdf \ - pdf-am ps ps-am tags tags-recursive uninstall uninstall-am \ - uninstall-info-am +.PRECIOUS: Makefile install-data-hook: + INSTALL_STRIP_FLAG="$(INSTALL_STRIP_FLAG)" \ prefix="$(prefix)" sysconfdir="$(sysconfdir)" \ - path_to_vi="$(path_to_vi)" path_to_sendmail="$(path_to_sendmail)" \ - ./install/install.sh + path_to_vi="$(path_to_vi)" path_to_sendmail="$(path_to_sendmail)" \ + $(top_srcdir)/installer/install.sh + +uninstall-hook: + rm -f ${prefix}/sbin/tripwire $(prefix)/sbin/twadmin $(prefix)/sbin/twprint $(prefix)/sbin/siggen + rm -Rf $(prefix)/doc + +check: + rm -Rf $(top_srcdir)/src/test-harness/twtest + rm -Rf $(top_srcdir)/bin/TWTestData + cd $(top_srcdir)/src/test-harness && perl ./twtest.pl + cd $(top_srcdir)/bin && ./twtest all + +test: check + +.PHONY: targets +targets: + @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/Packaging b/Packaging old mode 100755 new mode 100644 index 417e0b2..46775eb --- a/Packaging +++ b/Packaging @@ -9,10 +9,6 @@ Packaging for Open Source Tripwire is maintained by various third parties: * Debian: https://tracker.debian.org/pkg/tripwire * Gentoo: https://packages.gentoo.org/packages/app-admin/tripwire - Gentoo also has an SELinux policy for OST: - https://packages.gentoo.org/packages/sec-policy/selinux-tripwire - - * Chef cookbook: https://github.com/rackspace-cookbooks/rackspace_tripwire * FreeBSD Ports: http://svnweb.freebsd.org/ports/head/security/tripwire/ @@ -23,5 +19,19 @@ Packaging for Open Source Tripwire is maintained by various third parties: * NetBSD pkgsrc: http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/security/tripwire/README.html NOTE: At present (April 2016) pkgsrc only provides the obsolete Tripwire 1.2, from the mid-1990s. That version lacks contemporary hash algorithms, and you probably don't want to use it. + There's an unfinished pkgsrc port for OST 2.3+ here, if someone who understands pkgsrc + is looking for a fun(?) project: http://pkgsrc.se/wip/tripwire2 + + +A few third party projects that might be useful with OST + + * Chef cookbook: https://github.com/rackspace-cookbooks/rackspace_tripwire + + * Puppet module: https://github.com/razorsedge/puppet-tripwire + + * SELinux policies from Tresys: https://github.com/TresysTechnology/refpolicy-contrib/blob/master/tripwire.te + (and related .fc and .if files in the same repo) + * A Gentoo SELinux policy, different from the one above: https://packages.gentoo.org/packages/sec-policy/selinux-tripwire + * An experimental(?) Dockerfile for CentOS: https://hub.docker.com/r/prateeknischal/tripwire-play/ diff --git a/README.md b/README.md index 0e00007..7591e7f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,179 @@ -#Open Source Tripwire® +# Open Source Tripwire® -Open Source Tripwire® software is a security and data integrity tool useful for monitoring and alerting on specific file change(s) on a range of systems. The project is based on code originally contributed by [Tripwire, Inc.](http://www.tripwire.com) in 2000. +Open Source Tripwire® is a security and data integrity tool for monitoring and alerting on file & directory changes. This project is based on code originally contributed by [Tripwire, Inc.](http://www.tripwire.com) in 2000. -Open Source Tripwire is suitable for monitoring a small number of Linux servers, where centralized control and reporting is not needed and professional support or system automation is not a requirement. +## Overview +A Tripwire check compares the current filesystem state against a known baseline state, and alerts on any changes it detects. The baseline and check behavior are controlled by a policy file, which specifies which files or directories to monitor, and which attributes to monitor on them, such as hashes, file permissions, and ownership. + +When an expected change occurs, such as upgrading a package, the baseline database can be updated to the new known-good state. The policy can also be updated, for example to reduce noise or cover a newly installed package. + +## Getting Started + +This section covers manual setup of Open Source Tripwire. If installing via an RPM or Debian package, or via **make install**, a setup script will walk the user through the initial setup steps (key generation thru policy creation) and these will not need to be done by hand. + +### Generating Keys +The first step is to generate site and local key files. This is necessary because Tripwire policy, configuration, and database files are signed by default, and report files may also be signed. The site key is used to sign config and policy files, while databases and reports are signed with the local key. The idea here is that multiple machines can share a site key, but each will have its own local key. The policy and config files can then be created once and distributed across these machines. + +A common practice is to include the hostname in the local key filename, as follows: + +``` +./twadmin --generate-keys -L /etc/tripwire/${HOSTNAME}-local.key +./twadmin --generate-keys -S /etc/tripwire/site.key +``` + +### Creating a configuration file +The next step is to create a Tripwire config file. The config file contains a variety of settings including the locations of Tripwire binaries and key files, email report settings, and parameters that control baseline/check behavior. These settings are explained in detail in the **twconfig(4)** manual page. + +This command line reads and validates the config text in /path/to/twcfg.txt, writes the results to tw.cfg, and signs the resulting file with the provided site key: + +``` +./twadmin --create-cfgfile -S /path/to/site.key /path/to/twcfg.txt +``` +### Generating a policy file + +Now it's time to configure which files & directories OST will monitor. A few simple examples of policy rules: + +``` +/start/point -> $(IgnoreNone); # Get all attributes for this dir tree +/another/start -> +pinugS; # Get selected attributes for this dir tree +!/start/point/subdir/to/ignore; # Don't monitor this dir tree +``` +The Tripwire policy language is documented in detail in the **twpolicy(4)** manual page, and default policies for most common operating systems are available in the OST project's policy subdirectory. + +``` +./twadmin --create-polfile -S /path/to/site.key /etc/tripwire/twpol.txt +``` + +### Creating a baseline + +The next step is to baseline the system for the first time. This step is necessary even if the previous steps are handled by a setup/install script. + +``` +./tripwire --init +``` +This creates a database file in the configured directory, typically a file with a .twd extension in /var/lib/tripwire. The optional **--verbose** argument to init mode lists files and directories as they're being scanned. + +### Running a check +``` +./tripwire --check +``` +This runs a check, again with an optional **--verbose** option that displays what it's doing. Scan results are written to standard out, as well as a report file, which typically has a .twr extension and lives in /var/lib/tripwire/report. If email reporting is enabled, emails will be sent at the end of the check. + +A common way to use OST is to set up a cron job to run checks periodically, emailing results to an administrative account. Note that the OST install script currently does not create any cron jobs, and this will need to be done by hand. + +### Printing a report +``` +./twprint -m r -t [0-4] -r /path/to/reportfile.twr +``` +The -t argument specifies the level of report verbosity, where 0 is a single line summary of the report contents, and 4 displays all gathered attributes on all changed objects. The report level defaults to 3 if not specified on the command line or via the REPORTLEVEL config file option. + +Databases can be also printed with: + +``` +./twprint -m d -d /path/to/database.twd +``` + +### Updating a database +The simplest form of update updates the database with all the changes in a report file: + +``` +./tripwire --update --accept-all +``` + +While a +``` +./tripwire --update +``` +brings up a text report in the user's preferred editor (as configured in the config file's EDITOR option), with a checkbox next to each detected change. After saving and exiting the editor, the database will only be updated for those objects that remain selected with an **[x]**. + +### Updating a policy +Policy update mode modifies the current Tripwire policy without losing existing baselines. + +``` +./tripwire --update-policy updated-policy.txt +``` + +A check is run with the new policy as part of the update process. If this check detects changes, the default behavior is to display the changes and exit without updating the policy or database. To accept the changes and continue with the policy update, use the **-Z low** / **--secure-mode low** command line option. + +### Testing the email configuration +To test email configuration: + +``` +./tripwire --test --email user@domain.tld +``` +This sends a test email to the specified address, using the email settings specified in the config file. + +## Building OST + +### Prerequisites + +A C++ compiler. It's known to build with gcc and clang; OST should work with gcc versions as old as 2.95.2, although gcc older than version 3.1 will need an external STLPort package. + +A POSIX-like operating system, including Linux, macOS, various BSDs, Solaris, AIX, HP-UX, Minix, Haiku, GNU/Hurd, and others. Windows users can build OST under Cygwin, although this does not provide support for monitoring the Registry or any Windows-specific file attributes. + +Perl 5+ is needed to run the project's test suite. + +### Configuring & Building + +OST uses a standard automake build, so the first configuration step will generally be: +``` +./configure +``` + +Additional compiler arguments (such as Debian hardening options), non-default paths, and other options can be set up in this step. A ```./configure --help``` lists the available configuration options. + +The ```--prefix=/some/path``` option controls where a subsequent ```make install``` will install to, and where Tripwire binaries will look for a configuration file. + +The ```--enable-static``` option causes the build to create statically linked binaries. This is often used as a security enhancement, so that Tripwire will not rely on the shared libraries on the machine. This is not possible on all platforms, as some (like macOS and Solaris) don't provide the necessary static libraries to link against. + +Note that Linux systems that use NSS for name lookups will still employ shared libraries behind the scenes even when the OST binaries are statically linked. There have been occasional reports of segfaults when trying to do a name lookup in these circumstances, particularly when the binary was built on a different machine or it's trying to do an LDAP or NIS name lookup. If this occurs, there are two ways to work around it: Either switch to dynamic binaries, or set the Tripwire config file option ```RESOLVE_IDS_TO_NAMES=false```, which tells OST to just watch numeric user & group IDs and not perform name lookups. + +If the configure or make step fails with errors about the automake/autoconf version, it may be necessary to run the script +```./touchconfig.sh``` +before building the project. This script simply touches files in the correct order such that their last change times are not all identical, and that they're different in the right order. + +Then just +```make``` +to build the project. + +## Running the test suites + +the ```make check``` make target runs two things: The acceptance test suite in the src/test-harness directory, and unit tests by running twtest, which is built in the bin directory along with other Tripwire binaries. These tests can also be run separately: +```./twtest``` runs all unit tests, while ```./twtest list``` lists all available tests. +```./twtest Groupname``` runs all tests in a group, and +```./twtest Groupname/Testname``` just runs the specified test. + + +To run the acceptance tests manually, cd to the src/test-harness directory and run ```perl ./twtest.pl```. + + +## Deployment + +The ```make install``` target installs OST to the configured location, and ```make install-strip``` installs and removes symbols from the Tripwire binaries. A ```make dist``` creates a gzipped source bundle. + +## Authors + +* [Tripwire, Inc.](http://www.tripwire.com) + + +## License + +The developer of the original code and/or files is Tripwire, Inc. +Portions created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. +Tripwire is a registered trademark of Tripwire, Inc. All rights reserved. + +This program is free software. The contents of this file are subject to the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You may redistribute it and/or modify it only in compliance with the GNU General Public License. + +This program is distributed in the hope that it will be useful. However, +this program is distributed "AS-IS" WITHOUT ANY WARRANTY; INCLUDING THE +IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. +Please see the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +Nothing in the GNU General Public License or any other license to use the +code or files shall permit you to use Tripwire's trademarks, service marks, or other intellectual property without Tripwire's prior written consent. + +If you have any questions, please contact Tripwire, Inc. at either +info@tripwire.org or www.tripwire.org. diff --git a/ReadMe-2.4.3 b/ReadMe-2.4.3 index 6db0662..95d508b 100644 --- a/ReadMe-2.4.3 +++ b/ReadMe-2.4.3 @@ -1,4 +1,43 @@ -What's new in Open Source Tripwire 2.4.3: +What's new in Open Source Tripwire 2.4.3.x: + +* Useful ‘install-strip’, ‘check’, ‘uninstall’ & ‘distcheck’ make targets as of OST 2.4.3.5. Check target invokes both the test-harness framework and twtest unit tests. + +* Verify OST builds without errors w/ GCC 7.0.x; fix new warnings from the new compiler, including deprecation warnings; use std::unique_ptr instead of std::auto_ptr where available. + +* Add ‘--disable-extrawarnings’ configure option, for old compilers that don’t support the ’-Wextra’ compile option. + +* Clean up unit tests, enable various disabled tests, make results more useful. + +* Additional cleanup due to static analysis tool results (CppCheck, Flawfinder, Clang analyzer). + +* OST now includes optional iconv support when configured with --enable-iconv. +When enabled, binary database & report files store paths as UTF-16, making these files more +portable across machines with different character encodings. This is disabled by default +for the sake of compatibility with existing db & report files. + +* Use posix_fadvise (or equivalent) to avoid filling system disk cache with files we've already +read and aren't about to read again. Also use O_NOATIME where available, to avoid updating +file access times when we read a file. Add an optional new config param "HASH_DIRECT_IO" to use +direct i/o when hashing files. This doesn't seem to be any faster than normal i/o, but +including it anyway due to user request. + +* Add a new config file option RESOLVE_IDS_TO_NAMES to control whether we try to +resolve uid/gid values to user & group names. Static binaries are known to segfault when +doing this given certain nsswitch.conf setups (particularly LDAP/AD), so setting this +to false bypasses name resolution and just displays the numeric uid/gid. + +* Add a new optional --key-size argument to twadmin --generate-keys mode, with available +sizes of 1024 or 2048 bits. Previously twadmin always created 1024-bit El Gamal keys, +and this remains the default if --key-size is not specified, at least for the time being. + +* Fix a compilation issue with C++11 and -Werror=terminate. + +* Move build files to automake 1.15, and make a few build system fixes: "make dist" now +works properly, cross-compiled binaries can now compile with OpenSSL if available, and +specifying a build directory outside the source dir now works as expected. + +* Assorted platform tweaks: Add DOS/FreeDOS + DJGPP as a new platform; support Cygwin +//host/share/path syntax for UNC paths; passphrase & tempfile fixes for AROS. * This update fixes compilation errors on modern compilers (GCC 4.7+ and LLVM/clang), as well as some additional errors encountered on various platforms. This is intended @@ -28,18 +67,26 @@ defined incorrectly otherwise. * Added the long-requested MAILFROMADDRESS config param for email reporting. + The update has been tested on a variety of platforms: Linuxes -- CentOS 7 (amd64) + gcc 4.8.5 -- Ubuntu 14.0.4 (amd64) + gcc 4.x -- RHEL 3.4 (Itanium) + gcc 3.4.3 - Alpine Linux 3.3.3 + gcc 5.3.0 -- Android 6.0 (arm) + gcc 4.9 +- Alpine Linux 3.5.1 + gcc 6.2.1 +- Arch Linux 232 + gcc 6.3.1 +- Amazon Linux AMI 2016.09 + gcc 4.8.3 +- Android 6.0 (arm) + gcc 4.9 (NDK) +- CentOS 7 (amd64) + gcc 4.8.5 +- Fedora 24 Alpha 7 (amd64) + gcc 6.0.0 +- Fedora 27 Rawhide (amd64) + gcc 7.0.1 - Raspbian 7 (wheezy) (armv6l) + gcc 4.6.3 -- openSuSE Tumbleweed (20160408) (i586) + gcc 5.3.1 +- RHEL 3.4 (Itanium) + gcc 3.4.3 - RHEL 6.0 (powerpc64) + gcc 4.4.4 -- Fedora 24 Alpha 7 (amd64) + gcc 6.0.0 +- openSuSE Tumbleweed (20160408) (i586) + gcc 5.3.1 +- Oracle Linux 6.8 + gcc 4.4.7 +- Ubuntu 14.0.4 (amd64) + gcc 4.x +- Ubuntu 16.0.4 (amd64) + gcc 5.4.0 +- Wind River Pulsar Linux 8 + gcc 5.2.0 OSX - Mac OS X 10.11 + LLVM 7.0.2 / clang-700.1.81 @@ -55,7 +102,7 @@ BSDs UNIXes - Solaris 10 SPARC + gcc 3.4.6 - Solaris 10 x86 + gcc 3.4.3 -- OpenIndiana 151 + gcc 4.8.5 [an OpenSolaris/illumos distro] +- OpenIndiana 151 + gcc 4.8.5 - AIX 5.2 + gcc 4.3.1 - HP-UX 11.23 + gcc 4.2.3 @@ -69,26 +116,25 @@ Other - Sortix 1.0 + gcc 5.3.0 - Icaros 2.1 (AROS) + gcc 4.6.4 - MiNT 1.17 (Atari ST/TT) + gcc 4.6.4 +- FreeDOS 1.1 + gcc 6.1.0 (DJGPP) Building Notes: -* If cross compiling, a '--disable-openssl' argument must be passed to ./configure, -since its OpenSSL existence check currently uses an AC_TRY_RUN macro. Additionally, -generated Makefiles don't automagically find the cross-compiler's 'ar' and try to -use the local one, which fails. Until this is resolved, this can be fixed with a symlink -named 'ar' pointing at the cross-compiler copy, with a path such that make finds it -instead of the local 'ar'. - * The '--enable-static' configure argument is not guaranteed to work on all -platforms, and your mileage may vary. And when it works, it may not be doing -what you expect. For example, even if a program is statically linked with -glibc, the static glibc code may still load shared libraries behind the -scenes, for things like iconv character conversion and nsswitch name lookups. - -* To create PIE (Position-Independent Executable) binaries, add “-fPIE" to CFLAGS -and "-fPIE -pie" to LDFLAGS. This is required by recent Android versions, and -may be desirable elsewhere. It's simplest to add these to configure.in and run -autoreconf -i instead of hand-editing each Makefile individually. +platforms (it's known not to work on MacOS, for instance) and your mileage may vary. +And when it works, it may not be doing what you expect. For example, even if +a program is statically linked with glibc, the static glibc code may still load +shared libraries behind the scenes, for things like iconv character conversion +and nsswitch name lookups. + +* The build system currently doesn't autodetect clang at configure time +(though it detects llvm-gcc). To use clang, you'll need to set CC and CXX to +point at clang and clang++ before configuring & building. + +* The default compile flags don't include hardening options such as creating +PIE (Position-Independent Executable) binaries. To set these, you'll want to +set CFLAGS/CXXFLAGS/LDFLAGS by hand before running 'configure', or use a tool +such as dpkg-buildflags to set them to recommended values. * Older versions of Open Source Tripwire reportedly do not build on Tru64 UNIX. This is likely to be true with 2.4.3 as well, due to the lack of appropriate diff --git a/TRADEMARK b/TRADEMARK index e06b19a..15825ba 100644 --- a/TRADEMARK +++ b/TRADEMARK @@ -2,7 +2,7 @@ TRIPWIRE COPYRIGHT & TRADEMARK NOTICE COPYRIGHT The developer of the original code and/or files is Tripwire, Inc. Portions -created by Tripwire, Inc. are copyright 2000 Tripwire, Inc. +created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. TRADEMARK Tripwire is a registered trademark (the "Trademark") of Tripwire, Inc. All diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..2f7efbe --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-minimal \ No newline at end of file diff --git a/aclocal.m4 b/aclocal.m4 index 8c5cd1d..1995959 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -1,7 +1,7 @@ -# generated automatically by aclocal 1.8.5 -*- Autoconf -*- +# generated automatically by aclocal 1.15.1 -*- Autoconf -*- + +# Copyright (C) 1996-2017 Free Software Foundation, Inc. -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 -# Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -11,59 +11,62 @@ # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. -# -*- Autoconf -*- -# Copyright (C) 2002, 2003 Free Software Foundation, Inc. -# Generated from amversion.in; do not edit by hand. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, +[m4_warning([this file was generated for autoconf 2.69. +You have another version of autoconf. It may work, but is not guaranteed to. +If you have problems, you may need to regenerate the build system entirely. +To do so, use the procedure documented by the package, typically 'autoreconf'.])]) -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# Copyright (C) 2002-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. -AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version="1.8"]) +# (This private macro should not be called outside this file.) +AC_DEFUN([AM_AUTOMAKE_VERSION], +[am__api_version='1.15' +dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to +dnl require some minimum version. Point them to the right macro. +m4_if([$1], [1.15.1], [], + [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl +]) + +# _AM_AUTOCONF_VERSION(VERSION) +# ----------------------------- +# aclocal traces this macro to find the Autoconf version. +# This is a private macro too. Using m4_define simplifies +# the logic in aclocal, which can simply ignore this definition. +m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- -# Call AM_AUTOMAKE_VERSION so it can be traced. -# This function is AC_REQUIREd by AC_INIT_AUTOMAKE. +# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. +# This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], - [AM_AUTOMAKE_VERSION([1.8.5])]) - -# AM_AUX_DIR_EXPAND +[AM_AUTOMAKE_VERSION([1.15.1])dnl +m4_ifndef([AC_AUTOCONF_VERSION], + [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl +_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) -# Copyright (C) 2001, 2003 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# AM_AUX_DIR_EXPAND -*- Autoconf -*- -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets -# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to -# `$srcdir', `$srcdir/..', or `$srcdir/../..'. +# $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to +# '$srcdir', '$srcdir/..', or '$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and @@ -82,7 +85,7 @@ AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually -# harmless because $srcdir is `.', but things will broke when you +# harmless because $srcdir is '.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, @@ -100,42 +103,31 @@ AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], -[dnl Rely on autoconf to set up CDPATH properly. -AC_PREREQ([2.50])dnl -# expand $ac_aux_dir to an absolute path -am_aux_dir=`cd $ac_aux_dir && pwd` +[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl +# Expand $ac_aux_dir to an absolute path. +am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) -# AM_CONDITIONAL -*- Autoconf -*- - -# Copyright (C) 1997, 2000, 2001, 2003 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# AM_CONDITIONAL -*- Autoconf -*- -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# serial 6 +# Copyright (C) 1997-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], -[AC_PREREQ(2.52)dnl - ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], - [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl -AC_SUBST([$1_TRUE]) -AC_SUBST([$1_FALSE]) +[AC_PREREQ([2.52])dnl + m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE])dnl +AC_SUBST([$1_FALSE])dnl +_AM_SUBST_NOTMAKE([$1_TRUE])dnl +_AM_SUBST_NOTMAKE([$1_FALSE])dnl +m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' @@ -145,43 +137,28 @@ else fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then - AC_MSG_ERROR([conditional "$1" was never defined. -Usually this means the macro was only invoked conditionally.]) + AC_MSG_ERROR([[conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]]) fi])]) -# serial 7 -*- Autoconf -*- - -# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 -# Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# Copyright (C) 1999-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be +# There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... - # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. -# NAME is "CC", "CXX", "GCJ", or "OBJC". +# NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was @@ -194,11 +171,13 @@ AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl -ifelse([$1], CC, [depcc="$CC" am_compiler_list=], - [$1], CXX, [depcc="$CXX" am_compiler_list=], - [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], - [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], - [depcc="$$1" am_compiler_list=]) +m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], + [$1], [CXX], [depcc="$CXX" am_compiler_list=], + [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], + [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], + [$1], [UPC], [depcc="$UPC" am_compiler_list=], + [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], + [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], @@ -206,8 +185,9 @@ AC_CACHE_CHECK([dependency style of $depcc], # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up - # making a dummy file named `D' -- because `-MD' means `put the output - # in D'. + # making a dummy file named 'D' -- because '-MD' means "put the output + # in D". + rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. @@ -225,6 +205,16 @@ AC_CACHE_CHECK([dependency style of $depcc], if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi + am__universal=false + m4_case([$1], [CC], + [case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac], + [CXX], + [case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac]) + for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and @@ -236,34 +226,49 @@ AC_CACHE_CHECK([dependency style of $depcc], : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c - # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with - # Solaris 8's {/usr,}/bin/sh. - touch sub/conftst$i.h + # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with + # Solaris 10 /bin/sh. + echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + # We check with '-c' and '-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle '-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs. + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; nosideeffect) - # after this tag, mechanisms are not by side-effect, so they'll - # only be used when explicitly requested + # After this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok '-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; none) break ;; esac - # We check with `-c' and `-o' for the sake of the "dashmstdout" - # mode. It turns out that the SunPro C++ compiler does not properly - # handle `-M -o', and we need to detect this. if depmode=$depmode \ - source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ - $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && - grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message @@ -296,7 +301,7 @@ AM_CONDITIONAL([am__fastdep$1], [ # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. -# This macro is AC_REQUIREd in _AM_DEPENDENCIES +# This macro is AC_REQUIREd in _AM_DEPENDENCIES. AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl @@ -306,85 +311,85 @@ AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], -[AC_ARG_ENABLE(dependency-tracking, -[ --disable-dependency-tracking speeds up one-time build - --enable-dependency-tracking do not reject slow dependency extractors]) +[AC_ARG_ENABLE([dependency-tracking], [dnl +AS_HELP_STRING( + [--enable-dependency-tracking], + [do not reject slow dependency extractors]) +AS_HELP_STRING( + [--disable-dependency-tracking], + [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' + am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) -AC_SUBST([AMDEPBACKSLASH]) +AC_SUBST([AMDEPBACKSLASH])dnl +_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl +AC_SUBST([am__nodep])dnl +_AM_SUBST_NOTMAKE([am__nodep])dnl ]) -# Generate code to set up dependency tracking. -*- Autoconf -*- - -# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. +# Generate code to set up dependency tracking. -*- Autoconf -*- -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# Copyright (C) 1999-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -#serial 2 # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], -[for mf in $CONFIG_FILES; do - # Strip MF so we end up with the name of the file. - mf=`echo "$mf" | sed -e 's/:.*$//'` - # Check whether this is an Automake generated Makefile or not. - # We used to match only the files named `Makefile.in', but - # some people rename them; so instead we look at the file content. - # Grep'ing the first line is not enough: some people post-process - # each Makefile.in and add a new line on top of each file to say so. - # So let's grep whole file. - if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then - dirpart=`AS_DIRNAME("$mf")` - else - continue - fi - grep '^DEP_FILES *= *[[^ @%:@]]' < "$mf" > /dev/null || continue - # Extract the definition of DEP_FILES from the Makefile without - # running `make'. - DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` - test -z "$DEPDIR" && continue - # When using ansi2knr, U may be empty or an underscore; expand it - U=`sed -n 's/^U = //p' < "$mf"` - test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR" - # We invoke sed twice because it is the simplest approach to - # changing $(DEPDIR) to its actual value in the expansion. - for file in `sed -n ' - /^DEP_FILES = .*\\\\$/ { - s/^DEP_FILES = // - :loop - s/\\\\$// - p - n - /\\\\$/ b loop - p - } - /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \ - sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do - # Make sure the directory exists. - test -f "$dirpart/$file" && continue - fdir=`AS_DIRNAME(["$file"])` - AS_MKDIR_P([$dirpart/$fdir]) - # echo "creating $dirpart/$file" - echo '# dummy' > "$dirpart/$file" +[{ + # Older Autoconf quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + case $CONFIG_FILES in + *\'*) eval set x "$CONFIG_FILES" ;; + *) set x $CONFIG_FILES ;; + esac + shift + for mf + do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named 'Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then + dirpart=`AS_DIRNAME("$mf")` + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running 'make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "$am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`AS_DIRNAME(["$file"])` + AS_MKDIR_P([$dirpart/$fdir]) + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done done -done +} ])# _AM_OUTPUT_DEPENDENCY_COMMANDS @@ -393,7 +398,7 @@ done # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking -# is enabled. FIXME. This creates each `.P' file that we will +# is enabled. FIXME. This creates each '.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], @@ -401,54 +406,22 @@ AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) -# Like AC_CONFIG_HEADER, but automatically create stamp file. -*- Autoconf -*- +# Do all the work for Automake. -*- Autoconf -*- -# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# serial 7 - -# AM_CONFIG_HEADER is obsolete. It has been replaced by AC_CONFIG_HEADERS. -AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)]) - -# Do all the work for Automake. -*- Autoconf -*- +# Copyright (C) 1996-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# This macro actually does too much some checks are only needed if +# This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003 -# Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# serial 11 +dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. +m4_define([AC_PROG_CC], +m4_defn([AC_PROG_CC]) +[_AM_PROG_CC_C_O +]) # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) @@ -462,16 +435,20 @@ AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)]) # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], -[AC_PREREQ([2.58])dnl +[AC_PREREQ([2.65])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl -# test to see if srcdir already configured -if test "`cd $srcdir && pwd`" != "`pwd`" && - test -f $srcdir/config.status; then - AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) + fi fi # test whether we have cygpath @@ -487,47 +464,125 @@ AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], -[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl +[AC_DIAGNOSE([obsolete], + [$0: two- and three-arguments forms are deprecated.]) +m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl +dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. +m4_if( + m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), + [ok:ok],, + [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, -[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) - AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl +[AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) + AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl -AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) -AM_MISSING_PROG(AUTOCONF, autoconf) -AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) -AM_MISSING_PROG(AUTOHEADER, autoheader) -AM_MISSING_PROG(MAKEINFO, makeinfo) -AM_MISSING_PROG(AMTAR, tar) -AM_PROG_INSTALL_SH -AM_PROG_INSTALL_STRIP -AC_REQUIRE([AM_PROG_MKDIR_P])dnl -# We need awk for the "check" target. The system "awk" is bad on -# some platforms. +AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) +AM_MISSING_PROG([AUTOCONF], [autoconf]) +AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) +AM_MISSING_PROG([AUTOHEADER], [autoheader]) +AM_MISSING_PROG([MAKEINFO], [makeinfo]) +AC_REQUIRE([AM_PROG_INSTALL_SH])dnl +AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl +AC_REQUIRE([AC_PROG_MKDIR_P])dnl +# For better backward compatibility. To be removed once Automake 1.9.x +# dies out for good. For more background, see: +# +# +AC_SUBST([mkdir_p], ['$(MKDIR_P)']) +# We need awk for the "check" target (and possibly the TAP driver). The +# system "awk" is bad on some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl - +_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], + [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], + [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], - [_AM_DEPENDENCIES(CC)], - [define([AC_PROG_CC], - defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl + [_AM_DEPENDENCIES([CC])], + [m4_define([AC_PROG_CC], + m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], - [_AM_DEPENDENCIES(CXX)], - [define([AC_PROG_CXX], - defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl + [_AM_DEPENDENCIES([CXX])], + [m4_define([AC_PROG_CXX], + m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJC], + [_AM_DEPENDENCIES([OBJC])], + [m4_define([AC_PROG_OBJC], + m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl +AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], + [_AM_DEPENDENCIES([OBJCXX])], + [m4_define([AC_PROG_OBJCXX], + m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) +AC_REQUIRE([AM_SILENT_RULES])dnl +dnl The testsuite driver may need to know about EXEEXT, so add the +dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This +dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. +AC_CONFIG_COMMANDS_PRE(dnl +[m4_provide_if([_AM_COMPILER_EXEEXT], + [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl + +# POSIX will say in a future version that running "rm -f" with no argument +# is OK; and we want to be able to make that assumption in our Makefile +# recipes. So use an aggressive probe to check that the usage we want is +# actually supported "in the wild" to an acceptable degree. +# See automake bug#10828. +# To make any issue more visible, cause the running configure to be aborted +# by default if the 'rm' program in use doesn't match our expectations; the +# user can still override this though. +if rm -f && rm -fr && rm -rf; then : OK; else + cat >&2 <<'END' +Oops! + +Your 'rm' program seems unable to run without file operands specified +on the command line, even when the '-f' option is present. This is contrary +to the behaviour of most rm programs out there, and not conforming with +the upcoming POSIX standard: + +Please tell bug-automake@gnu.org about your system, including the value +of your $PATH and any error possibly output before this message. This +can help us improve future automake versions. + +END + if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then + echo 'Configuration will proceed anyway, since you have set the' >&2 + echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 + echo >&2 + else + cat >&2 <<'END' +Aborting the configuration process, to ensure you take notice of the issue. + +You can download and install GNU coreutils to get an 'rm' implementation +that behaves properly: . + +If you want to complete the configuration process using your problematic +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM +to "yes", and re-run configure. + +END + AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) + fi +fi +dnl The trailing newline in this macro's definition is deliberate, for +dnl backward compatibility and to allow trailing 'dnl'-style comments +dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) +dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not +dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further +dnl mangled by Autoconf and run in a shell conditional statement. +m4_define([_AC_COMPILER_EXEEXT], +m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header @@ -538,62 +593,44 @@ AC_PROVIDE_IFELSE([AC_PROG_CXX], # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. +_am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in - $1 | $1:* ) + $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done -echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count]) +echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) + +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. - -# Copyright (C) 2001, 2003 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl -install_sh=${install_sh-"$am_aux_dir/install-sh"} -AC_SUBST(install_sh)]) - -# -*- Autoconf -*- -# Copyright (C) 2003 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +if test x"${install_sh+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; + *) + install_sh="\${SHELL} $am_aux_dir/install-sh" + esac +fi +AC_SUBST([install_sh])]) -# serial 1 +# Copyright (C) 2003-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. @@ -608,26 +645,13 @@ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) -# Check to see how 'make' treats includes. -*- Autoconf -*- - -# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. +# Check to see how 'make' treats includes. -*- Autoconf -*- -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# serial 2 +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_MAKE_INCLUDE() # ----------------- @@ -636,7 +660,7 @@ AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: - @echo done + @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. @@ -646,24 +670,24 @@ am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf -# We grep out `Entering directory' and `Leaving directory' -# messages which can occur if `w' ends up in MAKEFLAGS. -# In particular we don't look at `^make:' because GNU make might -# be invoked under some other name (usually "gmake"), in which -# case it prints its new name instead of `make'. -if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then - am__include=include - am__quote= - _am_result=GNU -fi +# Ignore all kinds of additional output from 'make'. +case `$am_make -s -f confmf 2> /dev/null` in #( +*the\ am__doit\ target*) + am__include=include + am__quote= + _am_result=GNU + ;; +esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf - if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then - am__include=.include - am__quote="\"" - _am_result=BSD - fi + case `$am_make -s -f confmf 2> /dev/null` in #( + *the\ am__doit\ target*) + am__include=.include + am__quote="\"" + _am_result=BSD + ;; + esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) @@ -671,27 +695,13 @@ AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) -# -*- Autoconf -*- - - -# Copyright (C) 1997, 1999, 2000, 2001, 2003 Free Software Foundation, Inc. +# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# serial 3 +# Copyright (C) 1997-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ @@ -700,109 +710,66 @@ AC_DEFUN([AM_MISSING_PROG], $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) - # AM_MISSING_HAS_RUN # ------------------ -# Define MISSING if not defined so far and test if it supports --run. -# If it does, set am_missing_run to use it, otherwise, to nothing. +# Define MISSING if not defined so far and test if it is modern enough. +# If it is, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl -test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +AC_REQUIRE_AUX_FILE([missing])dnl +if test x"${MISSING+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; + *) + MISSING="\${SHELL} $am_aux_dir/missing" ;; + esac +fi # Use eval to expand $SHELL -if eval "$MISSING --run true"; then - am_missing_run="$MISSING --run " +if eval "$MISSING --is-lightweight"; then + am_missing_run="$MISSING " else am_missing_run= - AC_MSG_WARN([`missing' script is too old or missing]) + AC_MSG_WARN(['missing' script is too old or missing]) fi ]) -# AM_PROG_MKDIR_P -# --------------- -# Check whether `mkdir -p' is supported, fallback to mkinstalldirs otherwise. - -# Copyright (C) 2003, 2004 Free Software Foundation, Inc. - -# This program 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 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. - -# Automake 1.8 used `mkdir -m 0755 -p --' to ensure that directories -# created by `make install' are always world readable, even if the -# installer happens to have an overly restrictive umask (e.g. 077). -# This was a mistake. There are at least two reasons why we must not -# use `-m 0755': -# - it causes special bits like SGID to be ignored, -# - it may be too restrictive (some setups expect 775 directories). +# -*- Autoconf -*- +# Obsolete and "removed" macros, that must however still report explicit +# error messages when used, to smooth transition. # -# Do not use -m 0755 and let people choose whatever they expect by -# setting umask. +# Copyright (C) 1996-2017 Free Software Foundation, Inc. # -# We cannot accept any implementation of `mkdir' that recognizes `-p'. -# Some implementations (such as Solaris 8's) are not thread-safe: if a -# parallel make tries to run `mkdir -p a/b' and `mkdir -p a/c' -# concurrently, both version can detect that a/ is missing, but only -# one can create it and the other will error out. Consequently we -# restrict ourselves to GNU make (using the --version option ensures -# this.) -AC_DEFUN([AM_PROG_MKDIR_P], -[if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then - # Keeping the `.' argument allows $(mkdir_p) to be used without - # argument. Indeed, we sometimes output rules like - # $(mkdir_p) $(somedir) - # where $(somedir) is conditionally defined. - # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more - # expensive solution, as it forces Make to start a sub-shell.) - mkdir_p='mkdir -p -- .' -else - # On NextStep and OpenStep, the `mkdir' command does not - # recognize any option. It will interpret all options as - # directories to create, and then abort because `.' already - # exists. - for d in ./-p ./--version; - do - test -d $d && rmdir $d - done - # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists. - if test -f "$ac_aux_dir/mkinstalldirs"; then - mkdir_p='$(mkinstalldirs)' - else - mkdir_p='$(install_sh) -d' - fi -fi -AC_SUBST([mkdir_p])]) - -# Helper functions for option handling. -*- Autoconf -*- +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc. +AC_DEFUN([AM_CONFIG_HEADER], +[AC_DIAGNOSE([obsolete], +['$0': this macro is obsolete. +You should use the 'AC][_CONFIG_HEADERS' macro instead.])dnl +AC_CONFIG_HEADERS($@)]) -# This program 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 2, or (at your option) -# any later version. +AC_DEFUN([AM_PROG_CC_STDC], +[AC_PROG_CC +am_cv_prog_cc_stdc=$ac_cv_prog_cc_stdc +AC_DIAGNOSE([obsolete], +['$0': this macro is obsolete. +You should simply use the 'AC][_PROG_CC' macro instead. +Also, your code should no longer depend upon 'am_cv_prog_cc_stdc', +but upon 'ac_cv_prog_cc_stdc'.])]) -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +AC_DEFUN([AM_C_PROTOTYPES], + [AC_FATAL([automatic de-ANSI-fication support has been removed])]) +AU_DEFUN([fp_C_PROTOTYPES], [AM_C_PROTOTYPES]) -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# Helper functions for option handling. -*- Autoconf -*- -# serial 2 +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # _AM_MANGLE_OPTION(NAME) # ----------------------- @@ -810,16 +777,16 @@ AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) -# ------------------------------ +# -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], -[m4_define(_AM_MANGLE_OPTION([$1]), 1)]) +[m4_define(_AM_MANGLE_OPTION([$1]), [1])]) # _AM_SET_OPTIONS(OPTIONS) -# ---------------------------------- +# ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], -[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) +[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- @@ -827,59 +794,126 @@ AC_DEFUN([_AM_SET_OPTIONS], AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) +# Copyright (C) 1999-2017 Free Software Foundation, Inc. # -# Check to make sure that the build environment is sane. -# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc. +# _AM_PROG_CC_C_O +# --------------- +# Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC +# to automatically call this. +AC_DEFUN([_AM_PROG_CC_C_O], +[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl +AC_REQUIRE_AUX_FILE([compile])dnl +AC_LANG_PUSH([C])dnl +AC_CACHE_CHECK( + [whether $CC understands -c and -o together], + [am_cv_prog_cc_c_o], + [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) + # Make sure it works both with $CC and with simple cc. + # Following AC_PROG_CC_C_O, we do the test twice because some + # compilers refuse to overwrite an existing .o file with -o, + # though they will create one. + am_cv_prog_cc_c_o=yes + for am_i in 1 2; do + if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ + && test -f conftest2.$ac_objext; then + : OK + else + am_cv_prog_cc_c_o=no + break + fi + done + rm -f core conftest* + unset am_i]) +if test "$am_cv_prog_cc_c_o" != yes; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +AC_LANG_POP([C])]) -# This program 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 2, or (at your option) -# any later version. +# For backward compatibility. +AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# AM_RUN_LOG(COMMAND) +# ------------------- +# Run COMMAND, save the exit status in ac_status, and log it. +# (This has been adapted from Autoconf's _AC_RUN_LOG macro.) +AC_DEFUN([AM_RUN_LOG], +[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD + ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + (exit $ac_status); }]) -# serial 3 +# Check to make sure that the build environment is sane. -*- Autoconf -*- + +# Copyright (C) 1996-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) -# Just in case -sleep 1 -echo timestamp > conftest.file -# Do `set' in a subshell so we don't clobber the current shell's +# Reject unsafe characters in $srcdir or the absolute working directory +# name. Accept space and tab only in the latter. +am_lf=' +' +case `pwd` in + *[[\\\"\#\$\&\'\`$am_lf]]*) + AC_MSG_ERROR([unsafe absolute working directory name]);; +esac +case $srcdir in + *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) + AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; +esac + +# Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( - set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` - if test "$[*]" = "X"; then - # -L didn't work. - set X `ls -t $srcdir/configure conftest.file` - fi - rm -f conftest.file - if test "$[*]" != "X $srcdir/configure conftest.file" \ - && test "$[*]" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken -alias in your environment]) - fi - + am_has_slept=no + for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$[*]" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + if test "$[*]" != "X $srcdir/configure conftest.file" \ + && test "$[*]" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken + alias in your environment]) + fi + if test "$[2]" = conftest.file || test $am_try -eq 2; then + break + fi + # Just in case. + sleep 1 + am_has_slept=yes + done test "$[2]" = conftest.file ) then @@ -889,45 +923,260 @@ else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi -AC_MSG_RESULT(yes)]) - -# AM_PROG_INSTALL_STRIP - -# Copyright (C) 2001, 2003 Free Software Foundation, Inc. +AC_MSG_RESULT([yes]) +# If we didn't sleep, we still need to ensure time stamps of config.status and +# generated files are strictly newer. +am_sleep_pid= +if grep 'slept: no' conftest.file >/dev/null 2>&1; then + ( sleep 1 ) & + am_sleep_pid=$! +fi +AC_CONFIG_COMMANDS_PRE( + [AC_MSG_CHECKING([that generated files are newer than configure]) + if test -n "$am_sleep_pid"; then + # Hide warnings about reused PIDs. + wait $am_sleep_pid 2>/dev/null + fi + AC_MSG_RESULT([done])]) +rm -f conftest.file +]) -# This program 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 2, or (at your option) -# any later version. +# Copyright (C) 2009-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# AM_SILENT_RULES([DEFAULT]) +# -------------------------- +# Enable less verbose build rules; with the default set to DEFAULT +# ("yes" being less verbose, "no" or empty being verbose). +AC_DEFUN([AM_SILENT_RULES], +[AC_ARG_ENABLE([silent-rules], [dnl +AS_HELP_STRING( + [--enable-silent-rules], + [less verbose build output (undo: "make V=1")]) +AS_HELP_STRING( + [--disable-silent-rules], + [verbose build output (undo: "make V=0")])dnl +]) +case $enable_silent_rules in @%:@ ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; + *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; +esac +dnl +dnl A few 'make' implementations (e.g., NonStop OS and NextStep) +dnl do not support nested variable expansions. +dnl See automake bug#9928 and bug#10237. +am_make=${MAKE-make} +AC_CACHE_CHECK([whether $am_make supports nested variables], + [am_cv_make_support_nested_variables], + [if AS_ECHO([['TRUE=$(BAR$(V)) +BAR0=false +BAR1=true +V=1 +am__doit: + @$(TRUE) +.PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then + am_cv_make_support_nested_variables=yes +else + am_cv_make_support_nested_variables=no +fi]) +if test $am_cv_make_support_nested_variables = yes; then + dnl Using '$V' instead of '$(V)' breaks IRIX make. + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi +AC_SUBST([AM_V])dnl +AM_SUBST_NOTMAKE([AM_V])dnl +AC_SUBST([AM_DEFAULT_V])dnl +AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl +AC_SUBST([AM_DEFAULT_VERBOSITY])dnl +AM_BACKSLASH='\' +AC_SUBST([AM_BACKSLASH])dnl +_AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl +]) -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# Copyright (C) 2001-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. -# One issue with vendor `install' (even GNU) is that you can't +# AM_PROG_INSTALL_STRIP +# --------------------- +# One issue with vendor 'install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we -# always use install-sh in `make install-strip', and initialize +# always use install-sh in "make install-strip", and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl -# Installed binaries are usually stripped using `strip' when the user -# run `make install-strip'. However `strip' might not be the right +# Installed binaries are usually stripped using 'strip' when the user +# run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake -# will honor the `STRIP' environment variable to overrule this program. -dnl Don't test for $cross_compiling = yes, because it might be `maybe'. +# will honor the 'STRIP' environment variable to overrule this program. +dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi -INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s" +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) +# Copyright (C) 2006-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_SUBST_NOTMAKE(VARIABLE) +# --------------------------- +# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. +# This macro is traced by Automake. +AC_DEFUN([_AM_SUBST_NOTMAKE]) + +# AM_SUBST_NOTMAKE(VARIABLE) +# -------------------------- +# Public sister of _AM_SUBST_NOTMAKE. +AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) + +# Check how to create a tarball. -*- Autoconf -*- + +# Copyright (C) 2004-2017 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_PROG_TAR(FORMAT) +# -------------------- +# Check how to create a tarball in format FORMAT. +# FORMAT should be one of 'v7', 'ustar', or 'pax'. +# +# Substitute a variable $(am__tar) that is a command +# writing to stdout a FORMAT-tarball containing the directory +# $tardir. +# tardir=directory && $(am__tar) > result.tar +# +# Substitute a variable $(am__untar) that extract such +# a tarball read from stdin. +# $(am__untar) < result.tar +# +AC_DEFUN([_AM_PROG_TAR], +[# Always define AMTAR for backward compatibility. Yes, it's still used +# in the wild :-( We should find a proper way to deprecate it ... +AC_SUBST([AMTAR], ['$${TAR-tar}']) + +# We'll loop over all known methods to create a tar archive until one works. +_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' + +m4_if([$1], [v7], + [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], + + [m4_case([$1], + [ustar], + [# The POSIX 1988 'ustar' format is defined with fixed-size fields. + # There is notably a 21 bits limit for the UID and the GID. In fact, + # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 + # and bug#13588). + am_max_uid=2097151 # 2^21 - 1 + am_max_gid=$am_max_uid + # The $UID and $GID variables are not portable, so we need to resort + # to the POSIX-mandated id(1) utility. Errors in the 'id' calls + # below are definitely unexpected, so allow the users to see them + # (that is, avoid stderr redirection). + am_uid=`id -u || echo unknown` + am_gid=`id -g || echo unknown` + AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) + if test $am_uid -le $am_max_uid; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + _am_tools=none + fi + AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) + if test $am_gid -le $am_max_gid; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + _am_tools=none + fi], + + [pax], + [], + + [m4_fatal([Unknown tar format])]) + + AC_MSG_CHECKING([how to create a $1 tar archive]) + + # Go ahead even if we have the value already cached. We do so because we + # need to set the values for the 'am__tar' and 'am__untar' variables. + _am_tools=${am_cv_prog_tar_$1-$_am_tools} + + for _am_tool in $_am_tools; do + case $_am_tool in + gnutar) + for _am_tar in tar gnutar gtar; do + AM_RUN_LOG([$_am_tar --version]) && break + done + am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' + am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' + am__untar="$_am_tar -xf -" + ;; + plaintar) + # Must skip GNU tar: if it does not support --format= it doesn't create + # ustar tarball either. + (tar --version) >/dev/null 2>&1 && continue + am__tar='tar chf - "$$tardir"' + am__tar_='tar chf - "$tardir"' + am__untar='tar xf -' + ;; + pax) + am__tar='pax -L -x $1 -w "$$tardir"' + am__tar_='pax -L -x $1 -w "$tardir"' + am__untar='pax -r' + ;; + cpio) + am__tar='find "$$tardir" -print | cpio -o -H $1 -L' + am__tar_='find "$tardir" -print | cpio -o -H $1 -L' + am__untar='cpio -i -H $1 -d' + ;; + none) + am__tar=false + am__tar_=false + am__untar=false + ;; + esac + + # If the value was cached, stop now. We just wanted to have am__tar + # and am__untar set. + test -n "${am_cv_prog_tar_$1}" && break + + # tar/untar a dummy directory, and stop if the command works. + rm -rf conftest.dir + mkdir conftest.dir + echo GrepMe > conftest.dir/file + AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) + rm -rf conftest.dir + if test -s conftest.tar; then + AM_RUN_LOG([$am__untar /dev/null 2>&1 && break + fi + done + rm -rf conftest.dir + + AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) + AC_MSG_RESULT([$am_cv_prog_tar_$1])]) + +AC_SUBST([am__tar]) +AC_SUBST([am__untar]) +]) # _AM_PROG_TAR + m4_include([acinclude.m4]) diff --git a/bin/.fix b/bin/.fix deleted file mode 100644 index 8b0cb99..0000000 --- a/bin/.fix +++ /dev/null @@ -1 +0,0 @@ -needed diff --git a/compile b/compile new file mode 100755 index 0000000..2ab71e4 --- /dev/null +++ b/compile @@ -0,0 +1,348 @@ +#! /bin/sh +# Wrapper for compilers which do not understand '-c -o'. + +scriptversion=2016-01-11.22; # UTC + +# Copyright (C) 1999-2017 Free Software Foundation, Inc. +# Written by Tom Tromey . +# +# This program 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 2, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# This file is maintained in Automake, please report +# bugs to or send patches to +# . + +nl=' +' + +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent tools from complaining about whitespace usage. +IFS=" "" $nl" + +file_conv= + +# func_file_conv build_file lazy +# Convert a $build file to $host form and store it in $file +# Currently only supports Windows hosts. If the determined conversion +# type is listed in (the comma separated) LAZY, no conversion will +# take place. +func_file_conv () +{ + file=$1 + case $file in + / | /[!/]*) # absolute file, and not a UNC file + if test -z "$file_conv"; then + # lazily determine how to convert abs files + case `uname -s` in + MINGW*) + file_conv=mingw + ;; + CYGWIN*) + file_conv=cygwin + ;; + *) + file_conv=wine + ;; + esac + fi + case $file_conv/,$2, in + *,$file_conv,*) + ;; + mingw/*) + file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` + ;; + cygwin/*) + file=`cygpath -m "$file" || echo "$file"` + ;; + wine/*) + file=`winepath -w "$file" || echo "$file"` + ;; + esac + ;; + esac +} + +# func_cl_dashL linkdir +# Make cl look for libraries in LINKDIR +func_cl_dashL () +{ + func_file_conv "$1" + if test -z "$lib_path"; then + lib_path=$file + else + lib_path="$lib_path;$file" + fi + linker_opts="$linker_opts -LIBPATH:$file" +} + +# func_cl_dashl library +# Do a library search-path lookup for cl +func_cl_dashl () +{ + lib=$1 + found=no + save_IFS=$IFS + IFS=';' + for dir in $lib_path $LIB + do + IFS=$save_IFS + if $shared && test -f "$dir/$lib.dll.lib"; then + found=yes + lib=$dir/$lib.dll.lib + break + fi + if test -f "$dir/$lib.lib"; then + found=yes + lib=$dir/$lib.lib + break + fi + if test -f "$dir/lib$lib.a"; then + found=yes + lib=$dir/lib$lib.a + break + fi + done + IFS=$save_IFS + + if test "$found" != yes; then + lib=$lib.lib + fi +} + +# func_cl_wrapper cl arg... +# Adjust compile command to suit cl +func_cl_wrapper () +{ + # Assume a capable shell + lib_path= + shared=: + linker_opts= + for arg + do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + eat=1 + case $2 in + *.o | *.[oO][bB][jJ]) + func_file_conv "$2" + set x "$@" -Fo"$file" + shift + ;; + *) + func_file_conv "$2" + set x "$@" -Fe"$file" + shift + ;; + esac + ;; + -I) + eat=1 + func_file_conv "$2" mingw + set x "$@" -I"$file" + shift + ;; + -I*) + func_file_conv "${1#-I}" mingw + set x "$@" -I"$file" + shift + ;; + -l) + eat=1 + func_cl_dashl "$2" + set x "$@" "$lib" + shift + ;; + -l*) + func_cl_dashl "${1#-l}" + set x "$@" "$lib" + shift + ;; + -L) + eat=1 + func_cl_dashL "$2" + ;; + -L*) + func_cl_dashL "${1#-L}" + ;; + -static) + shared=false + ;; + -Wl,*) + arg=${1#-Wl,} + save_ifs="$IFS"; IFS=',' + for flag in $arg; do + IFS="$save_ifs" + linker_opts="$linker_opts $flag" + done + IFS="$save_ifs" + ;; + -Xlinker) + eat=1 + linker_opts="$linker_opts $2" + ;; + -*) + set x "$@" "$1" + shift + ;; + *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) + func_file_conv "$1" + set x "$@" -Tp"$file" + shift + ;; + *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) + func_file_conv "$1" mingw + set x "$@" "$file" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift + done + if test -n "$linker_opts"; then + linker_opts="-link$linker_opts" + fi + exec "$@" $linker_opts + exit 1 +} + +eat= + +case $1 in + '') + echo "$0: No command. Try '$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: compile [--help] [--version] PROGRAM [ARGS] + +Wrapper for compilers which do not understand '-c -o'. +Remove '-o dest.o' from ARGS, run PROGRAM with the remaining +arguments, and rename the output as expected. + +If you are trying to build a whole package this is not the +right script to run: please start by reading the file 'INSTALL'. + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "compile $scriptversion" + exit $? + ;; + cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ + icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) + func_cl_wrapper "$@" # Doesn't return... + ;; +esac + +ofile= +cfile= + +for arg +do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + # So we strip '-o arg' only if arg is an object. + eat=1 + case $2 in + *.o | *.obj) + ofile=$2 + ;; + *) + set x "$@" -o "$2" + shift + ;; + esac + ;; + *.c) + cfile=$1 + set x "$@" "$1" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift +done + +if test -z "$ofile" || test -z "$cfile"; then + # If no '-o' option was seen then we might have been invoked from a + # pattern rule where we don't need one. That is ok -- this is a + # normal compilation that the losing compiler can handle. If no + # '.c' file was seen then we are probably linking. That is also + # ok. + exec "$@" +fi + +# Name of file we expect compiler to create. +cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` + +# Create the lock directory. +# Note: use '[/\\:.-]' here to ensure that we don't use the same name +# that we are using for the .o file. Also, base the name on the expected +# object file name, since that is what matters with a parallel build. +lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d +while true; do + if mkdir "$lockdir" >/dev/null 2>&1; then + break + fi + sleep 1 +done +# FIXME: race condition here if user kills between mkdir and trap. +trap "rmdir '$lockdir'; exit 1" 1 2 15 + +# Run the compile. +"$@" +ret=$? + +if test -f "$cofile"; then + test "$cofile" = "$ofile" || mv "$cofile" "$ofile" +elif test -f "${cofile}bj"; then + test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" +fi + +rmdir "$lockdir" +exit $ret + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/config.guess b/config.guess index 471f5a5..a05ca70 100644 --- a/config.guess +++ b/config.guess @@ -1,8 +1,8 @@ #! /bin/sh # Attempt to guess a canonical system name. -# Copyright 1992-2016 Free Software Foundation, Inc. +# Copyright 1992-2017 Free Software Foundation, Inc. -timestamp='2016-02-11' +timestamp='2017-09-16' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ timestamp='2016-02-11' # General Public License for more details. # # You should have received a copy of the GNU General Public License -# along with this program; if not, see . +# along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a @@ -27,7 +27,7 @@ timestamp='2016-02-11' # Originally written by Per Bothner; maintained since 2000 by Ben Elliston. # # You can get the latest version of this script from: -# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess +# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess # # Please send patches to . @@ -50,7 +50,7 @@ version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. -Copyright 1992-2016 Free Software Foundation, Inc. +Copyright 1992-2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." @@ -186,9 +186,12 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched - # to ELF recently, or will in the future. + # to ELF recently (or will in the future) and ABI. case "${UNAME_MACHINE_ARCH}" in - arm*|earm*|i386|m68k|ns32k|sh3*|sparc|vax) + earm*) + os=netbsdelf + ;; + arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ @@ -256,6 +259,9 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:Sortix:*:*) echo ${UNAME_MACHINE}-unknown-sortix exit ;; + *:Redox:*:*) + echo ${UNAME_MACHINE}-unknown-redox + exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) @@ -312,15 +318,6 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in exitcode=$? trap '' 0 exit $exitcode ;; - Alpha\ *:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # Should we change UNAME_MACHINE based on the output of uname instead - # of the specific Alpha model? - echo alpha-pc-interix - exit ;; - 21064:Windows_NT:50:3) - echo alpha-dec-winnt3.5 - exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; @@ -386,7 +383,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in # This test works for both compilers. if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ - (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH=x86_64 @@ -684,7 +681,7 @@ EOF exit (0); } EOF - (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac @@ -701,7 +698,7 @@ EOF # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 - if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH=hppa2.0w @@ -834,10 +831,11 @@ EOF UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) - echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - *) - echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + UNAME_PROCESSOR=x86_64 ;; + i386) + UNAME_PROCESSOR=i586 ;; esac + echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:MidnightBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` @@ -860,10 +858,6 @@ EOF *:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; - i*:windows32*:*) - # uname -m includes "-pc" on this system. - echo ${UNAME_MACHINE}-mingw32 - exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; @@ -879,27 +873,12 @@ EOF echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; - [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) - echo i${UNAME_MACHINE}-pc-mks - exit ;; - 8664:Windows_NT:*) - echo x86_64-pc-mks - exit ;; - i*:Windows_NT*:* | Pentium*:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we - # UNAME_MACHINE based on the output of uname instead of i386? - echo i586-pc-interix - exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; - p*:CYGWIN*:*) - echo powerpcle-unknown-cygwin - exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; @@ -909,7 +888,7 @@ EOF exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland - echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix @@ -1006,6 +985,9 @@ EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; + mips64el:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; openrisc*:Linux:*:*) echo or1k-unknown-linux-${LIBC} exit ;; @@ -1038,6 +1020,9 @@ EOF ppcle:Linux:*:*) echo powerpcle-unknown-linux-${LIBC} exit ;; + riscv32:Linux:*:* | riscv64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux-${LIBC} exit ;; @@ -1285,6 +1270,9 @@ EOF SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; + SX-ACE:SUPER-UX:*:*) + echo sxace-nec-superux${UNAME_RELEASE} + exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; @@ -1300,14 +1288,21 @@ EOF if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then if [ "$CC_FOR_BUILD" != no_compiler_found ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ - (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ - grep IS_64BIT_ARCH >/dev/null + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi + # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc + if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_PPC >/dev/null + then + UNAME_PROCESSOR=powerpc + fi fi elif test "$UNAME_PROCESSOR" = i386 ; then # Avoid executing cc on OS X 10.9, as it ships with a stub @@ -1331,15 +1326,18 @@ EOF *:QNX:*:4*) echo i386-pc-qnx exit ;; - NEO-?:NONSTOP_KERNEL:*:*) + NEO-*:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; - NSR-?:NONSTOP_KERNEL:*:*) + NSR-*:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; + NSX-*:NONSTOP_KERNEL:*:*) + echo nsx-tandem-nsk${UNAME_RELEASE} + exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; @@ -1395,7 +1393,7 @@ EOF echo i386-pc-xenix exit ;; i*86:skyos:*:*) - echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'` exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos @@ -1414,18 +1412,17 @@ esac cat >&2 < in order to provide the needed -information to handle your system. +If $0 has already been updated, send the following data and any +information you think might be pertinent to config-patches@gnu.org to +provide the necessary information to handle your system. config.guess timestamp = $timestamp diff --git a/config.h.in b/config.h.in index 6258a87..f3f1b37 100644 --- a/config.h.in +++ b/config.h.in @@ -1,4 +1,4 @@ -/* config.h.in. Generated from configure.in by autoheader. */ +/* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD @@ -6,12 +6,36 @@ /* Compile with debug code */ #undef DEBUG +/* Enable use of /dev/urandom */ +#undef ENABLE_DEV_URANDOM + /* this is the prefix for STL exception functions */ #undef EXCEPTION_NAMESPACE /* Define to 1 if you have the header file. */ #undef HAVE_BITS_SIGNUM_H +/* Define to 1 if you have the header file. */ +#undef HAVE_COMMONCRYPTO_COMMONDIGEST_H + +/* Has /dev/arandom */ +#undef HAVE_DEV_ARANDOM + +/* Has /dev/random */ +#undef HAVE_DEV_RANDOM + +/* Has /dev/urandom */ +#undef HAVE_DEV_URANDOM + +/* Define to 1 if you have the `door_create' function. */ +#undef HAVE_DOOR_CREATE + +/* Define to 1 if you have the header file. */ +#undef HAVE_DOOR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_FCNTL_H + /* Uses the GNU gcc compiler */ #undef HAVE_GCC @@ -48,6 +72,15 @@ /* Define to 1 if you have the header file. */ #undef HAVE_OPENSSL_SHA_H +/* Define to 1 if you have the `port_create' function. */ +#undef HAVE_PORT_CREATE + +/* Define to 1 if you have the header file. */ +#undef HAVE_PORT_H + +/* Define to 1 if you have the `posix_fadvise' function. */ +#undef HAVE_POSIX_FADVISE + /* Define to 1 if you have the header file. */ #undef HAVE_SIGNUM_H @@ -69,15 +102,33 @@ /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H +/* Define to 1 if `st_blocks' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_BLOCKS + +/* Define to 1 if `st_rdev' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_RDEV + +/* Define to 1 if you have the `swab' function. */ +#undef HAVE_SWAB + /* Define to 1 if you have the header file. */ #undef HAVE_SYSLOG_H +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_FS_VX_IOCTL_H + /* Define to 1 if you have the header file. */ #undef HAVE_SYS_MOUNT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_PARAM_H +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOCKET_H + /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STATFS_H @@ -93,9 +144,15 @@ /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UNISTD_H + /* Define to 1 if you have the header file. */ #undef HAVE_SYS_USTAT_H +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UTSNAME_H + /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H @@ -144,6 +201,9 @@ /* The size of `long long', as computed by sizeof. */ #undef SIZEOF_LONG_LONG +/* The size of `time_t', as computed by sizeof. */ +#undef SIZEOF_TIME_T + /* Don't use gethostbyname() on Solaris */ #undef SOLARIS_NO_GETHOSTBYNAME diff --git a/config.sub b/config.sub index 6f126a0..ec385cc 100644 --- a/config.sub +++ b/config.sub @@ -1,8 +1,8 @@ #! /bin/sh # Configuration validation subroutine script. -# Copyright 1992-2016 Free Software Foundation, Inc. +# Copyright 1992-2017 Free Software Foundation, Inc. -timestamp='2016-01-01' +timestamp='2017-09-22' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -15,7 +15,7 @@ timestamp='2016-01-01' # General Public License for more details. # # You should have received a copy of the GNU General Public License -# along with this program; if not, see . +# along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a @@ -33,7 +33,7 @@ timestamp='2016-01-01' # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: -# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub +# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases @@ -67,7 +67,7 @@ Report bugs and patches to ." version="\ GNU config.sub ($timestamp) -Copyright 1992-2016 Free Software Foundation, Inc. +Copyright 1992-2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." @@ -117,7 +117,7 @@ case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \ - kopensolaris*-gnu* | \ + kopensolaris*-gnu* | cloudabi*-eabi* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` @@ -229,9 +229,6 @@ case $os in -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; - -windowsnt*) - os=`echo $os | sed -e 's/windowsnt/winnt/'` - ;; -psos*) os=-psos ;; @@ -263,7 +260,7 @@ case $basic_machine in | fido | fr30 | frv | ft32 \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ - | i370 | i860 | i960 | ia64 \ + | i370 | i860 | i960 | ia16 | ia64 \ | ip2k | iq2000 \ | k1om \ | le32 | le64 \ @@ -301,6 +298,7 @@ case $basic_machine in | open8 | or1k | or1knd | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ + | pru \ | pyramid \ | riscv32 | riscv64 \ | rl78 | rx \ @@ -314,6 +312,7 @@ case $basic_machine in | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | visium \ + | wasm32 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) @@ -387,7 +386,7 @@ case $basic_machine in | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ - | i*86-* | i860-* | i960-* | ia64-* \ + | i*86-* | i860-* | i960-* | ia16-* | ia64-* \ | ip2k-* | iq2000-* \ | k1om-* \ | le32-* | le64-* \ @@ -428,6 +427,7 @@ case $basic_machine in | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ + | pru-* \ | pyramid-* \ | riscv32-* | riscv64-* \ | rl78-* | romp-* | rs6000-* | rx-* \ @@ -444,6 +444,7 @@ case $basic_machine in | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | visium-* \ + | wasm32-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ @@ -643,6 +644,14 @@ case $basic_machine in basic_machine=m68k-bull os=-sysv3 ;; + e500v[12]) + basic_machine=powerpc-unknown + os=$os"spe" + ;; + e500v[12]-*) + basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + os=$os"spe" + ;; ebmon29k) basic_machine=a29k-amd os=-ebmon @@ -938,6 +947,9 @@ case $basic_machine in nsr-tandem) basic_machine=nsr-tandem ;; + nsx-tandem) + basic_machine=nsx-tandem + ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf @@ -1022,7 +1034,7 @@ case $basic_machine in ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; - ppcle | powerpclittle | ppc-le | powerpc-little) + ppcle | powerpclittle) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) @@ -1032,7 +1044,7 @@ case $basic_machine in ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; - ppc64le | powerpc64little | ppc64-le | powerpc64-little) + ppc64le | powerpc64little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) @@ -1233,6 +1245,9 @@ case $basic_machine in basic_machine=a29k-wrs os=-vxworks ;; + wasm32) + basic_machine=wasm32-unknown + ;; w65*) basic_machine=w65-wdc os=-none @@ -1241,6 +1256,9 @@ case $basic_machine in basic_machine=hppa1.1-winbond os=-proelf ;; + x64) + basic_machine=x86_64-pc + ;; xbox) basic_machine=i686-pc os=-mingw32 @@ -1348,8 +1366,8 @@ esac if [ x"$os" != x"" ] then case $os in - # First match some system type aliases - # that might get confused with valid system types. + # First match some system type aliases that might get confused + # with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux @@ -1369,9 +1387,9 @@ case $os in -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; - # First accept the basic system types. + # Now accept the basic system types. # The portable systems comes first. - # Each alternative MUST END IN A *, to match a version number. + # Each alternative MUST end in a * to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ @@ -1387,9 +1405,9 @@ case $os in | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ - | -chorusos* | -chorusrdb* | -cegcc* \ + | -chorusos* | -chorusrdb* | -cegcc* | -glidix* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ - | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ + | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ @@ -1399,7 +1417,7 @@ case $os in | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \ - | -onefs* | -tirtos*) + | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) @@ -1531,6 +1549,8 @@ case $os in ;; -nacl*) ;; + -ios) + ;; -none) ;; *) @@ -1626,6 +1646,9 @@ case $basic_machine in sparc-* | *-sun) os=-sunos4.1.1 ;; + pru-*) + os=-elf + ;; *-be) os=-beos ;; diff --git a/configure b/configure index e3499db..2b35c0d 100755 --- a/configure +++ b/configure @@ -1,6 +1,9 @@ #! /bin/sh +# From configure.ac Revision: 2.4.3.7 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.69. +# Generated by GNU Autoconf 2.69 for tripwire 2.4.3.7. +# +# Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. @@ -8,6 +11,8 @@ # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. +# +# The developer of the original code and/or files is Tripwire, Inc. Portions created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights reserved. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## @@ -264,10 +269,12 @@ fi $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else - $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, -$0: including any error possibly output before this -$0: message. Then install a modern shell, or manually run -$0: the script under such a shell if you do have one." + $as_echo "$0: Please tell bug-autoconf@gnu.org and +$0: https://github.com/Tripwire/tripwire-open-source/issues +$0: about your system, including any error possibly output +$0: before this message. Then install a modern shell, or +$0: manually run the script under such a shell if you do +$0: have one." fi exit 1 fi @@ -575,12 +582,12 @@ MFLAGS= MAKEFLAGS= # Identity of this package. -PACKAGE_NAME= -PACKAGE_TARNAME= -PACKAGE_VERSION= -PACKAGE_STRING= -PACKAGE_BUGREPORT= -PACKAGE_URL= +PACKAGE_NAME='tripwire' +PACKAGE_TARNAME='tripwire' +PACKAGE_VERSION='2.4.3.7' +PACKAGE_STRING='tripwire 2.4.3.7' +PACKAGE_BUGREPORT='https://github.com/Tripwire/tripwire-open-source/issues' +PACKAGE_URL='https://github.com/Tripwire/tripwire-open-source' ac_unique_file="src/tw/tw.cpp" # Factoring default headers for most tests. @@ -619,7 +626,9 @@ ac_includes_default="\ # include #endif" -ac_subst_vars='LTLIBOBJS +ac_subst_vars='am__EXEEXT_FALSE +am__EXEEXT_TRUE +LTLIBOBJS LIBOBJS CORE_CRYPT_O CXXCPP @@ -628,6 +637,7 @@ GREP CPP path_to_sendmail path_to_vi +AR LN LN_S YFLAGS @@ -642,6 +652,7 @@ CXX am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE +am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE @@ -655,14 +666,21 @@ CPPFLAGS LDFLAGS CFLAGS CC +AM_BACKSLASH +AM_DEFAULT_VERBOSITY +AM_DEFAULT_V +AM_V +am__untar +am__tar +AMTAR am__leading_dot SET_MAKE AWK mkdir_p +MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh -AMTAR MAKEINFO AUTOHEADER AUTOMAKE @@ -671,6 +689,7 @@ ACLOCAL VERSION PACKAGE CYGPATH_W +am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM @@ -727,9 +746,16 @@ SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking +enable_silent_rules +enable_extrawarnings enable_static enable_debug +enable_coverage +enable_profiling +enable_urandom enable_dependency_tracking +enable_commoncrypto +enable_iconv enable_openssl with_ssl_dir ' @@ -788,7 +814,7 @@ sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' -docdir='${datarootdir}/doc/${PACKAGE}' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' @@ -1288,7 +1314,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures this package to adapt to many kinds of systems. +\`configure' configures tripwire 2.4.3.7 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1336,7 +1362,7 @@ Fine tuning of the installation directories: --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/PACKAGE] + --docdir=DIR documentation root [DATAROOTDIR/doc/tripwire] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] @@ -1358,18 +1384,30 @@ _ACEOF fi if test -n "$ac_init_help"; then - + case $ac_init_help in + short | recursive ) echo "Configuration of tripwire 2.4.3.7:";; + esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-silent-rules less verbose build output (undo: "make V=1") + --disable-silent-rules verbose build output (undo: "make V=0") + —-disable-extrawarnings do not compile with -Wextra warnings enabled --enable-static compile static binaries --enable-debug compile with debuging enabled - --disable-dependency-tracking speeds up one-time build - --enable-dependency-tracking do not reject slow dependency extractors - --disable-openssl don't link against OpenSSL libraries + --enable-coverage enable code coverage + --enable-profiling enable profiling + --enable-urandom use /dev/urandom + --enable-dependency-tracking + do not reject slow dependency extractors + --disable-dependency-tracking + speeds up one-time build + --disable-commoncrypto Don't use CommonCrypto hash implementations (OSX only) + --enable-iconv Use iconv for locale-independent report and db files + --disable-openssl Don't link against OpenSSL libraries Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] @@ -1398,7 +1436,8 @@ Some influential environment variables: Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. -Report bugs to the package provider. +Report bugs to . +tripwire home page: . _ACEOF ac_status=$? fi @@ -1461,12 +1500,14 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -configure +tripwire configure 2.4.3.7 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. + +The developer of the original code and/or files is Tripwire, Inc. Portions created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights reserved. _ACEOF exit fi @@ -1700,6 +1741,10 @@ $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( $as_echo "## ---------------------------------------------------------------------- ## +## Report this to https://github.com/Tripwire/tripwire-open-source/issues ## +## ---------------------------------------------------------------------- ##" + ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 @@ -1985,6 +2030,63 @@ rm -f conftest.val } # ac_fn_c_compute_int +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if eval \${$4+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_member + # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. @@ -2205,6 +2307,10 @@ $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( $as_echo "## ---------------------------------------------------------------------- ## +## Report this to https://github.com/Tripwire/tripwire-open-source/issues ## +## ---------------------------------------------------------------------- ##" + ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 @@ -2338,7 +2444,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by $as_me, which was +It was created by tripwire $as_me 2.4.3.7, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ @@ -2826,7 +2932,8 @@ test -n "$target_alias" && test "$program_prefix$program_suffix$program_transform_name" = \ NONENONEs,x,x, && program_prefix=${target_alias}- -am__api_version="1.8" +am__api_version='1.15' + # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: @@ -2922,32 +3029,50 @@ test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } -# Just in case -sleep 1 -echo timestamp > conftest.file -# Do `set' in a subshell so we don't clobber the current shell's +# Reject unsafe characters in $srcdir or the absolute working directory +# name. Accept space and tab only in the latter. +am_lf=' +' +case `pwd` in + *[\\\"\#\$\&\'\`$am_lf]*) + as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; +esac +case $srcdir in + *[\\\"\#\$\&\'\`$am_lf\ \ ]*) + as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; +esac + +# Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( - set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` - if test "$*" = "X"; then - # -L didn't work. - set X `ls -t $srcdir/configure conftest.file` - fi - rm -f conftest.file - if test "$*" != "X $srcdir/configure conftest.file" \ - && test "$*" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - as_fn_error $? "ls -t appears to fail. Make sure there is not a broken -alias in your environment" "$LINENO" 5 - fi - + am_has_slept=no + for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + if test "$*" != "X $srcdir/configure conftest.file" \ + && test "$*" != "X conftest.file $srcdir/configure"; then + + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + as_fn_error $? "ls -t appears to fail. Make sure there is not a broken + alias in your environment" "$LINENO" 5 + fi + if test "$2" = conftest.file || test $am_try -eq 2; then + break + fi + # Just in case. + sleep 1 + am_has_slept=yes + done test "$2" = conftest.file ) then @@ -2959,6 +3084,16 @@ Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } +# If we didn't sleep, we still need to ensure time stamps of config.status and +# generated files are strictly newer. +am_sleep_pid= +if grep 'slept: no' conftest.file >/dev/null 2>&1; then + ( sleep 1 ) & + am_sleep_pid=$! +fi + +rm -f conftest.file + test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. @@ -2969,43 +3104,176 @@ test "$program_suffix" != NONE && ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` -# expand $ac_aux_dir to an absolute path -am_aux_dir=`cd $ac_aux_dir && pwd` +# Expand $ac_aux_dir to an absolute path. +am_aux_dir=`cd "$ac_aux_dir" && pwd` -test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" +if test x"${MISSING+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; + *) + MISSING="\${SHELL} $am_aux_dir/missing" ;; + esac +fi # Use eval to expand $SHELL -if eval "$MISSING --run true"; then - am_missing_run="$MISSING --run " +if eval "$MISSING --is-lightweight"; then + am_missing_run="$MISSING " else am_missing_run= - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 -$as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} -fi - -if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then - # Keeping the `.' argument allows $(mkdir_p) to be used without - # argument. Indeed, we sometimes output rules like - # $(mkdir_p) $(somedir) - # where $(somedir) is conditionally defined. - # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more - # expensive solution, as it forces Make to start a sub-shell.) - mkdir_p='mkdir -p -- .' -else - # On NextStep and OpenStep, the `mkdir' command does not - # recognize any option. It will interpret all options as - # directories to create, and then abort because `.' already - # exists. - for d in ./-p ./--version; - do - test -d $d && rmdir $d + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5 +$as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;} +fi + +if test x"${install_sh+set}" != xset; then + case $am_aux_dir in + *\ * | *\ *) + install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; + *) + install_sh="\${SHELL} $am_aux_dir/install-sh" + esac +fi + +# Installed binaries are usually stripped using 'strip' when the user +# run "make install-strip". However 'strip' might not be the right +# tool to use in cross-compilation environments, therefore Automake +# will honor the 'STRIP' environment variable to overrule this program. +if test "$cross_compiling" != no; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. +set dummy ${ac_tool_prefix}strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$STRIP"; then + ac_cv_prog_STRIP="$STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_STRIP="${ac_tool_prefix}strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +STRIP=$ac_cv_prog_STRIP +if test -n "$STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +$as_echo "$STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_STRIP"; then + ac_ct_STRIP=$STRIP + # Extract the first word of "strip", so it can be a program name with args. +set dummy strip; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_STRIP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_STRIP"; then + ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_STRIP="strip" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP +if test -n "$ac_ct_STRIP"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 +$as_echo "$ac_ct_STRIP" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_STRIP" = x; then + STRIP=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + STRIP=$ac_ct_STRIP + fi +else + STRIP="$ac_cv_prog_STRIP" +fi + +fi +INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 +$as_echo_n "checking for a thread-safe mkdir -p... " >&6; } +if test -z "$MKDIR_P"; then + if ${ac_cv_path_mkdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue + case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir (GNU coreutils) '* | \ + 'mkdir (coreutils) '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext + break 3;; + esac + done + done done - # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists. - if test -f "$ac_aux_dir/mkinstalldirs"; then - mkdir_p='$(mkinstalldirs)' +IFS=$as_save_IFS + +fi + + test -d ./--version && rmdir ./--version + if test "${ac_cv_path_mkdir+set}" = set; then + MKDIR_P="$ac_cv_path_mkdir -p" else - mkdir_p='$(install_sh) -d' + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + MKDIR_P="$ac_install_sh -d" fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 +$as_echo "$MKDIR_P" >&6; } for ac_prog in gawk mawk nawk awk do @@ -3089,10 +3357,53 @@ else fi rmdir .tst 2>/dev/null -# test to see if srcdir already configured -if test "`cd $srcdir && pwd`" != "`pwd`" && - test -f $srcdir/config.status; then - as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 +# Check whether --enable-silent-rules was given. +if test "${enable_silent_rules+set}" = set; then : + enableval=$enable_silent_rules; +fi + +case $enable_silent_rules in # ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; + *) AM_DEFAULT_VERBOSITY=1;; +esac +am_make=${MAKE-make} +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 +$as_echo_n "checking whether $am_make supports nested variables... " >&6; } +if ${am_cv_make_support_nested_variables+:} false; then : + $as_echo_n "(cached) " >&6 +else + if $as_echo 'TRUE=$(BAR$(V)) +BAR0=false +BAR1=true +V=1 +am__doit: + @$(TRUE) +.PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then + am_cv_make_support_nested_variables=yes +else + am_cv_make_support_nested_variables=no +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 +$as_echo "$am_cv_make_support_nested_variables" >&6; } +if test $am_cv_make_support_nested_variables = yes; then + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi +AM_BACKSLASH='\' + +if test "`cd $srcdir && pwd`" != "`pwd`"; then + # Use -I$(srcdir) only when $(srcdir) != ., so that make's output + # is not polluted with repeated "-I." + am__isrc=' -I$(srcdir)' + # test to see if srcdir already configured + if test -f $srcdir/config.status; then + as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 + fi fi # test whether we have cygpath @@ -3106,8 +3417,8 @@ fi # Define the identity of the package. - PACKAGE=tripwire - VERSION=2.4.3.1 + PACKAGE='tripwire' + VERSION='2.4.3.7' cat >>confdefs.h <<_ACEOF @@ -3135,124 +3446,92 @@ AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} +# For better backward compatibility. To be removed once Automake 1.9.x +# dies out for good. For more background, see: +# +# +mkdir_p='$(MKDIR_P)' -AMTAR=${AMTAR-"${am_missing_run}tar"} +# We need awk for the "check" target (and possibly the TAP driver). The +# system "awk" is bad on some platforms. +# Always define AMTAR for backward compatibility. Yes, it's still used +# in the wild :-( We should find a proper way to deprecate it ... +AMTAR='$${TAR-tar}' -install_sh=${install_sh-"$am_aux_dir/install-sh"} -# Installed binaries are usually stripped using `strip' when the user -# run `make install-strip'. However `strip' might not be the right -# tool to use in cross-compilation environments, therefore Automake -# will honor the `STRIP' environment variable to overrule this program. -if test "$cross_compiling" != no; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. -set dummy ${ac_tool_prefix}strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_STRIP+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$STRIP"; then - ac_cv_prog_STRIP="$STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_STRIP="${ac_tool_prefix}strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS +# We'll loop over all known methods to create a tar archive until one works. +_am_tools='gnutar pax cpio none' +am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' + + + + + + +# POSIX will say in a future version that running "rm -f" with no argument +# is OK; and we want to be able to make that assumption in our Makefile +# recipes. So use an aggressive probe to check that the usage we want is +# actually supported "in the wild" to an acceptable degree. +# See automake bug#10828. +# To make any issue more visible, cause the running configure to be aborted +# by default if the 'rm' program in use doesn't match our expectations; the +# user can still override this though. +if rm -f && rm -fr && rm -rf; then : OK; else + cat >&2 <<'END' +Oops! + +Your 'rm' program seems unable to run without file operands specified +on the command line, even when the '-f' option is present. This is contrary +to the behaviour of most rm programs out there, and not conforming with +the upcoming POSIX standard: + +Please tell bug-automake@gnu.org about your system, including the value +of your $PATH and any error possibly output before this message. This +can help us improve future automake versions. + +END + if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then + echo 'Configuration will proceed anyway, since you have set the' >&2 + echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 + echo >&2 + else + cat >&2 <<'END' +Aborting the configuration process, to ensure you take notice of the issue. + +You can download and install GNU coreutils to get an 'rm' implementation +that behaves properly: . + +If you want to complete the configuration process using your problematic +'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM +to "yes", and re-run configure. + +END + as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 + fi fi -fi -STRIP=$ac_cv_prog_STRIP -if test -n "$STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 -$as_echo "$STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi + +ac_config_headers="$ac_config_headers config.h" -fi -if test -z "$ac_cv_prog_STRIP"; then - ac_ct_STRIP=$STRIP - # Extract the first word of "strip", so it can be a program name with args. -set dummy strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_ac_ct_STRIP+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_STRIP"; then - ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_STRIP="strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP -if test -n "$ac_ct_STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 -$as_echo "$ac_ct_STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_STRIP" = x; then - STRIP=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - STRIP=$ac_ct_STRIP - fi -else - STRIP="$ac_cv_prog_STRIP" + + + +CFLAGS=${CFLAGS:-"-O -pipe -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} +CXXFLAGS=${CXXFLAGS:-"-O -pipe -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} + + +# This is primarily to support old compilers that don’t understand -Wextra +# Check whether --enable-extrawarnings was given. +if test "${enable_extrawarnings+set}" = set; then : + enableval=$enable_extrawarnings; fi +if test "x$enable_extrawarnings" != "xno" +then + CFLAGS="${CFLAGS} -Wextra -Wno-unused-parameter" + CXXFLAGS="${CXXFLAGS} -Wextra -Wno-unused-parameter" fi -INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s" - -# We need awk for the "check" target. The system "awk" is bad on -# some platforms. - - - -ac_config_headers="$ac_config_headers config.h" - - -rm -f src/tripwire/syslog.h 2> /dev/null -chmod 755 install-sh 2> /dev/null - -CFLAGS=${CFLAGS:-"-O -pipe -Wall -Wextra -Wno-unused-parameter -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} -CXXFLAGS=${CXXFLAGS:-"-O -pipe -Wall -Wextra -Wno-unused-parameter -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : @@ -3262,6 +3541,7 @@ fi if test "x$enable_static" = xyes then LDFLAGS="${LDFLAGS} -static" fi + # Check whether --enable-debug was given. if test "${enable_debug+set}" = set; then : enableval=$enable_debug; @@ -3274,205 +3554,55 @@ then $as_echo "#define DEBUG 1" >>confdefs.h -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_CC+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi +$as_echo "#define NDEBUG 1" >>confdefs.h fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_ac_ct_CC+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } +# Check whether --enable-coverage was given. +if test "${enable_coverage+set}" = set; then : + enableval=$enable_coverage; fi - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" +if test "x$enable_coverage" = xyes +then + CFLAGS="${CFLAGS} --coverage" + CXXFLAGS="${CXXFLAGS} --coverage" + LDFLAGS="${LDFLAGS} --coverage" fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_CC+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } +# Check whether --enable-profiling was given. +if test "${enable_profiling+set}" = set; then : + enableval=$enable_profiling; fi - - fi +if test "x$enable_profiling" = xyes +then + CFLAGS="${CFLAGS} -pg" + CXXFLAGS="${CXXFLAGS} -pg" + LDFLAGS="${LDFLAGS} -pg" fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_prog_CC+:} false; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } +# Check whether --enable-urandom was given. +if test "${enable_urandom+set}" = set; then : + enableval=$enable_urandom; fi +if test "x$enable_urandom" = xyes +then + +$as_echo "#define ENABLE_DEV_URANDOM 1" >>confdefs.h fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + for ac_prog in gcc clang suncc aCC xlC_r xlC cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 @@ -3516,7 +3646,7 @@ fi fi if test -z "$CC"; then ac_ct_CC=$CC - for ac_prog in cl.exe + for ac_prog in gcc clang suncc aCC xlC_r xlC cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 @@ -3571,8 +3701,6 @@ esac fi fi -fi - test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} @@ -4064,6 +4192,65 @@ ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 +$as_echo_n "checking whether $CC understands -c and -o together... " >&6; } +if ${am_cv_prog_cc_c_o+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF + # Make sure it works both with $CC and with simple cc. + # Following AC_PROG_CC_C_O, we do the test twice because some + # compilers refuse to overwrite an existing .o file with -o, + # though they will create one. + am_cv_prog_cc_c_o=yes + for am_i in 1 2; do + if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 + ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } \ + && test -f conftest2.$ac_objext; then + : OK + else + am_cv_prog_cc_c_o=no + break + fi + done + rm -f core conftest* + unset am_i +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 +$as_echo "$am_cv_prog_cc_c_o" >&6; } +if test "$am_cv_prog_cc_c_o" != yes; then + # Losing compiler, so override with the script. + # FIXME: It is wrong to rewrite CC. + # But if we don't then we get into trouble of one sort or another. + # A longer-term fix would be to have automake use am__CC in this case, + # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" + CC="$am_aux_dir/compile $CC" +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" @@ -4072,7 +4259,7 @@ ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: - @echo done + @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. @@ -4083,24 +4270,24 @@ am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf -# We grep out `Entering directory' and `Leaving directory' -# messages which can occur if `w' ends up in MAKEFLAGS. -# In particular we don't look at `^make:' because GNU make might -# be invoked under some other name (usually "gmake"), in which -# case it prints its new name instead of `make'. -if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then - am__include=include - am__quote= - _am_result=GNU -fi +# Ignore all kinds of additional output from 'make'. +case `$am_make -s -f confmf 2> /dev/null` in #( +*the\ am__doit\ target*) + am__include=include + am__quote= + _am_result=GNU + ;; +esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf - if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then - am__include=.include - am__quote="\"" - _am_result=BSD - fi + case `$am_make -s -f confmf 2> /dev/null` in #( + *the\ am__doit\ target*) + am__include=.include + am__quote="\"" + _am_result=BSD + ;; + esac fi @@ -4116,10 +4303,9 @@ fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' + am__nodep='_no' fi - - -if test "x$enable_dependency_tracking" != xno; then + if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else @@ -4129,7 +4315,6 @@ fi - depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 @@ -4141,8 +4326,9 @@ else # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up - # making a dummy file named `D' -- because `-MD' means `put the output - # in D'. + # making a dummy file named 'D' -- because '-MD' means "put the output + # in D". + rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. @@ -4160,6 +4346,11 @@ else if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi + am__universal=false + case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac + for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and @@ -4171,34 +4362,49 @@ else : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c - # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with - # Solaris 8's {/usr,}/bin/sh. - touch sub/conftst$i.h + # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with + # Solaris 10 /bin/sh. + echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + # We check with '-c' and '-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle '-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs. + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; nosideeffect) - # after this tag, mechanisms are not by side-effect, so they'll - # only be used when explicitly requested + # After this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok '-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; none) break ;; esac - # We check with `-c' and `-o' for the sake of the "dashmstdout" - # mode. It turns out that the SunPro C++ compiler does not properly - # handle `-M -o', and we need to detect this. if depmode=$depmode \ - source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ - $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && - grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message @@ -4226,9 +4432,7 @@ fi $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type - - -if + if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= @@ -4249,7 +4453,7 @@ if test -z "$CXX"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then - for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC + for ac_prog in g++ c++ clang++ sunCC aCC xlC_r xlC cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 @@ -4293,7 +4497,7 @@ fi fi if test -z "$CXX"; then ac_ct_CXX=$CXX - for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC + for ac_prog in g++ c++ clang++ sunCC aCC xlC_r xlC cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 @@ -4507,8 +4711,9 @@ else # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up - # making a dummy file named `D' -- because `-MD' means `put the output - # in D'. + # making a dummy file named 'D' -- because '-MD' means "put the output + # in D". + rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. @@ -4526,6 +4731,11 @@ else if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi + am__universal=false + case " $depcc " in #( + *\ -arch\ *\ -arch\ *) am__universal=true ;; + esac + for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and @@ -4537,34 +4747,49 @@ else : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c - # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with - # Solaris 8's {/usr,}/bin/sh. - touch sub/conftst$i.h + # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with + # Solaris 10 /bin/sh. + echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf + # We check with '-c' and '-o' for the sake of the "dashmstdout" + # mode. It turns out that the SunPro C++ compiler does not properly + # handle '-M -o', and we need to detect this. Also, some Intel + # versions had trouble with output in subdirs. + am__obj=sub/conftest.${OBJEXT-o} + am__minus_obj="-o $am__obj" case $depmode in + gcc) + # This depmode causes a compiler race in universal mode. + test "$am__universal" = false || continue + ;; nosideeffect) - # after this tag, mechanisms are not by side-effect, so they'll - # only be used when explicitly requested + # After this tag, mechanisms are not by side-effect, so they'll + # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; + msvc7 | msvc7msys | msvisualcpp | msvcmsys) + # This compiler won't grok '-c -o', but also, the minuso test has + # not run yet. These depmodes are late enough in the game, and + # so weak that their functioning should not be impacted. + am__obj=conftest.${OBJEXT-o} + am__minus_obj= + ;; none) break ;; esac - # We check with `-c' and `-o' for the sake of the "dashmstdout" - # mode. It turns out that the SunPro C++ compiler does not properly - # handle `-M -o', and we need to detect this. if depmode=$depmode \ - source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ + source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ - $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ + $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && + grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && - grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && + grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message @@ -4592,9 +4817,7 @@ fi $as_echo "$am_cv_CXX_dependencies_compiler_type" >&6; } CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type - - -if + if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then am__fastdepCXX_TRUE= @@ -4776,6 +4999,101 @@ else $as_echo "no" >&6; } fi + + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. +set dummy ${ac_tool_prefix}ar; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_AR+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_AR="${ac_tool_prefix}ar" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +$as_echo "$AR" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_AR"; then + ac_ct_AR=$AR + # Extract the first word of "ar", so it can be a program name with args. +set dummy ar; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_AR+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_AR"; then + ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_AR="ar" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_AR=$ac_cv_prog_ac_ct_AR +if test -n "$ac_ct_AR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 +$as_echo "$ac_ct_AR" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_AR" = x; then + AR=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + AR=$ac_ct_AR + fi +else + AR="$ac_cv_prog_AR" +fi + # Extract the first word of "vi", so it can be a program name with args. set dummy vi; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 @@ -5288,14 +5606,40 @@ do : " if test "x$ac_cv_header_sys_mount_h" = xyes; then : cat >>confdefs.h <<_ACEOF -#define HAVE_SYS_MOUNT_H 1 +#define HAVE_SYS_MOUNT_H 1 +_ACEOF + +fi + +done + +for ac_header in sys/ustat.h sys/sysmacros.h sys/syslog.h sys/socket.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + +for ac_header in unistd.h sys/unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done -for ac_header in sys/ustat.h sys/sysmacros.h sys/syslog.h +for ac_header in syslog.h langinfo.h sys/statfs.h sys/select.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" @@ -5308,7 +5652,7 @@ fi done -for ac_header in unistd.h syslog.h iconv.h langinfo.h sys/statfs.h +for ac_header in signum.h bits/signum.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" @@ -5316,12 +5660,12 @@ if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF - + break fi done -for ac_header in signum.h bits/signum.h +for ac_header in stdarg.h varargs.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" @@ -5334,7 +5678,7 @@ fi done -for ac_header in stdarg.h varargs.h +for ac_header in sys/utsname.h memory.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" @@ -5342,7 +5686,19 @@ if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF - break + +fi + +done + +for ac_header in sys/fs/vx_ioctl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "sys/fs/vx_ioctl.h" "ac_cv_header_sys_fs_vx_ioctl_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_fs_vx_ioctl_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SYS_FS_VX_IOCTL_H 1 +_ACEOF + fi done @@ -5814,6 +6170,39 @@ cat >>confdefs.h <<_ACEOF _ACEOF +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } +if ${ac_cv_sizeof_time_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (time_t))" "ac_cv_sizeof_time_t" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_time_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "cannot compute sizeof (time_t) +See \`config.log' for more details" "$LINENO" 5; } + else + ac_cv_sizeof_time_t=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_TIME_T $ac_cv_sizeof_time_t +_ACEOF + + $as_echo "#define USES_1S_COMPLEMENT 0" >>confdefs.h @@ -5839,6 +6228,26 @@ $as_echo "#define IS_UNIX 1" >>confdefs.h $as_echo "#define NDEBUG 1" >>confdefs.h +ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_rdev" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_RDEV 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_blocks" "ac_cv_member_struct_stat_st_blocks" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blocks" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 +_ACEOF + + +fi + + for ac_func in strftime gethostname gethostid do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` @@ -5863,6 +6272,134 @@ _ACEOF fi done +for ac_func in swab +do : + ac_fn_c_check_func "$LINENO" "swab" "ac_cv_func_swab" +if test "x$ac_cv_func_swab" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SWAB 1 +_ACEOF + +fi +done + + +for ac_header in fcntl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "fcntl.h" "ac_cv_header_fcntl_h" "$ac_includes_default" +if test "x$ac_cv_header_fcntl_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_FCNTL_H 1 +_ACEOF + for ac_func in posix_fadvise +do : + ac_fn_c_check_func "$LINENO" "posix_fadvise" "ac_cv_func_posix_fadvise" +if test "x$ac_cv_func_posix_fadvise" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_POSIX_FADVISE 1 +_ACEOF + +fi +done + +fi + +done + + +# Check whether --enable-commoncrypto was given. +if test "${enable_commoncrypto+set}" = set; then : + enableval=$enable_commoncrypto; +fi + + +if test "x${enable_commoncrypto}" != "xno" +then + for ac_header in CommonCrypto/CommonDigest.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "CommonCrypto/CommonDigest.h" "ac_cv_header_CommonCrypto_CommonDigest_h" "$ac_includes_default" +if test "x$ac_cv_header_CommonCrypto_CommonDigest_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_COMMONCRYPTO_COMMONDIGEST_H 1 +_ACEOF + +fi + +done + +fi + +for ac_header in door.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "door.h" "ac_cv_header_door_h" "$ac_includes_default" +if test "x$ac_cv_header_door_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DOOR_H 1 +_ACEOF + for ac_func in door_create +do : + ac_fn_c_check_func "$LINENO" "door_create" "ac_cv_func_door_create" +if test "x$ac_cv_func_door_create" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DOOR_CREATE 1 +_ACEOF + +fi +done + +fi + +done + + +for ac_header in port.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "port.h" "ac_cv_header_port_h" "$ac_includes_default" +if test "x$ac_cv_header_port_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_PORT_H 1 +_ACEOF + for ac_func in port_create +do : + ac_fn_c_check_func "$LINENO" "port_create" "ac_cv_func_port_create" +if test "x$ac_cv_func_port_create" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_PORT_CREATE 1 +_ACEOF + +fi +done + +fi + +done + + + +UNAME=`uname` + + +if [ $UNAME != "AROS" ]; then + + if test -c "/dev/random"; then + +$as_echo "#define HAVE_DEV_RANDOM 1" >>confdefs.h + + fi + + if test -c "/dev/urandom"; then + +$as_echo "#define HAVE_DEV_URANDOM 1" >>confdefs.h + + fi + + if test -c "/dev/arandom"; then + +$as_echo "#define HAVE_DEV_ARANDOM 1" >>confdefs.h + + fi + +fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lc" >&5 @@ -6081,6 +6618,128 @@ fi +# Check whether --enable-iconv was given. +if test "${enable_iconv+set}" = set; then : + enableval=$enable_iconv; +fi + + +if test "x${enable_iconv}" = xyes +then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv in -lc" >&5 +$as_echo_n "checking for iconv in -lc... " >&6; } +if ${ac_cv_lib_c_iconv+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char iconv (); +int +main () +{ +return iconv (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_iconv=yes +else + ac_cv_lib_c_iconv=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_iconv" >&5 +$as_echo "$ac_cv_lib_c_iconv" >&6; } +if test "x$ac_cv_lib_c_iconv" = xyes; then : + + for ac_header in iconv.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "iconv.h" "ac_cv_header_iconv_h" "$ac_includes_default" +if test "x$ac_cv_header_iconv_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_ICONV_H 1 +_ACEOF + +fi + +done + + +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv in -liconv" >&5 +$as_echo_n "checking for iconv in -liconv... " >&6; } +if ${ac_cv_lib_iconv_iconv+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-liconv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char iconv (); +int +main () +{ +return iconv (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_iconv_iconv=yes +else + ac_cv_lib_iconv_iconv=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_iconv" >&5 +$as_echo "$ac_cv_lib_iconv_iconv" >&6; } +if test "x$ac_cv_lib_iconv_iconv" = xyes; then : + + LIBS="-liconv $LIBS" + for ac_header in iconv.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "iconv.h" "ac_cv_header_iconv_h" "$ac_includes_default" +if test "x$ac_cv_header_iconv_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_ICONV_H 1 +_ACEOF + +fi + +done + + +else + : +fi + +fi + +fi + + ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' @@ -6444,6 +7103,9 @@ case $target in ;; *-*-netbsd*) ;; + *-*-libertybsd*) + CXXFLAGS="${CXXFLAGS} -DTW_LibertyBSD" + ;; i[0-9]86-pc-linux*) ;; sparc-*-linux*) @@ -6586,6 +7248,9 @@ else # Basic test to check for compatible library and # correct linking + if test "$cross_compiling" = yes; then + found_crypto=1 + else if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} @@ -6616,6 +7281,7 @@ rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi + fi if test ! -z "$found_crypto" ; then break; @@ -6680,6 +7346,11 @@ done fi fi +ac_config_commands="$ac_config_commands mk_lib" + +ac_config_commands="$ac_config_commands mk_bin" + + ac_config_files="$ac_config_files Makefile man/Makefile man/man4/Makefile man/man5/Makefile man/man8/Makefile src/Makefile src/cryptlib/Makefile src/core/Makefile src/db/Makefile src/fco/Makefile src/fs/Makefile src/tw/Makefile src/twcrypto/Makefile src/twparser/Makefile src/util/Makefile src/twprint/Makefile src/twadmin/Makefile src/siggen/Makefile src/tripwire/Makefile src/twtest/Makefile" @@ -6778,7 +7449,6 @@ DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= -U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' @@ -6793,6 +7463,22 @@ LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 +$as_echo_n "checking that generated files are newer than configure... " >&6; } + if test -n "$am_sleep_pid"; then + # Hide warnings about reused PIDs. + wait $am_sleep_pid 2>/dev/null + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 +$as_echo "done" >&6; } + if test -n "$EXEEXT"; then + am__EXEEXT_TRUE= + am__EXEEXT_FALSE='#' +else + am__EXEEXT_TRUE='#' + am__EXEEXT_FALSE= +fi + if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 @@ -7203,7 +7889,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by $as_me, which was +This file was extended by tripwire $as_me 2.4.3.7, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -7263,13 +7949,14 @@ $config_headers Configuration commands: $config_commands -Report bugs to the package provider." +Report bugs to . +tripwire home page: ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ -config.status +tripwire config.status 2.4.3.7 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" @@ -7280,6 +7967,7 @@ gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF @@ -7399,6 +8087,8 @@ do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; + "mk_lib") CONFIG_COMMANDS="$CONFIG_COMMANDS mk_lib" ;; + "mk_bin") CONFIG_COMMANDS="$CONFIG_COMMANDS mk_bin" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "man/Makefile") CONFIG_FILES="$CONFIG_FILES man/Makefile" ;; "man/man4/Makefile") CONFIG_FILES="$CONFIG_FILES man/man4/Makefile" ;; @@ -7867,6 +8557,11 @@ ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 @@ -7921,6 +8616,7 @@ s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ @@ -7966,21 +8662,22 @@ $as_echo "$as_me: $ac_file is unchanged" >&6;} || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. +_am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in - "$ac_file" | "$ac_file":* ) + $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done -echo "timestamp for "$ac_file"" >`$as_dirname -- "$ac_file" || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$ac_file" | +echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || +$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$_am_arg" : 'X\(//\)[^/]' \| \ + X"$_am_arg" : 'X\(//\)$' \| \ + X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -8007,17 +8704,28 @@ $as_echo "$as_me: executing $ac_file commands" >&6;} case $ac_file$ac_mode in - "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do - # Strip MF so we end up with the name of the file. - mf=`echo "$mf" | sed -e 's/:.*$//'` - # Check whether this is an Automake generated Makefile or not. - # We used to match only the files named `Makefile.in', but - # some people rename them; so instead we look at the file content. - # Grep'ing the first line is not enough: some people post-process - # each Makefile.in and add a new line on top of each file to say so. - # So let's grep whole file. - if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then - dirpart=`$as_dirname -- "$mf" || + "depfiles":C) test x"$AMDEP_TRUE" != x"" || { + # Older Autoconf quotes --file arguments for eval, but not when files + # are listed without --file. Let's play safe and only enable the eval + # if we detect the quoting. + case $CONFIG_FILES in + *\'*) eval set x "$CONFIG_FILES" ;; + *) set x $CONFIG_FILES ;; + esac + shift + for mf + do + # Strip MF so we end up with the name of the file. + mf=`echo "$mf" | sed -e 's/:.*$//'` + # Check whether this is an Automake generated Makefile or not. + # We used to match only the files named 'Makefile.in', but + # some people rename them; so instead we look at the file content. + # Grep'ing the first line is not enough: some people post-process + # each Makefile.in and add a new line on top of each file to say so. + # Grep'ing the whole file is not good either: AIX grep has a line + # limit of 2048, but all sed's we know have understand at least 4000. + if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then + dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ @@ -8040,34 +8748,26 @@ $as_echo X"$mf" | q } s/.*/./; q'` - else - continue - fi - grep '^DEP_FILES *= *[^ #]' < "$mf" > /dev/null || continue - # Extract the definition of DEP_FILES from the Makefile without - # running `make'. - DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` - test -z "$DEPDIR" && continue - # When using ansi2knr, U may be empty or an underscore; expand it - U=`sed -n 's/^U = //p' < "$mf"` - test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR" - # We invoke sed twice because it is the simplest approach to - # changing $(DEPDIR) to its actual value in the expansion. - for file in `sed -n ' - /^DEP_FILES = .*\\\\$/ { - s/^DEP_FILES = // - :loop - s/\\\\$// - p - n - /\\\\$/ b loop - p - } - /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \ - sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do - # Make sure the directory exists. - test -f "$dirpart/$file" && continue - fdir=`$as_dirname -- "$file" || + else + continue + fi + # Extract the definition of DEPDIR, am__include, and am__quote + # from the Makefile without running 'make'. + DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` + test -z "$DEPDIR" && continue + am__include=`sed -n 's/^am__include = //p' < "$mf"` + test -z "$am__include" && continue + am__quote=`sed -n 's/^am__quote = //p' < "$mf"` + # Find all dependency output files, they are included files with + # $(DEPDIR) in their names. We invoke sed twice because it is the + # simplest approach to changing $(DEPDIR) to its actual value in the + # expansion. + for file in `sed -n " + s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ + sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do + # Make sure the directory exists. + test -f "$dirpart/$file" && continue + fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ @@ -8090,12 +8790,15 @@ $as_echo X"$file" | q } s/.*/./; q'` - as_dir=$dirpart/$fdir; as_fn_mkdir_p - # echo "creating $dirpart/$file" - echo '# dummy' > "$dirpart/$file" + as_dir=$dirpart/$fdir; as_fn_mkdir_p + # echo "creating $dirpart/$file" + echo '# dummy' > "$dirpart/$file" + done done -done +} ;; + "mk_lib":C) test -d lib || mkdir lib ;; + "mk_bin":C) test -d bin || mkdir bin ;; esac done # for ac_tag diff --git a/configure.in b/configure.ac similarity index 72% rename from configure.in rename to configure.ac index da9f7fd..a45aa4b 100644 --- a/configure.in +++ b/configure.ac @@ -2,48 +2,83 @@ dnl Process this file with autoconf to produce a configure script. dnl dnl -AC_INIT +AC_INIT([tripwire], [2.4.3.7], [https://github.com/Tripwire/tripwire-open-source/issues], [tripwire], [https://github.com/Tripwire/tripwire-open-source]) AC_CONFIG_SRCDIR([src/tw/tw.cpp]) AC_CANONICAL_TARGET([]) -AM_INIT_AUTOMAKE(tripwire, 2.4.3.1) +AM_INIT_AUTOMAKE AM_CONFIG_HEADER(config.h) -dnl ################################# -dnl Cleanup Cruft Leftover From Patch -dnl ################################# -rm -f src/tripwire/syslog.h 2> /dev/null -chmod 755 install-sh 2> /dev/null +AC_COPYRIGHT([The developer of the original code and/or files is Tripwire, Inc. Portions created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights reserved.]) +AC_REVISION([$Revision: 2.4.3.7 $]) dnl ############### dnl Setup defaults dnl ############### -CFLAGS=${CFLAGS:-"-O -pipe -Wall -Wextra -Wno-unused-parameter -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} -CXXFLAGS=${CXXFLAGS:-"-O -pipe -Wall -Wextra -Wno-unused-parameter -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} +CFLAGS=${CFLAGS:-"-O -pipe -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} +CXXFLAGS=${CXXFLAGS:-"-O -pipe -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64"} dnl ##################### dnl Configuration options dnl ##################### + +# This is primarily to support old compilers that don’t understand -Wextra +AC_ARG_ENABLE(extrawarnings, [ —-disable-extrawarnings do not compile with -Wextra warnings enabled]) +if test "x$enable_extrawarnings" != "xno" +then + CFLAGS="${CFLAGS} -Wextra -Wno-unused-parameter" + CXXFLAGS="${CXXFLAGS} -Wextra -Wno-unused-parameter" +fi + AC_ARG_ENABLE(static, [ --enable-static compile static binaries]) if test "x$enable_static" = xyes then LDFLAGS="${LDFLAGS} -static" fi + AC_ARG_ENABLE(debug, [ --enable-debug compile with debuging enabled]) if test "x$enable_debug" = xyes then CFLAGS="${CFLAGS} -g" CXXFLAGS="${CXXFLAGS} -g" AC_DEFINE(DEBUG, 1, [Compile with debug code]) +else + AC_DEFINE(NDEBUG, 1, [Compile without debug code]) +fi + +AC_ARG_ENABLE(coverage, [ --enable-coverage enable code coverage]) +if test "x$enable_coverage" = xyes +then + CFLAGS="${CFLAGS} --coverage" + CXXFLAGS="${CXXFLAGS} --coverage" + LDFLAGS="${LDFLAGS} --coverage" +fi + +AC_ARG_ENABLE(profiling, [ --enable-profiling enable profiling]) +if test "x$enable_profiling" = xyes +then + CFLAGS="${CFLAGS} -pg" + CXXFLAGS="${CXXFLAGS} -pg" + LDFLAGS="${LDFLAGS} -pg" +fi + +AC_ARG_ENABLE(urandom, [ --enable-urandom use /dev/urandom]) +if test "x$enable_urandom" = xyes +then + AC_DEFINE(ENABLE_DEV_URANDOM, 1, [Enable use of /dev/urandom]) fi dnl ################### dnl Checks for programs dnl ################### -AC_PROG_CC -AC_PROG_CXX +AC_PROG_CC([gcc clang suncc aCC xlC_r xlC cl.exe]) +AC_PROG_CXX([g++ c++ clang++ sunCC aCC xlC_r xlC cl.exe]) AC_PROG_RANLIB AC_PROG_YACC AC_PROG_LN_S AC_PROG_LN +AN_MAKEVAR([AR], [AC_PROG_AR]) +AN_PROGRAM([ar], [AC_PROG_AR]) +AC_DEFUN([AC_PROG_AR], [AC_CHECK_TOOL(AR, ar, :)]) +AC_PROG_AR AC_PATH_PROG(path_to_vi, vi) AC_PATH_PROG(path_to_sendmail, sendmail, "", [$PATH:/usr/libexec]) @@ -63,10 +98,13 @@ AC_CHECK_HEADERS(sys/mount.h,,, #include #endif ]]) -AC_CHECK_HEADERS(sys/ustat.h sys/sysmacros.h sys/syslog.h) -AC_CHECK_HEADERS(unistd.h syslog.h iconv.h langinfo.h sys/statfs.h) +AC_CHECK_HEADERS(sys/ustat.h sys/sysmacros.h sys/syslog.h sys/socket.h) +AC_CHECK_HEADERS(unistd.h sys/unistd.h) +AC_CHECK_HEADERS(syslog.h langinfo.h sys/statfs.h sys/select.h) AC_CHECK_HEADERS(signum.h bits/signum.h, break ) AC_CHECK_HEADERS(stdarg.h varargs.h, break ) +AC_CHECK_HEADERS(sys/utsname.h memory.h) +AC_CHECK_HEADERS(sys/fs/vx_ioctl.h) dnl # Special case for malloc.h, because it's depreciated on most systems. CPPFLAGS_SAVE="${CPPFLAGS}" @@ -84,6 +122,7 @@ AC_C_BIGENDIAN AC_CHECK_SIZEOF(int) AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(long long) +AC_CHECK_SIZEOF(time_t) dnl All platforms we support use 2's complement, are byte aligned, etc... AC_DEFINE(USES_1S_COMPLEMENT, 0, [Uses one's complement]) @@ -100,11 +139,61 @@ AC_DEFINE(IS_UNIX, 1, [Is a unix type platform]) dnl whether or not to generate debuging code? AC_DEFINE(NDEBUG, 1, [don't generate debuging code]) +dnl look for struct stat members that aren't always there +AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blocks]) + dnl ############################# dnl Checks for standard functions dnl ############################# AC_CHECK_FUNCS(strftime gethostname gethostid) AC_CHECK_FUNCS(mkstemp mktemp, break) +AC_CHECK_FUNCS(swab) + +dnl check for posix_fadvise +AC_CHECK_HEADERS(fcntl.h, [AC_CHECK_FUNCS(posix_fadvise)]) + +dnl check for OSX builtin hash algorithms +AC_ARG_ENABLE(commoncrypto, + [ --disable-commoncrypto Don't use CommonCrypto hash implementations (OSX only)]) + +if test "x${enable_commoncrypto}" != "xno" +then + AC_CHECK_HEADERS(CommonCrypto/CommonDigest.h) +fi + +dnl check for door support (Solaris) +AC_CHECK_HEADERS(door.h, [AC_CHECK_FUNCS(door_create)]) + +dnl check for event port support (Solaris) +AC_CHECK_HEADERS(port.h, [AC_CHECK_FUNCS(port_create)]) + +dnl ############################################## +dnl check for various RNG/PRNG devices +dnl ############################################## + +UNAME=`uname` + +dnl ############################################## +dnl AROS pops up a "Please insert disk" dialog for /dev +dnl if script looks for devices (which don't exist) +dnl so don't even try looking. +dnl ############################################## + +if [[ $UNAME != "AROS" ]]; then + + if test -c "/dev/random"; then + AC_DEFINE(HAVE_DEV_RANDOM, [1], [Has /dev/random]) + fi + + if test -c "/dev/urandom"; then + AC_DEFINE(HAVE_DEV_URANDOM, [1], [Has /dev/urandom]) + fi + + if test -c "/dev/arandom"; then + AC_DEFINE(HAVE_DEV_ARANDOM, [1], [Has /dev/arandom]) + fi + +fi dnl ############################################## dnl Checks for various platform specific libraries @@ -124,6 +213,22 @@ AC_CHECK_LIB(c, gethostbyname, [:], [ AC_CHECK_LIB(network, gethostbyname, [LIBS="-lnetwork $LIBS"] [:]) ]) ]) + +AC_ARG_ENABLE(iconv, + [ --enable-iconv Use iconv for locale-independent report and db files]) + +if test "x${enable_iconv}" = xyes +then + dnl iconv? check the usual locations + AC_CHECK_LIB(c, iconv, [ + AC_CHECK_HEADERS(iconv.h) + ], [ + AC_CHECK_LIB(iconv, iconv, [ + LIBS="-liconv $LIBS" + AC_CHECK_HEADERS(iconv.h) + ], [:]) ]) +fi + dnl check for stl library AC_LANG_SAVE AC_LANG_CPLUSPLUS @@ -244,6 +349,9 @@ case $target in ;; *-*-netbsd*) ;; + *-*-libertybsd*) + CXXFLAGS="${CXXFLAGS} -DTW_LibertyBSD" + ;; i[[0-9]]86-pc-linux*) ;; sparc-*-linux*) @@ -282,7 +390,7 @@ if you are trying to compile a static binary. dnl Check for OpenSSL, now that we have a working compiler AC_ARG_ENABLE(openssl, - [ --disable-openssl don't link against OpenSSL libraries]) + [ --disable-openssl Don't link against OpenSSL libraries]) AC_ARG_WITH(ssl-dir, [ --with-ssl-dir=PATH Specify path to OpenSSL installation ], [ @@ -339,6 +447,9 @@ then # Basic test to check for compatible library and # correct linking + if test "$cross_compiling" = yes; then + found_crypto=1 + else AC_TRY_RUN( [ #include @@ -356,6 +467,7 @@ int main(void) break; ], [] ) + fi if test ! -z "$found_crypto" ; then break; @@ -406,6 +518,9 @@ if (test ! -z "$ac_cv_openssldir" && test "x$ac_cv_openssldir" != "xnot found") fi fi +AC_CONFIG_COMMANDS([mk_lib], [test -d lib || mkdir lib]) +AC_CONFIG_COMMANDS([mk_bin], [test -d bin || mkdir bin]) + dnl ##################################### dnl Export the variables we use dnl ##################################### diff --git a/clean b/contrib/clean.sh similarity index 100% rename from clean rename to contrib/clean.sh diff --git a/contrib/make-bin-dist b/contrib/make-bin-dist index 7fd07e0..a224d92 100755 --- a/contrib/make-bin-dist +++ b/contrib/make-bin-dist @@ -5,7 +5,7 @@ set -e PRODUCT=tripwire -VERSION=2.4.3.1 +VERSION=2.4.3.2 platform() { case `uname` in diff --git a/contrib/twpolmake.pl b/contrib/twpolmake.pl new file mode 100755 index 0000000..d397d9c --- /dev/null +++ b/contrib/twpolmake.pl @@ -0,0 +1,56 @@ +#!/usr/bin/perl +# Tripwire Policy File customize tool +# ---------------------------------------------------------------- +# Copyright (C) 2003 Hiroaki Izumi +# This program 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 2 +# of the License, or (at your option) any later version. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# ---------------------------------------------------------------- +# Usage: +# perl twpolmake.pl {Pol file} +# ---------------------------------------------------------------- +# +$POLFILE=$ARGV[0]; + +open(POL,"$POLFILE") or die "open error: $POLFILE" ; +my($myhost,$thost) ; +my($sharp,$tpath,$cond) ; +my($INRULE) = 0 ; + +while () { + chomp; + if (($thost) = /^HOSTNAME\s*=\s*(.*)\s*;/) { + $myhost = `hostname` ; chomp($myhost) ; + if ($thost ne $myhost) { + $_="HOSTNAME=\"$myhost\";" ; + } + } + elsif ( /^{/ ) { + $INRULE=1 ; + } + elsif ( /^}/ ) { + $INRULE=0 ; + } + elsif ($INRULE == 1 and ($sharp,$tpath,$cond) = /^(\s*\#?\s*)(\/\S+)\b(\s+->\s+.+)$/) { + $ret = ($sharp =~ s/\#//g) ; + if ($tpath eq '/sbin/e2fsadm' ) { + $cond =~ s/;\s+(tune2fs.*)$/; \#$1/ ; + } + if (! -s $tpath) { + $_ = "$sharp#$tpath$cond" if ($ret == 0) ; + } + else { + $_ = "$sharp$tpath$cond" ; + } + } + print "$_\n" ; +} +close(POL) ; diff --git a/install-sh b/install-sh index e9de238..0b0fdcb 100755 --- a/install-sh +++ b/install-sh @@ -1,251 +1,501 @@ #!/bin/sh -# # install - install a program, script, or datafile -# This comes from X11R5 (mit/util/scripts/install.sh). + +scriptversion=2013-12-25.23; # UTC + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -# Copyright 1991 by the Massachusetts Institute of Technology +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. # -# Permission to use, copy, modify, distribute, and sell this software and its -# documentation for any purpose is hereby granted without fee, provided that -# the above copyright notice appear in all copies and that both that -# copyright notice and this permission notice appear in supporting -# documentation, and that the name of M.I.T. not be used in advertising or -# publicity pertaining to distribution of the software without specific, -# written prior permission. M.I.T. makes no representations about the -# suitability of this software for any purpose. It is provided "as is" -# without express or implied warranty. +# +# FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent -# `make' implicit rules from creating a file called install from it +# 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written -# from scratch. It can only install one file at a time, a restriction -# shared with many OS's install programs. +# from scratch. + +tab=' ' +nl=' +' +IFS=" $tab$nl" +# Set DOITPROG to "echo" to test this script. -# set DOITPROG to echo to test this script +doit=${DOITPROG-} +doit_exec=${doit:-exec} -# Don't use :- since 4.3BSD and earlier shells don't like it. -doit="${DOITPROG-}" +# Put in absolute file names if you don't have them in your path; +# or use environment vars. +chgrpprog=${CHGRPPROG-chgrp} +chmodprog=${CHMODPROG-chmod} +chownprog=${CHOWNPROG-chown} +cmpprog=${CMPPROG-cmp} +cpprog=${CPPROG-cp} +mkdirprog=${MKDIRPROG-mkdir} +mvprog=${MVPROG-mv} +rmprog=${RMPROG-rm} +stripprog=${STRIPPROG-strip} -# put in absolute paths if you don't have them in your path; or use env. vars. +posix_mkdir= -mvprog="${MVPROG-mv}" -cpprog="${CPPROG-cp}" -chmodprog="${CHMODPROG-chmod}" -chownprog="${CHOWNPROG-chown}" -chgrpprog="${CHGRPPROG-chgrp}" -stripprog="${STRIPPROG-strip}" -rmprog="${RMPROG-rm}" -mkdirprog="${MKDIRPROG-mkdir}" +# Desired mode of installed file. +mode=0755 -transformbasename="" -transform_arg="" -instcmd="$mvprog" -chmodcmd="$chmodprog 0755" -chowncmd="" -chgrpcmd="" -stripcmd="" +chgrpcmd= +chmodcmd=$chmodprog +chowncmd= +mvcmd=$mvprog rmcmd="$rmprog -f" -mvcmd="$mvprog" -src="" -dst="" -dir_arg="" - -while [ x"$1" != x ]; do - case $1 in - -c) instcmd="$cpprog" - shift - continue;; - - -d) dir_arg=true - shift - continue;; - - -m) chmodcmd="$chmodprog $2" - shift - shift - continue;; - - -o) chowncmd="$chownprog $2" - shift - shift - continue;; - - -g) chgrpcmd="$chgrpprog $2" - shift - shift - continue;; - - -s) stripcmd="$stripprog" - shift - continue;; - - -t=*) transformarg=`echo $1 | sed 's/-t=//'` - shift - continue;; - - -b=*) transformbasename=`echo $1 | sed 's/-b=//'` - shift - continue;; - - *) if [ x"$src" = x ] - then - src=$1 - else - # this colon is to work around a 386BSD /bin/sh bug - : - dst=$1 - fi - shift - continue;; - esac -done +stripcmd= -if [ x"$src" = x ] -then - echo "install: no input file specified" - exit 1 -else - true -fi +src= +dst= +dir_arg= +dst_arg= -if [ x"$dir_arg" != x ]; then - dst=$src - src="" - - if [ -d $dst ]; then - instcmd=: - chmodcmd="" - else - instcmd=mkdir - fi -else - -# Waiting for this to be detected by the "$instcmd $src $dsttmp" command -# might cause directories to be created, which would be especially bad -# if $src (and thus $dsttmp) contains '*'. - - if [ -f $src -o -d $src ] - then - true - else - echo "install: $src does not exist" - exit 1 - fi - - if [ x"$dst" = x ] - then - echo "install: no destination specified" - exit 1 - else - true - fi - -# If destination is a directory, append the input filename; if your system -# does not like double slashes in filenames, you may need to add some logic - - if [ -d $dst ] - then - dst="$dst"/`basename $src` - else - true - fi -fi +copy_on_change=false +is_target_a_directory=possibly -## this sed command emulates the dirname command -dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` +usage="\ +Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... -# Make sure that the destination directory exists. -# this part is taken from Noah Friedman's mkinstalldirs script +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. -# Skip lots of stat calls in the usual case. -if [ ! -d "$dstdir" ]; then -defaultIFS=' -' -IFS="${IFS-${defaultIFS}}" +Options: + --help display this help and exit. + --version display version info and exit. -oIFS="${IFS}" -# Some sh's can't handle IFS=/ for some reason. -IFS='%' -set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` -IFS="${oIFS}" + -c (ignored) + -C install only if different (preserve the last data modification time) + -d create directories instead of installing files. + -g GROUP $chgrpprog installed files to GROUP. + -m MODE $chmodprog installed files to MODE. + -o USER $chownprog installed files to USER. + -s $stripprog installed files. + -t DIRECTORY install into DIRECTORY. + -T report an error if DSTFILE is a directory. -pathcomp='' +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG + RMPROG STRIPPROG +" -while [ $# -ne 0 ] ; do - pathcomp="${pathcomp}${1}" - shift +while test $# -ne 0; do + case $1 in + -c) ;; - if [ ! -d "${pathcomp}" ] ; - then - $mkdirprog "${pathcomp}" - else - true - fi + -C) copy_on_change=true;; - pathcomp="${pathcomp}/" -done -fi + -d) dir_arg=true;; -if [ x"$dir_arg" != x ] -then - $doit $instcmd $dst && + -g) chgrpcmd="$chgrpprog $2" + shift;; - if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && - if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && - if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && - if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi -else + --help) echo "$usage"; exit $?;; -# If we're going to rename the final executable, determine the name now. + -m) mode=$2 + case $mode in + *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + shift;; - if [ x"$transformarg" = x ] - then - dstfile=`basename $dst` - else - dstfile=`basename $dst $transformbasename | - sed $transformarg`$transformbasename - fi + -o) chowncmd="$chownprog $2" + shift;; -# don't allow the sed command to completely eliminate the filename + -s) stripcmd=$stripprog;; - if [ x"$dstfile" = x ] - then - dstfile=`basename $dst` - else - true - fi + -t) + is_target_a_directory=always + dst_arg=$2 + # Protect names problematic for 'test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + shift;; -# Make a temp file name in the proper directory. + -T) is_target_a_directory=never;; - dsttmp=$dstdir/#inst.$$# + --version) echo "$0 $scriptversion"; exit $?;; -# Move or copy the file name to the temp name + --) shift + break;; - $doit $instcmd $src $dsttmp && + -*) echo "$0: invalid option: $1" >&2 + exit 1;; - trap "rm -f ${dsttmp}" 0 && + *) break;; + esac + shift +done -# and set any options; do chmod last to preserve setuid bits +# We allow the use of options -d and -T together, by making -d +# take the precedence; this is for compatibility with GNU install. -# If any of these fail, we abort the whole thing. If we want to -# ignore errors from any of these, just make sure not to ignore -# errors from the above "$doit $instcmd $src $dsttmp" command. +if test -n "$dir_arg"; then + if test -n "$dst_arg"; then + echo "$0: target directory not allowed when installing a directory." >&2 + exit 1 + fi +fi - if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && - if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && - if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && - if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && +if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dst_arg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dst_arg" + shift # fnord + fi + shift # arg + dst_arg=$arg + # Protect names problematic for 'test' and other utilities. + case $dst_arg in + -* | [=\(\)!]) dst_arg=./$dst_arg;; + esac + done +fi -# Now rename the file to the real destination. +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call 'install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + if test $# -gt 1 || test "$is_target_a_directory" = always; then + if test ! -d "$dst_arg"; then + echo "$0: $dst_arg: Is not a directory." >&2 + exit 1 + fi + fi +fi - $doit $rmcmd -f $dstdir/$dstfile && - $doit $mvcmd $dsttmp $dstdir/$dstfile +if test -z "$dir_arg"; then + do_exit='(exit $ret); exit $ret' + trap "ret=129; $do_exit" 1 + trap "ret=130; $do_exit" 2 + trap "ret=141; $do_exit" 13 + trap "ret=143; $do_exit" 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi -fi && +for src +do + # Protect names problematic for 'test' and other utilities. + case $src in + -* | [=\(\)!]) src=./$src;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dst_arg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + dst=$dst_arg + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test "$is_target_a_directory" = never; then + echo "$0: $dst_arg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dst=$dstdir/`basename "$src"` + dstdir_status=0 + else + dstdir=`dirname "$dst"` + test -d "$dstdir" + dstdir_status=$? + fi + fi + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # Create intermediate dirs using mode 755 as modified by the umask. + # This is like FreeBSD 'install' as of 1997-10-28. + umask=`umask` + case $stripcmd.$umask in + # Optimize common cases. + *[2367][2367]) mkdir_umask=$umask;; + .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; + + *[0-7]) + mkdir_umask=`expr $umask + 22 \ + - $umask % 100 % 40 + $umask % 20 \ + - $umask % 10 % 4 + $umask % 2 + `;; + *) mkdir_umask=$umask,go-w;; + esac + + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + case $umask in + *[123567][0-7][0-7]) + # POSIX mkdir -p sets u+wx bits regardless of umask, which + # is incompatible with FreeBSD 'install' when (umask & 300) != 0. + ;; + *) + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 + + if (umask $mkdir_umask && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + ls_ld_tmpdir=`ls -ld "$tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/d" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null + fi + trap '' 0;; + esac;; + esac + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # The umask is ridiculous, or mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix='/';; + [-=\(\)!]*) prefix='./';; + *) prefix='';; + esac + + oIFS=$IFS + IFS=/ + set -f + set fnord $dstdir + shift + set +f + IFS=$oIFS + + prefixes= + + for d + do + test X"$d" = X && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask=$mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && + { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && + { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # If -C, don't bother to copy if it wouldn't change the file. + if $copy_on_change && + old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && + new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && + set -f && + set X $old && old=:$2:$4:$5:$6 && + set X $new && new=:$2:$4:$5:$6 && + set +f && + test "$old" = "$new" && + $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 + then + rm -f "$dsttmp" + else + # Rename the file to the real destination. + $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || + + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + { + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + test ! -f "$dst" || + $doit $rmcmd -f "$dst" 2>/dev/null || + { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && + { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } + } || + { echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + fi || exit 1 + + trap '' 0 + fi +done -exit 0 +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/install/install.cfg b/installer/install.cfg similarity index 100% rename from install/install.cfg rename to installer/install.cfg diff --git a/install/install.sh b/installer/install.sh similarity index 89% rename from install/install.sh rename to installer/install.sh index 68e2554..c8dc4da 100755 --- a/install/install.sh +++ b/installer/install.sh @@ -17,7 +17,7 @@ ## from Larry Wall's metaconfig. ##------------------------------------------------------- -PATH='.:/bin:/usr/bin' +PATH=".:/bin:/usr/bin:/usr/local/bin:$PATH" export PATH || (echo 'You must use sh to run this script'; kill $$) if [ ! -t 0 ] ; then echo "Say 'sh install.sh', not 'sh < install.sh'" @@ -28,7 +28,7 @@ fi ## The usage message. ##------------------------------------------------------- -USAGE="install.sh [] [-n] [-f] [-s ] [-l ]" +USAGE="install.sh [] [-n] [-f] [-s ] [-l ] [-d ]" ##------------------------------------------------------- ## Figure out how to do an echo without newline. @@ -42,18 +42,6 @@ else c="" fi -##------------------------------------------------------- -## Better have a copy of tar! -## If /bin/sh does not exist or is not readable (seems -## fairly unlikely), then this will fail. -##------------------------------------------------------- - -(tar cvf /dev/null /bin/sh) 2> /dev/null 1>&2 -if [ $? -ne 0 ]; then - echo "tar command not found -- aborting install." - exit 1 -fi - ##------------------------------------------------------- ## Can't live without sed. ##------------------------------------------------------- @@ -78,52 +66,24 @@ for p in $awknames; do fi done -##------------------------------------------------------- -## Does this system have a copy of grep we can use? -## Some greps don't return status (amazing, huh?), -## so we look for a copy of grep that -## returns 0 status for an exact match -## returns 0 status for a case-insensitive match -## returns 0 status for a wildcard match -## returns non-zero status for a failed match -##------------------------------------------------------- - -GREP="" -grepnames="grep egrep" -lcgrepstr="findensiemich" # all lower case -mcgrepstr="FindenSieMich" # mixed case -wcgrepstr="sie.ich$" # wild card match -nogrepstr="WoBistDu" # should not be able to find this -for p in $grepnames; do - (echo "$lcgrepstr" | $p "$lcgrepstr") 2> /dev/null 1>&2 - if [ $? -eq 0 ]; then - (echo "$lcgrepstr" | $p -i "$mcgrepstr") 2> /dev/null 1>&2 - if [ $? -eq 0 ]; then - (echo "$lcgrepstr" | $p "$wcgrepstr") 2> /dev/null 1>&2 - if [ $? -eq 0 ]; then - (echo "$lcgrepstr" | $p "$nogrepstr") 2> /dev/null 1>&2 - if [ $? -ne 0 ]; then - GREP=$p - break - fi - fi - fi - fi -done - ##------------------------------------------------------- ## Does this system have a pager that we can use? ## Use cat if desperate. ##------------------------------------------------------- MORE="cat" -morenames="more less cat" +morenames="less more most pg cat" for p in $morenames; do - ($p $0 < /dev/null) 2> /dev/null 1>&2 - if [ $? -eq 0 ]; then - MORE=$p - break - fi + pagerpath=`command -v $p` + + if [ -z $pagerpath ]; then + continue + fi + + if [ -x $pagerpath ]; then + MORE=$pagerpath + break + fi done ##------------------------------------------------------- @@ -144,8 +104,10 @@ fi ## Miscellaneous configuration parameters. ##------------------------------------------------------- -# prefix -prefix="${prefix:=/usr}" +# set a few location variables if caller didn't pass them to us +prefix="${prefix:=/usr/local}" +sysconfdir="${sysconfdir:=/usr/local/etc}" +path_to_vi="${path_to_vi:=/usr/bin/vi}" # License File name TWLICENSEFILE="COPYING" @@ -160,7 +122,7 @@ CLR_CONFIG_FILE="twcfg.txt" CLR_POLICY_FILE="twpol.txt" # Default installation script configuration file. -INSTALL_CONFIG_FILE="./install/install.cfg" +INSTALL_CONFIG_FILE="./installer/install.cfg" # Relative path to dir that contains the pkg files. PKG_DIR="pkg" @@ -192,10 +154,16 @@ TAR_DIR=${TAR_DIR:-${START_DIR}} OS=`uname -s` POLICYSRC="twpol-${OS:=GENERIC}.txt" -if [ ! -r ${TAR_DIR}/policy/${POLICYSRC} ] -then POLICYSRC="twpol-GENERIC.txt" +if [ ! -r ${TAR_DIR}/policy/${POLICYSRC} ]; then + OS=`uname -o` + POLICYSRC="twpol-${OS:=GENERIC}.txt" fi +if [ ! -r ${TAR_DIR}/policy/${POLICYSRC} ]; then + POLICYSRC="twpol-GENERIC.txt" +fi + + ##------------------------------------------------------- ## Parse the command line. ##------------------------------------------------------- @@ -218,6 +186,13 @@ while [ "x$1" != "x" ] ; do exit 1 ;; *) TW_LOCAL_PASS="$2"; shift ;; esac ;; + -d) case "$2" in + "" | -*) + echo "Error: missing install dir with -d option." 1>&2 + echo "$USAGE" + exit 1 ;; + *) prefix="$2"; sysconfdir="$2/bin"; shift ;; + esac ;; -*) echo "Error: unknown argument $1" 1>&2 echo "$USAGE" exit 1 ;; @@ -243,9 +218,8 @@ cat << END_OF_TEXT Installer program for: Tripwire(R) 2.4 Open Source -Copyright (C) 1998-2000 Tripwire (R) Security Systems, Inc. Tripwire (R) -is a registered trademark of the Purdue Research Foundation and is -licensed exclusively to Tripwire (R) Security Systems, Inc. +Copyright (C) 1998-2017 Tripwire, Inc. +Tripwire is a registered trademark of Tripwire, Inc. All rights reserved. END_OF_TEXT @@ -417,15 +391,49 @@ else ##------------------------------------------------------- ## Verify that the specified editor program exists ##------------------------------------------------------- - -TWEDITOR=${TWEDITOR:-'/bin/vi'} + +# If user specified an editor in $path_to_vi or $TWEDITOR, try that first. +# $path_to_vi defaults to /usr/bin/vi, so we usually succeed here. +# +if [ -n ${TWEDITOR} ]; then + TWEDITOR_PATH=`command -v $TWEDITOR` +fi + +# If user's environment includes $EDITOR, try that next +if [ -n ${EDITOR} ] && [ -z ${TWEDITOR_PATH} ]; then + TWEDITOR_PATH=`command -v $EDITOR` +fi + +# Ok, now search path for vi +if [ -z ${TWEDITOR_PATH} ]; then + TWEDITOR_PATH=`command -v vi` +fi + +# Try vim in case there isn't a link named vi +if [ -z ${TWEDITOR_PATH} ]; then + TWEDITOR_PATH=`command -v vim` +fi + +# No vi/vim? See if nano is present +if [ -z ${TWEDITOR_PATH} ]; then + TWEDITOR_PATH=`command -v nano` +fi + +# No vi or nano? See if emacs is available +if [ -z ${TWEDITOR_PATH} ]; then + TWEDITOR_PATH=`command -v emacs` +fi + +if [ -n ${TWEDITOR_PATH} ]; then + TWEDITOR=$TWEDITOR_PATH +fi if [ -x ${TWEDITOR} ]; then - echo "${TWEDITOR} exists. Continuing installation." - echo + echo "${TWEDITOR} exists. Continuing installation." + echo else - echo "${TWEDITOR} does not exist. Exiting." - exit 1 + echo "${TWEDITOR} not found. Continuing, but your configuration may need to be edited after installation." + echo fi ##------------------------------------------------------- @@ -569,10 +577,10 @@ echo #f1=' ff=$README ; d="" ; dd=$TWDOCS ; rr=0444 ' #f2=' ff=$REL_NOTES ; d="" ; dd=$TWDOCS ; rr=0444 ' f3=' ff=$TWLICENSEFILE ; d="" ; dd=$TWDOCS ; rr=0444 ' -#f4=' ff=tripwire ; d="/bin" ; dd=$TWBIN ; rr=0550 ' -#f5=' ff=twadmin ; d="/bin" ; dd=$TWBIN ; rr=0550 ' -#f6=' ff=twprint ; d="/bin" ; dd=$TWBIN ; rr=0550 ' -#f7=' ff=siggen ; d="/bin" ; dd=$TWBIN ; rr=0550 ' +f4=' ff=tripwire ; d="/bin" ; dd=$TWBIN ; rr=0550 ' +f5=' ff=twadmin ; d="/bin" ; dd=$TWBIN ; rr=0550 ' +f6=' ff=twprint ; d="/bin" ; dd=$TWBIN ; rr=0550 ' +f7=' ff=siggen ; d="/bin" ; dd=$TWBIN ; rr=0550 ' f8=' ff=TRADEMARK ; d="" ; dd=$TWDOCS ; rr=0444 ' f9=' ff=policyguide.txt ; d="/policy" ; dd=$TWDOCS ; rr=0444 ' f10=' ff=${POLICYSRC} ; d="/policy" ; dd=$TWPOLICY ; rr=0640 ' @@ -584,9 +592,12 @@ f10=' ff=${POLICYSRC} ; d="/policy" ; dd=$TWPOLICY ; rr=0640 ' #f16=' ff=twadmin.8 ; d="/man/man8" ; dd=$TWMAN/man8 ; rr=0444 ' #f17=' ff=twintro.8 ; d="/man/man8" ; dd=$TWMAN/man8 ; rr=0444 ' #f18=' ff=twprint.8 ; d="/man/man8" ; dd=$TWMAN/man8 ; rr=0444 ' +f19=' ff=COMMERCIAL ; d="" ; dd=$TWDOCS ; rr=0444 ' +f20=' ff=ReadMe-2.4.3 ; d="" ; dd=$TWDOCS ; rr=0444 ' +f21=' ff=ChangeLog ; d="" ; dd=$TWDOCS ; rr=0444 ' # Binaries and manpages are already installed by the install target -loosefiles="f3 f8 f9 f10" +loosefiles="f3 f4 f5 f6 f7 f8 f9 f10 f19 f20 f21" for i in $loosefiles; do eval "eval \"\$$i\"" @@ -605,6 +616,13 @@ for i in $loosefiles; do fi done +if [ -n "$INSTALL_STRIP_FLAG" ] ; then + echo "INSTALL_STRIP_FLAG is set, stripping binaries" + chmod u+w "$TWBIN/siggen" "$TWBIN/tripwire" "$TWBIN/twadmin" "$TWBIN/twprint" + strip "$TWBIN/siggen" "$TWBIN/tripwire" "$TWBIN/twadmin" "$TWBIN/twprint" + chmod u-w "$TWBIN/siggen" "$TWBIN/tripwire" "$TWBIN/twadmin" "$TWBIN/twprint" +fi + #Make extra sure we don't install the unit test binary to sbin if [ -e "$TWBIN/twtest" ] ; then rm -f "$TWBIN/twtest" @@ -918,7 +936,7 @@ cat << END_OF_TEXT ---------------------------------------------- The installation succeeded. -Please refer to $README_LOC +Please refer to documentation in $TWDOCS for release information and to the printed user documentation for further instructions on using Tripwire 2.4 Open Source. diff --git a/lcov.sh b/lcov.sh new file mode 100755 index 0000000..b8f85c5 --- /dev/null +++ b/lcov.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +if [ -d ./lcov ]; then + rm -Rf ./lcov +fi + +if [ -e ./lcov.dat ]; then + rm ./lcov.dat +fi + +if [ -e ./lcov.tgz ]; then + rm ./lcov.tgz +fi + +lcov --capture --directory src --output-file ./lcov.dat +genhtml ./lcov.dat --output-directory lcov +tar -zcvf lcov.tgz lcov + diff --git a/man/Makefile.in b/man/Makefile.in index ce20121..2218a28 100644 --- a/man/Makefile.in +++ b/man/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = .. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,35 +85,108 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = man -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = -RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ - html-recursive info-recursive install-data-recursive \ - install-exec-recursive install-info-recursive \ - install-recursive installcheck-recursive installdirs-recursive \ - pdf-recursive ps-recursive uninstall-info-recursive \ - uninstall-recursive +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -85,6 +210,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -96,6 +222,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -112,21 +239,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -156,12 +286,16 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies SUBDIRS = man4 man5 man8 all: all-recursive @@ -171,15 +305,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign man/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign man/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -196,19 +329,28 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -uninstall-info-am: +$(am__aclocal_m4_deps): # This directory's subdirectories are mostly independent; you can cd -# into them and run `make' without going through this Makefile. -# To change the values of `make' variables: instead of editing Makefiles, -# (1) if the variable is set in `config.status', edit `config.status' -# (which will cause the Makefiles to be regenerated when you run `make'); -# (2) otherwise, pass the desired values on the `make' command line. -$(RECURSIVE_TARGETS): - @set fnord $$MAKEFLAGS; amf=$$2; \ +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ - list='$(SUBDIRS)'; for subdir in $$list; do \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ @@ -216,60 +358,20 @@ $(RECURSIVE_TARGETS): else \ local_target="$$target"; \ fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" -mostlyclean-recursive clean-recursive distclean-recursive \ -maintainer-clean-recursive: - @set fnord $$MAKEFLAGS; amf=$$2; \ - dot_seen=no; \ - case "$@" in \ - distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ - *) list='$(SUBDIRS)' ;; \ - esac; \ - rev=''; for subdir in $$list; do \ - if test "$$subdir" = "."; then :; else \ - rev="$$subdir $$rev"; \ - fi; \ - done; \ - rev="$$rev ."; \ - target=`echo $@ | sed s/-recursive//`; \ - for subdir in $$rev; do \ - echo "Making $$target in $$subdir"; \ - if test "$$subdir" = "."; then \ - local_target="$$target-am"; \ - else \ - local_target="$$target"; \ - fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ - done && test -z "$$fail" -tags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ - done -ctags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ - done +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ @@ -281,79 +383,104 @@ TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ - tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done - list='$(SUBDIRS)'; for subdir in $$list; do \ + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ - test -d "$(distdir)/$$subdir" \ - || mkdir "$(distdir)/$$subdir" \ - || exit 1; \ - (cd $$subdir && \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ - top_distdir="../$(top_distdir)" \ - distdir="../$(distdir)/$$subdir" \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ @@ -373,16 +500,22 @@ install-am: all-am installcheck: installcheck-recursive install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -401,18 +534,38 @@ dvi-am: html: html-recursive +html-am: + info: info-recursive info-am: install-data-am: +install-dvi: install-dvi-recursive + +install-dvi-am: + install-exec-am: +install-html: install-html-recursive + +install-html-am: + install-info: install-info-recursive +install-info-am: + install-man: +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-recursive @@ -431,21 +584,23 @@ ps: ps-recursive ps-am: -uninstall-am: uninstall-info-am +uninstall-am: + +.MAKE: $(am__recursive_targets) install-am install-strip -uninstall-info: uninstall-info-recursive +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic cscopelist-am ctags ctags-am \ + distclean distclean-generic distclean-tags distdir dvi dvi-am \ + html html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic pdf \ + pdf-am ps ps-am tags tags-am uninstall uninstall-am -.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ - clean clean-generic clean-recursive ctags ctags-recursive \ - distclean distclean-generic distclean-recursive distclean-tags \ - distdir dvi dvi-am html html-am info info-am install \ - install-am install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - installdirs-am maintainer-clean maintainer-clean-generic \ - maintainer-clean-recursive mostlyclean mostlyclean-generic \ - mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ - uninstall uninstall-am uninstall-info-am +.PRECIOUS: Makefile #man_MANS = \ @@ -457,6 +612,7 @@ uninstall-info: uninstall-info-recursive # ./man8/twadmin.8 \ # ./man8/twintro.8 \ # ./man8/twprint.8 + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/man/man4/Makefile.am b/man/man4/Makefile.am index 3ee9884..7ea2fb8 100644 --- a/man/man4/Makefile.am +++ b/man/man4/Makefile.am @@ -1,3 +1,2 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = twconfig.4 twpolicy.4 -dist_man_MANS = twconfig.4 twpolicy.4 \ No newline at end of file +dist_man_MANS = twconfig.4 twpolicy.4 diff --git a/man/man4/Makefile.in b/man/man4/Makefile.in index 2062ed3..dbd0c2d 100644 --- a/man/man4/Makefile.in +++ b/man/man4/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,31 +85,80 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = man/man4 -DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } man4dir = $(mandir)/man4 am__installdirs = "$(DESTDIR)$(man4dir)" NROFF = nroff -MANS = $(dist_man_MANS) $(man_MANS) +MANS = $(dist_man_MANS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.in \ + $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -81,6 +182,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -92,6 +194,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -108,21 +211,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -152,14 +258,17 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = twconfig.4 twpolicy.4 dist_man_MANS = twconfig.4 twpolicy.4 all: all-am @@ -168,15 +277,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man4/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign man/man4/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man4/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign man/man4/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -193,83 +301,84 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -uninstall-info-am: -install-man4: $(man4_MANS) $(man_MANS) +$(am__aclocal_m4_deps): +install-man4: $(dist_man_MANS) @$(NORMAL_INSTALL) - test -z "$(man4dir)" || $(mkdir_p) "$(DESTDIR)$(man4dir)" - @list='$(man4_MANS) $(dist_man4_MANS) $(nodist_man4_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.4*) list="$$list $$i" ;; \ - esac; \ + @list1=''; \ + list2='$(dist_man_MANS)'; \ + test -n "$(man4dir)" \ + && test -n "`echo $$list1$$list2`" \ + || exit 0; \ + echo " $(MKDIR_P) '$(DESTDIR)$(man4dir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(man4dir)" || exit 1; \ + { for i in $$list1; do echo "$$i"; done; \ + if test -n "$$list2"; then \ + for i in $$list2; do echo "$$i"; done \ + | sed -n '/\.4[a-z]*$$/p'; \ + fi; \ + } | while read p; do \ + if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; echo "$$p"; \ + done | \ + sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^4][0-9a-z]*$$,4,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ + sed 'N;N;s,\n, ,g' | { \ + list=; while read file base inst; do \ + if test "$$base" = "$$inst"; then list="$$list $$file"; else \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man4dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man4dir)/$$inst" || exit $$?; \ + fi; \ done; \ - for i in $$list; do \ - if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \ - else file=$$i; fi; \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 4*) ;; \ - *) ext='4' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man4dir)/$$inst'"; \ - $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man4dir)/$$inst"; \ - done + for i in $$list; do echo "$$i"; done | $(am__base_list) | \ + while read files; do \ + test -z "$$files" || { \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man4dir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(man4dir)" || exit $$?; }; \ + done; } + uninstall-man4: @$(NORMAL_UNINSTALL) - @list='$(man4_MANS) $(dist_man4_MANS) $(nodist_man4_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.4*) list="$$list $$i" ;; \ - esac; \ - done; \ - for i in $$list; do \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 4*) ;; \ - *) ext='4' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " rm -f '$(DESTDIR)$(man4dir)/$$inst'"; \ - rm -f "$(DESTDIR)$(man4dir)/$$inst"; \ - done -tags: TAGS -TAGS: + @list=''; test -n "$(man4dir)" || exit 0; \ + files=`{ for i in $$list; do echo "$$i"; done; \ + l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ + sed -n '/\.4[a-z]*$$/p'; \ + } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^4][0-9a-z]*$$,4,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ + dir='$(DESTDIR)$(man4dir)'; $(am__uninstall_files_from_dir) +tags TAGS: -ctags: CTAGS -CTAGS: +ctags CTAGS: + +cscope cscopelist: distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @@ -278,7 +387,7 @@ check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man4dir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -290,16 +399,22 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -318,18 +433,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: install-data-am: install-man +install-dvi: install-dvi-am + +install-dvi-am: + install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: install-man4 +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -348,18 +483,26 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-man +uninstall-am: uninstall-man uninstall-man: uninstall-man4 -.PHONY: all all-am check check-am clean clean-generic distclean \ - distclean-generic distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-man4 install-strip installcheck installcheck-am \ - installdirs maintainer-clean maintainer-clean-generic \ - mostlyclean mostlyclean-generic pdf pdf-am ps ps-am uninstall \ - uninstall-am uninstall-info-am uninstall-man uninstall-man4 +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic cscopelist-am \ + ctags-am distclean distclean-generic distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-man4 install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic pdf \ + pdf-am ps ps-am tags-am uninstall uninstall-am uninstall-man \ + uninstall-man4 + +.PRECIOUS: Makefile + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. diff --git a/man/man4/twconfig.4 b/man/man4/twconfig.4 index 38e2ffe..df7c921 100644 --- a/man/man4/twconfig.4 +++ b/man/man4/twconfig.4 @@ -35,7 +35,7 @@ .. .nh .ad l -.TH TWCONFIG 4 "1 July 2000" +.TH TWCONFIG 4 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME twconfig \- \fITripwire\fP configuration file reference .SH DESCRIPTION @@ -215,6 +215,26 @@ parameter; reports displayed by other modes and other commands are not affected. .br Initial value: \fI3\fP +.IP \f(CWDBPRINTLEVEL\fP +Specifies the default level of report produced by the \fBtwprint +\(hy\(hyprint\(hydbfile\fP mode. Valid values for this option are 0 to +2. The output +level specified by this option can be overridden with the (\fB\(hyt\fP\ or\ \fB\(hy\(hyoutput\(hylevel\fP) option on the command line. If +this variable is not included in the configuration file, the default +output level is 2. +.br +Initial value: \fI2\fP +.IP \f(CWHASH_DIRECT_IO\fP +Use direct i/o when hashing files. (Linux-only as of OST 2.4.3.2) +.br +Initial value: \fIfalse\fP +.IP \f(CWRESOLVE_IDS_TO_NAMES\fP +Specifies whether to resolve uid/gid values to user & group names. Static +binaries may segfault while calling getpwuid/getgrgid in certain +nsswitch.conf configurations, and setting this to false will bypass +the name resolution step and prevent the segfault. +.br +Initial value: \fItrue\fP .SS Email Notification Variables .IP \f(CWMAILMETHOD Specifies the protocol to be used by \fITripwire\fR for email @@ -291,7 +311,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/man/man4/twpolicy.4 b/man/man4/twpolicy.4 index d896ea7..be7d214 100644 --- a/man/man4/twpolicy.4 +++ b/man/man4/twpolicy.4 @@ -36,7 +36,7 @@ .\" .nh .ad l -.TH TWPOLICY 4 "1 July 2000" +.TH TWPOLICY 4 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME twpolicy \- \fITripwire\fP policy file reference .SH DESCRIPTION @@ -537,7 +537,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/man/man5/Makefile.am b/man/man5/Makefile.am index 09a087d..3c6716b 100644 --- a/man/man5/Makefile.am +++ b/man/man5/Makefile.am @@ -1,3 +1,2 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = twfiles.5 -dist_man_MANS = twfiles.5 \ No newline at end of file +dist_man_MANS = twfiles.5 diff --git a/man/man5/Makefile.in b/man/man5/Makefile.in index 498de26..2d8dd98 100644 --- a/man/man5/Makefile.in +++ b/man/man5/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,31 +85,80 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = man/man5 -DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } man5dir = $(mandir)/man5 am__installdirs = "$(DESTDIR)$(man5dir)" NROFF = nroff -MANS = $(dist_man_MANS) $(man_MANS) +MANS = $(dist_man_MANS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.in \ + $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -81,6 +182,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -92,6 +194,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -108,21 +211,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -152,14 +258,17 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = twfiles.5 dist_man_MANS = twfiles.5 all: all-am @@ -168,15 +277,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man5/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign man/man5/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man5/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign man/man5/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -193,83 +301,84 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -uninstall-info-am: -install-man5: $(man5_MANS) $(man_MANS) +$(am__aclocal_m4_deps): +install-man5: $(dist_man_MANS) @$(NORMAL_INSTALL) - test -z "$(man5dir)" || $(mkdir_p) "$(DESTDIR)$(man5dir)" - @list='$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.5*) list="$$list $$i" ;; \ - esac; \ + @list1=''; \ + list2='$(dist_man_MANS)'; \ + test -n "$(man5dir)" \ + && test -n "`echo $$list1$$list2`" \ + || exit 0; \ + echo " $(MKDIR_P) '$(DESTDIR)$(man5dir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(man5dir)" || exit 1; \ + { for i in $$list1; do echo "$$i"; done; \ + if test -n "$$list2"; then \ + for i in $$list2; do echo "$$i"; done \ + | sed -n '/\.5[a-z]*$$/p'; \ + fi; \ + } | while read p; do \ + if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; echo "$$p"; \ + done | \ + sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ + sed 'N;N;s,\n, ,g' | { \ + list=; while read file base inst; do \ + if test "$$base" = "$$inst"; then list="$$list $$file"; else \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \ + fi; \ done; \ - for i in $$list; do \ - if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \ - else file=$$i; fi; \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 5*) ;; \ - *) ext='5' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ - $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst"; \ - done + for i in $$list; do echo "$$i"; done | $(am__base_list) | \ + while read files; do \ + test -z "$$files" || { \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \ + done; } + uninstall-man5: @$(NORMAL_UNINSTALL) - @list='$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.5*) list="$$list $$i" ;; \ - esac; \ - done; \ - for i in $$list; do \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 5*) ;; \ - *) ext='5' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " rm -f '$(DESTDIR)$(man5dir)/$$inst'"; \ - rm -f "$(DESTDIR)$(man5dir)/$$inst"; \ - done -tags: TAGS -TAGS: + @list=''; test -n "$(man5dir)" || exit 0; \ + files=`{ for i in $$list; do echo "$$i"; done; \ + l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ + sed -n '/\.5[a-z]*$$/p'; \ + } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ + dir='$(DESTDIR)$(man5dir)'; $(am__uninstall_files_from_dir) +tags TAGS: -ctags: CTAGS -CTAGS: +ctags CTAGS: + +cscope cscopelist: distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @@ -278,7 +387,7 @@ check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man5dir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -290,16 +399,22 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -318,18 +433,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: install-data-am: install-man +install-dvi: install-dvi-am + +install-dvi-am: + install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: install-man5 +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -348,18 +483,26 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-man +uninstall-am: uninstall-man uninstall-man: uninstall-man5 -.PHONY: all all-am check check-am clean clean-generic distclean \ - distclean-generic distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-man5 install-strip installcheck installcheck-am \ - installdirs maintainer-clean maintainer-clean-generic \ - mostlyclean mostlyclean-generic pdf pdf-am ps ps-am uninstall \ - uninstall-am uninstall-info-am uninstall-man uninstall-man5 +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic cscopelist-am \ + ctags-am distclean distclean-generic distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-man5 install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic pdf \ + pdf-am ps ps-am tags-am uninstall uninstall-am uninstall-man \ + uninstall-man5 + +.PRECIOUS: Makefile + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. diff --git a/man/man5/twfiles.5 b/man/man5/twfiles.5 index 775e86b..ebffc8c 100644 --- a/man/man5/twfiles.5 +++ b/man/man5/twfiles.5 @@ -25,7 +25,7 @@ .\" .nh .ad l -.TH TWFILES 5 "1 July 2000" +.TH TWFILES 5 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME twfiles \- overview of files used by \fITripwire\fR and file backup process .\" @@ -112,7 +112,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/man/man8/Makefile.am b/man/man8/Makefile.am index cf05479..a3d568b 100644 --- a/man/man8/Makefile.am +++ b/man/man8/Makefile.am @@ -1,3 +1,2 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = siggen.8 tripwire.8 twadmin.8 twintro.8 twprint.8 -dist_man_MANS = siggen.8 tripwire.8 twadmin.8 twintro.8 twprint.8 \ No newline at end of file +dist_man_MANS = siggen.8 tripwire.8 twadmin.8 twintro.8 twprint.8 diff --git a/man/man8/Makefile.in b/man/man8/Makefile.in index 41c700d..d6e21b4 100644 --- a/man/man8/Makefile.in +++ b/man/man8/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,31 +85,80 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = man/man8 -DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.am \ - $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } man8dir = $(mandir)/man8 am__installdirs = "$(DESTDIR)$(man8dir)" NROFF = nroff -MANS = $(dist_man_MANS) $(man_MANS) +MANS = $(dist_man_MANS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.in \ + $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -81,6 +182,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -92,6 +194,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -108,21 +211,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -152,14 +258,17 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -man_MANS = siggen.8 tripwire.8 twadmin.8 twintro.8 twprint.8 dist_man_MANS = siggen.8 tripwire.8 twadmin.8 twintro.8 twprint.8 all: all-am @@ -168,15 +277,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man8/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign man/man8/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign man/man8/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign man/man8/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -193,83 +301,84 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -uninstall-info-am: -install-man8: $(man8_MANS) $(man_MANS) +$(am__aclocal_m4_deps): +install-man8: $(dist_man_MANS) @$(NORMAL_INSTALL) - test -z "$(man8dir)" || $(mkdir_p) "$(DESTDIR)$(man8dir)" - @list='$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.8*) list="$$list $$i" ;; \ - esac; \ + @list1=''; \ + list2='$(dist_man_MANS)'; \ + test -n "$(man8dir)" \ + && test -n "`echo $$list1$$list2`" \ + || exit 0; \ + echo " $(MKDIR_P) '$(DESTDIR)$(man8dir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(man8dir)" || exit 1; \ + { for i in $$list1; do echo "$$i"; done; \ + if test -n "$$list2"; then \ + for i in $$list2; do echo "$$i"; done \ + | sed -n '/\.8[a-z]*$$/p'; \ + fi; \ + } | while read p; do \ + if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; echo "$$p"; \ + done | \ + sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ + sed 'N;N;s,\n, ,g' | { \ + list=; while read file base inst; do \ + if test "$$base" = "$$inst"; then list="$$list $$file"; else \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \ + fi; \ done; \ - for i in $$list; do \ - if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \ - else file=$$i; fi; \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 8*) ;; \ - *) ext='8' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ - $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \ - done + for i in $$list; do echo "$$i"; done | $(am__base_list) | \ + while read files; do \ + test -z "$$files" || { \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \ + done; } + uninstall-man8: @$(NORMAL_UNINSTALL) - @list='$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \ - l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ - for i in $$l2; do \ - case "$$i" in \ - *.8*) list="$$list $$i" ;; \ - esac; \ - done; \ - for i in $$list; do \ - ext=`echo $$i | sed -e 's/^.*\\.//'`; \ - case "$$ext" in \ - 8*) ;; \ - *) ext='8' ;; \ - esac; \ - inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ - inst=`echo $$inst | sed -e 's/^.*\///'`; \ - inst=`echo $$inst | sed '$(transform)'`.$$ext; \ - echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \ - rm -f "$(DESTDIR)$(man8dir)/$$inst"; \ - done -tags: TAGS -TAGS: + @list=''; test -n "$(man8dir)" || exit 0; \ + files=`{ for i in $$list; do echo "$$i"; done; \ + l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ + sed -n '/\.8[a-z]*$$/p'; \ + } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ + dir='$(DESTDIR)$(man8dir)'; $(am__uninstall_files_from_dir) +tags TAGS: -ctags: CTAGS -CTAGS: +ctags CTAGS: + +cscope cscopelist: distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @@ -278,7 +387,7 @@ check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man8dir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -290,16 +399,22 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -318,18 +433,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: install-data-am: install-man +install-dvi: install-dvi-am + +install-dvi-am: + install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: install-man8 +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -348,18 +483,26 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-man +uninstall-am: uninstall-man uninstall-man: uninstall-man8 -.PHONY: all all-am check check-am clean clean-generic distclean \ - distclean-generic distdir dvi dvi-am html html-am info info-am \ - install install-am install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-man8 install-strip installcheck installcheck-am \ - installdirs maintainer-clean maintainer-clean-generic \ - mostlyclean mostlyclean-generic pdf pdf-am ps ps-am uninstall \ - uninstall-am uninstall-info-am uninstall-man uninstall-man8 +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic cscopelist-am \ + ctags-am distclean distclean-generic distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-man8 install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic pdf \ + pdf-am ps ps-am tags-am uninstall uninstall-am uninstall-man \ + uninstall-man8 + +.PRECIOUS: Makefile + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. diff --git a/man/man8/siggen.8 b/man/man8/siggen.8 index c4bd893..8adc553 100644 --- a/man/man8/siggen.8 +++ b/man/man8/siggen.8 @@ -2,9 +2,9 @@ .\" Do not move or remove previous line. .\" Used by some man commands to know that tbl should be used. .nh -.TH SIGGEN 8 "19 Feb 2004" +.TH SIGGEN 8 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME -siggen \- signature gathering routine for Tripwire +siggen \- signature gathering utility for Tripwire .SH SYNOPSIS .B siggen [ @@ -54,6 +54,8 @@ Display Haval value, a 128-bit hash code. .TP .IR file1 " [ " "file2... " ] List of filesystem objects for which to display values. +.SH EXIT STATUS +\fBsiggen\fP exits 0 on success, 1 on error. .SH VERSION INFORMATION This man page describes .B siggen @@ -67,7 +69,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/man/man8/tripwire.8 b/man/man8/tripwire.8 index 5017f97..d0dd347 100644 --- a/man/man8/tripwire.8 +++ b/man/man8/tripwire.8 @@ -36,9 +36,9 @@ .\" .nh .ad l -.TH TRIPWIRE 8 "1 July 2000" +.TH TRIPWIRE 8 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME -tripwire \- a file integrity checker for \s-1UNIX\s0 systems +tripwire \- a file integrity checker for \s-1UNIX-like\s0 systems .SH SYNOPSIS .B tripwire .RB "{ " "-m i" " | " "--init" " } " @@ -554,6 +554,19 @@ Mode selector. Use the specified email address. This parameter must be supplied when test mode is used. Only one address may be specified. +.SH EXIT STATUS +.SS Integrity Checking Mode +\fBtripwire\fP exits 0 if no changes are detected. Otherwise the exit value is a bit mask: +.TP +\fB1\fP At least one file or directory has been added. +.TP +\fB2\fP At least one file or directory has been modified. +.TP +\fB4\fP At least one file or directory has been modified. +.TP +\fB8\fP Error(s) occurred during the check. +.SS All Other Modes +\fBtripwire\fP exits 0 on success, 8 on error. .SH VERSION INFORMATION This man page describes .B tripwire @@ -567,7 +580,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR twadmin (8), diff --git a/man/man8/twadmin.8 b/man/man8/twadmin.8 index 034c188..f56f6a7 100644 --- a/man/man8/twadmin.8 +++ b/man/man8/twadmin.8 @@ -17,7 +17,7 @@ .in \\n(.iu .. .ad l -.TH TWADMIN 8 "1 July 2000" +.TH TWADMIN 8 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME twadmin \- Tripwire administrative and utility tool .SH SYNOPSIS @@ -481,6 +481,10 @@ the local key. .BI \(hyQ " passphrase\fR, " --site-passphrase " passphrase" Specify site passphrase to be used when generating the site key. +.TP +.BI \(hyK " size\fR, " --key-size " size" +Specify the key size (1024 or 2048 bits) when generating +keys. (Default is 1024.) .\" ***************************************** .Hr .if \n(.t<700 .bp @@ -534,6 +538,8 @@ file. Specify passphrase used to decrypt the private key in the specified sitekey file. .\" ***************************************** +.SH EXIT STATUS +\fBtwadmin\fP exits 0 on success, 1 on error. .SH VERSION INFORMATION This man page describes .B twadmin @@ -547,7 +553,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/man/man8/twintro.8 b/man/man8/twintro.8 index 9279cf2..dd598ca 100644 --- a/man/man8/twintro.8 +++ b/man/man8/twintro.8 @@ -16,12 +16,12 @@ .\" .nh .ad l -.TH TWINTRO 8 "1 July 2000" +.TH TWINTRO 8 "04 Jan 2018" "Open Source Tripwire 2.4" .SH NAME twintro \- introduction to \fITripwire\fP software .SH DESCRIPTION .PP -\fITripwire 2.4\fP is a file integrity assessment product for Linux networks. Rather than preventing an intruder or virus +\fITripwire 2.4\fP is a file integrity assessment tool for UNIX-like systems. Rather than preventing an intruder or virus from attacking system files, \fITripwire\fP detects intrusions when they do occur. By comparing system files and directories against a previously stored "baseline" database, \fITripwire\fP finds any @@ -99,7 +99,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR tripwire (8), .BR twadmin (8), diff --git a/man/man8/twprint.8 b/man/man8/twprint.8 index ad33f86..c7277d6 100644 --- a/man/man8/twprint.8 +++ b/man/man8/twprint.8 @@ -2,7 +2,7 @@ .\" Do not move or remove previous line. .\" Used by some man commands to know that tbl should be used. .ad l -.TH TWPRINT 8 "1 July 2000" +.TH TWPRINT 8 "04 Jan 2018" "Open Source Tripwire 2.4" .nh .SH NAME twprint \- Tripwire database and report printer @@ -10,6 +10,9 @@ twprint \- Tripwire database and report printer .B twprint .RB "{ " "-m r" " | " "--print-report" " } " .RI "[ " options... " ]" +.if n .br +.if n .ti +.5i +.RI " [ " "object1" " [ " "object2..." " ]]" .br .B twprint .RB "{ " "-m d" " | " "--print-dbfile" " } " @@ -59,6 +62,7 @@ lbw(1.2i) lb. -L \fIlocalkey\fP --local-keyfile \fIlocalkey\fP -t \fR{ 0|1|2|3|4 }\fP --report-level \fR{ 0|1|2|3|4 }\fP .TE +.RI "[ " "object1" " [ " "object2..." " ]]" .RE .TP .BR "\(hym r" ", " --print-report @@ -83,10 +87,15 @@ Print the specified report file. Use the specified local key file to perform verification with reports which are signed. .TP -.BI \(hyt " level\fR, " --report-level " level +.BI \(hyt " level\fR, " --report-level " level" Specifies the detail level of the printed report, overriding the \f(CWREPORTLEVEL\fP variable in the configuration file. \fIlevel\fR must be a number from 0\ to\ 4. +.TP +.RI "[ " "object1" " [ " "object2..." " ]]" +List of filesystem objects in the report to print. If no +objects are specified, every object in the report will +be printed. .\" ***************************************** .SS Database printing mode: .RS 0.4i @@ -100,6 +109,7 @@ lbw(1.2i) lb. -c \fIcfgfile\fP --cfgfile \fIcfgfile\fP -d \fIdatabase\fP --dbfile \fIdatabase\fP -L \fIlocalkey\fP --local-keyfile \fIlocalkey\fP +-t \fR{ 0|1|2 }\fP --output-level \fR{ 0|1|2 }\fP .TE .RI "[ " "object1" " [ " "object2..." " ]]" .RE @@ -125,6 +135,11 @@ Print the specified database file. .BI \(hyL " localkey\fR, " --local-keyfile " localkey" Use the specified local key file to read the database. .TP +.BI \(hyt " level\fR, " --output-level " level" +Specifies the detail level of the printed database, overriding the +\f(CWDBPRINTLEVEL\fP variable in the configuration +file. \fIlevel\fR must be a number from 0\ to\ 2. +.TP .RI "[ " "object1" " [ " "object2..." " ]]" List of filesystem objects in the database to print. If no objects are specified, every object in the database will @@ -132,6 +147,8 @@ be printed. The format for a list of objects is: .if n .I "section: objname objname... section: objname..." .if t .br .if t .I "section: objectname objectname... section: objectname..." +.SH EXIT STATUS +\fBtwprint\fP exits 0 on success, 1 on error. .SH VERSION INFORMATION This man page describes .B twprint @@ -145,7 +162,7 @@ Permission is granted to copy and distribute modified versions of this man page .PP Permission is granted to copy and distribute translations of this man page into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by Tripwire, Inc. .PP -Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. +Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, Inc. in the United States and other countries. All rights reserved. .SH SEE ALSO .BR twintro (8), .BR tripwire (8), diff --git a/missing b/missing index 3aef1fb..f62bbae 100755 --- a/missing +++ b/missing @@ -1,7 +1,10 @@ #! /bin/sh -# Common stub for a few missing GNU programs while installing. -# Copyright 1996, 1997, 1999, 2000 Free Software Foundation, Inc. -# Originally by Fran,cois Pinard , 1996. +# Common wrapper for a few potentially missing GNU programs. + +scriptversion=2013-10-28.13; # UTC + +# Copyright (C) 1996-2014 Free Software Foundation, Inc. +# Originally written by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -14,9 +17,7 @@ # GNU General Public License for more details. # You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA -# 02111-1307, USA. +# along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a @@ -24,260 +25,191 @@ # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then - echo 1>&2 "Try \`$0 --help' for more information" + echo 1>&2 "Try '$0 --help' for more information" exit 1 fi -run=: - -# In the cases where this matters, `missing' is being run in the -# srcdir already. -if test -f configure.ac; then - configure_ac=configure.ac -else - configure_ac=configure.in -fi +case $1 in -case "$1" in ---run) - # Try to run requested program, and just exit if it succeeds. - run= - shift - "$@" && exit 0 - ;; -esac + --is-lightweight) + # Used by our autoconf macros to check whether the available missing + # script is modern enough. + exit 0 + ;; -# If it does not exist, or fails to run (possibly an outdated version), -# try to emulate it. -case "$1" in + --run) + # Back-compat with the calling convention used by older automake. + shift + ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... -Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an -error status if there is no known handling for PROGRAM. +Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due +to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit - --run try to run the given command, and emulate it if it fails Supported PROGRAM values: - aclocal touch file \`aclocal.m4' - autoconf touch file \`configure' - autoheader touch file \`config.h.in' - automake touch all \`Makefile.in' files - bison create \`y.tab.[ch]', if possible, from existing .[ch] - flex create \`lex.yy.c', if possible, from existing .c - help2man touch the output file - lex create \`lex.yy.c', if possible, from existing .c - makeinfo touch the output file - tar try tar, gnutar, gtar, then tar without non-portable flags - yacc create \`y.tab.[ch]', if possible, from existing .[ch]" + aclocal autoconf autoheader autom4te automake makeinfo + bison yacc flex lex help2man + +Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and +'g' are ignored when checking the name. + +Send bug reports to ." + exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) - echo "missing 0.3 - GNU automake" + echo "missing $scriptversion (GNU Automake)" + exit $? ;; -*) - echo 1>&2 "$0: Unknown \`$1' option" - echo 1>&2 "Try \`$0 --help' for more information" + echo 1>&2 "$0: unknown '$1' option" + echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; - aclocal) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified \`acinclude.m4' or \`${configure_ac}'. You might want - to install the \`Automake' and \`Perl' packages. Grab them from - any GNU archive site." - touch aclocal.m4 - ;; - - autoconf) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified \`${configure_ac}'. You might want to install the - \`Autoconf' and \`GNU m4' packages. Grab them from any GNU - archive site." - touch configure - ;; - - autoheader) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified \`acconfig.h' or \`${configure_ac}'. You might want - to install the \`Autoconf' and \`GNU m4' packages. Grab them - from any GNU archive site." - files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` - test -z "$files" && files="config.h" - touch_files= - for f in $files; do - case "$f" in - *:*) touch_files="$touch_files "`echo "$f" | - sed -e 's/^[^:]*://' -e 's/:.*//'`;; - *) touch_files="$touch_files $f.in";; - esac - done - touch $touch_files - ;; - - automake) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. - You might want to install the \`Automake' and \`Perl' packages. - Grab them from any GNU archive site." - find . -type f -name Makefile.am -print | - sed 's/\.am$/.in/' | - while read f; do touch "$f"; done - ;; - - bison|yacc) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified a \`.y' file. You may need the \`Bison' package - in order for those modifications to take effect. You can get - \`Bison' from any GNU archive site." - rm -f y.tab.c y.tab.h - if [ $# -ne 1 ]; then - eval LASTARG="\${$#}" - case "$LASTARG" in - *.y) - SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` - if [ -f "$SRCFILE" ]; then - cp "$SRCFILE" y.tab.c - fi - SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` - if [ -f "$SRCFILE" ]; then - cp "$SRCFILE" y.tab.h - fi - ;; - esac - fi - if [ ! -f y.tab.h ]; then - echo >y.tab.h - fi - if [ ! -f y.tab.c ]; then - echo 'main() { return 0; }' >y.tab.c - fi - ;; - - lex|flex) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified a \`.l' file. You may need the \`Flex' package - in order for those modifications to take effect. You can get - \`Flex' from any GNU archive site." - rm -f lex.yy.c - if [ $# -ne 1 ]; then - eval LASTARG="\${$#}" - case "$LASTARG" in - *.l) - SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` - if [ -f "$SRCFILE" ]; then - cp "$SRCFILE" lex.yy.c - fi - ;; - esac - fi - if [ ! -f lex.yy.c ]; then - echo 'main() { return 0; }' >lex.yy.c - fi - ;; - - help2man) - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified a dependency of a manual page. You may need the - \`Help2man' package in order for those modifications to take - effect. You can get \`Help2man' from any GNU archive site." - - file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` - if test -z "$file"; then - file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'` - fi - if [ -f "$file" ]; then - touch $file - else - test -z "$file" || exec >$file - echo ".ab help2man is required to generate this page" - exit 1 - fi - ;; - - makeinfo) - if test -z "$run" && (makeinfo --version > /dev/null 2>&1); then - # We have makeinfo, but it failed. - exit 1 - fi - - echo 1>&2 "\ -WARNING: \`$1' is missing on your system. You should only need it if - you modified a \`.texi' or \`.texinfo' file, or any other file - indirectly affecting the aspect of the manual. The spurious - call might also be the consequence of using a buggy \`make' (AIX, - DU, IRIX). You might want to install the \`Texinfo' package or - the \`GNU make' package. Grab either from any GNU archive site." - file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` - if test -z "$file"; then - file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` - file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file` - fi - touch $file - ;; - - tar) - shift - if test -n "$run"; then - echo 1>&2 "ERROR: \`tar' requires --run" - exit 1 - fi - - # We have already tried tar in the generic part. - # Look for gnutar/gtar before invocation to avoid ugly error - # messages. - if (gnutar --version > /dev/null 2>&1); then - gnutar ${1+"$@"} && exit 0 - fi - if (gtar --version > /dev/null 2>&1); then - gtar ${1+"$@"} && exit 0 - fi - firstarg="$1" - if shift; then - case "$firstarg" in - *o*) - firstarg=`echo "$firstarg" | sed s/o//` - tar "$firstarg" ${1+"$@"} && exit 0 - ;; - esac - case "$firstarg" in - *h*) - firstarg=`echo "$firstarg" | sed s/h//` - tar "$firstarg" ${1+"$@"} && exit 0 - ;; - esac - fi +esac - echo 1>&2 "\ -WARNING: I can't seem to be able to run \`tar' with the given arguments. - You may want to install GNU tar or Free paxutils, or check the - command line arguments." - exit 1 - ;; +# Run the given program, remember its exit status. +"$@"; st=$? + +# If it succeeded, we are done. +test $st -eq 0 && exit 0 + +# Also exit now if we it failed (or wasn't found), and '--version' was +# passed; such an option is passed most likely to detect whether the +# program is present and works. +case $2 in --version|--help) exit $st;; esac + +# Exit code 63 means version mismatch. This often happens when the user +# tries to use an ancient version of a tool on a file that requires a +# minimum version. +if test $st -eq 63; then + msg="probably too old" +elif test $st -eq 127; then + # Program was missing. + msg="missing on your system" +else + # Program was found and executed, but failed. Give up. + exit $st +fi - *) - echo 1>&2 "\ -WARNING: \`$1' is needed, and you do not seem to have it handy on your - system. You might have modified some files without having the - proper tools for further handling them. Check the \`README' file, - it often tells you about the needed prerequirements for installing - this package. You may also peek at any GNU archive site, in case - some other package would contain this missing \`$1' program." - exit 1 +perl_URL=http://www.perl.org/ +flex_URL=http://flex.sourceforge.net/ +gnu_software_URL=http://www.gnu.org/software + +program_details () +{ + case $1 in + aclocal|automake) + echo "The '$1' program is part of the GNU Automake package:" + echo "<$gnu_software_URL/automake>" + echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" + echo "<$gnu_software_URL/autoconf>" + echo "<$gnu_software_URL/m4/>" + echo "<$perl_URL>" + ;; + autoconf|autom4te|autoheader) + echo "The '$1' program is part of the GNU Autoconf package:" + echo "<$gnu_software_URL/autoconf/>" + echo "It also requires GNU m4 and Perl in order to run:" + echo "<$gnu_software_URL/m4/>" + echo "<$perl_URL>" + ;; + esac +} + +give_advice () +{ + # Normalize program name to check for. + normalized_program=`echo "$1" | sed ' + s/^gnu-//; t + s/^gnu//; t + s/^g//; t'` + + printf '%s\n' "'$1' is $msg." + + configure_deps="'configure.ac' or m4 files included by 'configure.ac'" + case $normalized_program in + autoconf*) + echo "You should only need it if you modified 'configure.ac'," + echo "or m4 files included by it." + program_details 'autoconf' + ;; + autoheader*) + echo "You should only need it if you modified 'acconfig.h' or" + echo "$configure_deps." + program_details 'autoheader' + ;; + automake*) + echo "You should only need it if you modified 'Makefile.am' or" + echo "$configure_deps." + program_details 'automake' + ;; + aclocal*) + echo "You should only need it if you modified 'acinclude.m4' or" + echo "$configure_deps." + program_details 'aclocal' + ;; + autom4te*) + echo "You might have modified some maintainer files that require" + echo "the 'autom4te' program to be rebuilt." + program_details 'autom4te' + ;; + bison*|yacc*) + echo "You should only need it if you modified a '.y' file." + echo "You may want to install the GNU Bison package:" + echo "<$gnu_software_URL/bison/>" + ;; + lex*|flex*) + echo "You should only need it if you modified a '.l' file." + echo "You may want to install the Fast Lexical Analyzer package:" + echo "<$flex_URL>" + ;; + help2man*) + echo "You should only need it if you modified a dependency" \ + "of a man page." + echo "You may want to install the GNU Help2man package:" + echo "<$gnu_software_URL/help2man/>" ;; -esac - -exit 0 + makeinfo*) + echo "You should only need it if you modified a '.texi' file, or" + echo "any other file indirectly affecting the aspect of the manual." + echo "You might want to install the Texinfo package:" + echo "<$gnu_software_URL/texinfo/>" + echo "The spurious makeinfo call might also be the consequence of" + echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" + echo "want to install GNU make:" + echo "<$gnu_software_URL/make/>" + ;; + *) + echo "You might have modified some files without having the proper" + echo "tools for further handling them. Check the 'README' file, it" + echo "often tells you about the needed prerequisites for installing" + echo "this package. You may also peek at any GNU archive site, in" + echo "case some other package contains this missing '$1' program." + ;; + esac +} + +give_advice "$1" | sed -e '1s/^/WARNING: /' \ + -e '2,$s/^/ /' >&2 + +# Propagate the correct exit status (expected to be 127 for a program +# not found, 63 for a program that failed due to version mismatch). +exit $st + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/mkinstalldirs b/mkinstalldirs index 0ea4d23..55d537f 100755 --- a/mkinstalldirs +++ b/mkinstalldirs @@ -1,40 +1,162 @@ #! /bin/sh # mkinstalldirs --- make directory hierarchy -# Author: Noah Friedman -# Created: 1993-05-16 -# Public domain -# $Id: mkinstalldirs,v 1.1 2001/02/18 15:08:31 pherman Exp $ +scriptversion=2009-04-28.21; # UTC + +# Original author: Noah Friedman +# Created: 1993-05-16 +# Public domain. +# +# This file is maintained in Automake, please report +# bugs to or send patches to +# . +nl=' +' +IFS=" "" $nl" errstatus=0 +dirmode= + +usage="\ +Usage: mkinstalldirs [-h] [--help] [--version] [-m MODE] DIR ... + +Create each directory DIR (with mode MODE, if specified), including all +leading file name components. + +Report bugs to ." + +# process command line arguments +while test $# -gt 0 ; do + case $1 in + -h | --help | --h*) # -h for help + echo "$usage" + exit $? + ;; + -m) # -m PERM arg + shift + test $# -eq 0 && { echo "$usage" 1>&2; exit 1; } + dirmode=$1 + shift + ;; + --version) + echo "$0 $scriptversion" + exit $? + ;; + --) # stop option processing + shift + break + ;; + -*) # unknown option + echo "$usage" 1>&2 + exit 1 + ;; + *) # first non-opt arg + break + ;; + esac +done for file do - set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'` - shift + if test -d "$file"; then + shift + else + break + fi +done + +case $# in + 0) exit 0 ;; +esac + +# Solaris 8's mkdir -p isn't thread-safe. If you mkdir -p a/b and +# mkdir -p a/c at the same time, both will detect that a is missing, +# one will create a, then the other will try to create a and die with +# a "File exists" error. This is a problem when calling mkinstalldirs +# from a parallel make. We use --version in the probe to restrict +# ourselves to GNU mkdir, which is thread-safe. +case $dirmode in + '') + if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then + echo "mkdir -p -- $*" + exec mkdir -p -- "$@" + else + # On NextStep and OpenStep, the 'mkdir' command does not + # recognize any option. It will interpret all options as + # directories to create, and then abort because '.' already + # exists. + test -d ./-p && rmdir ./-p + test -d ./--version && rmdir ./--version + fi + ;; + *) + if mkdir -m "$dirmode" -p --version . >/dev/null 2>&1 && + test ! -d ./--version; then + echo "mkdir -m $dirmode -p -- $*" + exec mkdir -m "$dirmode" -p -- "$@" + else + # Clean up after NextStep and OpenStep mkdir. + for d in ./-m ./-p ./--version "./$dirmode"; + do + test -d $d && rmdir $d + done + fi + ;; +esac + +for file +do + case $file in + /*) pathcomp=/ ;; + *) pathcomp= ;; + esac + oIFS=$IFS + IFS=/ + set fnord $file + shift + IFS=$oIFS + + for d + do + test "x$d" = x && continue + + pathcomp=$pathcomp$d + case $pathcomp in + -*) pathcomp=./$pathcomp ;; + esac - pathcomp= - for d - do - pathcomp="$pathcomp$d" - case "$pathcomp" in - -* ) pathcomp=./$pathcomp ;; - esac + if test ! -d "$pathcomp"; then + echo "mkdir $pathcomp" - if test ! -d "$pathcomp"; then - echo "mkdir $pathcomp" + mkdir "$pathcomp" || lasterr=$? - mkdir "$pathcomp" || lasterr=$? + if test ! -d "$pathcomp"; then + errstatus=$lasterr + else + if test ! -z "$dirmode"; then + echo "chmod $dirmode $pathcomp" + lasterr= + chmod "$dirmode" "$pathcomp" || lasterr=$? - if test ! -d "$pathcomp"; then - errstatus=$lasterr - fi - fi + if test ! -z "$lasterr"; then + errstatus=$lasterr + fi + fi + fi + fi - pathcomp="$pathcomp/" - done + pathcomp=$pathcomp/ + done done exit $errstatus -# mkinstalldirs ends here +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End: diff --git a/policy/policyguide.txt b/policy/policyguide.txt index 09bf2e9..f520b9d 100644 --- a/policy/policyguide.txt +++ b/policy/policyguide.txt @@ -191,7 +191,7 @@ $(DIR1) -> $(param1); # It is also possible to do a #============================================================================= # -# Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, # Inc. All rights reserved. # # Linux is a registered trademark of Linus Torvalds. diff --git a/policy/twpol-AIX.txt b/policy/twpol-AIX.txt index 7d4f37c..b2be119 100644 --- a/policy/twpol-AIX.txt +++ b/policy/twpol-AIX.txt @@ -60,13 +60,14 @@ HOSTNAME=; # ############################################################################## -Device = +pugsdr-intlbamcCMSH ; -Dynamic = +pinugtd-srlbamcCMSH ; -Growing = +pinugtdl-srbamcCMSH ; -IgnoreAll = -pinugtsdrlbamcCMSH ; -IgnoreNone = +pinugtsdrbamcCMSH-l ; -ReadOnly = +pinugtsdbmCM-rlacSH ; -Temporary = +pugt ; +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + @@section FS @@ -83,10 +84,10 @@ Temporary = +pugt ; rulename = "Tripwire Binaries", ) { - $(TWBIN)/siggen -> $(ReadOnly) ; - $(TWBIN)/tripwire -> $(ReadOnly) ; - $(TWBIN)/twadmin -> $(ReadOnly) ; - $(TWBIN)/twprint -> $(ReadOnly) ; + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; } # Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases @@ -103,14 +104,14 @@ Temporary = +pugt ; # afterward triggers this rule until a database update is run, since the # database file does not exist before that point. - $(TWDB) -> $(Dynamic) -i ; - $(TWPOL)/tw.pol -> $(ReadOnly) -i ; - $(TWPOL)/tw.cfg -> $(ReadOnly) -i ; - $(TWLKEY)/$(HOSTNAME)-local.key -> $(ReadOnly) ; - $(TWSKEY)/site.key -> $(ReadOnly) ; + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; # don't scan the individual reports - $(TWREPORT) -> $(Dynamic) (recurse=0) ; + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; } ################################################ @@ -124,7 +125,7 @@ Temporary = +pugt ; rulename = "OS Boot and Configuration Files", ) { - /etc -> $(IgnoreNone) -SHa ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; } ################################################### @@ -138,9 +139,9 @@ Temporary = +pugt ; rulename = "Mount Points", ) { - / -> $(ReadOnly) ; - /usr -> $(ReadOnly) ; - /var -> $(ReadOnly) ; + / -> $(SEC_READONLY) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; } ################################################### @@ -154,10 +155,10 @@ Temporary = +pugt ; rulename = "Misc Top-Level Directories", ) { - /lost+found -> $(ReadOnly) ; - /hacmplocal -> $(ReadOnly) ; - /homelocal -> $(ReadOnly) ; - /opt -> $(ReadOnly) ; + /lost+found -> $(SEC_READONLY) ; + /hacmplocal -> $(SEC_READONLY) ; + /homelocal -> $(SEC_READONLY) ; + /opt -> $(SEC_READONLY) ; !/var/adm/csd ; } @@ -172,7 +173,7 @@ Temporary = +pugt ; rulename = "System Devices", ) { - /dev -> $(Device) ; + /dev -> $(SEC_DEVICE) ; } ################################################ @@ -186,10 +187,10 @@ Temporary = +pugt ; rulename = "OS Binaries and Libraries", ) { - /sbin -> $(ReadOnly) ; - /usr/bin -> $(ReadOnly) ; - /usr/lib -> $(ReadOnly) ; - /usr/sbin -> $(ReadOnly) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; } ################################################ @@ -203,11 +204,11 @@ Temporary = +pugt ; rulename = "Root Directory and Files", ) { - #/.dtprofile -> $(Dynamic) ; + #/.dtprofile -> $(SEC_DYNAMIC) ; ! /.netscape/cache ; - /.netscape/history.dat -> $(Dynamic) ; - /.sh_history -> $(Dynamic) ; - #/.Xauthority -> $(ReadOnly) ; + /.netscape/history.dat -> $(SEC_DYNAMIC) ; + /.sh_history -> $(SEC_DYNAMIC) ; + #/.Xauthority -> $(SEC_READONLY) ; } ################################################ @@ -221,8 +222,8 @@ Temporary = +pugt ; rulename = "Temporary Directories", ) { - /tmp -> $(Temporary) ; - /var/tmp -> $(Temporary) ; + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; } ################################################ @@ -251,31 +252,31 @@ Temporary = +pugt ; rulename = "System and Boot Changes", ) { - /etc/es/objrepos -> $(ReadOnly) -SHacm ; - /etc/es/objrepos/HACMPresource -> $(ReadOnly) -SHCMcm ; - /etc/lpp/diagnostics/data -> $(ReadOnly) -SHCMacm ; - /etc/ntp.drift -> $(ReadOnly) -SHiacm ; + /etc/es/objrepos -> $(SEC_READONLY) -SHacm ; + /etc/es/objrepos/HACMPresource -> $(SEC_READONLY) -SHCMcm ; + /etc/lpp/diagnostics/data -> $(SEC_READONLY) -SHCMacm ; + /etc/ntp.drift -> $(SEC_READONLY) -SHiacm ; !/etc/objrepos ; - /etc/security -> $(ReadOnly) -SHacm ; - /usr/es/adm/cluster.log -> $(ReadOnly) -SHCMsbm ; - /usr/es/sbin/cluster/etc/objrepos/active -> $(ReadOnly) -SHim ; + /etc/security -> $(SEC_READONLY) -SHacm ; + /usr/es/adm/cluster.log -> $(SEC_READONLY) -SHCMsbm ; + /usr/es/sbin/cluster/etc/objrepos/active -> $(SEC_READONLY) -SHim ; !/usr/etc/sbin/cluster/history ; - /usr/share/lib/objrepos -> $(ReadOnly) -m ; - /usr/lib/objrepos -> $(ReadOnly) -m ; + /usr/share/lib/objrepos -> $(SEC_READONLY) -m ; + /usr/lib/objrepos -> $(SEC_READONLY) -m ; !/var/adm/SPlogs ; - /var/ha/log -> $(Growing) -i ; + /var/ha/log -> $(SEC_GROWING) -i ; !/var/adm ; !/var/ct ; - #/var/backups -> $(Dynamic) -i ; - #/var/db/host.random -> $(ReadOnly) -mCM ; - #/var/db/locate.database -> $(ReadOnly) -misCM ; - #/var/cron -> $(Growing) -i ; - #/var/log -> $(Growing) -i ; - #/var/run -> $(Dynamic) -i ; - #/var/mail -> $(Growing) ; - #/var/msgs/bounds -> $(ReadOnly) -smbCM ; - #/var/spool/clientmqueue -> $(Temporary) ; - #/var/spool/mqueue -> $(Temporary) ; + #/var/backups -> $(SEC_DYNAMIC) -i ; + #/var/db/host.random -> $(SEC_READONLY) -mCM ; + #/var/db/locate.database -> $(SEC_READONLY) -misCM ; + #/var/cron -> $(SEC_GROWING) -i ; + #/var/log -> $(SEC_GROWING) -i ; + #/var/run -> $(SEC_DYNAMIC) -i ; + #/var/mail -> $(SEC_GROWING) ; + #/var/msgs/bounds -> $(SEC_READONLY) -smbCM ; + #/var/spool/clientmqueue -> $(SEC_TEMPORARY) ; + #/var/spool/mqueue -> $(SEC_TEMPORARY) ; #!/var/tmp/vi.recover ; # perl script periodically removes this } diff --git a/policy/twpol-AROS.txt b/policy/twpol-AROS.txt new file mode 100644 index 0000000..edcb261 --- /dev/null +++ b/policy/twpol-AROS.txt @@ -0,0 +1,132 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for AROS ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + + +############################################################################## + +(rulename="OS Files",) +{ + AROS:System -> $(SEC_READONLY); + AROS:Devs -> $(SEC_READONLY); + AROS:Libs -> $(SEC_READONLY); + AROS:Tools-> $(SEC_READONLY); + AROS:Prefs -> $(SEC_READONLY); + AROS:Utilities -> $(SEC_READONLY); + AROS:WBStartup -> $(SEC_READONLY); +} + +(rulename="Development Tools",) +{ + Work:Development -> $(SEC_READONLY); +} + +(rulename="Extras",) +{ + Work:Extras -> $(SEC_READONLY); +} diff --git a/policy/twpol-Bitrig.txt b/policy/twpol-Bitrig.txt new file mode 100644 index 0000000..0df6110 --- /dev/null +++ b/policy/twpol-Bitrig.txt @@ -0,0 +1,292 @@ + ############################################################################## + # ## +############################################################################## # +# # # +# Tripwire 2.4 policy for Bitrig # # +# updated March 2018 # # +# ## +############################################################################## + + ############################################################################## + # ## +############################################################################## # +# # # +# Global Variable Definitions # # +# # # +# These are defined at install time by the installation script. You may # # +# manually edit these if you are using this file directly and not from the # # +# installation script itself. # # +# ## +############################################################################## + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + + ############################################################################## + # Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + + ######################################## + # ## +######################################## # +# # # +# Tripwire Binaries and Data Files # # +# ## +######################################## + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; + + # In this configuration /usr/local is a symbolic link to /home/local. + # We want to ignore the following directories since they are already + # scanned using the real directory or mount point. Otherwise we see + # duplicates in the reports. + + !/home/local ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Boot and Configuration Files # # +# ## +################################################ +( + rulename = "OS Boot and Configuration Files", +) +{ + /boot -> $(SEC_READONLY) ; + /bsd -> $(SEC_READONLY) ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; +} + + ################################################### + # ## +################################################### # +# # # +# Mount Points # # +# ## +################################################### +( + rulename = "Mount Points", +) +{ + / -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /floppy -> $(SEC_DYNAMIC) ; + /home -> $(SEC_READONLY) ; # Modify as needed + /mnt -> $(SEC_DYNAMIC) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; +} + + ################################################### + # ## +################################################### # +# # # +# Misc Top-Level Directories # # +# ## +################################################### +( + rulename = "Misc Top-Level Directories", +) +{ + /altroot -> $(SEC_DYNAMIC) ; + /stand -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# System Devices # # +# ## +################################################ +( + rulename = "System Devices", +) +{ + /dev -> $(SEC_DEVICE) ; + /dev/fd -> $(SEC_DEVICE) ; + /var/cron/tabs/.sock -> $(SEC_DEVICE) ; + /var/empty/dev/log -> $(SEC_DEVICE) ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Binaries and Libraries # # +# ## +################################################ +( + rulename = "OS Binaries and Libraries", +) +{ + /bin -> $(SEC_READONLY) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/libexec -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/X11R6/bin -> $(SEC_READONLY) ; + /usr/X11R6/lib -> $(SEC_READONLY) ; +} + ################################################ + # ## +################################################ # +# # # +# Usr Local Files # # +# ## +################################################ +#OK( + #OKrulename = "Usr Local Files", +#OK) +#OK{ + #OK/usr/local -> $(SEC_READONLY) ; + #OK/usr/local/bin -> $(SEC_READONLY) ; + #OK/usr/local/doc -> $(SEC_READONLY) ; + #OK/usr/local/etc -> $(SEC_READONLY) ; + #OK/usr/local/include -> $(SEC_READONLY) ; + #OK/usr/local/info -> $(SEC_READONLY) ; + #OK/usr/local/lib -> $(SEC_READONLY) ; + #OK/usr/local/libdata -> $(SEC_READONLY) ; + #OK/usr/local/libexec -> $(SEC_READONLY) ; + #OK/usr/local/man -> $(SEC_READONLY) ; + #OK/usr/local/sbin -> $(SEC_READONLY) ; + #OK/usr/local/share -> $(SEC_READONLY) ; + #OK/usr/local/src -> $(SEC_READONLY) ; +#OK} + + ################################################ + # ## +################################################ # +# # # +# Root Directory and Files # # +# ## +################################################ +( + rulename = "Root Directory and Files", +) +{ + /root -> $(SEC_IGNORE_NONE) -SHa ; + /root/.cshrc -> $(SEC_DYNAMIC) ; + /root/.profile -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# Temporary Directories # # +# ## +################################################ +( + rulename = "Temporary Directories", +) +{ + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; +} + + ################################################ + # ## +################################################ # +# # # +# System and Boot Changes # # +# ## +################################################ +( + rulename = "System and Boot Changes", +) +{ + /var/backups -> $(SEC_DYNAMIC) -i ; + /var/db/host.random -> $(SEC_READONLY) -mCM ; + /var/cron -> $(SEC_GROWING) -i ; + /var/log -> $(SEC_GROWING) -i ; + /var/run -> $(SEC_DYNAMIC) -i ; + /var/mail -> $(SEC_GROWING) ; + /var/msgs/bounds -> $(SEC_READONLY) -smbCM ; + /var/spool/clientmqueue -> $(SEC_TEMPORARY) ; + /var/spool/mqueue -> $(SEC_TEMPORARY) ; +} + +# +# $Id: twpol-OpenBSD.txt,v 1.2 2004/05/14 21:56:21 pherman Exp $ +# diff --git a/policy/twpol-Cygwin.txt b/policy/twpol-Cygwin.txt new file mode 100644 index 0000000..df6682c --- /dev/null +++ b/policy/twpol-Cygwin.txt @@ -0,0 +1,163 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for Cygwin ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + +############################################################################## + +(rulename="Binary files",) +{ + /bin -> $(SEC_READONLY) -a; + /usr/bin -> $(SEC_READONLY) -a; + /usr/local/bin -> $(SEC_READONLY) -a; +} + +(rulename="Development",) +{ + /usr/x86_64-pc-cygwin -> $(SEC_READONLY) -a; +} + +(rulename="Libexec",) +{ + /usr/libexec -> $(SEC_READONLY) -a; +} + +(rulename="Admin binaries",) +{ + /sbin -> $(SEC_READONLY) -a; + /usr/sbin -> $(SEC_READONLY) -a; +} + +(rulename="Libraries",) +{ + /lib -> $(SEC_READONLY) -a; + /usr/lib -> $(SEC_READONLY) -a; + /usr/local/lib -> $(SEC_READONLY) -a; +} + +(rulename="Etc",) +{ + /etc -> $(SEC_READONLY) -a; + /usr/local/etc -> $(SEC_READONLY) -a; +} + +(rulename="Dev",) +{ + /dev -> $(SEC_DEVICE); +} + +(rulename="Tmp",) +{ + /tmp -> $(SEC_TEMPORARY); + /var/tmp -> $(SEC_TEMPORARY); + /usr/tmp -> $(SEC_TEMPORARY); +} + +(rulename="Log",) +{ + /var/log -> $(SEC_GROWING); +} diff --git a/policy/twpol-Darwin.txt b/policy/twpol-Darwin.txt index 9443209..eb73510 100644 --- a/policy/twpol-Darwin.txt +++ b/policy/twpol-Darwin.txt @@ -2,8 +2,8 @@ # ## ############################################################################## # # # # -# Policy file for Mac OS X # # -# September 3, 2003 # # +# Tripwire 2.4 policy for Mac OS X # # +# updated March 2018 # # # ## ############################################################################## @@ -28,7 +28,7 @@ TWDB=; TWSKEY=; TWLKEY=; TWREPORT=; -#USER1=frodo ; +HOSTNAME=; ############################################################################## @@ -67,9 +67,10 @@ SEC_DYNAMIC = +pinugt-dsrlbamcCMSH ; SEC_READONLY = +pinugtsbmCM-drlacSH ; SEC_GROWING = +pinugtl-dsrbamcCMSH ; -IgnoreAll = -pinugtsdrlbamcCMSH ; -IgnoreNone = +pinugtsdrbamcCMSH-l ; -Temporary = +pugt ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_TEMPORARY = +pugt ; + @@section FS @@ -109,7 +110,7 @@ Temporary = +pugt ; $(TWDB) -> $(SEC_DYNAMIC) -i ; $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; - $(TWLKEY)/local.key -> $(SEC_READONLY) ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; $(TWSKEY)/site.key -> $(SEC_READONLY) ; # don't scan the individual reports @@ -129,14 +130,14 @@ Temporary = +pugt ; rulename = "OS Boot and Configuration Files", severity=100 ) { - /mach.sym -> $(SEC_READONLY)-im ; + #/mach.sym -> $(SEC_READONLY)-im ; /mach_kernel -> $(SEC_READONLY) ; /private/etc -> $(SEC_READONLY)-m ; #/private/etc/appletalk.cfg -> $(SEC_READONLY)-im ; #/private/etc/appletalk.nvram.en0 -> $(SEC_DYNAMIC) ; /private/etc/cups/certs -> $(SEC_DYNAMIC) -i(recurse=0) ; - /private/etc/smb.conf -> $(SEC_READONLY)-im ; + #/private/etc/smb.conf -> $(SEC_READONLY)-im ; /Library -> $(SEC_READONLY) ; /System -> $(SEC_READONLY) ; @@ -182,8 +183,6 @@ Temporary = +pugt ; ) { /dev -> $(SEC_DEVICE)(recurse=0) ; - #/private/var/cron/tabs/.sock -> $(SEC_DEVICE) ; - } ################################################ @@ -203,8 +202,8 @@ Temporary = +pugt ; /usr/lib -> $(SEC_READONLY) ; /usr/libexec -> $(SEC_READONLY) ; /usr/sbin -> $(SEC_READONLY) ; - #/usr/X11R6 -> $(SEC_READONLY)(recurse=2) ; # May not be present - #/usr/X11R6/man -> $(SEC_DYNAMIC)-i(recurse=1) ; # May not be present + /usr/X11 -> $(SEC_READONLY)(recurse=2) ; # May not be present + #/usr/X11/man -> $(SEC_DYNAMIC)-i(recurse=1) ; # May not be present /usr/share -> $(SEC_READONLY) ; /usr/share/man -> $(SEC_DYNAMIC)-i(recurse=1) ; @@ -223,12 +222,6 @@ Temporary = +pugt ; ) { /Applications -> $(SEC_READONLY)-im(recurse=2) ; - "/Applications (Mac OS 9)" -> $(SEC_READONLY) ; - - - !/Applications/Internet/P2P/Downloads ; - !/Applications/Games/"Warcraft III Folder"/Save ; - } ################################################ @@ -243,10 +236,19 @@ Temporary = +pugt ; ) { /usr/local -> $(SEC_READONLY) ; - #/usr/local/bin -> $(SEC_READONLY) ; + /usr/local/sbin -> $(SEC_READONLY) ; + /usr/local/bin -> $(SEC_READONLY) ; + /usr/local/include -> $(SEC_READONLY) ; + /usr/local/opt -> $(SEC_READONLY) ; + /usr/local/libexec -> $(SEC_READONLY) ; + /usr/local/lib -> $(SEC_READONLY) ; /usr/local/etc -> $(SEC_READONLY) ; - #/usr/local/sbin -> $(SEC_READONLY) ; - #/usr/local/share -> $(SEC_READONLY) ; + /usr/local/share -> $(SEC_READONLY) ; + /usr/local/man -> $(SEC_READONLY) ; + /usr/local/Frameworks -> $(SEC_READONLY) ; + # Homebrew + /usr/local/.git -> $(SEC_READONLY) ; + /usr/local/Cellar -> $(SEC_READONLY) ; } @@ -263,24 +265,26 @@ Temporary = +pugt ; { /private/tmp -> $(SEC_DYNAMIC)-in(recurse=0) ; + /private/tftpboot -> $(SEC_READONLY)-i ; + /private/var -> $(SEC_READONLY)-i ; /private/var/backups -> $(SEC_READONLY)-imc(severity=100) ; #/private/var/backups/local.nidump -> $(SEC_DYNAMIC) -i(severity=100) ; #/private/var/cron -> $(SEC_DYNAMIC) -i ; /private/var/db -> $(SEC_READONLY)-im ; /private/var/db/BootCache.playlist -> $(SEC_DYNAMIC) -i ; - /private/var/db/netinfo/local.nidb/Store.384 -> $(SEC_READONLY)-imc(severity=100) ; + #/private/var/db/netinfo/local.nidb/Store.384 -> $(SEC_READONLY)-imc(severity=100) ; #/private/var/db/netinfo/local.nidb/Store.672 -> $(SEC_READONLY)-imc(severity=100) ; - /private/var/db/prebindOnDemandBadFiles -> $(SEC_DYNAMIC) -i ; + #/private/var/db/prebindOnDemandBadFiles -> $(SEC_DYNAMIC) -i ; /private/var/log -> $(SEC_DYNAMIC) -i ; #/private/var/mail -> $(SEC_DYNAMIC) ; /private/var/msgs/bounds -> $(SEC_READONLY)-smbCM ; /private/var/root/Library/Caches -> $(SEC_DYNAMIC) -i ; /private/var/run -> $(SEC_DYNAMIC) -i(rulename="Running Services") ; #/private/var/slp.regfile -> $(SEC_READONLY)-im ; - /private/var/spool/clientmqueue -> $(SEC_DYNAMIC)(recurse=0) ; + #/private/var/spool/clientmqueue -> $(SEC_DYNAMIC)(recurse=0) ; /private/var/spool/mqueue -> $(SEC_DYNAMIC)(recurse=0) ; - /private/var/spool/lock -> $(SEC_DYNAMIC) -i(recurse=1) ; + #/private/var/spool/lock -> $(SEC_DYNAMIC) -i(recurse=1) ; /private/var/spool/cups -> $(SEC_DYNAMIC) -i(recurse=0) ; /private/var/tmp -> $(SEC_DYNAMIC) -i(recurse=0) ; /private/var/vm -> $(SEC_DYNAMIC)(recurse=0) ; @@ -294,37 +298,19 @@ Temporary = +pugt ; !/private/var/db/dhcpd_leases ; !/private/var/db/locate.database ; !/private/var/db/SystemEntropyCache ; + !/private/var/db/mds/messages/se_SecurityMessages ; !/private/var/db/samba/secrets.tdb ; - -} - - - - ################################################ - # ## -################################################ # -# # # -# Classic Environment # # -# ## -################################################ -( - rulename = "Classic Environment", severity=100 -) -{ - - /"System Folder" -> $(SEC_READONLY) ; - /"System Folder"/Preferences -> $(SEC_DYNAMIC)-i(recurse=0) ; - /"System Folder"/Extensions -> $(SEC_READONLY)-im ; - /"System Folder/Apple Menu Items" -> $(SEC_READONLY)-im(recurse=0) ; - /"System Folder"/Clipboard -> $(SEC_DYNAMIC) ; - - !/"System Folder"/VolumeNameIconPict ; - + !/private/var/db/ntp.drift ; + !/private/var/folders ; + !/private/var/vm/sleepimage ; + !/private/var/vm/swap0 ; + !/private/var/vm/swap[1-9][0-9]* ; + # Sophos + !/Library/Caches/com.sophos.sau ; + !/Library/Caches/com.sophos.sxld ; } - - ################################################### # ## ################################################### # @@ -375,7 +361,3 @@ Temporary = +pugt ; #!"/Users/$(USER1)/.lpoptions" ; #!"/Users/$(USER1)/.Trash" ; } - -# -# JTI -# diff --git a/policy/twpol-DragonFly.txt b/policy/twpol-DragonFly.txt new file mode 100644 index 0000000..a0c0a3e --- /dev/null +++ b/policy/twpol-DragonFly.txt @@ -0,0 +1,664 @@ +# +# Policy file for DragonFly BSD +# (adapted from FreeBSD policy) +# +# $FreeBSD: ports/security/tripwire/files/twpol.txt,v 1.2 2002/03/04 16:55:21 cy Exp $ +# $Id: twpol-FreeBSD.txt,v 1.1 2003/06/08 02:00:06 pherman Exp $ + +# +# This is the example Tripwire Policy file. It is intended as a place to +# start creating your own custom Tripwire Policy file. Referring to it as +# well as the Tripwire Policy Guide should give you enough information to +# make a good custom Tripwire Policy file that better covers your +# configuration and security needs. A text version of this policy file is +# called twpol.txt. +# +# Note that this file is tuned to an install of FreeBSD using +# buildworld. If run unmodified, this file should create no errors on +# database creation, or violations on a subsiquent integrity check. +# However it is impossible for there to be one policy file for all machines, +# so this existing one errs on the side of security. Your FreeBSD +# configuration will most likey differ from the one our policy file was +# tuned to, and will therefore require some editing of the default +# Tripwire Policy file. +# +# The example policy file is best run with 'Loose Directory Checking' +# enabled. Set LOOSEDIRECTORYCHECKING=TRUE in the Tripwire Configuration +# file. +# +# Email support is not included and must be added to this file. +# Add the 'emailto=' to the rule directive section of each rule (add a comma +# after the 'severity=' line and add an 'emailto=' and include the email +# addresses you want the violation reports to go to). Addresses are +# semi-colon delimited. +# + + + +# +# Global Variable Definitions +# +# These are defined at install time by the installation script. You may +# Manually edit these if you are using this file directly and not from the +# installation script itself. +# + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +@@section FS +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +SEC_CRIT = $(SEC_IGNORE_NONE)-SHa ; # Critical files that cannot change +SEC_SUID = $(SEC_IGNORE_NONE)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(SEC_READONLY) ; # Binaries that should not change +SEC_CONFIG = $(SEC_DYNAMIC) ; # Config files that are changed infrequently but accessed often +SEC_TTY = $(SEC_DYNAMIC)-ugp ; # Tty files that change ownership at login +SEC_LOG = $(SEC_GROWING) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = $(SEC_TEMPORARY) ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability + + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", + severity = $(SIG_HI) +) +{ + $(TWBIN)/siggen -> $(SEC_BIN) ; + $(TWBIN)/tripwire -> $(SEC_BIN) ; + $(TWBIN)/twadmin -> $(SEC_BIN) ; + $(TWBIN)/twprint -> $(SEC_BIN) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", + severity = $(SIG_HI) +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_CONFIG) -i ; + $(TWPOL)/tw.pol -> $(SEC_BIN) -i ; + $(TWPOL)/tw.cfg -> $(SEC_BIN) -i ; + $(TWPOL)/twcfg.txt -> $(SEC_BIN) ; + $(TWPOL)/twpol.txt -> $(SEC_BIN) ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_BIN) ; + $(TWSKEY)/site.key -> $(SEC_BIN) ; + + #don't scan the individual reports + $(TWREPORT) -> $(SEC_CONFIG) (recurse=0) ; +} + + +# Tripwire HQ Connector Binaries +#( +# rulename = "Tripwire HQ Connector Binaries", +# severity = $(SIG_HI) +#) +#{ +# $(TWBIN)/hqagent -> $(SEC_BIN) ; +#} +# +# Tripwire HQ Connector - Configuration Files, Keys, and Logs + +# +# Note: File locations here are different than in a stock HQ Connector +# installation. This is because Tripwire 2.3 uses a different path +# structure than Tripwire 2.2.1. +# +# You may need to update your HQ Agent configuation file (or this policy +# file) to correct the paths. We have attempted to support the FHS standard +# here by placing the HQ Agent files similarly to the way Tripwire 2.3 +# places them. +# + +#( +# rulename = "Tripwire HQ Connector Data Files", +# severity = $(SIG_HI) +#) +#{ +# +# # NOTE: Removing the inode attribute because when Tripwire creates a backup +# # it does so by renaming the old file and creating a new one (which will +# # have a new inode number). Leaving inode turned on for keys, which +# # shouldn't ever change. +# +# +# $(TWBIN)/agent.cfg -> $(SEC_BIN) -i ; +# $(TWLKEY)/authentication.key -> $(SEC_BIN) ; +# $(TWDB)/tasks.dat -> $(SEC_CONFIG) ; +# $(TWDB)/schedule.dat -> $(SEC_CONFIG) ; +# +# # Uncomment if you have agent logging enabled. +# #/var/log/tripwire/agent.log -> $(SEC_LOG) ; +#} + + + +# Commonly accessed directories that should remain static with regards to owner and group +( + rulename = "Invariant Directories", + severity = $(SIG_MED) +) +{ + / -> $(SEC_INVARIANT) (recurse = false) ; + /home -> $(SEC_INVARIANT) (recurse = false) ; +} + +# +# First, root's "home" +# + +( + rulename = "Root's home", + severity = $(SIG_HI) +) +{ + # /.rhosts -> $(SEC_CRIT) ; + /.profile -> $(SEC_CRIT) ; + /.cshrc -> $(SEC_CRIT) ; + /.login -> $(SEC_CRIT) ; + # /.exrc -> $(SEC_CRIT) ; + # /.logout -> $(SEC_CRIT) ; + # /.forward -> $(SEC_CRIT) ; + /root -> $(SEC_CRIT) (recurse = true) ; + !/root/.history ; + !/root/.bash_history ; + # !/root/.lsof_SYSTEM_NAME ; # Uncomment if lsof is installed +} + + +# +# FreeBSD Kernel +# + +( + rulename = "FreeBSD Kernel", + severity = $(SIG_HI) +) +{ + /kernel -> $(SEC_CRIT) ; + /kernel.old -> $(SEC_CRIT) ; + /kernel.GENERIC -> $(SEC_CRIT) ; +} + + +# +# FreeBSD Modules +# + +( + rulename = "FreeBSD Modules", + severity = $(SIG_HI) +) +{ + /modules -> $(SEC_CRIT) (recurse = true) ; + /modules.old -> $(SEC_CRIT) (recurse = true) ; + # /lkm -> $(SEC_CRIT) (recurse = true) ; # uncomment if using lkm kld +} + + +# +# System Administration Programs +# + +( + rulename = "System Administration Programs", + severity = $(SIG_HI) +) +{ + /sbin -> $(SEC_CRIT) (recurse = true) ; + /usr/sbin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# User Utilities +# + +( + rulename = "User Utilities", + severity = $(SIG_HI) +) +{ + /bin -> $(SEC_CRIT) (recurse = true) ; + /usr/bin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# /dev +# + +( + rulename = "/dev", + severity = $(SIG_HI) +) +{ + /dev -> $(Device) (recurse = true) ; + !/dev/vga ; + !/dev/dri ; + /dev/console -> $(SEC_TTY) ; + /dev/ttyv0 -> $(SEC_TTY) ; + /dev/ttyv1 -> $(SEC_TTY) ; + /dev/ttyv2 -> $(SEC_TTY) ; + /dev/ttyv3 -> $(SEC_TTY) ; + /dev/ttyv4 -> $(SEC_TTY) ; + /dev/ttyv5 -> $(SEC_TTY) ; + /dev/ttyv6 -> $(SEC_TTY) ; + /dev/ttyv7 -> $(SEC_TTY) ; + /dev/ttyp0 -> $(SEC_TTY) ; + /dev/ttyp1 -> $(SEC_TTY) ; + /dev/ttyp2 -> $(SEC_TTY) ; + /dev/ttyp3 -> $(SEC_TTY) ; + /dev/ttyp4 -> $(SEC_TTY) ; + /dev/ttyp5 -> $(SEC_TTY) ; + /dev/ttyp6 -> $(SEC_TTY) ; + /dev/ttyp7 -> $(SEC_TTY) ; + /dev/ttyp8 -> $(SEC_TTY) ; + /dev/ttyp9 -> $(SEC_TTY) ; + /dev/ttypa -> $(SEC_TTY) ; + /dev/ttypb -> $(SEC_TTY) ; + /dev/ttypc -> $(SEC_TTY) ; + /dev/ttypd -> $(SEC_TTY) ; + /dev/ttype -> $(SEC_TTY) ; + /dev/ttypf -> $(SEC_TTY) ; + /dev/ttypg -> $(SEC_TTY) ; + /dev/ttyph -> $(SEC_TTY) ; + /dev/ttypi -> $(SEC_TTY) ; + /dev/ttypj -> $(SEC_TTY) ; + /dev/ttypl -> $(SEC_TTY) ; + /dev/ttypm -> $(SEC_TTY) ; + /dev/ttypn -> $(SEC_TTY) ; + /dev/ttypo -> $(SEC_TTY) ; + /dev/ttypp -> $(SEC_TTY) ; + /dev/ttypq -> $(SEC_TTY) ; + /dev/ttypr -> $(SEC_TTY) ; + /dev/ttyps -> $(SEC_TTY) ; + /dev/ttypt -> $(SEC_TTY) ; + /dev/ttypu -> $(SEC_TTY) ; + /dev/ttypv -> $(SEC_TTY) ; + /dev/cuaa0 -> $(SEC_TTY) ; # modem +} + + +# +# /etc +# + +( + rulename = "/etc", + severity = $(SIG_HI) +) +{ + /etc -> $(SEC_CRIT) (recurse = true) ; + # /etc/mail/aliases -> $(SEC_CONFIG) ; + /etc/dumpdates -> $(SEC_CONFIG) ; + /etc/motd -> $(SEC_CONFIG) ; + !/etc/ppp/connect-errors ; + /etc/skeykeys -> $(SEC_CONFIG) ; + # Uncomment the following 4 lines if your password file does not change + # /etc/passwd -> $(SEC_CONFIG) ; + # /etc/master.passwd -> $(SEC_CONFIG) ; + # /etc/pwd.db -> $(SEC_CONFIG) ; + # /etc/spwd.db -> $(SEC_CONFIG) ; +} + + +# +# Copatibility (Linux) +# + +( + rulename = "Linux Compatibility", + severity = $(SIG_HI) +) +{ + /compat -> $(SEC_CRIT) (recurse = true) ; +# +# Uncomment the following if Linux compatibility is used. Replace +# HOSTNAME1 and HOSTNAME2 with the hosts that have Linux emulation port +# installed. +# +#@@ifhost HOSTNAME1 || HOSTNAME2 +# /compat/linux/etc -> $(SEC_INVARIANT) (recurse = false) ; +# /compat/linux/etc/X11 -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/pam.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/profile.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/real -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/bashrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/csh.login -> $(SEC_CONFIG) ; +# /compat/linux/etc/host.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.allow -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.deny -> $(SEC_CONFIG) ; +# /compat/linux/etc/info-dir -> $(SEC_CONFIG) ; +# /compat/linux/etc/inputrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/ld.so.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/nsswitch.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/profile -> $(SEC_CONFIG) ; +# /compat/linux/etc/redhat-release -> $(SEC_CONFIG) ; +# /compat/linux/etc/rpc -> $(SEC_CONFIG) ; +# /compat/linux/etc/securetty -> $(SEC_CONFIG) ; +# /compat/linux/etc/shells -> $(SEC_CONFIG) ; +# /compat/linux/etc/termcap -> $(SEC_CONFIG) ; +# /compat/linux/etc/yp.conf -> $(SEC_CONFIG) ; +# !/compat/linux/etc/ld.so.cache ; +# !/compat/linux/var/spool/mail ; +#@@endif +} + + +# +# Libraries, include files, and other system files +# + +( + rulename = "Libraries, include files, and other system files", + severity = $(SIG_HI) +) +{ + /usr/include -> $(SEC_CRIT) (recurse = true) ; + /usr/lib -> $(SEC_CRIT) (recurse = true) ; + /usr/libdata -> $(SEC_CRIT) (recurse = true) ; + /usr/libexec -> $(SEC_CRIT) (recurse = true) ; + /usr/share -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man -> $(SEC_CONFIG) ; + !/usr/share/man/whatis ; + !/usr/share/man/.glimpse_filenames ; + !/usr/share/man/.glimpse_filenames_index ; + !/usr/share/man/.glimpse_filetimes ; + !/usr/share/man/.glimpse_filters ; + !/usr/share/man/.glimpse_index ; + !/usr/share/man/.glimpse_messages ; + !/usr/share/man/.glimpse_partitions ; + !/usr/share/man/.glimpse_statistics ; + !/usr/share/man/.glimpse_turbo ; + /usr/share/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/man/cat1 ; + ! /usr/share/man/cat2 ; + ! /usr/share/man/cat3 ; + ! /usr/share/man/cat4 ; + ! /usr/share/man/cat5 ; + ! /usr/share/man/cat6 ; + ! /usr/share/man/cat7 ; + ! /usr/share/man/cat8 ; + ! /usr/share/man/cat9 ; + ! /usr/share/man/catl ; + ! /usr/share/man/catn ; + /usr/share/perl/man -> $(SEC_CONFIG) ; + !/usr/share/perl/man/whatis ; + !/usr/share/perl/man/.glimpse_filenames ; + !/usr/share/perl/man/.glimpse_filenames_index ; + !/usr/share/perl/man/.glimpse_filetimes ; + !/usr/share/perl/man/.glimpse_filters ; + !/usr/share/perl/man/.glimpse_index ; + !/usr/share/perl/man/.glimpse_messages ; + !/usr/share/perl/man/.glimpse_partitions ; + !/usr/share/perl/man/.glimpse_statistics ; + !/usr/share/perl/man/.glimpse_turbo ; + /usr/share/perl/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/perl/man/cat3 ; + /usr/local/lib/perl5/5.00503/man -> $(SEC_CONFIG) ; + ! /usr/local/lib/perl5/5.00503/man/whatis ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filters ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filetimes ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_messages ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_statistics ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_index ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_turbo ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_partitions ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames_index ; + /usr/local/lib/perl5/5.00503/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/lib/perl5/5.00503/man/cat3 ; +} + + +# +# X11R6 +# + +( + rulename = "X11R6", + severity = $(SIG_HI) +) +{ + /usr/X11R6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/lib/X11/xdm -> $(SEC_CONFIG) (recurse = true) ; + !/usr/X11R6/lib/X11/xdm/xdm-errors ; + !/usr/X11R6/lib/X11/xdm/authdir/authfiles ; + !/usr/X11R6/lib/X11/xdm/xdm-pid ; + /usr/X11R6/lib/X11/xkb/compiled -> $(SEC_CONFIG) (recurse = true) ; + /usr/X11R6/man -> $(SEC_CONFIG) ; + !/usr/X11R6/man/whatis ; + !/usr/X11R6/man/.glimpse_filenames ; + !/usr/X11R6/man/.glimpse_filenames_index ; + !/usr/X11R6/man/.glimpse_filetimes ; + !/usr/X11R6/man/.glimpse_filters ; + !/usr/X11R6/man/.glimpse_index ; + !/usr/X11R6/man/.glimpse_messages ; + !/usr/X11R6/man/.glimpse_partitions ; + !/usr/X11R6/man/.glimpse_statistics ; + !/usr/X11R6/man/.glimpse_turbo ; + /usr/X11R6/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/X11R6/man/cat1 ; + ! /usr/X11R6/man/cat2 ; + ! /usr/X11R6/man/cat3 ; + ! /usr/X11R6/man/cat4 ; + ! /usr/X11R6/man/cat5 ; + ! /usr/X11R6/man/cat6 ; + ! /usr/X11R6/man/cat7 ; + ! /usr/X11R6/man/cat8 ; + ! /usr/X11R6/man/cat9 ; + ! /usr/X11R6/man/catl ; + ! /usr/X11R6/man/catn ; +} + + +# +# sources +# + +( + rulename = "Sources", + severity = $(SIG_HI) +) +{ + /usr/src -> $(SEC_CRIT) (recurse = true) ; + /usr/src/sys/compile -> $(SEC_CONFIG) (recurse = false) ; +} + + +# +# NIS +# + +( + rulename = "NIS", + severity = $(SIG_HI) +) +{ + /var/yp -> $(SEC_CRIT) (recurse = true) ; + !/var/yp/binding ; +} + + +# +# Temporary directories +# +( + rulename = "Temporary directories", + recurse = false, + severity = $(SIG_LOW) +) +{ + /usr/tmp -> $(SEC_INVARIANT) ; + /var/tmp -> $(SEC_INVARIANT) ; + /var/preserve -> $(SEC_INVARIANT) ; + /tmp -> $(SEC_INVARIANT) ; +} + +# +# Local files +# + +( + rulename = "Local files", + severity = $(SIG_MED) +) +{ + /usr/local/bin -> $(SEC_BIN) (recurse = true) ; + /usr/local/sbin -> $(SEC_BIN) (recurse = true) ; + /usr/local/etc -> $(SEC_BIN) (recurse = true) ; + /usr/local/lib -> $(SEC_BIN) (recurse = true ) ; + /usr/local/libexec -> $(SEC_BIN) (recurse = true ) ; + /usr/local/share -> $(SEC_BIN) (recurse = true ) ; + /usr/local/man -> $(SEC_CONFIG) ; + !/usr/local/man/whatis ; + !/usr/local/man/.glimpse_filenames ; + !/usr/local/man/.glimpse_filenames_index ; + !/usr/local/man/.glimpse_filetimes ; + !/usr/local/man/.glimpse_filters ; + !/usr/local/man/.glimpse_index ; + !/usr/local/man/.glimpse_messages ; + !/usr/local/man/.glimpse_partitions ; + !/usr/local/man/.glimpse_statistics ; + !/usr/local/man/.glimpse_turbo ; + /usr/local/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/man/cat1 ; + ! /usr/local/man/cat2 ; + ! /usr/local/man/cat3 ; + ! /usr/local/man/cat4 ; + ! /usr/local/man/cat5 ; + ! /usr/local/man/cat6 ; + ! /usr/local/man/cat7 ; + ! /usr/local/man/cat8 ; + ! /usr/local/man/cat9 ; + ! /usr/local/man/catl ; + ! /usr/local/man/catn ; + /usr/local/krb5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man -> $(SEC_CONFIG) ; + !/usr/local/krb5/man/whatis ; + !/usr/local/krb5/man/.glimpse_filenames ; + !/usr/local/krb5/man/.glimpse_filenames_index ; + !/usr/local/krb5/man/.glimpse_filetimes ; + !/usr/local/krb5/man/.glimpse_filters ; + !/usr/local/krb5/man/.glimpse_index ; + !/usr/local/krb5/man/.glimpse_messages ; + !/usr/local/krb5/man/.glimpse_partitions ; + !/usr/local/krb5/man/.glimpse_statistics ; + !/usr/local/krb5/man/.glimpse_turbo ; + /usr/local/krb5/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/krb5/man/cat1 ; + ! /usr/local/krb5/man/cat2 ; + ! /usr/local/krb5/man/cat3 ; + ! /usr/local/krb5/man/cat4 ; + ! /usr/local/krb5/man/cat5 ; + ! /usr/local/krb5/man/cat6 ; + ! /usr/local/krb5/man/cat7 ; + ! /usr/local/krb5/man/cat8 ; + ! /usr/local/krb5/man/cat9 ; + ! /usr/local/krb5/man/catl ; + ! /usr/local/krb5/man/catn ; + /usr/local/www -> $(SEC_CONFIG) (recurse = true) ; +} + + +( + rulename = "Security Control", + severity = $(SIG_HI) +) +{ + /etc/group -> $(SEC_CRIT) ; + /etc/crontab -> $(SEC_CRIT) ; +} + +#============================================================================= +# +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Inc. in the United States and other countries. All rights reserved. +# +# FreeBSD is a registered trademark of the FreeBSD Project Inc. +# +# UNIX is a registered trademark of The Open Group. +# +#============================================================================= +# +# Permission is granted to make and distribute verbatim copies of this document +# provided the copyright notice and this permission notice are preserved on all +# copies. +# +# Permission is granted to copy and distribute modified versions of this +# document under the conditions for verbatim copying, provided that the entire +# resulting derived work is distributed under the terms of a permission notice +# identical to this one. +# +# Permission is granted to copy and distribute translations of this document +# into another language, under the above conditions for modified versions, +# except that this permission notice may be stated in a translation approved by +# Tripwire, Inc. +# +# DCM diff --git a/policy/twpol-FreeBSD.txt b/policy/twpol-FreeBSD.txt index 351a320..68b3ad7 100644 --- a/policy/twpol-FreeBSD.txt +++ b/policy/twpol-FreeBSD.txt @@ -53,16 +53,24 @@ TWREPORT=; HOSTNAME=; @@section FS -SEC_CRIT = $(IgnoreNone)-SHa ; # Critical files that cannot change -SEC_SUID = $(IgnoreNone)-SHa ; # Binaries with the SUID or SGID flags set -SEC_BIN = $(ReadOnly) ; # Binaries that should not change -SEC_CONFIG = $(Dynamic) ; # Config files that are changed infrequently but accessed often -SEC_TTY = $(Dynamic)-ugp ; # Tty files that change ownership at login -SEC_LOG = $(Growing) ; # Files that grow, but that should never change ownership -SEC_INVARIANT = +tpug ; # Directories that should never change permission or ownership -SIG_LOW = 33 ; # Non-critical files that are of minimal security impact -SIG_MED = 66 ; # Non-critical files that are of significant security impact -SIG_HI = 100 ; # Critical files that are significant points of vulnerability +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +SEC_CRIT = $(SEC_IGNORE_NONE)-SHa ; # Critical files that cannot change +SEC_SUID = $(SEC_IGNORE_NONE)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(SEC_READONLY) ; # Binaries that should not change +SEC_CONFIG = $(SEC_DYNAMIC) ; # Config files that are changed infrequently but accessed often +SEC_TTY = $(SEC_DYNAMIC)-ugp ; # Tty files that change ownership at login +SEC_LOG = $(SEC_GROWING) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = $(SEC_TEMPORARY) ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability # Tripwire Binaries @@ -629,7 +637,7 @@ SIG_HI = 100 ; # Critical files that are significant point #============================================================================= # -# Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, # Inc. in the United States and other countries. All rights reserved. # # FreeBSD is a registered trademark of the FreeBSD Project Inc. diff --git a/policy/twpol-GENERIC.txt b/policy/twpol-GENERIC.txt index e30ae4c..cbf0cdb 100644 --- a/policy/twpol-GENERIC.txt +++ b/policy/twpol-GENERIC.txt @@ -65,15 +65,24 @@ TWREPORT=; HOSTNAME=; @@section FS -SEC_CRIT = $(IgnoreNone)-SHa ; # Critical files that cannot change -SEC_SUID = $(IgnoreNone)-SHa ; # Binaries with the SUID or SGID flags set -SEC_BIN = $(ReadOnly) ; # Binaries that should not change -SEC_CONFIG = $(Dynamic) ; # Config files that are changed infrequently but accessed often -SEC_LOG = $(Growing) ; # Files that grow, but that should never change ownership -SEC_INVARIANT = +tpug ; # Directories that should never change permission or ownership -SIG_LOW = 33 ; # Non-critical files that are of minimal security impact -SIG_MED = 66 ; # Non-critical files that are of significant security impact -SIG_HI = 100 ; # Critical files that are significant points of vulnerability +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +SEC_CRIT = $(SEC_IGNORE_NONE)-SHa ; # Critical files that cannot change +SEC_SUID = $(SEC_IGNORE_NONE)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(SEC_READONLY) ; # Binaries that should not change +SEC_CONFIG = $(SEC_DYNAMIC) ; # Config files that are changed infrequently but accessed often +SEC_TTY = $(SEC_DYNAMIC)-ugp ; # Tty files that change ownership at login +SEC_LOG = $(SEC_GROWING) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = $(SEC_TEMPORARY) ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability # Tripwire Binaries @@ -114,56 +123,6 @@ SIG_HI = 100 ; # Critical files that are significant point } -# Tripwire HQ Connector Binaries -#( -# rulename = "Tripwire HQ Connector Binaries", -# severity = $(SIG_HI) -#) -#{ -# $(TWBIN)/hqagent -> $(SEC_BIN) ; -#} -# -# Tripwire HQ Connector - Configuration Files, Keys, and Logs - - ############################################################################## - # ## -############################################################################## # -# # # -# Note: File locations here are different than in a stock HQ Connector # # -# installation. This is because Tripwire 2.3 uses a different path # # -# structure than Tripwire 2.2.1. # # -# # # -# You may need to update your HQ Agent configuation file (or this policy # # -# file) to correct the paths. We have attempted to support the FHS standard # # -# here by placing the HQ Agent files similarly to the way Tripwire 2.3 # # -# places them. # # -# ## -############################################################################## - -#( -# rulename = "Tripwire HQ Connector Data Files", -# severity = $(SIG_HI) -#) -#{ -# ############################################################################# -# ############################################################################## -# # NOTE: Removing the inode attribute because when Tripwire creates a backup ## -# # it does so by renaming the old file and creating a new one (which will ## -# # have a new inode number). Leaving inode turned on for keys, which ## -# # shouldn't ever change. ## -# ############################################################################# -# -# $(TWBIN)/agent.cfg -> $(SEC_BIN) -i ; -# $(TWLKEY)/authentication.key -> $(SEC_BIN) ; -# $(TWDB)/tasks.dat -> $(SEC_CONFIG) ; -# $(TWDB)/schedule.dat -> $(SEC_CONFIG) ; -# -# # Uncomment if you have agent logging enabled. -# #/var/log/tripwire/agent.log -> $(SEC_LOG) ; -#} - - - # Commonly accessed directories that should remain static with regards to owner and group ( rulename = "Invariant Directories", @@ -1078,7 +1037,7 @@ SIG_HI = 100 ; # Critical files that are significant point #============================================================================= # -# Copyright 2000 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, # Inc. in the United States and other countries. All rights reserved. # # Linux is a registered trademark of Linus Torvalds. diff --git a/policy/twpol-GNU.txt b/policy/twpol-GNU.txt new file mode 100644 index 0000000..baa9164 --- /dev/null +++ b/policy/twpol-GNU.txt @@ -0,0 +1,159 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for GNU/Hurd ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + +############################################################################## + +(rulename="Boot files",) +{ + /boot -> $(SEC_READONLY) -a; +} + +(rulename="Binary files",) +{ + /bin -> $(SEC_READONLY) -a; + /usr/bin -> $(SEC_READONLY) -a; + /usr/local/bin -> $(SEC_READONLY) -a; +} + +(rulename="Admin binaries",) +{ + /servers -> $(SEC_READONLY) -a; + /sbin -> $(SEC_READONLY) -a; + /usr/sbin -> $(SEC_READONLY) -a; + /hurd -> $(SEC_READONLY) -a; +} + +(rulename="Libraries",) +{ + /lib -> $(SEC_READONLY) -a; + /usr/lib -> $(SEC_READONLY) -a; + /usr/local/lib -> $(SEC_READONLY) -a; +} + +(rulename="Etc",) +{ + /etc -> $(SEC_READONLY) -a; + /usr/local/etc -> $(SEC_READONLY) -a; +} + +(rulename="Dev",) +{ + /dev -> $(SEC_DEVICE); +} + +(rulename="Tmp",) +{ + /tmp -> $(SEC_TEMPORARY); + /var/tmp -> $(SEC_TEMPORARY); +} + +(rulename="Log",) +{ + /var/log -> $(SEC_GROWING); +} diff --git a/policy/twpol-HP-UX.txt b/policy/twpol-HP-UX.txt new file mode 100644 index 0000000..5624e2b --- /dev/null +++ b/policy/twpol-HP-UX.txt @@ -0,0 +1,1106 @@ + ############################################################################## + # ## +############################################################################## # +# # # +# Policy file for HP-UX # # +# (adapted from OST generic policy) # # +# ## +############################################################################## + + + ############################################################################## + # ## +############################################################################## # +# # # +# This is the example Tripwire Policy file. It is intended as a place to # # +# start creating your own custom Tripwire Policy file. Referring to it as # # +# well as the Tripwire Policy Guide should give you enough information to # # +# make a good custom Tripwire Policy file that better covers your # # +# configuration and security needs. A text version of this policy file is # # +# called twpol.txt. # # +# # # +# Note that this file is tuned to an 'everything' install of Red Hat Linux. # # +# If run unmodified, this file should create no errors on database # # +# creation, or violations on a subsiquent integrity check. However, it is # # +# impossible for there to be one policy file for all machines, so this # # +# existing one errs on the side of security. Your Linux configuration will # # +# most likey differ from the one our policy file was tuned to, and will # # +# therefore require some editing of the default Tripwire Policy file. # # +# # # +# The example policy file is best run with 'Loose Directory Checking' # # +# enabled. Set LOOSEDIRECTORYCHECKING=TRUE in the Tripwire Configuration # # +# file. # # +# # # +# Email support is not included and must be added to this file. # # +# Add the 'emailto=' to the rule directive section of each rule (add a comma # # +# after the 'severity=' line and add an 'emailto=' and include the email # # +# addresses you want the violation reports to go to). Addresses are # # +# semi-colon delimited. # # +# ## +############################################################################## + + + + ############################################################################## + # ## +############################################################################## # +# # # +# Global Variable Definitions # # +# # # +# These are defined at install time by the installation script. You may # # +# Manually edit these if you are using this file directly and not from the # # +# installation script itself. # # +# ## +############################################################################## + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +@@section FS +SEC_CRIT = $(IgnoreNone)-SHa ; # Critical files that cannot change +SEC_SUID = $(IgnoreNone)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(ReadOnly) ; # Binaries that should not change +SEC_CONFIG = $(Dynamic) ; # Config files that are changed infrequently but accessed often +SEC_LOG = $(Growing) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = +tpug ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability + + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", + severity = $(SIG_HI) +) +{ + $(TWBIN)/siggen -> $(SEC_BIN) ; + $(TWBIN)/tripwire -> $(SEC_BIN) ; + $(TWBIN)/twadmin -> $(SEC_BIN) ; + $(TWBIN)/twprint -> $(SEC_BIN) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", + severity = $(SIG_HI) +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_CONFIG) -i ; + $(TWPOL)/tw.pol -> $(SEC_BIN) -i ; + $(TWPOL)/tw.cfg -> $(SEC_BIN) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_BIN) ; + $(TWSKEY)/site.key -> $(SEC_BIN) ; + + #don't scan the individual reports + $(TWREPORT) -> $(SEC_CONFIG) (recurse=0) ; +} + + +# Tripwire HQ Connector Binaries +#( +# rulename = "Tripwire HQ Connector Binaries", +# severity = $(SIG_HI) +#) +#{ +# $(TWBIN)/hqagent -> $(SEC_BIN) ; +#} +# +# Tripwire HQ Connector - Configuration Files, Keys, and Logs + + ############################################################################## + # ## +############################################################################## # +# # # +# Note: File locations here are different than in a stock HQ Connector # # +# installation. This is because Tripwire 2.3 uses a different path # # +# structure than Tripwire 2.2.1. # # +# # # +# You may need to update your HQ Agent configuation file (or this policy # # +# file) to correct the paths. We have attempted to support the FHS standard # # +# here by placing the HQ Agent files similarly to the way Tripwire 2.3 # # +# places them. # # +# ## +############################################################################## + +#( +# rulename = "Tripwire HQ Connector Data Files", +# severity = $(SIG_HI) +#) +#{ +# ############################################################################# +# ############################################################################## +# # NOTE: Removing the inode attribute because when Tripwire creates a backup ## +# # it does so by renaming the old file and creating a new one (which will ## +# # have a new inode number). Leaving inode turned on for keys, which ## +# # shouldn't ever change. ## +# ############################################################################# +# +# $(TWBIN)/agent.cfg -> $(SEC_BIN) -i ; +# $(TWLKEY)/authentication.key -> $(SEC_BIN) ; +# $(TWDB)/tasks.dat -> $(SEC_CONFIG) ; +# $(TWDB)/schedule.dat -> $(SEC_CONFIG) ; +# +# # Uncomment if you have agent logging enabled. +# #/var/log/tripwire/agent.log -> $(SEC_LOG) ; +#} + + + +# Commonly accessed directories that should remain static with regards to owner and group +( + rulename = "Invariant Directories", + severity = $(SIG_MED) +) +{ + / -> $(SEC_INVARIANT) (recurse = 0) ; + /home -> $(SEC_INVARIANT) (recurse = 0) ; + /etc -> $(SEC_INVARIANT) (recurse = 0) ; +} + ################################################ + # ## +################################################ # +# # # +# File System and Disk Administration Programs # # +# ## +################################################ + +( + rulename = "File System and Disk Administraton Programs", + severity = $(SIG_HI) +) +{ + /sbin/accton -> $(SEC_CRIT) ; + /sbin/badblocks -> $(SEC_CRIT) ; + /sbin/busybox -> $(SEC_CRIT) ; + /sbin/busybox.anaconda -> $(SEC_CRIT) ; + /sbin/convertquota -> $(SEC_CRIT) ; + /sbin/dosfsck -> $(SEC_CRIT) ; + /sbin/debugfs -> $(SEC_CRIT) ; + /sbin/debugreiserfs -> $(SEC_CRIT) ; + /sbin/dumpe2fs -> $(SEC_CRIT) ; + /sbin/dump -> $(SEC_CRIT) ; + /sbin/dump.static -> $(SEC_CRIT) ; + # /sbin/e2fsadm -> $(SEC_CRIT) ; tune2fs? + /sbin/e2fsck -> $(SEC_CRIT) ; + /sbin/e2label -> $(SEC_CRIT) ; + /sbin/fdisk -> $(SEC_CRIT) ; + /sbin/fsck -> $(SEC_CRIT) ; + /sbin/fsck.ext2 -> $(SEC_CRIT) ; + /sbin/fsck.ext3 -> $(SEC_CRIT) ; + /sbin/fsck.minix -> $(SEC_CRIT) ; + /sbin/fsck.msdos -> $(SEC_CRIT) ; + /sbin/fsck.vfat -> $(SEC_CRIT) ; + /sbin/ftl_check -> $(SEC_CRIT) ; + /sbin/ftl_format -> $(SEC_CRIT) ; + /sbin/hdparm -> $(SEC_CRIT) ; + #/sbin/lvchange -> $(SEC_CRIT) ; + #/sbin/lvcreate -> $(SEC_CRIT) ; + #/sbin/lvdisplay -> $(SEC_CRIT) ; + #/sbin/lvextend -> $(SEC_CRIT) ; + #/sbin/lvmchange -> $(SEC_CRIT) ; + #/sbin/lvmcreate_initrd -> $(SEC_CRIT) ; + #/sbin/lvmdiskscan -> $(SEC_CRIT) ; + #/sbin/lvmsadc -> $(SEC_CRIT) ; + #/sbin/lvmsar -> $(SEC_CRIT) ; + #/sbin/lvreduce -> $(SEC_CRIT) ; + #/sbin/lvremove -> $(SEC_CRIT) ; + #/sbin/lvrename -> $(SEC_CRIT) ; + #/sbin/lvscan -> $(SEC_CRIT) ; + /sbin/mkbootdisk -> $(SEC_CRIT) ; + /sbin/mkdosfs -> $(SEC_CRIT) ; + /sbin/mke2fs -> $(SEC_CRIT) ; + /sbin/mkfs -> $(SEC_CRIT) ; + /sbin/mkfs.bfs -> $(SEC_CRIT) ; + /sbin/mkfs.ext2 -> $(SEC_CRIT) ; + /sbin/mkfs.minix -> $(SEC_CRIT) ; + /sbin/mkfs.msdos -> $(SEC_CRIT) ; + /sbin/mkfs.vfat -> $(SEC_CRIT) ; + /sbin/mkinitrd -> $(SEC_CRIT) ; + #/sbin/mkpv -> $(SEC_CRIT) ; + /sbin/mkraid -> $(SEC_CRIT) ; + /sbin/mkreiserfs -> $(SEC_CRIT) ; + /sbin/mkswap -> $(SEC_CRIT) ; + #/sbin/mtx -> $(SEC_CRIT) ; + /sbin/pam_console_apply -> $(SEC_CRIT) ; + /sbin/parted -> $(SEC_CRIT) ; + /sbin/pcinitrd -> $(SEC_CRIT) ; + #/sbin/pvchange -> $(SEC_CRIT) ; + #/sbin/pvcreate -> $(SEC_CRIT) ; + #/sbin/pvdata -> $(SEC_CRIT) ; + #/sbin/pvdisplay -> $(SEC_CRIT) ; + #/sbin/pvmove -> $(SEC_CRIT) ; + #/sbin/pvscan -> $(SEC_CRIT) ; + /sbin/quotacheck -> $(SEC_CRIT) ; + /sbin/quotaon -> $(SEC_CRIT) ; + /sbin/raidstart -> $(SEC_CRIT) ; + /sbin/reiserfsck -> $(SEC_CRIT) ; + /sbin/resize2fs -> $(SEC_CRIT) ; + /sbin/resize_reiserfs -> $(SEC_CRIT) ; + /sbin/restore -> $(SEC_CRIT) ; + /sbin/restore.static -> $(SEC_CRIT) ; + /sbin/scsi_info -> $(SEC_CRIT) ; + /sbin/sfdisk -> $(SEC_CRIT) ; + /sbin/stinit -> $(SEC_CRIT) ; + #/sbin/tapeinfo -> $(SEC_CRIT) ; + /sbin/tune2fs -> $(SEC_CRIT) ; + /sbin/unpack -> $(SEC_CRIT) ; + /sbin/update -> $(SEC_CRIT) ; + #/sbin/vgcfgbackup -> $(SEC_CRIT) ; + #/sbin/vgcfgrestore -> $(SEC_CRIT) ; + #/sbin/vgchange -> $(SEC_CRIT) ; + #/sbin/vgck -> $(SEC_CRIT) ; + #/sbin/vgcreate -> $(SEC_CRIT) ; + #/sbin/vgdisplay -> $(SEC_CRIT) ; + #/sbin/vgexport -> $(SEC_CRIT) ; + #/sbin/vgextend -> $(SEC_CRIT) ; + #/sbin/vgimport -> $(SEC_CRIT) ; + #/sbin/vgmerge -> $(SEC_CRIT) ; + #/sbin/vgmknodes -> $(SEC_CRIT) ; + #/sbin/vgreduce -> $(SEC_CRIT) ; + #/sbin/vgremove -> $(SEC_CRIT) ; + #/sbin/vgrename -> $(SEC_CRIT) ; + #/sbin/vgscan -> $(SEC_CRIT) ; + #/sbin/vgsplit -> $(SEC_CRIT) ; + /bin/chgrp -> $(SEC_CRIT) ; + /bin/chmod -> $(SEC_CRIT) ; + /bin/chown -> $(SEC_CRIT) ; + /bin/cp -> $(SEC_CRIT) ; + /bin/cpio -> $(SEC_CRIT) ; + /bin/mount -> $(SEC_CRIT) ; + /bin/umount -> $(SEC_CRIT) ; + /bin/mkdir -> $(SEC_CRIT) ; + /bin/mknod -> $(SEC_CRIT) ; + /bin/mktemp -> $(SEC_CRIT) ; + /bin/rm -> $(SEC_CRIT) ; + /bin/rmdir -> $(SEC_CRIT) ; + /bin/touch -> $(SEC_CRIT) ; +} + + ################################## + # ## +################################## # +# # # +# Kernel Administration Programs # # +# ## +################################## + +( + rulename = "Kernel Administration Programs", + severity = $(SIG_HI) +) +{ + /sbin/adjtimex -> $(SEC_CRIT) ; + /sbin/ctrlaltdel -> $(SEC_CRIT) ; + /sbin/depmod -> $(SEC_CRIT) ; + /sbin/insmod -> $(SEC_CRIT) ; + /sbin/insmod.static -> $(SEC_CRIT) ; + /sbin/insmod_ksymoops_clean -> $(SEC_CRIT) ; + /sbin/klogd -> $(SEC_CRIT) ; + /sbin/ldconfig -> $(SEC_CRIT) ; + /sbin/minilogd -> $(SEC_CRIT) ; + /sbin/modinfo -> $(SEC_CRIT) ; + #/sbin/nuactlun -> $(SEC_CRIT) ; + #/sbin/nuscsitcpd -> $(SEC_CRIT) ; + /sbin/pivot_root -> $(SEC_CRIT) ; + /sbin/sndconfig -> $(SEC_CRIT) ; + /sbin/sysctl -> $(SEC_CRIT) ; +} + + ####################### + # ## +####################### # +# # # +# Networking Programs # # +# ## +####################### + +( + rulename = "Networking Programs", + severity = $(SIG_HI) +) +{ + /etc/sysconfig/network-scripts/ifdown -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-cipcb -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-ippp -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-ipv6 -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-isdn -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-post -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-ppp -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-sit -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifdown-sl -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-aliases -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-cipcb -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-ippp -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-ipv6 -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-isdn -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-plip -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-plusb -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-post -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-ppp -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-routes -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-sit -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-sl -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/ifup-wireless -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/network-functions -> $(SEC_CRIT) ; + /etc/sysconfig/network-scripts/network-functions-ipv6 -> $(SEC_CRIT) ; + /bin/ping -> $(SEC_CRIT) ; + /sbin/agetty -> $(SEC_CRIT) ; + /sbin/arp -> $(SEC_CRIT) ; + /sbin/arping -> $(SEC_CRIT) ; + /sbin/dhcpcd -> $(SEC_CRIT) ; + /sbin/ether-wake -> $(SEC_CRIT) ; + #/sbin/getty -> $(SEC_CRIT) ; + /sbin/ifcfg -> $(SEC_CRIT) ; + /sbin/ifconfig -> $(SEC_CRIT) ; + /sbin/ifdown -> $(SEC_CRIT) ; + /sbin/ifenslave -> $(SEC_CRIT) ; + /sbin/ifport -> $(SEC_CRIT) ; + /sbin/ifup -> $(SEC_CRIT) ; + /sbin/ifuser -> $(SEC_CRIT) ; + /sbin/ip -> $(SEC_CRIT) ; + /sbin/ip6tables -> $(SEC_CRIT) ; + /sbin/ipchains -> $(SEC_CRIT) ; + /sbin/ipchains-restore -> $(SEC_CRIT) ; + /sbin/ipchains-save -> $(SEC_CRIT) ; + /sbin/ipfwadm -> $(SEC_CRIT) ; + /sbin/ipmaddr -> $(SEC_CRIT) ; + /sbin/iptables -> $(SEC_CRIT) ; + /sbin/iptables-restore -> $(SEC_CRIT) ; + /sbin/iptables-save -> $(SEC_CRIT) ; + /sbin/iptunnel -> $(SEC_CRIT) ; + #/sbin/ipvsadm -> $(SEC_CRIT) ; + #/sbin/ipvsadm-restore -> $(SEC_CRIT) ; + #/sbin/ipvsadm-save -> $(SEC_CRIT) ; + /sbin/ipx_configure -> $(SEC_CRIT) ; + /sbin/ipx_interface -> $(SEC_CRIT) ; + /sbin/ipx_internal_net -> $(SEC_CRIT) ; + /sbin/iwconfig -> $(SEC_CRIT) ; + /sbin/iwgetid -> $(SEC_CRIT) ; + /sbin/iwlist -> $(SEC_CRIT) ; + /sbin/iwpriv -> $(SEC_CRIT) ; + /sbin/iwspy -> $(SEC_CRIT) ; + /sbin/mgetty -> $(SEC_CRIT) ; + /sbin/mingetty -> $(SEC_CRIT) ; + /sbin/nameif -> $(SEC_CRIT) ; + /sbin/netreport -> $(SEC_CRIT) ; + /sbin/plipconfig -> $(SEC_CRIT) ; + /sbin/portmap -> $(SEC_CRIT) ; + /sbin/ppp-watch -> $(SEC_CRIT) ; + #/sbin/rarp -> $(SEC_CRIT) ; + /sbin/route -> $(SEC_CRIT) ; + /sbin/slattach -> $(SEC_CRIT) ; + /sbin/tc -> $(SEC_CRIT) ; + #/sbin/uugetty -> $(SEC_CRIT) ; + /sbin/vgetty -> $(SEC_CRIT) ; + /sbin/ypbind -> $(SEC_CRIT) ; +} + + ################################## + # ## +################################## # +# # # +# System Administration Programs # # +# ## +################################## + +( + rulename = "System Administration Programs", + severity = $(SIG_HI) +) +{ + /sbin/chkconfig -> $(SEC_CRIT) ; + /sbin/fuser -> $(SEC_CRIT) ; + /sbin/halt -> $(SEC_CRIT) ; + /sbin/init -> $(SEC_CRIT) ; + /sbin/initlog -> $(SEC_CRIT) ; + /sbin/install-info -> $(SEC_CRIT) ; + /sbin/killall5 -> $(SEC_CRIT) ; + #/sbin/linuxconf -> $(SEC_CRIT) ; + #/sbin/linuxconf-auth -> $(SEC_CRIT) ; + /sbin/pam_tally -> $(SEC_CRIT) ; + /sbin/pwdb_chkpwd -> $(SEC_CRIT) ; + #/sbin/remadmin -> $(SEC_CRIT) ; + /sbin/rescuept -> $(SEC_CRIT) ; + /sbin/rmt -> $(SEC_CRIT) ; + /sbin/rpc.lockd -> $(SEC_CRIT) ; + /sbin/rpc.statd -> $(SEC_CRIT) ; + /sbin/rpcdebug -> $(SEC_CRIT) ; + /sbin/service -> $(SEC_CRIT) ; + /sbin/setsysfont -> $(SEC_CRIT) ; + /sbin/shutdown -> $(SEC_CRIT) ; + /sbin/sulogin -> $(SEC_CRIT) ; + /sbin/swapon -> $(SEC_CRIT) ; + /sbin/syslogd -> $(SEC_CRIT) ; + /sbin/unix_chkpwd -> $(SEC_CRIT) ; + /bin/pwd -> $(SEC_CRIT) ; + /bin/uname -> $(SEC_CRIT) ; +} + + ######################################## + # ## +######################################## # +# # # +# Hardware and Device Control Programs # # +# ## +######################################## +( + rulename = "Hardware and Device Control Programs", + severity = $(SIG_HI) +) +{ + /bin/setserial -> $(SEC_CRIT) ; + /bin/sfxload -> $(SEC_CRIT) ; + /sbin/blockdev -> $(SEC_CRIT) ; + /sbin/cardctl -> $(SEC_CRIT) ; + /sbin/cardmgr -> $(SEC_CRIT) ; + /sbin/cbq -> $(SEC_CRIT) ; + /sbin/dump_cis -> $(SEC_CRIT) ; + /sbin/elvtune -> $(SEC_CRIT) ; + /sbin/hotplug -> $(SEC_CRIT) ; + /sbin/hwclock -> $(SEC_CRIT) ; + /sbin/ide_info -> $(SEC_CRIT) ; + #/sbin/isapnp -> $(SEC_CRIT) ; + /sbin/kbdrate -> $(SEC_CRIT) ; + /sbin/losetup -> $(SEC_CRIT) ; + /sbin/lspci -> $(SEC_CRIT) ; + /sbin/lspnp -> $(SEC_CRIT) ; + /sbin/mii-tool -> $(SEC_CRIT) ; + /sbin/pack_cis -> $(SEC_CRIT) ; + #/sbin/pnpdump -> $(SEC_CRIT) ; + /sbin/probe -> $(SEC_CRIT) ; + /sbin/pump -> $(SEC_CRIT) ; + /sbin/setpci -> $(SEC_CRIT) ; + /sbin/shapecfg -> $(SEC_CRIT) ; +} + + ############################### + # ## +############################### # +# # # +# System Information Programs # # +# ## +############################### +( + rulename = "System Information Programs", + severity = $(SIG_HI) +) +{ + /sbin/consoletype -> $(SEC_CRIT) ; + /sbin/kernelversion -> $(SEC_CRIT) ; + /sbin/runlevel -> $(SEC_CRIT) ; +} + + #################################### + # ## +#################################### # +# # # +# Application Information Programs # # +# ## +#################################### + +( + rulename = "Application Information Programs", + severity = $(SIG_HI) +) +{ + /sbin/genksyms -> $(SEC_CRIT) ; + #/sbin/genksyms.old -> $(SEC_CRIT) ; + /sbin/rtmon -> $(SEC_CRIT) ; +} + + ########################## + # ## +########################## # +# # # +# Shell Related Programs # # +# ## +########################## +( + rulename = "Shell Related Programs", + severity = $(SIG_HI) +) +{ + /sbin/getkey -> $(SEC_CRIT) ; + /sbin/nash -> $(SEC_CRIT) ; + /sbin/sash -> $(SEC_CRIT) ; +} + + + ################ + # ## +################ # +# # # +# OS Utilities # # +# ## +################ +( + rulename = "Operating System Utilities", + severity = $(SIG_HI) +) +{ + /bin/arch -> $(SEC_CRIT) ; + /bin/ash -> $(SEC_CRIT) ; + /bin/ash.static -> $(SEC_CRIT) ; + /bin/aumix-minimal -> $(SEC_CRIT) ; + /bin/basename -> $(SEC_CRIT) ; + /bin/cat -> $(SEC_CRIT) ; + /bin/consolechars -> $(SEC_CRIT) ; + /bin/cut -> $(SEC_CRIT) ; + /bin/date -> $(SEC_CRIT) ; + /bin/dd -> $(SEC_CRIT) ; + /bin/df -> $(SEC_CRIT) ; + /bin/dmesg -> $(SEC_CRIT) ; + /bin/doexec -> $(SEC_CRIT) ; + /bin/echo -> $(SEC_CRIT) ; + /bin/ed -> $(SEC_CRIT) ; + /bin/egrep -> $(SEC_CRIT) ; + /bin/false -> $(SEC_CRIT) ; + /bin/fgrep -> $(SEC_CRIT) ; + /bin/gawk -> $(SEC_CRIT) ; + /bin/gawk-3.1.0 -> $(SEC_CRIT) ; + /bin/gettext -> $(SEC_CRIT) ; + /bin/grep -> $(SEC_CRIT) ; + /bin/gunzip -> $(SEC_CRIT) ; + /bin/gzip -> $(SEC_CRIT) ; + /bin/hostname -> $(SEC_CRIT) ; + /bin/igawk -> $(SEC_CRIT) ; + /bin/ipcalc -> $(SEC_CRIT) ; + /bin/kill -> $(SEC_CRIT) ; + /bin/ln -> $(SEC_CRIT) ; + /bin/loadkeys -> $(SEC_CRIT) ; + /bin/login -> $(SEC_CRIT) ; + /bin/ls -> $(SEC_CRIT) ; + /bin/mail -> $(SEC_CRIT) ; + /bin/more -> $(SEC_CRIT) ; + /bin/mt -> $(SEC_CRIT) ; + /bin/mv -> $(SEC_CRIT) ; + /bin/netstat -> $(SEC_CRIT) ; + /bin/nice -> $(SEC_CRIT) ; + /bin/pgawk -> $(SEC_CRIT) ; + /bin/ps -> $(SEC_CRIT) ; + /bin/rpm -> $(SEC_CRIT) ; + /bin/sed -> $(SEC_CRIT) ; + /bin/sleep -> $(SEC_CRIT) ; + /bin/sort -> $(SEC_CRIT) ; + /bin/stty -> $(SEC_CRIT) ; + /bin/su -> $(SEC_CRIT) ; + /bin/sync -> $(SEC_CRIT) ; + /bin/tar -> $(SEC_CRIT) ; + /bin/true -> $(SEC_CRIT) ; + /bin/usleep -> $(SEC_CRIT) ; + /bin/vi -> $(SEC_CRIT) ; + /bin/zcat -> $(SEC_CRIT) ; + /bin/zsh -> $(SEC_CRIT) ; + #/bin/zsh-4.0.2 -> $(SEC_CRIT) ; + /sbin/sln -> $(SEC_CRIT) ; + /usr/bin/vimtutor -> $(SEC_CRIT) ; +} + + ############################## + # ## +############################## # +# # # +# Critical Utility Sym-Links # # +# ## +############################## +( + rulename = "Critical Utility Sym-Links", + severity = $(SIG_HI) +) +{ + #/sbin/askrunlevel -> $(SEC_CRIT) ; + /sbin/clock -> $(SEC_CRIT) ; + #/sbin/fixperm -> $(SEC_CRIT) ; + /sbin/fsck.reiserfs -> $(SEC_CRIT) ; + #/sbin/fsconf -> $(SEC_CRIT) ; + /sbin/ipfwadm-wrapper -> $(SEC_CRIT) ; + /sbin/kallsyms -> $(SEC_CRIT) ; + /sbin/ksyms -> $(SEC_CRIT) ; + /sbin/lsmod -> $(SEC_CRIT) ; + #/sbin/mailconf -> $(SEC_CRIT) ; + /sbin/mkfs.reiserfs -> $(SEC_CRIT) ; + #/sbin/modemconf -> $(SEC_CRIT) ; + /sbin/modprobe -> $(SEC_CRIT) ; + /sbin/mount.ncp -> $(SEC_CRIT) ; + /sbin/mount.ncpfs -> $(SEC_CRIT) ; + /sbin/mount.smb -> $(SEC_CRIT) ; + /sbin/mount.smbfs -> $(SEC_CRIT) ; + #/sbin/netconf -> $(SEC_CRIT) ; + /sbin/pidof -> $(SEC_CRIT) ; + /sbin/poweroff -> $(SEC_CRIT) ; + /sbin/quotaoff -> $(SEC_CRIT) ; + /sbin/raid0run -> $(SEC_CRIT) ; + /sbin/raidhotadd -> $(SEC_CRIT) ; + /sbin/raidhotgenerateerror -> $(SEC_CRIT) ; + /sbin/raidhotremove -> $(SEC_CRIT) ; + /sbin/raidstop -> $(SEC_CRIT) ; + /sbin/rdump -> $(SEC_CRIT) ; + /sbin/rdump.static -> $(SEC_CRIT) ; + /sbin/reboot -> $(SEC_CRIT) ; + /sbin/rmmod -> $(SEC_CRIT) ; + /sbin/rrestore -> $(SEC_CRIT) ; + /sbin/rrestore.static -> $(SEC_CRIT) ; + /sbin/swapoff -> $(SEC_CRIT) ; + /sbin/telinit -> $(SEC_CRIT) ; + #/sbin/userconf -> $(SEC_CRIT) ; + #/sbin/uucpconf -> $(SEC_CRIT) ; + #/sbin/vregistry -> $(SEC_CRIT) ; + /bin/awk -> $(SEC_CRIT) ; + /bin/bash2 -> $(SEC_CRIT) ; + /bin/bsh -> $(SEC_CRIT) ; + /bin/csh -> $(SEC_CRIT) ; + /bin/dnsdomainname -> $(SEC_CRIT) ; + /bin/domainname -> $(SEC_CRIT) ; + /bin/ex -> $(SEC_CRIT) ; + /bin/gtar -> $(SEC_CRIT) ; + /bin/nisdomainname -> $(SEC_CRIT) ; + /bin/red -> $(SEC_CRIT) ; + /bin/rvi -> $(SEC_CRIT) ; + /bin/rview -> $(SEC_CRIT) ; + /bin/view -> $(SEC_CRIT) ; + /bin/ypdomainname -> $(SEC_CRIT) ; +} + + + ######################### + # ## +######################### # +# # # +# Temporary directories # # +# ## +######################### +( + rulename = "Temporary directories", + recurse = false, + severity = $(SIG_LOW) +) +{ + /usr/tmp -> $(SEC_INVARIANT) ; + /var/tmp -> $(SEC_INVARIANT) ; + /tmp -> $(SEC_INVARIANT) ; +} + + ############### + # ## +############### # +# # # +# Local files # # +# ## +############### +( + rulename = "User binaries", + severity = $(SIG_MED) +) +{ + /sbin -> $(SEC_BIN) (recurse = 1) ; + /usr/bin -> $(SEC_BIN) (recurse = 1) ; + /usr/sbin -> $(SEC_BIN) (recurse = 1) ; + /usr/local/bin -> $(SEC_BIN) (recurse = 1) ; +} + +( + rulename = "Shell Binaries", + severity = $(SIG_HI) +) +{ + /bin/bash -> $(SEC_BIN) ; + /bin/ksh -> $(SEC_BIN) ; + # /bin/psh -> $(SEC_BIN) ; # No longer used? + # /bin/Rsh -> $(SEC_BIN) ; # No longer used? + /bin/sh -> $(SEC_BIN) ; + # /bin/shell -> $(SEC_SUID) ; # No longer used? + # /bin/tsh -> $(SEC_BIN) ; # No longer used? + /bin/tcsh -> $(SEC_BIN) ; + /sbin/nologin -> $(SEC_BIN) ; +} + +( + rulename = "Security Control", + severity = $(SIG_HI) +) +{ + /etc/group -> $(SEC_CRIT) ; + /etc/security -> $(SEC_CRIT) ; + #/var/spool/cron/crontabs -> $(SEC_CRIT) ; # Uncomment when this file exists +} + +#( +# rulename = "Boot Scripts", +# severity = $(SIG_HI) +#) +#{ +# /etc/rc -> $(SEC_CONFIG) ; +# /etc/rc.bsdnet -> $(SEC_CONFIG) ; +# /etc/rc.dt -> $(SEC_CONFIG) ; +# /etc/rc.net -> $(SEC_CONFIG) ; +# /etc/rc.net.serial -> $(SEC_CONFIG) ; +# /etc/rc.nfs -> $(SEC_CONFIG) ; +# /etc/rc.powerfail -> $(SEC_CONFIG) ; +# /etc/rc.tcpip -> $(SEC_CONFIG) ; +# /etc/trcfmt.Z -> $(SEC_CONFIG) ; +#} + +( + rulename = "Login Scripts", + severity = $(SIG_HI) +) +{ + /etc/bashrc -> $(SEC_CONFIG) ; + /etc/csh.cshrc -> $(SEC_CONFIG) ; + /etc/csh.login -> $(SEC_CONFIG) ; + /etc/inputrc -> $(SEC_CONFIG) ; + # /etc/tsh_profile -> $(SEC_CONFIG) ; #Uncomment when this file exists + /etc/profile -> $(SEC_CONFIG) ; +} + +# Libraries +( + rulename = "Libraries", + severity = $(SIG_MED) +) +{ + /usr/lib -> $(SEC_BIN) ; + /usr/local/lib -> $(SEC_BIN) ; +} + + + ###################################################### + # ## +###################################################### # +# # # +# Critical System Boot Files # # +# These files are critical to a correct system boot. # # +# ## +###################################################### + +( + rulename = "Critical system boot files", + severity = $(SIG_HI) +) +{ + /boot -> $(SEC_CRIT) ; + #/sbin/devfsd -> $(SEC_CRIT) ; + /sbin/grub -> $(SEC_CRIT) ; + /sbin/grub-install -> $(SEC_CRIT) ; + /sbin/grub-md5-crypt -> $(SEC_CRIT) ; + /sbin/installkernel -> $(SEC_CRIT) ; + /sbin/lilo -> $(SEC_CRIT) ; + /sbin/mkkerneldoth -> $(SEC_CRIT) ; + !/boot/System.map ; + !/boot/module-info ; + /usr/share/grub/i386-redhat/e2fs_stage1_5 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/fat_stage1_5 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/ffs_stage1_5 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/minix_stage1_5 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/reiserfs_stage1_5 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/stage1 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/stage2 -> $(SEC_CRIT) ; + /usr/share/grub/i386-redhat/vstafs_stage1_5 -> $(SEC_CRIT) ; + # other boot files may exist. Look for: + #/ufsboot -> $(SEC_CRIT) ; +} + ################################################## + ################################################### + # These files change every time the system boots ## + ################################################## +( + rulename = "System boot changes", + severity = $(SIG_HI) +) +{ + !/var/run/ftp.pids-all ; # Comes and goes on reboot. + !/root/.enlightenment ; + /dev/log -> $(SEC_CONFIG) ; + /dev/cua0 -> $(SEC_CONFIG) ; + # /dev/printer -> $(SEC_CONFIG) ; # Uncomment if you have a printer device + /dev/console -> $(SEC_CONFIG) -u ; # User ID may change on console login/logout. + /dev/tty1 -> $(SEC_CONFIG) ; # tty devices + /dev/tty2 -> $(SEC_CONFIG) ; # tty devices + /dev/tty3 -> $(SEC_CONFIG) ; # are extremely + /dev/tty4 -> $(SEC_CONFIG) ; # variable + /dev/tty5 -> $(SEC_CONFIG) ; + /dev/tty6 -> $(SEC_CONFIG) ; + /dev/urandom -> $(SEC_CONFIG) ; + /dev/initctl -> $(SEC_CONFIG) ; + /var/lock/subsys -> $(SEC_CONFIG) ; + #/var/lock/subsys/amd -> $(SEC_CONFIG) ; + /var/lock/subsys/anacron -> $(SEC_CONFIG) ; + /var/lock/subsys/apmd -> $(SEC_CONFIG) ; + #/var/lock/subsys/arpwatch -> $(SEC_CONFIG) ; + /var/lock/subsys/atd -> $(SEC_CONFIG) ; + /var/lock/subsys/autofs -> $(SEC_CONFIG) ; + #/var/lock/subsys/bcm5820 -> $(SEC_CONFIG) ; + #/var/lock/subsys/bgpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/bootparamd -> $(SEC_CONFIG) ; + #/var/lock/subsys/canna -> $(SEC_CONFIG) ; + /var/lock/subsys/crond -> $(SEC_CONFIG) ; + #/var/lock/subsys/cWnn -> $(SEC_CONFIG) ; + #/var/lock/subsys/dhcpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/firewall -> $(SEC_CONFIG) ; + #/var/lock/subsys/freeWnn -> $(SEC_CONFIG) ; + #/var/lock/subsys/gated -> $(SEC_CONFIG) ; + /var/lock/subsys/gpm -> $(SEC_CONFIG) ; + #/var/lock/subsys/httpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/identd -> $(SEC_CONFIG) ; + #/var/lock/subsys/innd -> $(SEC_CONFIG) ; + /var/lock/subsys/ipchains -> $(SEC_CONFIG) ; + #/var/lock/subsys/iptables -> $(SEC_CONFIG) ; + #/var/lock/subsys/ipvsadm -> $(SEC_CONFIG) ; + #/var/lock/subsys/irda -> $(SEC_CONFIG) ; + #/var/lock/subsys/iscsi -> $(SEC_CONFIG) ; + #/var/lock/subsys/isdn -> $(SEC_CONFIG) ; + #/var/lock/subsys/junkbuster -> $(SEC_CONFIG) ; + #/var/lock/subsys/kadmin -> $(SEC_CONFIG) ; + /var/lock/subsys/keytable -> $(SEC_CONFIG) ; + #/var/lock/subsys/kprop -> $(SEC_CONFIG) ; + #/var/lock/subsys/krb524 -> $(SEC_CONFIG) ; + #/var/lock/subsys/krb5kdc -> $(SEC_CONFIG) ; + /var/lock/subsys/kudzu -> $(SEC_CONFIG) ; + #/var/lock/subsys/kWnn -> $(SEC_CONFIG) ; + #/var/lock/subsys/ldap -> $(SEC_CONFIG) ; + #/var/lock/subsys/linuxconf -> $(SEC_CONFIG) ; + #/var/lock/subsys/lpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/mars_nwe -> $(SEC_CONFIG) ; + #/var/lock/subsys/mcserv -> $(SEC_CONFIG) ; + #/var/lock/subsys/mysqld -> $(SEC_CONFIG) ; + #/var/lock/subsys/named -> $(SEC_CONFIG) ; + /var/lock/subsys/netfs -> $(SEC_CONFIG) ; + /var/lock/subsys/network -> $(SEC_CONFIG) ; + #/var/lock/subsys/nfs -> $(SEC_CONFIG) ; + /var/lock/subsys/nfslock -> $(SEC_CONFIG) ; + #/var/lock/subsys/nscd -> $(SEC_CONFIG) ; + #/var/lock/subsys/ntpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/ospf6d -> $(SEC_CONFIG) ; + #/var/lock/subsys/ospfd -> $(SEC_CONFIG) ; + /var/lock/subsys/pcmcia -> $(SEC_CONFIG) ; + /var/lock/subsys/portmap -> $(SEC_CONFIG) ; + #/var/lock/subsys/postgresql -> $(SEC_CONFIG) ; + #/var/lock/subsys/pxe -> $(SEC_CONFIG) ; + #/var/lock/subsys/radvd -> $(SEC_CONFIG) ; + /var/lock/subsys/random -> $(SEC_CONFIG) ; + #/var/lock/subsys/rarpd -> $(SEC_CONFIG) ; + /var/lock/subsys/reconfig -> $(SEC_CONFIG) ; + /var/lock/subsys/rhnsd -> $(SEC_CONFIG) ; + #/var/lock/subsys/ripd -> $(SEC_CONFIG) ; + #/var/lock/subsys/ripngd -> $(SEC_CONFIG) ; + #/var/lock/subsys/routed -> $(SEC_CONFIG) ; + #/var/lock/subsys/rstatd -> $(SEC_CONFIG) ; + #/var/lock/subsys/rusersd -> $(SEC_CONFIG) ; + #/var/lock/subsys/rwalld -> $(SEC_CONFIG) ; + #/var/lock/subsys/rwhod -> $(SEC_CONFIG) ; + /var/lock/subsys/sendmail -> $(SEC_CONFIG) ; + #/var/lock/subsys/smb -> $(SEC_CONFIG) ; + #/var/lock/subsys/snmpd -> $(SEC_CONFIG) ; + #/var/lock/subsys/squid -> $(SEC_CONFIG) ; + /var/lock/subsys/sshd -> $(SEC_CONFIG) ; + /var/lock/subsys/syslog -> $(SEC_CONFIG) ; + #/var/lock/subsys/tux -> $(SEC_CONFIG) ; + #/var/lock/subsys/tWnn -> $(SEC_CONFIG) ; + #/var/lock/subsys/ups -> $(SEC_CONFIG) ; + #/var/lock/subsys/vncserver -> $(SEC_CONFIG) ; + #/var/lock/subsys/wine -> $(SEC_CONFIG) ; + /var/lock/subsys/xfs -> $(SEC_CONFIG) ; + /var/lock/subsys/xinetd -> $(SEC_CONFIG) ; + /var/lock/subsys/ypbind -> $(SEC_CONFIG) ; + #/var/lock/subsys/yppasswdd -> $(SEC_CONFIG) ; + #/var/lock/subsys/ypserv -> $(SEC_CONFIG) ; + #/var/lock/subsys/ypxfrd -> $(SEC_CONFIG) ; + #/var/lock/subsys/zebra -> $(SEC_CONFIG) ; + /var/run -> $(SEC_CONFIG) ; + /var/log -> $(SEC_CONFIG) ; + /etc/ioctl.save -> $(SEC_CONFIG) ; + /etc/issue.net -> $(SEC_CONFIG) -i ; # Inode number changes + /etc/issue -> $(SEC_CONFIG) ; + /etc/mtab -> $(SEC_CONFIG) -i ; # Inode number changes on any mount/unmount + /lib/modules -> $(SEC_CONFIG) ; + /etc/.pwd.lock -> $(SEC_CONFIG) ; + # /lib/modules/preferred -> $(SEC_CONFIG) ; #Uncomment when this file exists +} + +# These files change the behavior of the root account +( + rulename = "Root config files", + severity = 100 +) +{ + /root -> $(SEC_CRIT) ; # Catch all additions to /root + #/root/.Xresources -> $(SEC_CONFIG) ; + /root/.bashrc -> $(SEC_CONFIG) ; + /root/.bash_profile -> $(SEC_CONFIG) ; + /root/.bash_logout -> $(SEC_CONFIG) ; + /root/.cshrc -> $(SEC_CONFIG) ; + /root/.tcshrc -> $(SEC_CONFIG) ; + /root/Mail -> $(SEC_CONFIG) ; + #/root/mail -> $(SEC_CONFIG) ; + #/root/.amandahosts -> $(SEC_CONFIG) ; + #/root/.addressbook.lu -> $(SEC_CONFIG) ; + #/root/.addressbook -> $(SEC_CONFIG) ; + /root/.bash_history -> $(SEC_CONFIG) ; + /root/.elm -> $(SEC_CONFIG) ; + #/root/.esd_auth -> $(SEC_CONFIG) ; + /root/.gnome_private -> $(SEC_CONFIG) ; + /root/.gnome-desktop -> $(SEC_CONFIG) ; + /root/.gnome -> $(SEC_CONFIG) ; + /root/.ICEauthority -> $(SEC_CONFIG) ; + #/root/.mc -> $(SEC_CONFIG) ; + #/root/.pinerc -> $(SEC_CONFIG) ; + /root/.sawfish -> $(SEC_CONFIG) ; + /root/.Xauthority -> $(SEC_CONFIG) -i ; # Changes Inode number on login + #/root/.xauth -> $(SEC_CONFIG) ; + /root/.xsession-errors -> $(SEC_CONFIG) ; +} + + ################################ + # ## +################################ # +# # # +# Critical configuration files # # +# ## +################################ +( + rulename = "Critical configuration files", + severity = $(SIG_HI) +) +{ + #/etc/conf.linuxconf -> $(SEC_BIN) ; + /etc/crontab -> $(SEC_BIN) ; + /etc/cron.hourly -> $(SEC_BIN) ; + /etc/cron.daily -> $(SEC_BIN) ; + /etc/cron.weekly -> $(SEC_BIN) ; + /etc/cron.monthly -> $(SEC_BIN) ; + /etc/default -> $(SEC_BIN) ; + /etc/fstab -> $(SEC_BIN) ; + /etc/exports -> $(SEC_BIN) ; + /etc/group- -> $(SEC_BIN) ; # changes should be infrequent + /etc/host.conf -> $(SEC_BIN) ; + /etc/hosts.allow -> $(SEC_BIN) ; + /etc/hosts.deny -> $(SEC_BIN) ; + /etc/httpd/conf -> $(SEC_BIN) ; # changes should be infrequent + /etc/protocols -> $(SEC_BIN) ; + /etc/services -> $(SEC_BIN) ; + /etc/rc.d/init.d -> $(SEC_BIN) ; + /etc/rc.d -> $(SEC_BIN) ; + /etc/mail.rc -> $(SEC_BIN) ; + /etc/modules.conf -> $(SEC_BIN) ; + /etc/motd -> $(SEC_BIN) ; + /etc/named.conf -> $(SEC_BIN) ; + /etc/passwd -> $(SEC_CONFIG) ; + /etc/passwd- -> $(SEC_CONFIG) ; + /etc/profile.d -> $(SEC_BIN) ; + /var/lib/nfs/rmtab -> $(SEC_BIN) ; + /usr/sbin/fixrmtab -> $(SEC_BIN) ; + /etc/rpc -> $(SEC_BIN) ; + /etc/sysconfig -> $(SEC_BIN) ; + /etc/samba/smb.conf -> $(SEC_CONFIG) ; + #/etc/gettydefs -> $(SEC_BIN) ; + /etc/nsswitch.conf -> $(SEC_BIN) ; + /etc/yp.conf -> $(SEC_BIN) ; + /etc/hosts -> $(SEC_CONFIG) ; + /etc/xinetd.conf -> $(SEC_CONFIG) ; + /etc/inittab -> $(SEC_CONFIG) ; + /etc/resolv.conf -> $(SEC_CONFIG) ; + /etc/syslog.conf -> $(SEC_CONFIG) ; +} + + #################### + # ## +#################### # +# # # +# Critical devices # # +# ## +#################### +( + rulename = "Critical devices", + severity = $(SIG_HI), + recurse = false +) +{ + /dev/kmem -> $(Device) ; + /dev/mem -> $(Device) ; + /dev/null -> $(Device) ; + /dev/zero -> $(Device) ; + /proc/devices -> $(Device) ; + /proc/net -> $(Device) ; + /proc/sys -> $(Device) ; + /proc/cpuinfo -> $(Device) ; + /proc/modules -> $(Device) ; + /proc/mounts -> $(Device) ; + /proc/dma -> $(Device) ; + /proc/filesystems -> $(Device) ; + /proc/pci -> $(Device) ; + /proc/interrupts -> $(Device) ; + /proc/driver/rtc -> $(Device) ; + /proc/ioports -> $(Device) ; + #/proc/scsi -> $(Device) ; + /proc/kcore -> $(Device) ; + /proc/self -> $(Device) ; + /proc/kmsg -> $(Device) ; + /proc/stat -> $(Device) ; + /proc/ksyms -> $(Device) ; + /proc/loadavg -> $(Device) ; + /proc/uptime -> $(Device) ; + /proc/locks -> $(Device) ; + /proc/version -> $(Device) ; + /proc/mdstat -> $(Device) ; + /proc/meminfo -> $(Device) ; + /proc/cmdline -> $(Device) ; + /proc/misc -> $(Device) ; +} + +# Rest of critical system binaries +( + rulename = "OS executables and libraries", + severity = $(SIG_HI) +) +{ + /bin -> $(SEC_BIN) ; + /lib -> $(SEC_BIN) ; +} + +#============================================================================= +# +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Inc. in the United States and other countries. All rights reserved. +# +# Linux is a registered trademark of Linus Torvalds. +# +# UNIX is a registered trademark of The Open Group. +# +#============================================================================= +# +# Permission is granted to make and distribute verbatim copies of this document +# provided the copyright notice and this permission notice are preserved on all +# copies. +# +# Permission is granted to copy and distribute modified versions of this +# document under the conditions for verbatim copying, provided that the entire +# resulting derived work is distributed under the terms of a permission notice +# identical to this one. +# +# Permission is granted to copy and distribute translations of this document +# into another language, under the above conditions for modified versions, +# except that this permission notice may be stated in a translation approved by +# Tripwire, Inc. +# +# DCM +# +# $Id: twpol-GENERIC.txt,v 1.1 2003/06/08 02:00:06 pherman Exp $ +# diff --git a/policy/twpol-Haiku.txt b/policy/twpol-Haiku.txt new file mode 100644 index 0000000..b77e308 --- /dev/null +++ b/policy/twpol-Haiku.txt @@ -0,0 +1,178 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for Haiku ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + + +############################################################################## + + +### System dir ############################################################### +# +(rulename = "System Directory",) +{ + /boot/system -> $(SEC_READONLY) -a; +} + + +### Other bin dirs ############################################################ +# +(rulename = "Binary Directories",) +{ + /boot/home/config/bin -> $(SEC_READONLY) -a; + /boot/common/bin -> $(SEC_READONLY) -a; + /boot/apps -> $(SEC_READONLY) -a; +# /boot/develop/tools/gnupro/bin -> $(SEC_READONLY) -a; #uncomment to monitor dev tools if present +} + + +### Other lib dirs ############################################################ +# +(rulename = "Library Directories",) +{ + /boot/common/lib -> $(SEC_READONLY) -a; + /boot/home/config/lib -> $(SEC_READONLY) -a; +} + +### Other boot dirs ########################################################### +# +(rulename = "Boot Directories",) +{ + /boot/common/boot -> $(SEC_READONLY) -a; + /boot/home/config/boot -> $(SEC_READONLY) -a; +} + +### Settings ################################################################## +# +(rulename = "Settings",) +{ + /boot/common/settings -> $(SEC_READONLY) -a; + /boot/common/data -> $(SEC_READONLY) -a; + /boot/common/etc -> $(SEC_READONLY) -a; + /boot/home/config/settings -> $(SEC_READONLY) -a; +} + +# Logs ######################################################################## +# +(rulename = "Logs",) +{ + /boot/common/var/log -> $(SEC_GROWING) -a; +} + +# Dev ######################################################################### +# +(rulename = "Devices",) +{ + /dev -> $(SEC_DEVICE) -a; +} + +# Temp dirs ######################### +# +(rulename = "Temp Directories",) +{ + /boot/common/cache/tmp -> $(SEC_TEMPORARY) -a; +} \ No newline at end of file diff --git a/policy/twpol-LibertyBSD.txt b/policy/twpol-LibertyBSD.txt new file mode 100644 index 0000000..8fdf26d --- /dev/null +++ b/policy/twpol-LibertyBSD.txt @@ -0,0 +1,292 @@ + ############################################################################## + # ## +############################################################################## # +# # # +# Tripwire 2.4 policy for LibertyBSD # # +# updated March 2018 # # +# ## +############################################################################## + + ############################################################################## + # ## +############################################################################## # +# # # +# Global Variable Definitions # # +# # # +# These are defined at install time by the installation script. You may # # +# manually edit these if you are using this file directly and not from the # # +# installation script itself. # # +# ## +############################################################################## + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + + ############################################################################## + # Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + + ######################################## + # ## +######################################## # +# # # +# Tripwire Binaries and Data Files # # +# ## +######################################## + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; + + # In this configuration /usr/local is a symbolic link to /home/local. + # We want to ignore the following directories since they are already + # scanned using the real directory or mount point. Otherwise we see + # duplicates in the reports. + + !/home/local ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Boot and Configuration Files # # +# ## +################################################ +( + rulename = "OS Boot and Configuration Files", +) +{ + /boot -> $(SEC_READONLY) ; + /bsd -> $(SEC_READONLY) ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; +} + + ################################################### + # ## +################################################### # +# # # +# Mount Points # # +# ## +################################################### +( + rulename = "Mount Points", +) +{ + / -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /floppy -> $(SEC_DYNAMIC) ; + /home -> $(SEC_READONLY) ; # Modify as needed + /mnt -> $(SEC_DYNAMIC) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; +} + + ################################################### + # ## +################################################### # +# # # +# Misc Top-Level Directories # # +# ## +################################################### +( + rulename = "Misc Top-Level Directories", +) +{ + /altroot -> $(SEC_DYNAMIC) ; + /stand -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# System Devices # # +# ## +################################################ +( + rulename = "System Devices", +) +{ + /dev -> $(SEC_DEVICE) ; + /dev/fd -> $(SEC_DEVICE) ; + /var/cron/tabs/.sock -> $(SEC_DEVICE) ; + /var/empty/dev/log -> $(SEC_DEVICE) ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Binaries and Libraries # # +# ## +################################################ +( + rulename = "OS Binaries and Libraries", +) +{ + /bin -> $(SEC_READONLY) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/libexec -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/X11R6/bin -> $(SEC_READONLY) ; + /usr/X11R6/lib -> $(SEC_READONLY) ; +} + ################################################ + # ## +################################################ # +# # # +# Usr Local Files # # +# ## +################################################ +#OK( + #OKrulename = "Usr Local Files", +#OK) +#OK{ + #OK/usr/local -> $(SEC_READONLY) ; + #OK/usr/local/bin -> $(SEC_READONLY) ; + #OK/usr/local/doc -> $(SEC_READONLY) ; + #OK/usr/local/etc -> $(SEC_READONLY) ; + #OK/usr/local/include -> $(SEC_READONLY) ; + #OK/usr/local/info -> $(SEC_READONLY) ; + #OK/usr/local/lib -> $(SEC_READONLY) ; + #OK/usr/local/libdata -> $(SEC_READONLY) ; + #OK/usr/local/libexec -> $(SEC_READONLY) ; + #OK/usr/local/man -> $(SEC_READONLY) ; + #OK/usr/local/sbin -> $(SEC_READONLY) ; + #OK/usr/local/share -> $(SEC_READONLY) ; + #OK/usr/local/src -> $(SEC_READONLY) ; +#OK} + + ################################################ + # ## +################################################ # +# # # +# Root Directory and Files # # +# ## +################################################ +( + rulename = "Root Directory and Files", +) +{ + /root -> $(SEC_IGNORE_NONE) -SHa ; + /root/.cshrc -> $(SEC_DYNAMIC) ; + /root/.profile -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# Temporary Directories # # +# ## +################################################ +( + rulename = "Temporary Directories", +) +{ + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; +} + + ################################################ + # ## +################################################ # +# # # +# System and Boot Changes # # +# ## +################################################ +( + rulename = "System and Boot Changes", +) +{ + /var/backups -> $(SEC_DYNAMIC) -i ; + /var/db/host.random -> $(SEC_READONLY) -mCM ; + /var/cron -> $(SEC_GROWING) -i ; + /var/log -> $(SEC_GROWING) -i ; + /var/run -> $(SEC_DYNAMIC) -i ; + /var/mail -> $(SEC_GROWING) ; + /var/msgs/bounds -> $(SEC_READONLY) -smbCM ; + /var/spool/clientmqueue -> $(SEC_TEMPORARY) ; + /var/spool/mqueue -> $(SEC_TEMPORARY) ; +} + +# +# $Id: twpol-OpenBSD.txt,v 1.2 2004/05/14 21:56:21 pherman Exp $ +# diff --git a/policy/twpol-Linux.txt b/policy/twpol-Linux.txt index 9e1d983..ece0e34 100644 --- a/policy/twpol-Linux.txt +++ b/policy/twpol-Linux.txt @@ -2,7 +2,8 @@ # ## ############################################################################## # # # # -# Policy file for Red Hat Linux # # +# Tripwire 2.4 policy for Linux (RPM) # # +# updated March 2018 # # # ## ############################################################################## @@ -59,13 +60,13 @@ HOSTNAME=; # ############################################################################## -Device = +pugsdr-intlbamcCMSH ; -Dynamic = +pinugtd-srlbamcCMSH ; -Growing = +pinugtdl-srbamcCMSH ; -IgnoreAll = -pinugtsdrlbamcCMSH ; -IgnoreNone = +pinugtsdrbamcCMSH-l ; -ReadOnly = +pinugtsdbmCM-rlacSH ; -Temporary = +pugt ; +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; @@section FS @@ -82,10 +83,10 @@ Temporary = +pugt ; rulename = "Tripwire Binaries", ) { - $(TWBIN)/siggen -> $(ReadOnly) ; - $(TWBIN)/tripwire -> $(ReadOnly) ; - $(TWBIN)/twadmin -> $(ReadOnly) ; - $(TWBIN)/twprint -> $(ReadOnly) ; + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; } # Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases @@ -102,14 +103,14 @@ Temporary = +pugt ; # afterward triggers this rule until a database update is run, since the # database file does not exist before that point. - $(TWDB) -> $(Dynamic) -i ; - $(TWPOL)/tw.pol -> $(ReadOnly) -i ; - $(TWPOL)/tw.cfg -> $(ReadOnly) -i ; - $(TWLKEY)/$(HOSTNAME)-local.key -> $(ReadOnly) ; - $(TWSKEY)/site.key -> $(ReadOnly) ; + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; # don't scan the individual reports - $(TWREPORT) -> $(Dynamic) (recurse=0) ; + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; } ################################################ @@ -123,10 +124,10 @@ Temporary = +pugt ; rulename = "RPM Checksum Files", ) { - /var/lib/rpm -> $(ReadOnly); - /var/lib/rpm/__db.001 -> $(Dynamic) ; - /var/lib/rpm/__db.002 -> $(Dynamic) ; - /var/lib/rpm/__db.003 -> $(Dynamic) ; + /var/lib/rpm -> $(SEC_READONLY); + /var/lib/rpm/__db.001 -> $(SEC_DYNAMIC) ; + /var/lib/rpm/__db.002 -> $(SEC_DYNAMIC) ; + /var/lib/rpm/__db.003 -> $(SEC_DYNAMIC) ; } ################################################ @@ -140,18 +141,18 @@ Temporary = +pugt ; rulename = "Global Configuration Files", ) { - /etc -> $(IgnoreNone) -SHa ; - /etc/adjtime -> $(Dynamic) ; - /etc/aliases.db -> $(Dynamic) ; - /etc/bashrc -> $(Dynamic) ; - /etc/csh.cshrc -> $(Dynamic) ; - /etc/csh.login -> $(Dynamic) ; - /etc/mail/statistics -> $(Growing) ; - /etc/profile -> $(Dynamic) -i ; - /etc/mtab -> $(Dynamic) -i ; - /etc/rc.d -> $(IgnoreNone) -SHa ; - /etc/sysconfig -> $(IgnoreNone) -SHa ; - /etc/sysconfig/hwconf -> $(Dynamic) -m ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; + /etc/adjtime -> $(SEC_DYNAMIC) ; + /etc/aliases.db -> $(SEC_DYNAMIC) ; + /etc/bashrc -> $(SEC_DYNAMIC) ; + /etc/csh.cshrc -> $(SEC_DYNAMIC) ; + /etc/csh.login -> $(SEC_DYNAMIC) ; + /etc/mail/statistics -> $(SEC_GROWING) ; + /etc/profile -> $(SEC_DYNAMIC) -i ; + /etc/mtab -> $(SEC_DYNAMIC) -i ; + /etc/rc.d -> $(SEC_IGNORE_NONE) -SHa ; + /etc/sysconfig -> $(SEC_IGNORE_NONE) -SHa ; + /etc/sysconfig/hwconf -> $(SEC_DYNAMIC) -m ; } ################################################ @@ -165,10 +166,10 @@ Temporary = +pugt ; rulename = "OS Boot Files and Mount Points", ) { - /boot -> $(ReadOnly) ; - /cdrom -> $(Dynamic) ; - /floppy -> $(Dynamic) ; - /mnt -> $(Dynamic) ; + /boot -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /floppy -> $(SEC_DYNAMIC) ; + /mnt -> $(SEC_DYNAMIC) ; } ################################################ @@ -182,12 +183,12 @@ Temporary = +pugt ; rulename = "OS Devices and Misc Directories", ) { - /dev -> $(Device) ; - /initrd -> $(Dynamic) ; - /opt -> $(Dynamic) ; - /lost+found -> $(Dynamic) ; - /var/lost+found -> $(Dynamic) ; - /home/lost+found -> $(Dynamic) ; + /dev -> $(SEC_DEVICE) ; + /initrd -> $(SEC_DYNAMIC) ; + /opt -> $(SEC_DYNAMIC) ; + /lost+found -> $(SEC_DYNAMIC) ; + /var/lost+found -> $(SEC_DYNAMIC) ; + /home/lost+found -> $(SEC_DYNAMIC) ; !/dev/pts ; # Ignore this file !/dev/shm ; # Ignore this file } @@ -203,14 +204,14 @@ Temporary = +pugt ; rulename = "OS Binaries and Libraries", ) { - /bin -> $(ReadOnly) ; - /lib -> $(ReadOnly) ; - /sbin -> $(ReadOnly) ; - /usr/bin -> $(ReadOnly) ; - /usr/lib -> $(ReadOnly) ; - /usr/libexec -> $(ReadOnly) ; - /usr/sbin -> $(ReadOnly) ; - /usr/X11R6/lib -> $(ReadOnly) ; + /bin -> $(SEC_READONLY) ; + /lib -> $(SEC_READONLY) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/libexec -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/X11R6/lib -> $(SEC_READONLY) ; } ################################################ # ## @@ -224,19 +225,19 @@ Temporary = +pugt ; ) { !/home/local; - /usr/local -> $(ReadOnly) ; - /usr/local/bin -> $(ReadOnly) ; - /usr/local/doc -> $(ReadOnly) ; - /usr/local/etc -> $(ReadOnly) ; - /usr/local/games -> $(ReadOnly) ; - /usr/local/include -> $(ReadOnly) ; - /usr/local/lib -> $(ReadOnly) ; - /usr/local/libexec -> $(ReadOnly) ; - /usr/local/man -> $(ReadOnly) ; - /usr/local/sbin -> $(ReadOnly) ; - /usr/local/share -> $(ReadOnly) ; - /usr/local/src -> $(ReadOnly) ; - /usr/local/sysinfo -> $(ReadOnly) ; + /usr/local -> $(SEC_READONLY) ; + /usr/local/bin -> $(SEC_READONLY) ; + /usr/local/doc -> $(SEC_READONLY) ; + /usr/local/etc -> $(SEC_READONLY) ; + /usr/local/games -> $(SEC_READONLY) ; + /usr/local/include -> $(SEC_READONLY) ; + /usr/local/lib -> $(SEC_READONLY) ; + /usr/local/libexec -> $(SEC_READONLY) ; + /usr/local/man -> $(SEC_READONLY) ; + /usr/local/sbin -> $(SEC_READONLY) ; + /usr/local/share -> $(SEC_READONLY) ; + /usr/local/src -> $(SEC_READONLY) ; + /usr/local/sysinfo -> $(SEC_READONLY) ; } ################################################ @@ -250,29 +251,29 @@ Temporary = +pugt ; rulename = "Root Directory and Files", ) { - /root -> $(IgnoreNone) -SHa ; - /root/.bashrc -> $(Dynamic) ; - /root/.bash_history -> $(Dynamic) ; - #/root/.bash_logout -> $(Dynamic) ; - /root/.bash_profile -> $(Dynamic) ; - /root/.cshrc -> $(Dynamic) ; - #/root/.enlightenment -> $(Dynamic) ; - #/root/.esd-auth -> $(Dynamic) ; + /root -> $(SEC_IGNORE_NONE) -SHa ; + /root/.bashrc -> $(SEC_DYNAMIC) ; + /root/.bash_history -> $(SEC_DYNAMIC) ; + #/root/.bash_logout -> $(SEC_DYNAMIC) ; + /root/.bash_profile -> $(SEC_DYNAMIC) ; + /root/.cshrc -> $(SEC_DYNAMIC) ; + #/root/.enlightenment -> $(SEC_DYNAMIC) ; + #/root/.esd-auth -> $(SEC_DYNAMIC) ; !/root/.gconf ; !/root/.gconfd ; - #/root/.gnome -> $(Dynamic) ; - #/root/.gnome-desktop -> $(Dynamic) ; - #/root/.gnome2 -> $(Dynamic) ; - #/root/.gtkrc -> $(Dynamic) ; - #/root/.gtkrc-1.2-gnome2 -> $(Dynamic) ; - #/root/.metacity -> $(Dynamic) ; - #/root/.nautilus -> $(Dynamic) ; - #/root/.rhn-applet.conf -> $(Dynamic) ; - #/root/.tcshrc -> $(Dynamic) ; - #/root/.xauth -> $(Dynamic) ; - #/root/.ICEauthority -> $(Dynamic) ; - #/root/.Xauthority -> $(Dynamic) -i ; - #/root/.Xresources -> $(Dynamic) ; + #/root/.gnome -> $(SEC_DYNAMIC) ; + #/root/.gnome-desktop -> $(SEC_DYNAMIC) ; + #/root/.gnome2 -> $(SEC_DYNAMIC) ; + #/root/.gtkrc -> $(SEC_DYNAMIC) ; + #/root/.gtkrc-1.2-gnome2 -> $(SEC_DYNAMIC) ; + #/root/.metacity -> $(SEC_DYNAMIC) ; + #/root/.nautilus -> $(SEC_DYNAMIC) ; + #/root/.rhn-applet.conf -> $(SEC_DYNAMIC) ; + #/root/.tcshrc -> $(SEC_DYNAMIC) ; + #/root/.xauth -> $(SEC_DYNAMIC) ; + #/root/.ICEauthority -> $(SEC_DYNAMIC) ; + #/root/.Xauthority -> $(SEC_DYNAMIC) -i ; + #/root/.Xresources -> $(SEC_DYNAMIC) ; } ################################################ @@ -286,12 +287,12 @@ Temporary = +pugt ; rulename = "Temporary Directories", ) { - /usr/tmp -> $(Temporary) ; - /var/tmp -> $(Temporary) ; - /tmp -> $(Temporary) ; - #/tmp/.fam-socket -> $(Temporary) ; - #/tmp/.ICE-unix -> $(Temporary) ; - #/tmp/.X11-unix -> $(Temporary) ; + /usr/tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; + /tmp -> $(SEC_TEMPORARY) ; + #/tmp/.fam-socket -> $(SEC_TEMPORARY) ; + #/tmp/.ICE-unix -> $(SEC_TEMPORARY) ; + #/tmp/.X11-unix -> $(SEC_TEMPORARY) ; !/tmp/orbit-root ; } @@ -306,21 +307,21 @@ Temporary = +pugt ; rulename = "System Boot Changes", ) { - /.autofsck -> $(Dynamic) -m ; - /var/cache/man/whatis -> $(Growing) ; - /var/lib/logrotate.status -> $(Growing) ; - #/var/lib/nfs/statd -> $(Growing) ; + /.autofsck -> $(SEC_DYNAMIC) -m ; + /var/cache/man/whatis -> $(SEC_GROWING) ; + /var/lib/logrotate.status -> $(SEC_GROWING) ; + #/var/lib/nfs/statd -> $(SEC_GROWING) ; !/var/lib/random-seed ; - #/var/lib/slocate/slocate.db -> $(Growing) -is ; - /var/lock/subsys -> $(Dynamic) -i ; - /var/log -> $(Growing) -i ; + #/var/lib/slocate/slocate.db -> $(SEC_GROWING) -is ; + /var/lock/subsys -> $(SEC_DYNAMIC) -i ; + /var/log -> $(SEC_GROWING) -i ; !/var/log/sa; !/var/log/cisco; - /var/run -> $(Dynamic) -i ; - /etc/cron.daily -> $(Growing); - /etc/cron.weekly -> $(Growing); - /etc/cron.monthly -> $(Growing); - /var/spool/mail -> $(Growing); + /var/run -> $(SEC_DYNAMIC) -i ; + /etc/cron.daily -> $(SEC_GROWING); + /etc/cron.weekly -> $(SEC_GROWING); + /etc/cron.monthly -> $(SEC_GROWING); + /var/spool/mail -> $(SEC_GROWING); } ################################################ @@ -334,10 +335,10 @@ Temporary = +pugt ; rulename = "Monitor Filesystems", ) { - / -> $(ReadOnly) ; - /home -> $(ReadOnly) ; # Modify as needed - /usr -> $(ReadOnly) ; - /var -> $(ReadOnly) ; + / -> $(SEC_READONLY) ; + /home -> $(SEC_READONLY) ; # Modify as needed + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; } ################################################ diff --git a/policy/twpol-MidnightBSD.txt b/policy/twpol-MidnightBSD.txt new file mode 100644 index 0000000..a9dcac9 --- /dev/null +++ b/policy/twpol-MidnightBSD.txt @@ -0,0 +1,664 @@ +# +# Policy file for MidnightBSD +# (adapted from FreeBSD policy) +# +# $FreeBSD: ports/security/tripwire/files/twpol.txt,v 1.2 2002/03/04 16:55:21 cy Exp $ +# $Id: twpol-FreeBSD.txt,v 1.1 2003/06/08 02:00:06 pherman Exp $ + +# +# This is the example Tripwire Policy file. It is intended as a place to +# start creating your own custom Tripwire Policy file. Referring to it as +# well as the Tripwire Policy Guide should give you enough information to +# make a good custom Tripwire Policy file that better covers your +# configuration and security needs. A text version of this policy file is +# called twpol.txt. +# +# Note that this file is tuned to an install of FreeBSD using +# buildworld. If run unmodified, this file should create no errors on +# database creation, or violations on a subsiquent integrity check. +# However it is impossible for there to be one policy file for all machines, +# so this existing one errs on the side of security. Your FreeBSD +# configuration will most likey differ from the one our policy file was +# tuned to, and will therefore require some editing of the default +# Tripwire Policy file. +# +# The example policy file is best run with 'Loose Directory Checking' +# enabled. Set LOOSEDIRECTORYCHECKING=TRUE in the Tripwire Configuration +# file. +# +# Email support is not included and must be added to this file. +# Add the 'emailto=' to the rule directive section of each rule (add a comma +# after the 'severity=' line and add an 'emailto=' and include the email +# addresses you want the violation reports to go to). Addresses are +# semi-colon delimited. +# + + + +# +# Global Variable Definitions +# +# These are defined at install time by the installation script. You may +# Manually edit these if you are using this file directly and not from the +# installation script itself. +# + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +@@section FS +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +SEC_CRIT = $(SEC_IGNORE_NONE)-SHa ; # Critical files that cannot change +SEC_SUID = $(SEC_IGNORE_NONE)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(SEC_READONLY) ; # Binaries that should not change +SEC_CONFIG = $(SEC_DYNAMIC) ; # Config files that are changed infrequently but accessed often +SEC_TTY = $(SEC_DYNAMIC)-ugp ; # Tty files that change ownership at login +SEC_LOG = $(SEC_GROWING) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = $(SEC_TEMPORARY) ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability + + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", + severity = $(SIG_HI) +) +{ + $(TWBIN)/siggen -> $(SEC_BIN) ; + $(TWBIN)/tripwire -> $(SEC_BIN) ; + $(TWBIN)/twadmin -> $(SEC_BIN) ; + $(TWBIN)/twprint -> $(SEC_BIN) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", + severity = $(SIG_HI) +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_CONFIG) -i ; + $(TWPOL)/tw.pol -> $(SEC_BIN) -i ; + $(TWPOL)/tw.cfg -> $(SEC_BIN) -i ; + $(TWPOL)/twcfg.txt -> $(SEC_BIN) ; + $(TWPOL)/twpol.txt -> $(SEC_BIN) ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_BIN) ; + $(TWSKEY)/site.key -> $(SEC_BIN) ; + + #don't scan the individual reports + $(TWREPORT) -> $(SEC_CONFIG) (recurse=0) ; +} + + +# Tripwire HQ Connector Binaries +#( +# rulename = "Tripwire HQ Connector Binaries", +# severity = $(SIG_HI) +#) +#{ +# $(TWBIN)/hqagent -> $(SEC_BIN) ; +#} +# +# Tripwire HQ Connector - Configuration Files, Keys, and Logs + +# +# Note: File locations here are different than in a stock HQ Connector +# installation. This is because Tripwire 2.3 uses a different path +# structure than Tripwire 2.2.1. +# +# You may need to update your HQ Agent configuation file (or this policy +# file) to correct the paths. We have attempted to support the FHS standard +# here by placing the HQ Agent files similarly to the way Tripwire 2.3 +# places them. +# + +#( +# rulename = "Tripwire HQ Connector Data Files", +# severity = $(SIG_HI) +#) +#{ +# +# # NOTE: Removing the inode attribute because when Tripwire creates a backup +# # it does so by renaming the old file and creating a new one (which will +# # have a new inode number). Leaving inode turned on for keys, which +# # shouldn't ever change. +# +# +# $(TWBIN)/agent.cfg -> $(SEC_BIN) -i ; +# $(TWLKEY)/authentication.key -> $(SEC_BIN) ; +# $(TWDB)/tasks.dat -> $(SEC_CONFIG) ; +# $(TWDB)/schedule.dat -> $(SEC_CONFIG) ; +# +# # Uncomment if you have agent logging enabled. +# #/var/log/tripwire/agent.log -> $(SEC_LOG) ; +#} + + + +# Commonly accessed directories that should remain static with regards to owner and group +( + rulename = "Invariant Directories", + severity = $(SIG_MED) +) +{ + / -> $(SEC_INVARIANT) (recurse = false) ; + /home -> $(SEC_INVARIANT) (recurse = false) ; +} + +# +# First, root's "home" +# + +( + rulename = "Root's home", + severity = $(SIG_HI) +) +{ + # /.rhosts -> $(SEC_CRIT) ; + /.profile -> $(SEC_CRIT) ; + /.cshrc -> $(SEC_CRIT) ; + /.login -> $(SEC_CRIT) ; + # /.exrc -> $(SEC_CRIT) ; + # /.logout -> $(SEC_CRIT) ; + # /.forward -> $(SEC_CRIT) ; + /root -> $(SEC_CRIT) (recurse = true) ; + !/root/.history ; + !/root/.bash_history ; + # !/root/.lsof_SYSTEM_NAME ; # Uncomment if lsof is installed +} + + +# +# FreeBSD Kernel +# + +( + rulename = "FreeBSD Kernel", + severity = $(SIG_HI) +) +{ + /kernel -> $(SEC_CRIT) ; + /kernel.old -> $(SEC_CRIT) ; + /kernel.GENERIC -> $(SEC_CRIT) ; +} + + +# +# FreeBSD Modules +# + +( + rulename = "FreeBSD Modules", + severity = $(SIG_HI) +) +{ + /modules -> $(SEC_CRIT) (recurse = true) ; + /modules.old -> $(SEC_CRIT) (recurse = true) ; + # /lkm -> $(SEC_CRIT) (recurse = true) ; # uncomment if using lkm kld +} + + +# +# System Administration Programs +# + +( + rulename = "System Administration Programs", + severity = $(SIG_HI) +) +{ + /sbin -> $(SEC_CRIT) (recurse = true) ; + /usr/sbin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# User Utilities +# + +( + rulename = "User Utilities", + severity = $(SIG_HI) +) +{ + /bin -> $(SEC_CRIT) (recurse = true) ; + /usr/bin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# /dev +# + +( + rulename = "/dev", + severity = $(SIG_HI) +) +{ + /dev -> $(Device) (recurse = true) ; + !/dev/vga ; + !/dev/dri ; + /dev/console -> $(SEC_TTY) ; + /dev/ttyv0 -> $(SEC_TTY) ; + /dev/ttyv1 -> $(SEC_TTY) ; + /dev/ttyv2 -> $(SEC_TTY) ; + /dev/ttyv3 -> $(SEC_TTY) ; + /dev/ttyv4 -> $(SEC_TTY) ; + /dev/ttyv5 -> $(SEC_TTY) ; + /dev/ttyv6 -> $(SEC_TTY) ; + /dev/ttyv7 -> $(SEC_TTY) ; + /dev/ttyp0 -> $(SEC_TTY) ; + /dev/ttyp1 -> $(SEC_TTY) ; + /dev/ttyp2 -> $(SEC_TTY) ; + /dev/ttyp3 -> $(SEC_TTY) ; + /dev/ttyp4 -> $(SEC_TTY) ; + /dev/ttyp5 -> $(SEC_TTY) ; + /dev/ttyp6 -> $(SEC_TTY) ; + /dev/ttyp7 -> $(SEC_TTY) ; + /dev/ttyp8 -> $(SEC_TTY) ; + /dev/ttyp9 -> $(SEC_TTY) ; + /dev/ttypa -> $(SEC_TTY) ; + /dev/ttypb -> $(SEC_TTY) ; + /dev/ttypc -> $(SEC_TTY) ; + /dev/ttypd -> $(SEC_TTY) ; + /dev/ttype -> $(SEC_TTY) ; + /dev/ttypf -> $(SEC_TTY) ; + /dev/ttypg -> $(SEC_TTY) ; + /dev/ttyph -> $(SEC_TTY) ; + /dev/ttypi -> $(SEC_TTY) ; + /dev/ttypj -> $(SEC_TTY) ; + /dev/ttypl -> $(SEC_TTY) ; + /dev/ttypm -> $(SEC_TTY) ; + /dev/ttypn -> $(SEC_TTY) ; + /dev/ttypo -> $(SEC_TTY) ; + /dev/ttypp -> $(SEC_TTY) ; + /dev/ttypq -> $(SEC_TTY) ; + /dev/ttypr -> $(SEC_TTY) ; + /dev/ttyps -> $(SEC_TTY) ; + /dev/ttypt -> $(SEC_TTY) ; + /dev/ttypu -> $(SEC_TTY) ; + /dev/ttypv -> $(SEC_TTY) ; + /dev/cuaa0 -> $(SEC_TTY) ; # modem +} + + +# +# /etc +# + +( + rulename = "/etc", + severity = $(SIG_HI) +) +{ + /etc -> $(SEC_CRIT) (recurse = true) ; + # /etc/mail/aliases -> $(SEC_CONFIG) ; + /etc/dumpdates -> $(SEC_CONFIG) ; + /etc/motd -> $(SEC_CONFIG) ; + !/etc/ppp/connect-errors ; + /etc/skeykeys -> $(SEC_CONFIG) ; + # Uncomment the following 4 lines if your password file does not change + # /etc/passwd -> $(SEC_CONFIG) ; + # /etc/master.passwd -> $(SEC_CONFIG) ; + # /etc/pwd.db -> $(SEC_CONFIG) ; + # /etc/spwd.db -> $(SEC_CONFIG) ; +} + + +# +# Copatibility (Linux) +# + +( + rulename = "Linux Compatibility", + severity = $(SIG_HI) +) +{ + /compat -> $(SEC_CRIT) (recurse = true) ; +# +# Uncomment the following if Linux compatibility is used. Replace +# HOSTNAME1 and HOSTNAME2 with the hosts that have Linux emulation port +# installed. +# +#@@ifhost HOSTNAME1 || HOSTNAME2 +# /compat/linux/etc -> $(SEC_INVARIANT) (recurse = false) ; +# /compat/linux/etc/X11 -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/pam.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/profile.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/real -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/bashrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/csh.login -> $(SEC_CONFIG) ; +# /compat/linux/etc/host.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.allow -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.deny -> $(SEC_CONFIG) ; +# /compat/linux/etc/info-dir -> $(SEC_CONFIG) ; +# /compat/linux/etc/inputrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/ld.so.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/nsswitch.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/profile -> $(SEC_CONFIG) ; +# /compat/linux/etc/redhat-release -> $(SEC_CONFIG) ; +# /compat/linux/etc/rpc -> $(SEC_CONFIG) ; +# /compat/linux/etc/securetty -> $(SEC_CONFIG) ; +# /compat/linux/etc/shells -> $(SEC_CONFIG) ; +# /compat/linux/etc/termcap -> $(SEC_CONFIG) ; +# /compat/linux/etc/yp.conf -> $(SEC_CONFIG) ; +# !/compat/linux/etc/ld.so.cache ; +# !/compat/linux/var/spool/mail ; +#@@endif +} + + +# +# Libraries, include files, and other system files +# + +( + rulename = "Libraries, include files, and other system files", + severity = $(SIG_HI) +) +{ + /usr/include -> $(SEC_CRIT) (recurse = true) ; + /usr/lib -> $(SEC_CRIT) (recurse = true) ; + /usr/libdata -> $(SEC_CRIT) (recurse = true) ; + /usr/libexec -> $(SEC_CRIT) (recurse = true) ; + /usr/share -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man -> $(SEC_CONFIG) ; + !/usr/share/man/whatis ; + !/usr/share/man/.glimpse_filenames ; + !/usr/share/man/.glimpse_filenames_index ; + !/usr/share/man/.glimpse_filetimes ; + !/usr/share/man/.glimpse_filters ; + !/usr/share/man/.glimpse_index ; + !/usr/share/man/.glimpse_messages ; + !/usr/share/man/.glimpse_partitions ; + !/usr/share/man/.glimpse_statistics ; + !/usr/share/man/.glimpse_turbo ; + /usr/share/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/man/cat1 ; + ! /usr/share/man/cat2 ; + ! /usr/share/man/cat3 ; + ! /usr/share/man/cat4 ; + ! /usr/share/man/cat5 ; + ! /usr/share/man/cat6 ; + ! /usr/share/man/cat7 ; + ! /usr/share/man/cat8 ; + ! /usr/share/man/cat9 ; + ! /usr/share/man/catl ; + ! /usr/share/man/catn ; + /usr/share/perl/man -> $(SEC_CONFIG) ; + !/usr/share/perl/man/whatis ; + !/usr/share/perl/man/.glimpse_filenames ; + !/usr/share/perl/man/.glimpse_filenames_index ; + !/usr/share/perl/man/.glimpse_filetimes ; + !/usr/share/perl/man/.glimpse_filters ; + !/usr/share/perl/man/.glimpse_index ; + !/usr/share/perl/man/.glimpse_messages ; + !/usr/share/perl/man/.glimpse_partitions ; + !/usr/share/perl/man/.glimpse_statistics ; + !/usr/share/perl/man/.glimpse_turbo ; + /usr/share/perl/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/perl/man/cat3 ; + /usr/local/lib/perl5/5.00503/man -> $(SEC_CONFIG) ; + ! /usr/local/lib/perl5/5.00503/man/whatis ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filters ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filetimes ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_messages ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_statistics ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_index ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_turbo ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_partitions ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames_index ; + /usr/local/lib/perl5/5.00503/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/lib/perl5/5.00503/man/cat3 ; +} + + +# +# X11R6 +# + +( + rulename = "X11R6", + severity = $(SIG_HI) +) +{ + /usr/X11R6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/lib/X11/xdm -> $(SEC_CONFIG) (recurse = true) ; + !/usr/X11R6/lib/X11/xdm/xdm-errors ; + !/usr/X11R6/lib/X11/xdm/authdir/authfiles ; + !/usr/X11R6/lib/X11/xdm/xdm-pid ; + /usr/X11R6/lib/X11/xkb/compiled -> $(SEC_CONFIG) (recurse = true) ; + /usr/X11R6/man -> $(SEC_CONFIG) ; + !/usr/X11R6/man/whatis ; + !/usr/X11R6/man/.glimpse_filenames ; + !/usr/X11R6/man/.glimpse_filenames_index ; + !/usr/X11R6/man/.glimpse_filetimes ; + !/usr/X11R6/man/.glimpse_filters ; + !/usr/X11R6/man/.glimpse_index ; + !/usr/X11R6/man/.glimpse_messages ; + !/usr/X11R6/man/.glimpse_partitions ; + !/usr/X11R6/man/.glimpse_statistics ; + !/usr/X11R6/man/.glimpse_turbo ; + /usr/X11R6/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/X11R6/man/cat1 ; + ! /usr/X11R6/man/cat2 ; + ! /usr/X11R6/man/cat3 ; + ! /usr/X11R6/man/cat4 ; + ! /usr/X11R6/man/cat5 ; + ! /usr/X11R6/man/cat6 ; + ! /usr/X11R6/man/cat7 ; + ! /usr/X11R6/man/cat8 ; + ! /usr/X11R6/man/cat9 ; + ! /usr/X11R6/man/catl ; + ! /usr/X11R6/man/catn ; +} + + +# +# sources +# + +( + rulename = "Sources", + severity = $(SIG_HI) +) +{ + /usr/src -> $(SEC_CRIT) (recurse = true) ; + /usr/src/sys/compile -> $(SEC_CONFIG) (recurse = false) ; +} + + +# +# NIS +# + +( + rulename = "NIS", + severity = $(SIG_HI) +) +{ + /var/yp -> $(SEC_CRIT) (recurse = true) ; + !/var/yp/binding ; +} + + +# +# Temporary directories +# +( + rulename = "Temporary directories", + recurse = false, + severity = $(SIG_LOW) +) +{ + /usr/tmp -> $(SEC_INVARIANT) ; + /var/tmp -> $(SEC_INVARIANT) ; + /var/preserve -> $(SEC_INVARIANT) ; + /tmp -> $(SEC_INVARIANT) ; +} + +# +# Local files +# + +( + rulename = "Local files", + severity = $(SIG_MED) +) +{ + /usr/local/bin -> $(SEC_BIN) (recurse = true) ; + /usr/local/sbin -> $(SEC_BIN) (recurse = true) ; + /usr/local/etc -> $(SEC_BIN) (recurse = true) ; + /usr/local/lib -> $(SEC_BIN) (recurse = true ) ; + /usr/local/libexec -> $(SEC_BIN) (recurse = true ) ; + /usr/local/share -> $(SEC_BIN) (recurse = true ) ; + /usr/local/man -> $(SEC_CONFIG) ; + !/usr/local/man/whatis ; + !/usr/local/man/.glimpse_filenames ; + !/usr/local/man/.glimpse_filenames_index ; + !/usr/local/man/.glimpse_filetimes ; + !/usr/local/man/.glimpse_filters ; + !/usr/local/man/.glimpse_index ; + !/usr/local/man/.glimpse_messages ; + !/usr/local/man/.glimpse_partitions ; + !/usr/local/man/.glimpse_statistics ; + !/usr/local/man/.glimpse_turbo ; + /usr/local/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/man/cat1 ; + ! /usr/local/man/cat2 ; + ! /usr/local/man/cat3 ; + ! /usr/local/man/cat4 ; + ! /usr/local/man/cat5 ; + ! /usr/local/man/cat6 ; + ! /usr/local/man/cat7 ; + ! /usr/local/man/cat8 ; + ! /usr/local/man/cat9 ; + ! /usr/local/man/catl ; + ! /usr/local/man/catn ; + /usr/local/krb5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man -> $(SEC_CONFIG) ; + !/usr/local/krb5/man/whatis ; + !/usr/local/krb5/man/.glimpse_filenames ; + !/usr/local/krb5/man/.glimpse_filenames_index ; + !/usr/local/krb5/man/.glimpse_filetimes ; + !/usr/local/krb5/man/.glimpse_filters ; + !/usr/local/krb5/man/.glimpse_index ; + !/usr/local/krb5/man/.glimpse_messages ; + !/usr/local/krb5/man/.glimpse_partitions ; + !/usr/local/krb5/man/.glimpse_statistics ; + !/usr/local/krb5/man/.glimpse_turbo ; + /usr/local/krb5/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/krb5/man/cat1 ; + ! /usr/local/krb5/man/cat2 ; + ! /usr/local/krb5/man/cat3 ; + ! /usr/local/krb5/man/cat4 ; + ! /usr/local/krb5/man/cat5 ; + ! /usr/local/krb5/man/cat6 ; + ! /usr/local/krb5/man/cat7 ; + ! /usr/local/krb5/man/cat8 ; + ! /usr/local/krb5/man/cat9 ; + ! /usr/local/krb5/man/catl ; + ! /usr/local/krb5/man/catn ; + /usr/local/www -> $(SEC_CONFIG) (recurse = true) ; +} + + +( + rulename = "Security Control", + severity = $(SIG_HI) +) +{ + /etc/group -> $(SEC_CRIT) ; + /etc/crontab -> $(SEC_CRIT) ; +} + +#============================================================================= +# +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Inc. in the United States and other countries. All rights reserved. +# +# FreeBSD is a registered trademark of the FreeBSD Project Inc. +# +# UNIX is a registered trademark of The Open Group. +# +#============================================================================= +# +# Permission is granted to make and distribute verbatim copies of this document +# provided the copyright notice and this permission notice are preserved on all +# copies. +# +# Permission is granted to copy and distribute modified versions of this +# document under the conditions for verbatim copying, provided that the entire +# resulting derived work is distributed under the terms of a permission notice +# identical to this one. +# +# Permission is granted to copy and distribute translations of this document +# into another language, under the above conditions for modified versions, +# except that this permission notice may be stated in a translation approved by +# Tripwire, Inc. +# +# DCM diff --git a/policy/twpol-Minix.txt b/policy/twpol-Minix.txt new file mode 100644 index 0000000..18ae8a9 --- /dev/null +++ b/policy/twpol-Minix.txt @@ -0,0 +1,176 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for Minix ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + +############################################################################## + +(rulename="Boot files",) +{ + /boot -> $(SEC_READONLY) -a; + /boot_monitor -> $(SEC_READONLY) -a; + /boot.cfg -> $(SEC_READONLY) -a; +} + +(rulename="Binary files",) +{ + /bin -> $(SEC_READONLY) -a; + /usr/bin -> $(SEC_READONLY) -a; + /usr/local/bin -> $(SEC_READONLY) -a; + /usr/pkg/bin -> $(SEC_READONLY) -a; +} + +(rulename="Development",) +{ + /usr/pkg/gnu/bin -> $(SEC_READONLY) -a; + /usr/pkg/i386-elf32-minix/bin -> $(SEC_READONLY) -a; +} + +(rulename="Libexec",) +{ + /usr/libexec -> $(SEC_READONLY) -a; + /usr/pkg/libexec -> $(SEC_READONLY) -a; +} + +(rulename="Admin binaries",) +{ + /service -> $(SEC_READONLY) -a; + /sbin -> $(SEC_READONLY) -a; + /usr/sbin -> $(SEC_READONLY) -a; + /usr/pkg/sbin -> $(SEC_READONLY) -a; +} + +(rulename="Libraries",) +{ + /lib -> $(SEC_READONLY) -a; + /usr/lib -> $(SEC_READONLY) -a; + /usr/pkg/lib -> $(SEC_READONLY) -a; +} + +(rulename="Etc",) +{ + /etc -> $(SEC_READONLY) -a; + /usr/etc -> $(SEC_READONLY) -a; + /usr/pkg/etc -> $(SEC_READONLY) -a; +} + +(rulename="Dev",) +{ + /dev -> $(SEC_DEVICE); +} + +(rulename="Tmp",) +{ + /tmp -> $(SEC_TEMPORARY); + /var/tmp -> $(SEC_TEMPORARY); + /usr/tmp -> $(SEC_TEMPORARY); +} + +(rulename="Log",) +{ + /var/log -> $(SEC_GROWING); +} diff --git a/policy/twpol-MirBSD.txt b/policy/twpol-MirBSD.txt new file mode 100644 index 0000000..b9ce2a4 --- /dev/null +++ b/policy/twpol-MirBSD.txt @@ -0,0 +1,292 @@ + ############################################################################## + # ## +############################################################################## # +# # # +# Tripwire 2.4 policy for MirOS BSD # # +# updated March 2018 # # +# ## +############################################################################## + + ############################################################################## + # ## +############################################################################## # +# # # +# Global Variable Definitions # # +# # # +# These are defined at install time by the installation script. You may # # +# manually edit these if you are using this file directly and not from the # # +# installation script itself. # # +# ## +############################################################################## + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + + ############################################################################## + # Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + + ######################################## + # ## +######################################## # +# # # +# Tripwire Binaries and Data Files # # +# ## +######################################## + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; + + # In this configuration /usr/local is a symbolic link to /home/local. + # We want to ignore the following directories since they are already + # scanned using the real directory or mount point. Otherwise we see + # duplicates in the reports. + + !/home/local ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Boot and Configuration Files # # +# ## +################################################ +( + rulename = "OS Boot and Configuration Files", +) +{ + /boot -> $(SEC_READONLY) ; + /bsd -> $(SEC_READONLY) ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; +} + + ################################################### + # ## +################################################### # +# # # +# Mount Points # # +# ## +################################################### +( + rulename = "Mount Points", +) +{ + / -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /floppy -> $(SEC_DYNAMIC) ; + /home -> $(SEC_READONLY) ; # Modify as needed + /mnt -> $(SEC_DYNAMIC) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; +} + + ################################################### + # ## +################################################### # +# # # +# Misc Top-Level Directories # # +# ## +################################################### +( + rulename = "Misc Top-Level Directories", +) +{ + /altroot -> $(SEC_DYNAMIC) ; + /stand -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# System Devices # # +# ## +################################################ +( + rulename = "System Devices", +) +{ + /dev -> $(SEC_DEVICE) ; + /dev/fd -> $(SEC_DEVICE) ; + /var/cron/tabs/.sock -> $(SEC_DEVICE) ; + /var/empty/dev/log -> $(SEC_DEVICE) ; +} + + ################################################ + # ## +################################################ # +# # # +# OS Binaries and Libraries # # +# ## +################################################ +( + rulename = "OS Binaries and Libraries", +) +{ + /bin -> $(SEC_READONLY) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/libexec -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/X11R6/bin -> $(SEC_READONLY) ; + /usr/X11R6/lib -> $(SEC_READONLY) ; +} + ################################################ + # ## +################################################ # +# # # +# Usr Local Files # # +# ## +################################################ +#OK( + #OKrulename = "Usr Local Files", +#OK) +#OK{ + #OK/usr/local -> $(SEC_READONLY) ; + #OK/usr/local/bin -> $(SEC_READONLY) ; + #OK/usr/local/doc -> $(SEC_READONLY) ; + #OK/usr/local/etc -> $(SEC_READONLY) ; + #OK/usr/local/include -> $(SEC_READONLY) ; + #OK/usr/local/info -> $(SEC_READONLY) ; + #OK/usr/local/lib -> $(SEC_READONLY) ; + #OK/usr/local/libdata -> $(SEC_READONLY) ; + #OK/usr/local/libexec -> $(SEC_READONLY) ; + #OK/usr/local/man -> $(SEC_READONLY) ; + #OK/usr/local/sbin -> $(SEC_READONLY) ; + #OK/usr/local/share -> $(SEC_READONLY) ; + #OK/usr/local/src -> $(SEC_READONLY) ; +#OK} + + ################################################ + # ## +################################################ # +# # # +# Root Directory and Files # # +# ## +################################################ +( + rulename = "Root Directory and Files", +) +{ + /root -> $(SEC_IGNORE_NONE) -SHa ; + /root/.cshrc -> $(SEC_DYNAMIC) ; + /root/.profile -> $(SEC_DYNAMIC) ; +} + + ################################################ + # ## +################################################ # +# # # +# Temporary Directories # # +# ## +################################################ +( + rulename = "Temporary Directories", +) +{ + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; +} + + ################################################ + # ## +################################################ # +# # # +# System and Boot Changes # # +# ## +################################################ +( + rulename = "System and Boot Changes", +) +{ + /var/backups -> $(SEC_DYNAMIC) -i ; + /var/db/host.random -> $(SEC_READONLY) -mCM ; + /var/cron -> $(SEC_GROWING) -i ; + /var/log -> $(SEC_GROWING) -i ; + /var/run -> $(SEC_DYNAMIC) -i ; + /var/mail -> $(SEC_GROWING) ; + /var/msgs/bounds -> $(SEC_READONLY) -smbCM ; + /var/spool/clientmqueue -> $(SEC_TEMPORARY) ; + /var/spool/mqueue -> $(SEC_TEMPORARY) ; +} + +# +# $Id: twpol-OpenBSD.txt,v 1.2 2004/05/14 21:56:21 pherman Exp $ +# diff --git a/policy/twpol-NetBSD.txt b/policy/twpol-NetBSD.txt new file mode 100644 index 0000000..9e9f070 --- /dev/null +++ b/policy/twpol-NetBSD.txt @@ -0,0 +1,664 @@ +# +# Policy file for NetBSD +# (adapted from FreeBSD policy) +# +# $FreeBSD: ports/security/tripwire/files/twpol.txt,v 1.2 2002/03/04 16:55:21 cy Exp $ +# $Id: twpol-FreeBSD.txt,v 1.1 2003/06/08 02:00:06 pherman Exp $ + +# +# This is the example Tripwire Policy file. It is intended as a place to +# start creating your own custom Tripwire Policy file. Referring to it as +# well as the Tripwire Policy Guide should give you enough information to +# make a good custom Tripwire Policy file that better covers your +# configuration and security needs. A text version of this policy file is +# called twpol.txt. +# +# Note that this file is tuned to an install of FreeBSD using +# buildworld. If run unmodified, this file should create no errors on +# database creation, or violations on a subsiquent integrity check. +# However it is impossible for there to be one policy file for all machines, +# so this existing one errs on the side of security. Your FreeBSD +# configuration will most likey differ from the one our policy file was +# tuned to, and will therefore require some editing of the default +# Tripwire Policy file. +# +# The example policy file is best run with 'Loose Directory Checking' +# enabled. Set LOOSEDIRECTORYCHECKING=TRUE in the Tripwire Configuration +# file. +# +# Email support is not included and must be added to this file. +# Add the 'emailto=' to the rule directive section of each rule (add a comma +# after the 'severity=' line and add an 'emailto=' and include the email +# addresses you want the violation reports to go to). Addresses are +# semi-colon delimited. +# + + + +# +# Global Variable Definitions +# +# These are defined at install time by the installation script. You may +# Manually edit these if you are using this file directly and not from the +# installation script itself. +# + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +@@section FS +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +SEC_CRIT = $(SEC_IGNORE_NONE)-SHa ; # Critical files that cannot change +SEC_SUID = $(SEC_IGNORE_NONE)-SHa ; # Binaries with the SUID or SGID flags set +SEC_BIN = $(SEC_READONLY) ; # Binaries that should not change +SEC_CONFIG = $(SEC_DYNAMIC) ; # Config files that are changed infrequently but accessed often +SEC_TTY = $(SEC_DYNAMIC)-ugp ; # Tty files that change ownership at login +SEC_LOG = $(SEC_GROWING) ; # Files that grow, but that should never change ownership +SEC_INVARIANT = $(SEC_TEMPORARY) ; # Directories that should never change permission or ownership +SIG_LOW = 33 ; # Non-critical files that are of minimal security impact +SIG_MED = 66 ; # Non-critical files that are of significant security impact +SIG_HI = 100 ; # Critical files that are significant points of vulnerability + + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", + severity = $(SIG_HI) +) +{ + $(TWBIN)/siggen -> $(SEC_BIN) ; + $(TWBIN)/tripwire -> $(SEC_BIN) ; + $(TWBIN)/twadmin -> $(SEC_BIN) ; + $(TWBIN)/twprint -> $(SEC_BIN) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", + severity = $(SIG_HI) +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_CONFIG) -i ; + $(TWPOL)/tw.pol -> $(SEC_BIN) -i ; + $(TWPOL)/tw.cfg -> $(SEC_BIN) -i ; + $(TWPOL)/twcfg.txt -> $(SEC_BIN) ; + $(TWPOL)/twpol.txt -> $(SEC_BIN) ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_BIN) ; + $(TWSKEY)/site.key -> $(SEC_BIN) ; + + #don't scan the individual reports + $(TWREPORT) -> $(SEC_CONFIG) (recurse=0) ; +} + + +# Tripwire HQ Connector Binaries +#( +# rulename = "Tripwire HQ Connector Binaries", +# severity = $(SIG_HI) +#) +#{ +# $(TWBIN)/hqagent -> $(SEC_BIN) ; +#} +# +# Tripwire HQ Connector - Configuration Files, Keys, and Logs + +# +# Note: File locations here are different than in a stock HQ Connector +# installation. This is because Tripwire 2.3 uses a different path +# structure than Tripwire 2.2.1. +# +# You may need to update your HQ Agent configuation file (or this policy +# file) to correct the paths. We have attempted to support the FHS standard +# here by placing the HQ Agent files similarly to the way Tripwire 2.3 +# places them. +# + +#( +# rulename = "Tripwire HQ Connector Data Files", +# severity = $(SIG_HI) +#) +#{ +# +# # NOTE: Removing the inode attribute because when Tripwire creates a backup +# # it does so by renaming the old file and creating a new one (which will +# # have a new inode number). Leaving inode turned on for keys, which +# # shouldn't ever change. +# +# +# $(TWBIN)/agent.cfg -> $(SEC_BIN) -i ; +# $(TWLKEY)/authentication.key -> $(SEC_BIN) ; +# $(TWDB)/tasks.dat -> $(SEC_CONFIG) ; +# $(TWDB)/schedule.dat -> $(SEC_CONFIG) ; +# +# # Uncomment if you have agent logging enabled. +# #/var/log/tripwire/agent.log -> $(SEC_LOG) ; +#} + + + +# Commonly accessed directories that should remain static with regards to owner and group +( + rulename = "Invariant Directories", + severity = $(SIG_MED) +) +{ + / -> $(SEC_INVARIANT) (recurse = false) ; + /home -> $(SEC_INVARIANT) (recurse = false) ; +} + +# +# First, root's "home" +# + +( + rulename = "Root's home", + severity = $(SIG_HI) +) +{ + # /.rhosts -> $(SEC_CRIT) ; + /.profile -> $(SEC_CRIT) ; + /.cshrc -> $(SEC_CRIT) ; + /.login -> $(SEC_CRIT) ; + # /.exrc -> $(SEC_CRIT) ; + # /.logout -> $(SEC_CRIT) ; + # /.forward -> $(SEC_CRIT) ; + /root -> $(SEC_CRIT) (recurse = true) ; + !/root/.history ; + !/root/.bash_history ; + # !/root/.lsof_SYSTEM_NAME ; # Uncomment if lsof is installed +} + + +# +# FreeBSD Kernel +# + +( + rulename = "FreeBSD Kernel", + severity = $(SIG_HI) +) +{ + /kernel -> $(SEC_CRIT) ; + /kernel.old -> $(SEC_CRIT) ; + /kernel.GENERIC -> $(SEC_CRIT) ; +} + + +# +# FreeBSD Modules +# + +( + rulename = "FreeBSD Modules", + severity = $(SIG_HI) +) +{ + /modules -> $(SEC_CRIT) (recurse = true) ; + /modules.old -> $(SEC_CRIT) (recurse = true) ; + # /lkm -> $(SEC_CRIT) (recurse = true) ; # uncomment if using lkm kld +} + + +# +# System Administration Programs +# + +( + rulename = "System Administration Programs", + severity = $(SIG_HI) +) +{ + /sbin -> $(SEC_CRIT) (recurse = true) ; + /usr/sbin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# User Utilities +# + +( + rulename = "User Utilities", + severity = $(SIG_HI) +) +{ + /bin -> $(SEC_CRIT) (recurse = true) ; + /usr/bin -> $(SEC_CRIT) (recurse = true) ; +} + + +# +# /dev +# + +( + rulename = "/dev", + severity = $(SIG_HI) +) +{ + /dev -> $(Device) (recurse = true) ; + !/dev/vga ; + !/dev/dri ; + /dev/console -> $(SEC_TTY) ; + /dev/ttyv0 -> $(SEC_TTY) ; + /dev/ttyv1 -> $(SEC_TTY) ; + /dev/ttyv2 -> $(SEC_TTY) ; + /dev/ttyv3 -> $(SEC_TTY) ; + /dev/ttyv4 -> $(SEC_TTY) ; + /dev/ttyv5 -> $(SEC_TTY) ; + /dev/ttyv6 -> $(SEC_TTY) ; + /dev/ttyv7 -> $(SEC_TTY) ; + /dev/ttyp0 -> $(SEC_TTY) ; + /dev/ttyp1 -> $(SEC_TTY) ; + /dev/ttyp2 -> $(SEC_TTY) ; + /dev/ttyp3 -> $(SEC_TTY) ; + /dev/ttyp4 -> $(SEC_TTY) ; + /dev/ttyp5 -> $(SEC_TTY) ; + /dev/ttyp6 -> $(SEC_TTY) ; + /dev/ttyp7 -> $(SEC_TTY) ; + /dev/ttyp8 -> $(SEC_TTY) ; + /dev/ttyp9 -> $(SEC_TTY) ; + /dev/ttypa -> $(SEC_TTY) ; + /dev/ttypb -> $(SEC_TTY) ; + /dev/ttypc -> $(SEC_TTY) ; + /dev/ttypd -> $(SEC_TTY) ; + /dev/ttype -> $(SEC_TTY) ; + /dev/ttypf -> $(SEC_TTY) ; + /dev/ttypg -> $(SEC_TTY) ; + /dev/ttyph -> $(SEC_TTY) ; + /dev/ttypi -> $(SEC_TTY) ; + /dev/ttypj -> $(SEC_TTY) ; + /dev/ttypl -> $(SEC_TTY) ; + /dev/ttypm -> $(SEC_TTY) ; + /dev/ttypn -> $(SEC_TTY) ; + /dev/ttypo -> $(SEC_TTY) ; + /dev/ttypp -> $(SEC_TTY) ; + /dev/ttypq -> $(SEC_TTY) ; + /dev/ttypr -> $(SEC_TTY) ; + /dev/ttyps -> $(SEC_TTY) ; + /dev/ttypt -> $(SEC_TTY) ; + /dev/ttypu -> $(SEC_TTY) ; + /dev/ttypv -> $(SEC_TTY) ; + /dev/cuaa0 -> $(SEC_TTY) ; # modem +} + + +# +# /etc +# + +( + rulename = "/etc", + severity = $(SIG_HI) +) +{ + /etc -> $(SEC_CRIT) (recurse = true) ; + # /etc/mail/aliases -> $(SEC_CONFIG) ; + /etc/dumpdates -> $(SEC_CONFIG) ; + /etc/motd -> $(SEC_CONFIG) ; + !/etc/ppp/connect-errors ; + /etc/skeykeys -> $(SEC_CONFIG) ; + # Uncomment the following 4 lines if your password file does not change + # /etc/passwd -> $(SEC_CONFIG) ; + # /etc/master.passwd -> $(SEC_CONFIG) ; + # /etc/pwd.db -> $(SEC_CONFIG) ; + # /etc/spwd.db -> $(SEC_CONFIG) ; +} + + +# +# Copatibility (Linux) +# + +( + rulename = "Linux Compatibility", + severity = $(SIG_HI) +) +{ + /compat -> $(SEC_CRIT) (recurse = true) ; +# +# Uncomment the following if Linux compatibility is used. Replace +# HOSTNAME1 and HOSTNAME2 with the hosts that have Linux emulation port +# installed. +# +#@@ifhost HOSTNAME1 || HOSTNAME2 +# /compat/linux/etc -> $(SEC_INVARIANT) (recurse = false) ; +# /compat/linux/etc/X11 -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/pam.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/profile.d -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/real -> $(SEC_CONFIG) (recurse = true) ; +# /compat/linux/etc/bashrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/csh.login -> $(SEC_CONFIG) ; +# /compat/linux/etc/host.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.allow -> $(SEC_CONFIG) ; +# /compat/linux/etc/hosts.deny -> $(SEC_CONFIG) ; +# /compat/linux/etc/info-dir -> $(SEC_CONFIG) ; +# /compat/linux/etc/inputrc -> $(SEC_CONFIG) ; +# /compat/linux/etc/ld.so.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/nsswitch.conf -> $(SEC_CONFIG) ; +# /compat/linux/etc/profile -> $(SEC_CONFIG) ; +# /compat/linux/etc/redhat-release -> $(SEC_CONFIG) ; +# /compat/linux/etc/rpc -> $(SEC_CONFIG) ; +# /compat/linux/etc/securetty -> $(SEC_CONFIG) ; +# /compat/linux/etc/shells -> $(SEC_CONFIG) ; +# /compat/linux/etc/termcap -> $(SEC_CONFIG) ; +# /compat/linux/etc/yp.conf -> $(SEC_CONFIG) ; +# !/compat/linux/etc/ld.so.cache ; +# !/compat/linux/var/spool/mail ; +#@@endif +} + + +# +# Libraries, include files, and other system files +# + +( + rulename = "Libraries, include files, and other system files", + severity = $(SIG_HI) +) +{ + /usr/include -> $(SEC_CRIT) (recurse = true) ; + /usr/lib -> $(SEC_CRIT) (recurse = true) ; + /usr/libdata -> $(SEC_CRIT) (recurse = true) ; + /usr/libexec -> $(SEC_CRIT) (recurse = true) ; + /usr/share -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man -> $(SEC_CONFIG) ; + !/usr/share/man/whatis ; + !/usr/share/man/.glimpse_filenames ; + !/usr/share/man/.glimpse_filenames_index ; + !/usr/share/man/.glimpse_filetimes ; + !/usr/share/man/.glimpse_filters ; + !/usr/share/man/.glimpse_index ; + !/usr/share/man/.glimpse_messages ; + !/usr/share/man/.glimpse_partitions ; + !/usr/share/man/.glimpse_statistics ; + !/usr/share/man/.glimpse_turbo ; + /usr/share/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/share/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/man/cat1 ; + ! /usr/share/man/cat2 ; + ! /usr/share/man/cat3 ; + ! /usr/share/man/cat4 ; + ! /usr/share/man/cat5 ; + ! /usr/share/man/cat6 ; + ! /usr/share/man/cat7 ; + ! /usr/share/man/cat8 ; + ! /usr/share/man/cat9 ; + ! /usr/share/man/catl ; + ! /usr/share/man/catn ; + /usr/share/perl/man -> $(SEC_CONFIG) ; + !/usr/share/perl/man/whatis ; + !/usr/share/perl/man/.glimpse_filenames ; + !/usr/share/perl/man/.glimpse_filenames_index ; + !/usr/share/perl/man/.glimpse_filetimes ; + !/usr/share/perl/man/.glimpse_filters ; + !/usr/share/perl/man/.glimpse_index ; + !/usr/share/perl/man/.glimpse_messages ; + !/usr/share/perl/man/.glimpse_partitions ; + !/usr/share/perl/man/.glimpse_statistics ; + !/usr/share/perl/man/.glimpse_turbo ; + /usr/share/perl/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/share/perl/man/cat3 ; + /usr/local/lib/perl5/5.00503/man -> $(SEC_CONFIG) ; + ! /usr/local/lib/perl5/5.00503/man/whatis ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filters ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filetimes ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_messages ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_statistics ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_index ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_turbo ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_partitions ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames ; + ! /usr/local/lib/perl5/5.00503/man/.glimpse_filenames_index ; + /usr/local/lib/perl5/5.00503/man/man3 -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/lib/perl5/5.00503/man/cat3 ; +} + + +# +# X11R6 +# + +( + rulename = "X11R6", + severity = $(SIG_HI) +) +{ + /usr/X11R6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/lib/X11/xdm -> $(SEC_CONFIG) (recurse = true) ; + !/usr/X11R6/lib/X11/xdm/xdm-errors ; + !/usr/X11R6/lib/X11/xdm/authdir/authfiles ; + !/usr/X11R6/lib/X11/xdm/xdm-pid ; + /usr/X11R6/lib/X11/xkb/compiled -> $(SEC_CONFIG) (recurse = true) ; + /usr/X11R6/man -> $(SEC_CONFIG) ; + !/usr/X11R6/man/whatis ; + !/usr/X11R6/man/.glimpse_filenames ; + !/usr/X11R6/man/.glimpse_filenames_index ; + !/usr/X11R6/man/.glimpse_filetimes ; + !/usr/X11R6/man/.glimpse_filters ; + !/usr/X11R6/man/.glimpse_index ; + !/usr/X11R6/man/.glimpse_messages ; + !/usr/X11R6/man/.glimpse_partitions ; + !/usr/X11R6/man/.glimpse_statistics ; + !/usr/X11R6/man/.glimpse_turbo ; + /usr/X11R6/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/X11R6/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/X11R6/man/cat1 ; + ! /usr/X11R6/man/cat2 ; + ! /usr/X11R6/man/cat3 ; + ! /usr/X11R6/man/cat4 ; + ! /usr/X11R6/man/cat5 ; + ! /usr/X11R6/man/cat6 ; + ! /usr/X11R6/man/cat7 ; + ! /usr/X11R6/man/cat8 ; + ! /usr/X11R6/man/cat9 ; + ! /usr/X11R6/man/catl ; + ! /usr/X11R6/man/catn ; +} + + +# +# sources +# + +( + rulename = "Sources", + severity = $(SIG_HI) +) +{ + /usr/src -> $(SEC_CRIT) (recurse = true) ; + /usr/src/sys/compile -> $(SEC_CONFIG) (recurse = false) ; +} + + +# +# NIS +# + +( + rulename = "NIS", + severity = $(SIG_HI) +) +{ + /var/yp -> $(SEC_CRIT) (recurse = true) ; + !/var/yp/binding ; +} + + +# +# Temporary directories +# +( + rulename = "Temporary directories", + recurse = false, + severity = $(SIG_LOW) +) +{ + /usr/tmp -> $(SEC_INVARIANT) ; + /var/tmp -> $(SEC_INVARIANT) ; + /var/preserve -> $(SEC_INVARIANT) ; + /tmp -> $(SEC_INVARIANT) ; +} + +# +# Local files +# + +( + rulename = "Local files", + severity = $(SIG_MED) +) +{ + /usr/local/bin -> $(SEC_BIN) (recurse = true) ; + /usr/local/sbin -> $(SEC_BIN) (recurse = true) ; + /usr/local/etc -> $(SEC_BIN) (recurse = true) ; + /usr/local/lib -> $(SEC_BIN) (recurse = true ) ; + /usr/local/libexec -> $(SEC_BIN) (recurse = true ) ; + /usr/local/share -> $(SEC_BIN) (recurse = true ) ; + /usr/local/man -> $(SEC_CONFIG) ; + !/usr/local/man/whatis ; + !/usr/local/man/.glimpse_filenames ; + !/usr/local/man/.glimpse_filenames_index ; + !/usr/local/man/.glimpse_filetimes ; + !/usr/local/man/.glimpse_filters ; + !/usr/local/man/.glimpse_index ; + !/usr/local/man/.glimpse_messages ; + !/usr/local/man/.glimpse_partitions ; + !/usr/local/man/.glimpse_statistics ; + !/usr/local/man/.glimpse_turbo ; + /usr/local/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/man/cat1 ; + ! /usr/local/man/cat2 ; + ! /usr/local/man/cat3 ; + ! /usr/local/man/cat4 ; + ! /usr/local/man/cat5 ; + ! /usr/local/man/cat6 ; + ! /usr/local/man/cat7 ; + ! /usr/local/man/cat8 ; + ! /usr/local/man/cat9 ; + ! /usr/local/man/catl ; + ! /usr/local/man/catn ; + /usr/local/krb5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man -> $(SEC_CONFIG) ; + !/usr/local/krb5/man/whatis ; + !/usr/local/krb5/man/.glimpse_filenames ; + !/usr/local/krb5/man/.glimpse_filenames_index ; + !/usr/local/krb5/man/.glimpse_filetimes ; + !/usr/local/krb5/man/.glimpse_filters ; + !/usr/local/krb5/man/.glimpse_index ; + !/usr/local/krb5/man/.glimpse_messages ; + !/usr/local/krb5/man/.glimpse_partitions ; + !/usr/local/krb5/man/.glimpse_statistics ; + !/usr/local/krb5/man/.glimpse_turbo ; + /usr/local/krb5/man/man1 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man2 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man3 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man4 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man5 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man6 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man7 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man8 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/man9 -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/manl -> $(SEC_CRIT) (recurse = true) ; + /usr/local/krb5/man/mann -> $(SEC_CRIT) (recurse = true) ; + ! /usr/local/krb5/man/cat1 ; + ! /usr/local/krb5/man/cat2 ; + ! /usr/local/krb5/man/cat3 ; + ! /usr/local/krb5/man/cat4 ; + ! /usr/local/krb5/man/cat5 ; + ! /usr/local/krb5/man/cat6 ; + ! /usr/local/krb5/man/cat7 ; + ! /usr/local/krb5/man/cat8 ; + ! /usr/local/krb5/man/cat9 ; + ! /usr/local/krb5/man/catl ; + ! /usr/local/krb5/man/catn ; + /usr/local/www -> $(SEC_CONFIG) (recurse = true) ; +} + + +( + rulename = "Security Control", + severity = $(SIG_HI) +) +{ + /etc/group -> $(SEC_CRIT) ; + /etc/crontab -> $(SEC_CRIT) ; +} + +#============================================================================= +# +# Copyright 2000-2018 Tripwire, Inc. Tripwire is a registered trademark of Tripwire, +# Inc. in the United States and other countries. All rights reserved. +# +# FreeBSD is a registered trademark of the FreeBSD Project Inc. +# +# UNIX is a registered trademark of The Open Group. +# +#============================================================================= +# +# Permission is granted to make and distribute verbatim copies of this document +# provided the copyright notice and this permission notice are preserved on all +# copies. +# +# Permission is granted to copy and distribute modified versions of this +# document under the conditions for verbatim copying, provided that the entire +# resulting derived work is distributed under the terms of a permission notice +# identical to this one. +# +# Permission is granted to copy and distribute translations of this document +# into another language, under the above conditions for modified versions, +# except that this permission notice may be stated in a translation approved by +# Tripwire, Inc. +# +# DCM diff --git a/policy/twpol-OpenBSD.txt b/policy/twpol-OpenBSD.txt index 1591119..34e1743 100644 --- a/policy/twpol-OpenBSD.txt +++ b/policy/twpol-OpenBSD.txt @@ -2,8 +2,8 @@ # ## ############################################################################## # # # # -# Policy file for OpenBSD 3.5 # # -# May 20, 2003 # # +# Tripwire 2.4 policy for OpenBSD # # +# updated March 2018 # # # ## ############################################################################## @@ -60,13 +60,13 @@ HOSTNAME=; # ############################################################################## -Device = +pugsdr-intlbamcCMSH ; -Dynamic = +pinugtd-srlbamcCMSH ; -Growing = +pinugtdl-srbamcCMSH ; -IgnoreAll = -pinugtsdrlbamcCMSH ; -IgnoreNone = +pinugtsdrbamcCMSH-l ; -ReadOnly = +pinugtsdbmCM-rlacSH ; -Temporary = +pugt ; +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; @@section FS @@ -83,10 +83,10 @@ Temporary = +pugt ; rulename = "Tripwire Binaries", ) { - $(TWBIN)/siggen -> $(ReadOnly) ; - $(TWBIN)/tripwire -> $(ReadOnly) ; - $(TWBIN)/twadmin -> $(ReadOnly) ; - $(TWBIN)/twprint -> $(ReadOnly) ; + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; } # Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases @@ -103,14 +103,14 @@ Temporary = +pugt ; # afterward triggers this rule until a database update is run, since the # database file does not exist before that point. - $(TWDB) -> $(Dynamic) -i ; - $(TWPOL)/tw.pol -> $(ReadOnly) -i ; - $(TWPOL)/tw.cfg -> $(ReadOnly) -i ; - $(TWLKEY)/$(HOSTNAME)-local.key -> $(ReadOnly) ; - $(TWSKEY)/site.key -> $(ReadOnly) ; + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; # don't scan the individual reports - $(TWREPORT) -> $(Dynamic) (recurse=0) ; + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; # In this configuration /usr/local is a symbolic link to /home/local. # We want to ignore the following directories since they are already @@ -131,9 +131,9 @@ Temporary = +pugt ; rulename = "OS Boot and Configuration Files", ) { - /boot -> $(ReadOnly) ; - /bsd -> $(ReadOnly) ; - /etc -> $(IgnoreNone) -SHa ; + /boot -> $(SEC_READONLY) ; + /bsd -> $(SEC_READONLY) ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; } ################################################### @@ -147,13 +147,13 @@ Temporary = +pugt ; rulename = "Mount Points", ) { - / -> $(ReadOnly) ; - /cdrom -> $(Dynamic) ; - /floppy -> $(Dynamic) ; - /home -> $(ReadOnly) ; # Modify as needed - /mnt -> $(Dynamic) ; - /usr -> $(ReadOnly) ; - /var -> $(ReadOnly) ; + / -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /floppy -> $(SEC_DYNAMIC) ; + /home -> $(SEC_READONLY) ; # Modify as needed + /mnt -> $(SEC_DYNAMIC) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; } ################################################### @@ -167,8 +167,8 @@ Temporary = +pugt ; rulename = "Misc Top-Level Directories", ) { - /altroot -> $(Dynamic) ; - /stand -> $(Dynamic) ; + /altroot -> $(SEC_DYNAMIC) ; + /stand -> $(SEC_DYNAMIC) ; } ################################################ @@ -182,10 +182,10 @@ Temporary = +pugt ; rulename = "System Devices", ) { - /dev -> $(Device) ; - /dev/fd -> $(Device) ; - /var/cron/tabs/.sock -> $(Device) ; - /var/empty/dev/log -> $(Device) ; + /dev -> $(SEC_DEVICE) ; + /dev/fd -> $(SEC_DEVICE) ; + /var/cron/tabs/.sock -> $(SEC_DEVICE) ; + /var/empty/dev/log -> $(SEC_DEVICE) ; } ################################################ @@ -199,14 +199,14 @@ Temporary = +pugt ; rulename = "OS Binaries and Libraries", ) { - /bin -> $(ReadOnly) ; - /sbin -> $(ReadOnly) ; - /usr/bin -> $(ReadOnly) ; - /usr/lib -> $(ReadOnly) ; - /usr/libexec -> $(ReadOnly) ; - /usr/sbin -> $(ReadOnly) ; - /usr/X11R6/bin -> $(ReadOnly) ; - /usr/X11R6/lib -> $(ReadOnly) ; + /bin -> $(SEC_READONLY) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/libexec -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/X11R6/bin -> $(SEC_READONLY) ; + /usr/X11R6/lib -> $(SEC_READONLY) ; } ################################################ # ## @@ -219,19 +219,19 @@ Temporary = +pugt ; #OKrulename = "Usr Local Files", #OK) #OK{ - #OK/usr/local -> $(ReadOnly) ; - #OK/usr/local/bin -> $(ReadOnly) ; - #OK/usr/local/doc -> $(ReadOnly) ; - #OK/usr/local/etc -> $(ReadOnly) ; - #OK/usr/local/include -> $(ReadOnly) ; - #OK/usr/local/info -> $(ReadOnly) ; - #OK/usr/local/lib -> $(ReadOnly) ; - #OK/usr/local/libdata -> $(ReadOnly) ; - #OK/usr/local/libexec -> $(ReadOnly) ; - #OK/usr/local/man -> $(ReadOnly) ; - #OK/usr/local/sbin -> $(ReadOnly) ; - #OK/usr/local/share -> $(ReadOnly) ; - #OK/usr/local/src -> $(ReadOnly) ; + #OK/usr/local -> $(SEC_READONLY) ; + #OK/usr/local/bin -> $(SEC_READONLY) ; + #OK/usr/local/doc -> $(SEC_READONLY) ; + #OK/usr/local/etc -> $(SEC_READONLY) ; + #OK/usr/local/include -> $(SEC_READONLY) ; + #OK/usr/local/info -> $(SEC_READONLY) ; + #OK/usr/local/lib -> $(SEC_READONLY) ; + #OK/usr/local/libdata -> $(SEC_READONLY) ; + #OK/usr/local/libexec -> $(SEC_READONLY) ; + #OK/usr/local/man -> $(SEC_READONLY) ; + #OK/usr/local/sbin -> $(SEC_READONLY) ; + #OK/usr/local/share -> $(SEC_READONLY) ; + #OK/usr/local/src -> $(SEC_READONLY) ; #OK} ################################################ @@ -245,9 +245,9 @@ Temporary = +pugt ; rulename = "Root Directory and Files", ) { - /root -> $(IgnoreNone) -SHa ; - /root/.cshrc -> $(Dynamic) ; - /root/.profile -> $(Dynamic) ; + /root -> $(SEC_IGNORE_NONE) -SHa ; + /root/.cshrc -> $(SEC_DYNAMIC) ; + /root/.profile -> $(SEC_DYNAMIC) ; } ################################################ @@ -261,8 +261,8 @@ Temporary = +pugt ; rulename = "Temporary Directories", ) { - /tmp -> $(Temporary) ; - /var/tmp -> $(Temporary) ; + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; } ################################################ @@ -276,15 +276,15 @@ Temporary = +pugt ; rulename = "System and Boot Changes", ) { - /var/backups -> $(Dynamic) -i ; - /var/db/host.random -> $(ReadOnly) -mCM ; - /var/cron -> $(Growing) -i ; - /var/log -> $(Growing) -i ; - /var/run -> $(Dynamic) -i ; - /var/mail -> $(Growing) ; - /var/msgs/bounds -> $(ReadOnly) -smbCM ; - /var/spool/clientmqueue -> $(Temporary) ; - /var/spool/mqueue -> $(Temporary) ; + /var/backups -> $(SEC_DYNAMIC) -i ; + /var/db/host.random -> $(SEC_READONLY) -mCM ; + /var/cron -> $(SEC_GROWING) -i ; + /var/log -> $(SEC_GROWING) -i ; + /var/run -> $(SEC_DYNAMIC) -i ; + /var/mail -> $(SEC_GROWING) ; + /var/msgs/bounds -> $(SEC_READONLY) -smbCM ; + /var/spool/clientmqueue -> $(SEC_TEMPORARY) ; + /var/spool/mqueue -> $(SEC_TEMPORARY) ; } # diff --git a/policy/twpol-SunOS.txt b/policy/twpol-SunOS.txt index 338adfb..a188fef 100644 --- a/policy/twpol-SunOS.txt +++ b/policy/twpol-SunOS.txt @@ -2,7 +2,8 @@ # ## ############################################################################## # # # # -# Policy file for Solaris 8 # # +# Tripwire 2.4 policy for Solaris # # +# updated March 2018 # # # ## ############################################################################## @@ -61,13 +62,13 @@ HOSTNAME=; # ############################################################################## -Device = +pugsdr-intlbamcCMSH ; -Dynamic = +pinugtd-srlbamcCMSH ; -Growing = +pinugtdl-srbamcCMSH ; -IgnoreAll = -pinugtsdrlbamcCMSH ; -IgnoreNone = +pinugtsdrbamcCMSH-l ; -ReadOnly = +pinugtsdbmCM-rlacSH ; -Temporary = +pugt ; +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; @@section FS @@ -84,10 +85,10 @@ Temporary = +pugt ; rulename = "Tripwire Binaries", ) { - $(TWBIN)/siggen -> $(ReadOnly) ; - $(TWBIN)/tripwire -> $(ReadOnly) ; - $(TWBIN)/twadmin -> $(ReadOnly) ; - $(TWBIN)/twprint -> $(ReadOnly) ; + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; } # Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases @@ -104,14 +105,14 @@ Temporary = +pugt ; # afterward triggers this rule until a database update is run, since the # database file does not exist before that point. - $(TWDB) -> $(Dynamic) -i ; - $(TWPOL)/tw.pol -> $(ReadOnly) -i ; - $(TWPOL)/tw.cfg -> $(ReadOnly) -i ; - $(TWLKEY)/$(HOSTNAME)-local.key -> $(ReadOnly) ; - $(TWSKEY)/site.key -> $(ReadOnly) ; + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; # don't scan the individual reports - $(TWREPORT) -> $(Dynamic) (recurse=0) ; + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; # In this configuration /usr/local is a symbolic link to /home/local. # We want to ignore the following directories since they are already @@ -132,8 +133,8 @@ Temporary = +pugt ; rulename = "OS Boot and Configuration Files", ) { - /etc -> $(IgnoreNone) -SHa ; - /kernel -> $(ReadOnly) ; + /etc -> $(SEC_IGNORE_NONE) -SHa ; + /kernel -> $(SEC_READONLY) ; } ################################################### @@ -147,13 +148,13 @@ Temporary = +pugt ; rulename = "Mount Points", ) { - / -> $(ReadOnly) ; - /cdrom -> $(Dynamic) ; - /home -> $(ReadOnly) ; - /mnt -> $(Dynamic) ; - /usr -> $(ReadOnly) ; - /var -> $(ReadOnly) ; - /opt -> $(ReadOnly) ; + / -> $(SEC_READONLY) ; + /cdrom -> $(SEC_DYNAMIC) ; + /home -> $(SEC_READONLY) ; + /mnt -> $(SEC_DYNAMIC) ; + /usr -> $(SEC_READONLY) ; + /var -> $(SEC_READONLY) ; + /opt -> $(SEC_READONLY) ; } ################################################### @@ -167,7 +168,7 @@ Temporary = +pugt ; rulename = "Misc Top-Level Directories", ) { - /lost+found -> $(ReadOnly) ; + /lost+found -> $(SEC_READONLY) ; } ################################################ @@ -181,8 +182,8 @@ Temporary = +pugt ; rulename = "System Devices", ) { - /dev -> $(Device) ; - /devices -> $(Device) ; + /dev -> $(SEC_DEVICE) ; + /devices -> $(SEC_DEVICE) ; } ################################################ @@ -196,12 +197,12 @@ Temporary = +pugt ; rulename = "OS Binaries and Libraries", ) { - /sbin -> $(ReadOnly) ; - /usr/bin -> $(ReadOnly) ; - /usr/lib -> $(ReadOnly) ; - /usr/sbin -> $(ReadOnly) ; - /usr/openwin/bin -> $(ReadOnly) ; - /usr/openwin/lib -> $(ReadOnly) ; + /sbin -> $(SEC_READONLY) ; + /usr/bin -> $(SEC_READONLY) ; + /usr/lib -> $(SEC_READONLY) ; + /usr/sbin -> $(SEC_READONLY) ; + /usr/openwin/bin -> $(SEC_READONLY) ; + /usr/openwin/lib -> $(SEC_READONLY) ; } ################################################ @@ -216,9 +217,9 @@ Temporary = +pugt ; ) { ! /.netscape/cache ; - /.bash_history -> $(ReadOnly) -smbCM; - /.sh_history -> $(Dynamic) ; - /.Xauthority -> $(ReadOnly) ; + /.bash_history -> $(SEC_READONLY) -smbCM; + /.sh_history -> $(SEC_DYNAMIC) ; + /.Xauthority -> $(SEC_READONLY) ; } ################################################ @@ -232,8 +233,8 @@ Temporary = +pugt ; rulename = "Temporary Directories", ) { - /tmp -> $(Temporary) ; - /var/tmp -> $(Temporary) ; + /tmp -> $(SEC_TEMPORARY) ; + /var/tmp -> $(SEC_TEMPORARY) ; } ################################################ @@ -295,17 +296,17 @@ Temporary = +pugt ; rulename = "System and Boot Changes", ) { - /etc/.pwd.lock -> $(ReadOnly) -cm; - /etc/coreadm.conf -> $(ReadOnly) -cm; - /var/adm -> $(Growing) -i; - #/var/backups -> $(Dynamic) -i ; - /var/cron/log -> $(Growing) -i ; - #/var/db/host.random -> $(ReadOnly) -mCM ; - #/var/db/locate.database -> $(ReadOnly) -misCM ; - /var/log -> $(Growing) -i ; - #/var/run -> $(Dynamic) -i ; - #/var/mail -> $(Growing) ; - #/var/msgs/bounds -> $(ReadOnly) -smbCM ; + /etc/.pwd.lock -> $(SEC_READONLY) -cm; + /etc/coreadm.conf -> $(SEC_READONLY) -cm; + /var/adm -> $(SEC_GROWING) -i; + #/var/backups -> $(SEC_DYNAMIC) -i ; + /var/cron/log -> $(SEC_GROWING) -i ; + #/var/db/host.random -> $(SEC_READONLY) -mCM ; + #/var/db/locate.database -> $(SEC_READONLY) -misCM ; + /var/log -> $(SEC_GROWING) -i ; + #/var/run -> $(SEC_DYNAMIC) -i ; + #/var/mail -> $(SEC_GROWING) ; + #/var/msgs/bounds -> $(SEC_READONLY) -smbCM ; !/var/sendmail ; !/var/spool/clientmqueue ; !/var/spool/mqueue ; diff --git a/policy/twpol-Syllable.txt b/policy/twpol-Syllable.txt new file mode 100644 index 0000000..bbb1bd3 --- /dev/null +++ b/policy/twpol-Syllable.txt @@ -0,0 +1,184 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for Syllable ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + + +############################################################################## + + +### System dir ############################################################### +# +(rulename = "System Directory",) +{ + /boot/system -> $(SEC_READONLY) -a; +} + + +### Other bin dirs ############################################################ +# +(rulename = "Binary Directories",) +{ + /boot/bin -> $(SEC_READONLY) -a; + /usr/bin -> $(SEC_READONLY) -a; + /usr/local/bin -> $(SEC_READONLY) -a; + /boot/Applications -> $(SEC_READONLY) -a; + /resources/index/bin -> $(SEC_READONLY) -a; +} + +(rulename = "Admin Binary Directories",) +{ + /usr/local/sbin -> $(SEC_READONLY) -a; + /resources/index/sbin -> $(SEC_READONLY) -a; + /usr/local/libexec -> $(SEC_READONLY) -a; + /resources/index/libexec -> $(SEC_READONLY) -a; +} + + +### Other lib dirs ############################################################ +# +(rulename = "Library Directories",) +{ + /usr/local/lib -> $(SEC_READONLY) -a; + /resources/index/lib -> $(SEC_READONLY) -a; +} + +### Other boot dirs ########################################################### +# +(rulename = "Boot Directories",) +{ + /boot/boot/grub -> $(SEC_READONLY) -a; +} + +### Settings ################################################################## +# +(rulename = "Settings",) +{ + /boot/etc -> $(SEC_READONLY) -a; + /usr/local/etc -> $(SEC_READONLY) -a; +} + +# Logs ######################################################################## +# +(rulename = "Logs",) +{ + /var/log -> $(SEC_GROWING) -a; +} + +# Dev ######################################################################### +# +(rulename = "Devices",) +{ + /dev -> $(SEC_DEVICE) -a; +} + +# Temp dirs ######################### +# +(rulename = "Temp Directories",) +{ + /boot/tmp -> $(SEC_TEMPORARY) -a; +} diff --git a/policy/twpol-skyos.txt b/policy/twpol-skyos.txt new file mode 100644 index 0000000..0bd3c4e --- /dev/null +++ b/policy/twpol-skyos.txt @@ -0,0 +1,183 @@ +############################################################################### +# ## +# Default Tripwire 2.4 Policy file for SkyOS ## +# ## +############################################################################### + + +############################################################################### +# ## +# Global Variable Definitions ## +# ## +# These are defined at install time by the installation script. You may ## +# Manually edit these if you are using this file directly and not from the ## +# installation script itself. ## +# ## +############################################################################### + +@@section GLOBAL +TWROOT=; +TWBIN=; +TWPOL=; +TWDB=; +TWSKEY=; +TWLKEY=; +TWREPORT=; +HOSTNAME=; + +############################################################################## +# Predefined Variables # +############################################################################## +# +# Property Masks +# +# - ignore the following properties +# + check the following properties +# +# a access timestamp (mutually exclusive with +CMSH) +# b number of blocks allocated +# c inode creation/modification timestamp +# d ID of device on which inode resides +# g group id of owner +# i inode number +# l growing files (logfiles for example) +# m modification timestamp +# n number of links +# p permission and file mode bits +# r ID of device pointed to by inode (valid only for device objects) +# s file size +# t file type +# u user id of owner +# +# C CRC-32 hash +# H HAVAL hash +# M MD5 hash +# S SHA hash +# +############################################################################## + +SEC_DEVICE = +pugsdr-intlbamcCMSH ; +SEC_DYNAMIC = +pinugtd-srlbamcCMSH ; +SEC_GROWING = +pinugtdl-srbamcCMSH ; +SEC_IGNORE_ALL = -pinugtsdrlbamcCMSH ; +SEC_IGNORE_NONE = +pinugtsdrbamcCMSH-l ; +SEC_READONLY = +pinugtsdbmCM-rlacSH ; +SEC_TEMPORARY = +pugt ; + +@@section FS + +######################################### +# ## +# Tripwire Binaries and Data Files ## +# ## +######################################### + +# Tripwire Binaries +( + rulename = "Tripwire Binaries", +) +{ + $(TWBIN)/siggen -> $(SEC_READONLY) ; + $(TWBIN)/tripwire -> $(SEC_READONLY) ; + $(TWBIN)/twadmin -> $(SEC_READONLY) ; + $(TWBIN)/twprint -> $(SEC_READONLY) ; +} + +# Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases +( + rulename = "Tripwire Data Files", +) +{ + # NOTE: We remove the inode attribute because when Tripwire creates a backup, + # it does so by renaming the old file and creating a new one (which will + # have a new inode number). Inode is left turned on for keys, which shouldn't + # ever change. + + # NOTE: The first integrity check triggers this rule and each integrity check + # afterward triggers this rule until a database update is run, since the + # database file does not exist before that point. + + $(TWDB) -> $(SEC_DYNAMIC) -i ; + $(TWPOL)/tw.pol -> $(SEC_READONLY) -i ; + $(TWPOL)/tw.cfg -> $(SEC_READONLY) -i ; + $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_READONLY) ; + $(TWSKEY)/site.key -> $(SEC_READONLY) ; + + # don't scan the individual reports + $(TWREPORT) -> $(SEC_DYNAMIC) (recurse=0) ; +} + + +############################################################################## + + +### System dir ############################################################### +# +(rulename = "System Directory",) +{ + /boot/system -> $(SEC_READONLY) -a; + /boot/system/registry.rsm -> $(SEC_READONLY) -am; +} + +(rulename = "System Files",) +{ + /boot/kernel.sys -> $(SEC_READONLY) -a; + /boot/kernel.dbg -> $(SEC_READONLY) -a; + /boot/init.scr -> $(SEC_READONLY) -a; + /boot/install.sif -> $(SEC_READONLY) -a; +} + +### Other bin dirs ############################################################ +# +(rulename = "Binary Directories",) +{ + /boot/programs -> $(SEC_READONLY) -a; +} + +### Other lib dirs ############################################################ +# +(rulename = "Library Directories",) +{ + /usr/lib -> $(SEC_READONLY) -a; + /usr/local/lib -> $(SEC_READONLY) -a; +} + +### Other boot dirs ########################################################### +# +(rulename = "Boot Directories",) +{ + /boot/boot/grub -> $(SEC_READONLY) -a; +} + +### Settings ################################################################## +# +(rulename = "Settings",) +{ + /boot/programs/unix/etc -> $(SEC_READONLY) -a; + /usr/local/etc -> $(SEC_READONLY) -a; +} + +# Logs ######################################################################## +# +(rulename = "Logs",) +{ + /var/log -> $(SEC_GROWING) -a; +} + +# Dev ######################################################################### +# +(rulename = "Devices",) +{ + /dev -> $(SEC_DEVICE) -a; + /fifo -> $(SEC_DEVICE) -a; + /pty -> $(SEC_DEVICE) -as; + /systeminterface -> $(SEC_DEVICE) -a; + /umfs -> $(SEC_DEVICE) -a; +} + +# Temp dirs ######################### +# +(rulename = "Temp Directories",) +{ + /boot/temp -> $(SEC_TEMPORARY) -a; +} diff --git a/src/Makefile.am b/src/Makefile.am index 81df04b..7e6ffd8 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,3 +1,14 @@ SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util SUBDIRS+= twprint twadmin siggen tripwire twtest +EXTRA_DIST = buildnum.h buildnum.txt buildnuminc.pl dep_addprefix.pl rmcr.pl check_st.pl prime.pl parser test-harness core/md5.cpp core/sha.cpp +install: + true + +uninstall: + true + +clean-local: clean-local-check +.PHONY: clean-local-check +clean-local-check: + -rm -rf test-harness/twtest \ No newline at end of file diff --git a/src/Makefile.in b/src/Makefile.in index f32c498..be0d740 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,15 +13,67 @@ # PARTICULAR PURPOSE. @SET_MAKE@ -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = .. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -33,33 +85,106 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = SOURCES = DIST_SOURCES = -RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ - html-recursive info-recursive install-data-recursive \ - install-exec-recursive install-info-recursive \ - install-recursive installcheck-recursive installdirs-recursive \ - pdf-recursive ps-recursive uninstall-info-recursive \ - uninstall-recursive +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + distdir +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -83,6 +208,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -94,6 +220,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -110,21 +237,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -154,13 +284,19 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ -SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util twprint twadmin siggen tripwire twtest +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util twprint \ + twadmin siggen tripwire twtest +EXTRA_DIST = buildnum.h buildnum.txt buildnuminc.pl dep_addprefix.pl rmcr.pl check_st.pl prime.pl parser test-harness core/md5.cpp core/sha.cpp all: all-recursive .SUFFIXES: @@ -168,15 +304,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --gnu src/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -193,19 +328,28 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -uninstall-info-am: +$(am__aclocal_m4_deps): # This directory's subdirectories are mostly independent; you can cd -# into them and run `make' without going through this Makefile. -# To change the values of `make' variables: instead of editing Makefiles, -# (1) if the variable is set in `config.status', edit `config.status' -# (which will cause the Makefiles to be regenerated when you run `make'); -# (2) otherwise, pass the desired values on the `make' command line. -$(RECURSIVE_TARGETS): - @set fnord $$MAKEFLAGS; amf=$$2; \ +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ - list='$(SUBDIRS)'; for subdir in $$list; do \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ @@ -213,60 +357,20 @@ $(RECURSIVE_TARGETS): else \ local_target="$$target"; \ fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" -mostlyclean-recursive clean-recursive distclean-recursive \ -maintainer-clean-recursive: - @set fnord $$MAKEFLAGS; amf=$$2; \ - dot_seen=no; \ - case "$@" in \ - distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ - *) list='$(SUBDIRS)' ;; \ - esac; \ - rev=''; for subdir in $$list; do \ - if test "$$subdir" = "."; then :; else \ - rev="$$subdir $$rev"; \ - fi; \ - done; \ - rev="$$rev ."; \ - target=`echo $@ | sed s/-recursive//`; \ - for subdir in $$rev; do \ - echo "Making $$target in $$subdir"; \ - if test "$$subdir" = "."; then \ - local_target="$$target-am"; \ - else \ - local_target="$$target"; \ - fi; \ - (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ - || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ - done && test -z "$$fail" -tags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ - done -ctags-recursive: - list='$(SUBDIRS)'; for subdir in $$list; do \ - test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ - done +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ @@ -278,79 +382,104 @@ TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ - tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done - list='$(SUBDIRS)'; for subdir in $$list; do \ + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ - test -d "$(distdir)/$$subdir" \ - || mkdir "$(distdir)/$$subdir" \ - || exit 1; \ - (cd $$subdir && \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ - top_distdir="../$(top_distdir)" \ - distdir="../$(distdir)/$$subdir" \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ @@ -360,33 +489,37 @@ check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: -install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive -uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive -clean-am: clean-generic mostlyclean-am +clean-am: clean-generic clean-local mostlyclean-am distclean: distclean-recursive -rm -f Makefile @@ -398,18 +531,38 @@ dvi-am: html: html-recursive +html-am: + info: info-recursive info-am: install-data-am: +install-dvi: install-dvi-recursive + +install-dvi-am: + install-exec-am: +install-html: install-html-recursive + +install-html-am: + install-info: install-info-recursive +install-info-am: + install-man: +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-recursive @@ -428,21 +581,36 @@ ps: ps-recursive ps-am: -uninstall-am: uninstall-info-am - -uninstall-info: uninstall-info-recursive - -.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ - clean clean-generic clean-recursive ctags ctags-recursive \ - distclean distclean-generic distclean-recursive distclean-tags \ - distdir dvi dvi-am html html-am info info-am install \ - install-am install-data install-data-am install-exec \ - install-exec-am install-info install-info-am install-man \ - install-strip installcheck installcheck-am installdirs \ - installdirs-am maintainer-clean maintainer-clean-generic \ - maintainer-clean-recursive mostlyclean mostlyclean-generic \ - mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ - uninstall uninstall-am uninstall-info-am +uninstall-am: + +.MAKE: $(am__recursive_targets) install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ + check-am clean clean-generic clean-local cscopelist-am ctags \ + ctags-am distclean distclean-generic distclean-tags distdir \ + dvi dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am + +.PRECIOUS: Makefile + + +install: + true + +uninstall: + true + +clean-local: clean-local-check +.PHONY: clean-local-check +clean-local-check: + -rm -rf test-harness/twtest # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. diff --git a/src/buildnum.h b/src/buildnum.h index aecfd70..934eed0 100644 --- a/src/buildnum.h +++ b/src/buildnum.h @@ -1,2 +1 @@ #define BUILD_NUM _T("0") - diff --git a/src/buildnum.txt b/src/buildnum.txt index d00491f..573541a 100644 --- a/src/buildnum.txt +++ b/src/buildnum.txt @@ -1 +1 @@ -1 +0 diff --git a/src/core/Makefile.am b/src/core/Makefile.am index 06fd356..2b48224 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -1,27 +1,41 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libcore.a +libcore_adir=. libcore_a_SOURCES = \ file_unix.cpp unixfsservices.cpp \ archive.cpp charutil.cpp \ cmdlineparser.cpp codeconvert.cpp core.cpp coreerrors.cpp \ corestrings.cpp crc32.cpp debug.cpp displayencoder.cpp \ - displayutil.cpp error.cpp errorbucketimpl.cpp errortable.cpp \ + displayutil.cpp epoch.cpp error.cpp errorbucketimpl.cpp errortable.cpp \ errorutil.cpp fileerror.cpp fileheader.cpp fsservices.cpp \ growheap.cpp hashtable.cpp haval.cpp msystem.cpp ntmbs.cpp \ - objectpool.cpp refcountobj.cpp serializable.cpp serializer.cpp \ - serializerimpl.cpp serializerutil.cpp serstring.cpp \ + refcountobj.cpp serializable.cpp serializer.cpp \ + serializerimpl.cpp serializerutil.cpp serstring.cpp \ srefcountobj.cpp srefcounttbl.cpp stdcore.cpp stringutil.cpp \ - timebomb.cpp timeconvert.cpp tw_signal.cpp twlimits.cpp twlocale.cpp \ - unixexcept.cpp usernotify.cpp usernotifystdout.cpp utf8.cpp \ + timeconvert.cpp tw_signal.cpp twlimits.cpp twlocale.cpp \ + unixexcept.cpp usernotify.cpp usernotifystdout.cpp \ wchar16.cpp +libcore_a_HEADERS = archive.h charutil.h cmdlineparser.h codeconvert.h \ + core.h coreerrors.h corestrings.h crc32.h debug.h displayencoder.h \ + displayutil.h epoch.h error.h errorbucket.h errorbucketimpl.h errorgeneral.h \ + errortable.h errorutil.h file.h fileerror.h fileheader.h fixedfilebuf.h \ + fsservices.h growheap.h hashtable.h haval.h md5.h msystem.h ntdbs.h \ + ntmbs.h package.h platform.h refcountobj.h resources.h \ + serializable.h serializer.h serializerimpl.h serializerutil.h serstring.h \ + sha.h srefcountobj.h srefcounttbl.h stdcore.h stringutil.h tasktimer.h \ + tchar.h timeconvert.h tw_signal.h twlimits.h twlocale.h \ + twstringslang.h typed.h types.h unixexcept.h unixfsservices.h upperbound.h \ + usernotify.h usernotifystdout.h wchar16.h + libcore_a_LIBADD = @CORE_CRYPT_O@ libcore_a_DEPENDENCIES = @CORE_CRYPT_O@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libcore_a_OBJECTS) $(libcore_a_LIBADD) diff --git a/src/core/Makefile.in b/src/core/Makefile.in index 0b62769..5ee6d53 100644 --- a/src/core/Makefile.in +++ b/src/core/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libcore_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,57 +87,135 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/core -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libcore_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libcore_a_AR = $(AR) $(ARFLAGS) am_libcore_a_OBJECTS = file_unix.$(OBJEXT) unixfsservices.$(OBJEXT) \ archive.$(OBJEXT) charutil.$(OBJEXT) cmdlineparser.$(OBJEXT) \ codeconvert.$(OBJEXT) core.$(OBJEXT) coreerrors.$(OBJEXT) \ corestrings.$(OBJEXT) crc32.$(OBJEXT) debug.$(OBJEXT) \ - displayencoder.$(OBJEXT) displayutil.$(OBJEXT) error.$(OBJEXT) \ - errorbucketimpl.$(OBJEXT) errortable.$(OBJEXT) \ + displayencoder.$(OBJEXT) displayutil.$(OBJEXT) epoch.$(OBJEXT) \ + error.$(OBJEXT) errorbucketimpl.$(OBJEXT) errortable.$(OBJEXT) \ errorutil.$(OBJEXT) fileerror.$(OBJEXT) fileheader.$(OBJEXT) \ fsservices.$(OBJEXT) growheap.$(OBJEXT) hashtable.$(OBJEXT) \ haval.$(OBJEXT) msystem.$(OBJEXT) ntmbs.$(OBJEXT) \ - objectpool.$(OBJEXT) refcountobj.$(OBJEXT) \ - serializable.$(OBJEXT) serializer.$(OBJEXT) \ - serializerimpl.$(OBJEXT) serializerutil.$(OBJEXT) \ - serstring.$(OBJEXT) srefcountobj.$(OBJEXT) \ - srefcounttbl.$(OBJEXT) stdcore.$(OBJEXT) stringutil.$(OBJEXT) \ - timebomb.$(OBJEXT) timeconvert.$(OBJEXT) tw_signal.$(OBJEXT) \ - twlimits.$(OBJEXT) twlocale.$(OBJEXT) unixexcept.$(OBJEXT) \ - usernotify.$(OBJEXT) usernotifystdout.$(OBJEXT) utf8.$(OBJEXT) \ - wchar16.$(OBJEXT) + refcountobj.$(OBJEXT) serializable.$(OBJEXT) \ + serializer.$(OBJEXT) serializerimpl.$(OBJEXT) \ + serializerutil.$(OBJEXT) serstring.$(OBJEXT) \ + srefcountobj.$(OBJEXT) srefcounttbl.$(OBJEXT) \ + stdcore.$(OBJEXT) stringutil.$(OBJEXT) timeconvert.$(OBJEXT) \ + tw_signal.$(OBJEXT) twlimits.$(OBJEXT) twlocale.$(OBJEXT) \ + unixexcept.$(OBJEXT) usernotify.$(OBJEXT) \ + usernotifystdout.$(OBJEXT) wchar16.$(OBJEXT) libcore_a_OBJECTS = $(am_libcore_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libcore_a_SOURCES) DIST_SOURCES = $(libcore_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libcore_adir)" +HEADERS = $(libcore_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -102,7 +231,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -110,6 +239,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -121,6 +251,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -137,21 +268,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -181,32 +315,50 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libcore.a +libcore_adir = . libcore_a_SOURCES = \ file_unix.cpp unixfsservices.cpp \ archive.cpp charutil.cpp \ cmdlineparser.cpp codeconvert.cpp core.cpp coreerrors.cpp \ corestrings.cpp crc32.cpp debug.cpp displayencoder.cpp \ - displayutil.cpp error.cpp errorbucketimpl.cpp errortable.cpp \ + displayutil.cpp epoch.cpp error.cpp errorbucketimpl.cpp errortable.cpp \ errorutil.cpp fileerror.cpp fileheader.cpp fsservices.cpp \ growheap.cpp hashtable.cpp haval.cpp msystem.cpp ntmbs.cpp \ - objectpool.cpp refcountobj.cpp serializable.cpp serializer.cpp \ - serializerimpl.cpp serializerutil.cpp serstring.cpp \ + refcountobj.cpp serializable.cpp serializer.cpp \ + serializerimpl.cpp serializerutil.cpp serstring.cpp \ srefcountobj.cpp srefcounttbl.cpp stdcore.cpp stringutil.cpp \ - timebomb.cpp timeconvert.cpp tw_signal.cpp twlimits.cpp twlocale.cpp \ - unixexcept.cpp usernotify.cpp usernotifystdout.cpp utf8.cpp \ + timeconvert.cpp tw_signal.cpp twlimits.cpp twlocale.cpp \ + unixexcept.cpp usernotify.cpp usernotifystdout.cpp \ wchar16.cpp +libcore_a_HEADERS = archive.h charutil.h cmdlineparser.h codeconvert.h \ + core.h coreerrors.h corestrings.h crc32.h debug.h displayencoder.h \ + displayutil.h epoch.h error.h errorbucket.h errorbucketimpl.h errorgeneral.h \ + errortable.h errorutil.h file.h fileerror.h fileheader.h fixedfilebuf.h \ + fsservices.h growheap.h hashtable.h haval.h md5.h msystem.h ntdbs.h \ + ntmbs.h package.h platform.h refcountobj.h resources.h \ + serializable.h serializer.h serializerimpl.h serializerutil.h serstring.h \ + sha.h srefcountobj.h srefcounttbl.h stdcore.h stringutil.h tasktimer.h \ + tchar.h timeconvert.h tw_signal.h twlimits.h twlocale.h \ + twstringslang.h typed.h types.h unixexcept.h unixfsservices.h upperbound.h \ + usernotify.h usernotifystdout.h wchar16.h + libcore_a_LIBADD = @CORE_CRYPT_O@ libcore_a_DEPENDENCIES = @CORE_CRYPT_O@ +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -215,15 +367,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/core/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/core/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/core/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/core/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -240,13 +391,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libcore.a: $(libcore_a_OBJECTS) $(libcore_a_DEPENDENCIES) - -rm -f libcore.a - $(libcore_a_AR) libcore.a $(libcore_a_OBJECTS) $(libcore_a_LIBADD) - $(RANLIB) libcore.a + +libcore.a: $(libcore_a_OBJECTS) $(libcore_a_DEPENDENCIES) $(EXTRA_libcore_a_DEPENDENCIES) + $(AM_V_at)-rm -f libcore.a + $(AM_V_AR)$(libcore_a_AR) libcore.a $(libcore_a_OBJECTS) $(libcore_a_LIBADD) + $(AM_V_at)$(RANLIB) libcore.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -255,91 +408,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libcore_aHEADERS: $(libcore_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libcore_a_HEADERS)'; test -n "$(libcore_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libcore_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libcore_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libcore_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libcore_adir)" || exit $$?; \ + done + +uninstall-libcore_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libcore_a_HEADERS)'; test -n "$(libcore_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libcore_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libcore_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -350,16 +533,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -379,18 +569,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libcore_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -409,22 +619,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libcore_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libcore_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libcore_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libcore_a_OBJECTS) $(libcore_a_LIBADD) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/core/archive.cpp b/src/core/archive.cpp index f9e7a16..83f88e7 100644 --- a/src/core/archive.cpp +++ b/src/core/archive.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,65 +49,34 @@ #include "file.h" #include "stringutil.h" -#include "corestrings.h" // for: STR_ERR2_ARCH_CRYPTO_ERR - - - -#if FSEEK_TAKES_INT32 -#define FSEEK(x, y, z) fseek((x), (int32)(y), (z)) -#else -#define FSEEK(x, y, z) fseek((x), (y), (z)) -#endif - - -//============================================================================= -// Utility Functions -//============================================================================= - -/////////////////////////////////////////////////////////////////////////////// -// util_IsDir -- returns true if a given file is a directory -/////////////////////////////////////////////////////////////////////////////// -bool util_IsDir( const TSTRING& fileName ) -{ - cFSStatArgs s; - try - { - iFSServices::GetInstance()->Stat( fileName, s ); - } - catch( eFSServices ) - { - return false; - } - - return( s.mFileType == cFSStatArgs::TY_DIR ); -} +#include "corestrings.h" // for: STR_ERR2_ARCH_CRYPTO_ERR //============================================================================= // eArchiveCrypto //============================================================================= -TSTRING eArchiveCrypto::GetMsg( ) const +TSTRING eArchiveCrypto::GetMsg() const { // RAD: Updated this to use new stringtable - return ( mMsg + TSS_GetString( cCore, core::STR_ERR2_ARCH_CRYPTO_ERR ) ); + return (mMsg + TSS_GetString(cCore, core::STR_ERR2_ARCH_CRYPTO_ERR)); } //============================================================================= -// cArchive +// cArchive //============================================================================= // convenience methods // // Specific Read functions throw eArchive if EOF is reached because -// if the caller is requesting a certain amount of data to be present, +// if the caller is requesting a certain amount of data to be present, // reaching EOF is unexpected // // ReadBlob and WriteBlob return number of bytes read or written. Notice // that ReadBlob does not throw an exception since eventually EOF is expected. // // ReadBlob can take NULL as a destination pointer -// -// All write functions throw exceptions for unexpected events like +// +// All write functions throw exceptions for unexpected events like // running out of memory or disk space. // @@ -136,7 +105,7 @@ void cArchive::ReadInt64(int64& ret) // throw(eArchive) } // NOTE:BAM 10/11/99 -- we store unsigned size, but it really only works with -// lengths < INT16_MAX due to sign extension in integral promotion during the +// lengths < INT16_MAX due to sign extension in integral promotion during the // resize() in ReadString(). // format for written string: 16-bit unsigned size, then a list of 16-bit UCS2 (Unicode) characters // not including terminating NULL @@ -144,25 +113,25 @@ void cArchive::ReadString(TSTRING& ret) // throw(eArchive) { // read in size of string int16 size; - ReadInt16( size ); + ReadInt16(size); // create buffer for WCHAR16 string wc16_string ws; - ws.resize( size ); + ws.resize(size); WCHAR16* pwc = (WCHAR16*)ws.data(); - for( int n = 0; n < size; n++ ) + for (int n = 0; n < size; n++) { int16 i16; - ReadInt16( i16 ); + ReadInt16(i16); *pwc++ = i16; } // convert WCHAR16 string to a TSTRING - ret = cStringUtil::WstrToTstr( ws ); + ret = cStringUtil::WstrToTstr(ws); } -int cArchive::ReadBlob(void* pBlob, int count) +int cArchive::ReadBlob(void* pBlob, int count) { return Read(pBlob, count); } @@ -186,7 +155,7 @@ void cArchive::WriteInt64(int64 i) // throw(eArchive) } // NOTE:BAM 10/11/99 -- we store unsigned size, but it really only works with -// lengths < INT16_MAX due to sign extension in integral promotion during the +// lengths < INT16_MAX due to sign extension in integral promotion during the // resize() in ReadString(). // format for written string: 16-bit unsigned size, then a list of 16-bit UCS2 (Unicode) characters // not including terminating NULL @@ -194,20 +163,20 @@ void cArchive::WriteString(TSTRING s) // throw(eArchive) { // convert string to a UCS2 string wc16_string ws; - cStringUtil::Convert( ws, s ); // Make convert "type-dispatched" + cStringUtil::Convert(ws, s); // Make convert "type-dispatched" - // we assume that we can represent the size as a unsigned 16-bit number + // we assume that we can represent the size as a unsigned 16-bit number // (we actually write it as a signed number, but we cast it) - if( ws.length() > TSS_INT16_MAX ) - ThrowAndAssert( eArchiveStringTooLong() ); + if (ws.length() > TSS_INT16_MAX) + ThrowAndAssert(eArchiveStringTooLong()); - WriteInt16( static_cast( ws.length() ) ); + WriteInt16(static_cast(ws.length())); // write out each 16 bit character // RAD:09/03/99 -- Optimized for performance with "const" wc16_string::const_iterator at = ws.begin(); - while ( at != ws.end() ) - WriteInt16( *at++ ); + while (at != ws.end()) + WriteInt16(*at++); } @@ -221,27 +190,30 @@ int32 cArchive::GetStorageSize(const TSTRING& str) { int32 size = sizeof(int32); // the length is always stored // - // after the length, all of the characters in the string are written as 16-bit values, + // after the length, all of the characters in the string are written as 16-bit values, // except for the null character // - size += ( str.length() * 2 ); + size += (str.length() * 2); return size; } int64 cArchive::Copy(cArchive* pFrom, int64 amt) { - enum { BUF_SIZE = 2048 }; - int8 buf[BUF_SIZE]; - int64 amtLeft = amt; + enum + { + BUF_SIZE = 2048 + }; + int8 buf[BUF_SIZE]; + int64 amtLeft = amt; - while(amtLeft > 0) + while (amtLeft > 0) { int64 amtToRead = amtLeft > (int64)BUF_SIZE ? (int64)BUF_SIZE : amtLeft; - int64 amtRead = pFrom->ReadBlob(buf, static_cast( amtToRead ) ); + int64 amtRead = pFrom->ReadBlob(buf, static_cast(amtToRead)); amtLeft -= amtRead; - WriteBlob(buf, static_cast( amtRead ) ); - if(amtRead < amtToRead) + WriteBlob(buf, static_cast(amtRead)); + if (amtRead < amtToRead) break; } @@ -255,7 +227,7 @@ int64 cArchive::Copy(cArchive* pFrom, int64 amt) cMemMappedArchive::cMemMappedArchive() { - mpMappedMem = 0; + mpMappedMem = 0; mMappedOffset = 0; mMappedLength = 0; } @@ -300,13 +272,13 @@ void cMemMappedArchive::SetNewMap(void* pMap, int64 offset, int64 length) const { if (pMap == 0) { - mpMappedMem = 0; + mpMappedMem = 0; mMappedOffset = 0; mMappedLength = 0; } else { - mpMappedMem = pMap; + mpMappedMem = pMap; mMappedOffset = offset; mMappedLength = length; } @@ -319,14 +291,13 @@ void cMemMappedArchive::SetNewMap(void* pMap, int64 offset, int64 length) const // mapped. /////////////////////////////////////////////////////////////////////////////// -cMemoryArchive::cMemoryArchive(int maxSize) -: mMaxAllocatedLen(maxSize) +cMemoryArchive::cMemoryArchive(int maxSize) : mMaxAllocatedLen(maxSize) { ASSERT(maxSize > 0); - mpMemory = 0; + mpMemory = 0; mAllocatedLen = 0; - mLogicalSize = 0; - mReadHead = 0; + mLogicalSize = 0; + mReadHead = 0; } cMemoryArchive::~cMemoryArchive() @@ -352,13 +323,15 @@ void cMemoryArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) offset = mLogicalSize + (int)offset; break; default: - ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); + ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME), + TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR))); } if (offset > mLogicalSize) - ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); + ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME), + TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR))); - mReadHead = static_cast( offset ); + mReadHead = static_cast(offset); } int64 cMemoryArchive::CurrentPos() const @@ -381,8 +354,8 @@ void cMemoryArchive::Truncate() void cMemoryArchive::MapArchive(int64 offset, int64 len) // throw(eArchive) { - if ( offset + (int)len > mLogicalSize ) - AllocateMemory( static_cast( offset + len ) ); + if (offset + (int)len > mLogicalSize) + AllocateMemory(static_cast(offset + len)); SetNewMap(mpMemory + offset, offset, len); } @@ -430,14 +403,14 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive) { // grow the buffer // only error if we are in debug mode -#ifdef _DEBUG +#ifdef DEBUG if (len > mMaxAllocatedLen) ThrowAndAssert(eArchiveOutOfMem()); #endif - if( 0 == mAllocatedLen ) + if (0 == mAllocatedLen) mAllocatedLen = MIN_ALLOCATED_SIZE; - + while (mAllocatedLen < len) mAllocatedLen *= 2; @@ -447,7 +420,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive) memcpy(pNewMem, mpMemory, mLogicalSize); delete [] mpMemory; } - mpMemory = pNewMem; + mpMemory = pNewMem; mLogicalSize = len; // update memory map if there is one @@ -467,7 +440,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive) ASSERT(mpMemory); memcpy(pNewMem, mpMemory, len); delete [] mpMemory; - mpMemory = pNewMem; + mpMemory = pNewMem; mLogicalSize = len; // update memory map if there is one @@ -495,33 +468,27 @@ class cFixedMemArchive : public cBidirArchive //----------------------------------------------------------------------------- // cFixedMemArchive //----------------------------------------------------------------------------- -cFixedMemArchive::cFixedMemArchive() -: mpMemory (0), - mSize (0), - mReadHead (0) +cFixedMemArchive::cFixedMemArchive() : mpMemory(0), mSize(0), mReadHead(0) { } -cFixedMemArchive::cFixedMemArchive( int8* pMem, int32 size ) -: mpMemory (0), - mSize (0), - mReadHead (0) +cFixedMemArchive::cFixedMemArchive(int8* pMem, int32 size) : mpMemory(0), mSize(0), mReadHead(0) { - Attach( pMem, size ); + Attach(pMem, size); } cFixedMemArchive::~cFixedMemArchive() { } -void cFixedMemArchive::Attach( int8* pMem, int32 size ) +void cFixedMemArchive::Attach(int8* pMem, int32 size) { - mpMemory = pMem; - mSize = size; - mReadHead = 0; + mpMemory = pMem; + mSize = size; + mReadHead = 0; } -void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) +void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) { switch (from) { @@ -534,21 +501,23 @@ void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) offset = mSize + (int)offset; break; default: - ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); + ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME), + TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR))); } if (offset > mSize) - ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); + ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME), + TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR))); - mReadHead = static_cast( offset ); + mReadHead = static_cast(offset); } -int64 cFixedMemArchive::CurrentPos() const +int64 cFixedMemArchive::CurrentPos() const { return mReadHead; } -int64 cFixedMemArchive::Length() const +int64 cFixedMemArchive::Length() const { return mSize; } @@ -558,12 +527,12 @@ bool cFixedMemArchive::EndOfFile() return (mReadHead >= mSize); } -int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive) +int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive) { - ASSERT( pDest ); + ASSERT(pDest); if (mReadHead + count > mSize) { - count = static_cast( mSize - mReadHead ); + count = static_cast(mSize - mReadHead); if (count <= 0) return 0; } @@ -576,11 +545,11 @@ int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive) return count; } -int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive) +int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive) { if (mReadHead + count > mSize) { - ASSERT( false ); + ASSERT(false); throw eArchiveWrite(); } @@ -597,11 +566,9 @@ int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive) /////////////////////////////////////////////////////////////////////////////// //Ctor -- Initialize member variables to 0 or NULL equivalents. -cFileArchive::cFileArchive() : - mFileSize(0), - mReadHead(0), - isWritable(false) -{} +cFileArchive::cFileArchive() : mFileSize(0), mReadHead(0), isWritable(false) +{ +} cFileArchive::~cFileArchive() { @@ -609,16 +576,16 @@ cFileArchive::~cFileArchive() bool cFileArchive::EndOfFile() { - return ( mReadHead >= mFileSize ); + return (mReadHead >= mFileSize); } //////////////////////////////////////////////////////////////////////// // Seek -- This is where the actual offset is performed. The default // for each archive will be 0. ///////////////////////////////////////////////////////////////////////// -void cFileArchive::Seek( int64 offset, SeekFrom from) // throw(eArchive) +void cFileArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) { - try + try { switch (from) { @@ -631,19 +598,19 @@ void cFileArchive::Seek( int64 offset, SeekFrom from) // throw(eArchive) offset = mFileSize + offset; break; default: - throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; + throw eArchiveSeek(mCurrentFilename, iFSServices::GetInstance()->GetErrString()); } - if ( offset > mFileSize ) - throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; + if (offset > mFileSize) + throw eArchiveSeek(mCurrentFilename, iFSServices::GetInstance()->GetErrString()); mReadHead = offset; mCurrentFile.Seek(mReadHead, cFile::SEEK_BEGIN); - //This is where the actual read/writehead is set!! - }//try - catch( eFile& fileError ) + //This is where the actual read/writehead is set!! + } //try + catch (eFile& fileError) { - throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveSeek(mCurrentFilename, fileError.GetDescription())); } } @@ -657,13 +624,13 @@ int64 cFileArchive::CurrentPos(void) const ///////////////////////////////////////////////////////////////////////// int64 cFileArchive::Length(void) const { - try + try { return mCurrentFile.GetSize(); } - catch(eFile& fileError) + catch (eFile& fileError) { - throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveSeek(mCurrentFilename, fileError.GetDescription())); } } @@ -672,24 +639,26 @@ int64 cFileArchive::Length(void) const ///////////////////////////////////////////////////////////////////////// void cFileArchive::OpenRead(const TCHAR* filename, uint32 openFlags) { - try + try { // set up open flags uint32 flags = cFile::OPEN_READ; - flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 ); - flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 ); - flags |= ( ( openFlags & FA_NONBLOCKING ) ? cFile::OPEN_NONBLOCKING :0 ); + flags |= ((openFlags & FA_OPEN_TRUNCATE) ? cFile::OPEN_TRUNCATE : 0); + flags |= ((openFlags & FA_OPEN_TEXT) ? cFile::OPEN_TEXT : 0); + flags |= ((openFlags & FA_SCANNING) ? cFile::OPEN_SCANNING : 0); + flags |= ((openFlags & FA_DIRECT) ? cFile::OPEN_DIRECT : 0); + mOpenFlags = openFlags; mCurrentFilename = filename; - mCurrentFile.Open( filename, flags ); + mCurrentFile.Open(filename, flags); isWritable = false; - mFileSize = mCurrentFile.GetSize(); - mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); + mFileSize = mCurrentFile.GetSize(); + mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN); } - catch(eFile& fileError) + catch (eFile& fileError) { - throw(eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveOpen(mCurrentFilename, fileError.GetDescription())); } } @@ -698,24 +667,26 @@ void cFileArchive::OpenRead(const TCHAR* filename, uint32 openFlags) ///////////////////////////////////////////////////////////////////////// void cFileArchive::OpenReadWrite(const TCHAR* filename, uint32 openFlags) { - try - { + try + { // set up open flags uint32 flags = cFile::OPEN_WRITE; - flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 ); - flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 ); - flags |= ( ( openFlags & FA_NONBLOCKING ) ? cFile::OPEN_NONBLOCKING :0 ); + flags |= ((openFlags & FA_OPEN_TRUNCATE) ? cFile::OPEN_TRUNCATE : 0); + flags |= ((openFlags & FA_OPEN_TEXT) ? cFile::OPEN_TEXT : 0); + flags |= ((openFlags & FA_SCANNING) ? cFile::OPEN_SCANNING : 0); + flags |= ((openFlags & FA_DIRECT) ? cFile::OPEN_DIRECT : 0); + mOpenFlags = openFlags; mCurrentFilename = filename; - mCurrentFile.Open( filename, flags ); + mCurrentFile.Open(filename, flags); isWritable = true; mFileSize = mCurrentFile.GetSize(); - mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); + mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN); } - catch(eFile& fileError) + catch (eFile& fileError) { - throw( eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveOpen(mCurrentFilename, fileError.GetDescription())); } } @@ -733,65 +704,65 @@ TSTRING cFileArchive::GetCurrentFilename(void) const ///////////////////////////////////////////////////////////////////////// void cFileArchive::Close() { - try + try { mCurrentFile.Close(); - mFileSize = 0; - mReadHead = 0; + mFileSize = 0; + mReadHead = 0; mCurrentFilename = _T(""); } - catch(eFile& fileError) + catch (eFile& fileError) { - throw( eArchive( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchive(mCurrentFilename, fileError.GetDescription())); } } ///////////////////////////////////////////////////////////////////////// -// Read -- Read places bytes in location designated by pDest. Returns +// Read -- Read places bytes in location designated by pDest. Returns // The actual amount read into *pDest. ///////////////////////////////////////////////////////////////////////// int cFileArchive::Read(void* pDest, int count) { - try + + try { - if ( mReadHead + count > mFileSize ) - count = static_cast( mFileSize - mReadHead ); + if (mReadHead + count > mFileSize && !(mOpenFlags & FA_DIRECT)) + count = static_cast(mFileSize - mReadHead); - if ( pDest != NULL ) + if (pDest != NULL) { - int nbRead = - static_cast( mCurrentFile.Read( pDest, count ) ); + int nbRead = static_cast(mCurrentFile.Read(pDest, count)); // 'count' may not be equal to 'nbRead' if the file is open in // text mode. count = nbRead; - if(count < 0) count = 0; + if (count < 0) + count = 0; } else { - int i; + int i; int32 dummy; - for (i = count; ; i -= sizeof(int32)) + for (i = count;; i -= sizeof(int32)) { if (i < (int)sizeof(int32)) { if (i > 0) - mCurrentFile.Read( &dummy, i ); + mCurrentFile.Read(&dummy, i); break; } - mCurrentFile.Read( &dummy, i ); + mCurrentFile.Read(&dummy, i); } } mReadHead += count; return count; } - catch( eFile& fileError ) + catch (eFile& fileError) { - throw( eArchiveRead( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveRead(mCurrentFilename, fileError.GetDescription())); } - } ///////////////////////////////////////////////////////////////////////// @@ -800,38 +771,38 @@ int cFileArchive::Read(void* pDest, int count) ///////////////////////////////////////////////////////////////////////// int cFileArchive::Write(const void* pDest, int count) // throw(eArchive) { - try + try { int64 actual_count = 0; - ASSERT( mCurrentFile.isWritable ); + ASSERT(mCurrentFile.isWritable); - actual_count = mCurrentFile.Write( pDest, count ); + actual_count = mCurrentFile.Write(pDest, count); - if ( actual_count < count ) + if (actual_count < count) { //Disk full?? - throw eArchiveWrite( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; + throw eArchiveWrite(mCurrentFilename, iFSServices::GetInstance()->GetErrString()); } // increment the read/write head mReadHead += actual_count; // increase the size, if needed - if( mReadHead > mFileSize ) + if (mReadHead > mFileSize) { - #if 0 // IS_SUNPRO - // These two lines seem to be all there is between code that crashes and code that works for sunpro +#if 0 // IS_SUNPRO \ + // These two lines seem to be all there is between code that crashes and code that works for sunpro cDebug d("cFileArchive::Write()"); d.TraceDebug(_T("file(%s) adjusted mFileSize = %d mReadHead = %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead); - #endif +#endif mFileSize = mReadHead; } return (int)actual_count; } - catch( eFile& fileError ) + catch (eFile& fileError) { - throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveWrite(mCurrentFilename, fileError.GetDescription())); } } @@ -839,91 +810,92 @@ int cFileArchive::Write(const void* pDest, int count) // throw(eArchive) ///////////////////////////////////////////////////////////////////////// // Truncate ///////////////////////////////////////////////////////////////////////// -void cFileArchive::Truncate() // throw(eArchive) +void cFileArchive::Truncate() // throw(eArchive) { - ASSERT( mCurrentFile.IsOpen() ); - ASSERT( mCurrentFile.isWritable ); + ASSERT(mCurrentFile.IsOpen()); + ASSERT(mCurrentFile.isWritable); - try + try { - mCurrentFile.Truncate ( mReadHead ); + mCurrentFile.Truncate(mReadHead); } - catch( eFile& fileError ) + catch (eFile& fileError) { //TODO: create an error number for truncate... - throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) ); + throw(eArchiveWrite(mCurrentFilename, fileError.GetDescription())); } mFileSize = mReadHead; } - ///////////////////////////////////////////////////////////////////////// // OpenReadWrite -- Opens the file to be read or written to // // since we'll never open an existing file, the truncateFile flag is unnecessary. ///////////////////////////////////////////////////////////////////////// -void cLockedTemporaryFileArchive::OpenReadWrite( const TCHAR* filename, uint32 openFlags ) +void cLockedTemporaryFileArchive::OpenReadWrite(const TCHAR* filename, uint32 openFlags) { - TSTRING strTempFile; + TSTRING strTempFile; - try { + try + { - ASSERT( !mCurrentFile.IsOpen() ); // shouldn't be able to create a new file when we're already open - if ( mCurrentFile.IsOpen() ) - throw( eArchive( mCurrentFilename, _T("Internal Error") ) ); + ASSERT(!mCurrentFile.IsOpen()); // shouldn't be able to create a new file when we're already open + if (mCurrentFile.IsOpen()) + throw(eArchive(mCurrentFilename, _T("Internal Error"))); - /////////////////////////////////////////////////////////////////////////////// - // if filename is NULL, create a temp file for the caller - if( filename == NULL ) - { - try - { - iFSServices::GetInstance()->GetTempDirName( strTempFile ); - strTempFile += _T("twtempXXXXXX"); - iFSServices::GetInstance()->MakeTempFilename( strTempFile ); - } - catch( eFSServices& fileError) - { - TSTRING errStr = TSS_GetString( cCore, core::STR_BAD_TEMPDIRECTORY ); - throw eArchiveOpen(strTempFile, errStr); - } - } - /////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////// + // if filename is NULL, create a temp file for the caller + if (filename == NULL) + { + try + { + iFSServices::GetInstance()->GetTempDirName(strTempFile); + strTempFile += _T("twtempXXXXXX"); + iFSServices::GetInstance()->MakeTempFilename(strTempFile); + } + catch (eFSServices& fileError) + { + TSTRING errStr = TSS_GetString(cCore, core::STR_BAD_TEMPDIRECTORY); + throw eArchiveOpen(strTempFile, errStr); + } + } + /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - // create file - - // set up flags - uint32 flags = cFile::OPEN_WRITE | cFile::OPEN_LOCKED_TEMP | cFile::OPEN_CREATE | cFile::OPEN_EXCLUSIVE; - if ( openFlags & FA_OPEN_TRUNCATE ) - flags |= cFile::OPEN_TRUNCATE; - if ( openFlags & FA_OPEN_TEXT ) - flags |= cFile::OPEN_TEXT; - - // open file - mCurrentFilename = filename ? filename : strTempFile.c_str(); - mCurrentFile.Open( mCurrentFilename, flags ); - - isWritable = true; - mFileSize = mCurrentFile.GetSize(); - mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); + /////////////////////////////////////////////////////////////////////////////// + // create file + + // set up flags + uint32 flags = cFile::OPEN_WRITE | cFile::OPEN_LOCKED_TEMP | cFile::OPEN_CREATE | cFile::OPEN_EXCLUSIVE; + if (openFlags & FA_OPEN_TRUNCATE) + flags |= cFile::OPEN_TRUNCATE; + if (openFlags & FA_OPEN_TEXT) + flags |= cFile::OPEN_TEXT; + + // open file + mCurrentFilename = filename ? filename : strTempFile.c_str(); + mCurrentFile.Open(mCurrentFilename, flags); + + isWritable = true; + mFileSize = mCurrentFile.GetSize(); + mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN); #if 0 // IS_SUNPRO cDebug d("cLockedTemporaryFileArchive::OpenReadWrite()"); d.TraceDebug(_T("file(%s) set mFileSize to %d mReadHead to %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead); #endif - }//try - catch (eFile& fileError) { - TSTRING errStr = TSS_GetString( cCore, core::STR_BAD_TEMPDIRECTORY ); - eArchiveOpen e(strTempFile, errStr); - throw e; - } + } //try + catch (eFile& fileError) + { + TSTRING errStr = TSS_GetString(cCore, core::STR_BAD_TEMPDIRECTORY); + eArchiveOpen e(strTempFile, errStr); + throw e; + } - /////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////// @@ -933,4 +905,3 @@ void cLockedTemporaryFileArchive::Close() // Note: this deletes the file as well cFileArchive::Close(); } - diff --git a/src/core/archive.h b/src/core/archive.h index e4dccfb..69700ee 100644 --- a/src/core/archive.h +++ b/src/core/archive.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -56,69 +56,71 @@ //============================================================================= // eArchive exception classes //============================================================================= -TSS_FILE_EXCEPTION( eArchive, eFileError ); -TSS_FILE_EXCEPTION( eArchiveOpen, eArchive ); -TSS_FILE_EXCEPTION( eArchiveWrite, eArchive ); -TSS_FILE_EXCEPTION( eArchiveRead, eArchive ); -TSS_FILE_EXCEPTION( eArchiveEOF, eArchive ); -TSS_FILE_EXCEPTION( eArchiveSeek, eArchive ); -TSS_FILE_EXCEPTION( eArchiveMemmap, eArchive ); -TSS_FILE_EXCEPTION( eArchiveOutOfMem, eArchive ); -TSS_FILE_EXCEPTION( eArchiveInvalidOp, eArchive ); -TSS_FILE_EXCEPTION( eArchiveFormat, eArchive ); -TSS_FILE_EXCEPTION( eArchiveNotRegularFile, eArchive ); -TSS_BEGIN_EXCEPTION( eArchiveCrypto, eArchive ) - - virtual TSTRING GetMsg() const; - // eCryptoArchive appends a special string to the end of - // all exception messages +TSS_FILE_EXCEPTION(eArchive, eFileError); +TSS_FILE_EXCEPTION(eArchiveOpen, eArchive); +TSS_FILE_EXCEPTION(eArchiveWrite, eArchive); +TSS_FILE_EXCEPTION(eArchiveRead, eArchive); +TSS_FILE_EXCEPTION(eArchiveEOF, eArchive); +TSS_FILE_EXCEPTION(eArchiveSeek, eArchive); +TSS_FILE_EXCEPTION(eArchiveMemmap, eArchive); +TSS_FILE_EXCEPTION(eArchiveOutOfMem, eArchive); +TSS_FILE_EXCEPTION(eArchiveInvalidOp, eArchive); +TSS_FILE_EXCEPTION(eArchiveFormat, eArchive); +TSS_FILE_EXCEPTION(eArchiveNotRegularFile, eArchive); +TSS_BEGIN_EXCEPTION(eArchiveCrypto, eArchive) + +virtual TSTRING GetMsg() const; +// eCryptoArchive appends a special string to the end of +// all exception messages TSS_END_EXCEPTION() -TSS_EXCEPTION( eArchiveStringTooLong, eArchive ); +TSS_EXCEPTION(eArchiveStringTooLong, eArchive); // throw( eArchiveOpen( cErrorUtil::MakeFileError( fileError.GetMsg(), strTempFile ) ) ); //============================================================================= -// cArchive +// cArchive //============================================================================= class cArchive { public: - virtual ~cArchive() {} - + virtual ~cArchive() + { + } + // convenience methods // // Specific Read functions throw(eArchive) if EOF is reached because - // if the caller is requesting a certain amount of data to be present, + // if the caller is requesting a certain amount of data to be present, // reaching EOF is unexpected // // ReadBlob and WriteBlob return number of bytes read or written. Notice // that ReadBlob does not throw an exception since eventually EOF is expected. // // ReadBlob can take NULL as a destination pointer - // - // All write functions throw exceptions for unexpected events like + // + // All write functions throw exceptions for unexpected events like // running out of memory or disk space. // - void ReadInt16(int16& ret); // throw(eArchive) - void ReadInt32(int32& ret); // throw(eArchive) - void ReadInt64(int64& ret); // throw(eArchive) - void ReadString(TSTRING& ret); // throw(eArchive) - int ReadBlob(void* pBlob, int count); - void WriteInt16(int16 i); // throw(eArchive) - void WriteInt32(int32 i); // throw(eArchive) - void WriteInt64(int64 i); // throw(eArchive) - void WriteString(TSTRING s); // throw(eArchive) - void WriteBlob(const void* pBlob, int count); // throw(eArchive) + void ReadInt16(int16& ret); // throw(eArchive) + void ReadInt32(int32& ret); // throw(eArchive) + void ReadInt64(int64& ret); // throw(eArchive) + void ReadString(TSTRING& ret); // throw(eArchive) + int ReadBlob(void* pBlob, int count); + void WriteInt16(int16 i); // throw(eArchive) + void WriteInt32(int32 i); // throw(eArchive) + void WriteInt64(int64 i); // throw(eArchive) + void WriteString(TSTRING s); // throw(eArchive) + void WriteBlob(const void* pBlob, int count); // throw(eArchive) static int32 GetStorageSize(const TSTRING& str); - // this method calculates how many bytes the given string will take up in the archive and returns - // that value - // NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also - // need to change. + // this method calculates how many bytes the given string will take up in the archive and returns + // that value + // NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also + // need to change. - int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive) + int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive) // this method copies amt bytes from pFrom to itself, throwing an eArchive if anything goes wrong. // only makes sense to call for reading archives @@ -126,7 +128,7 @@ class cArchive protected: // overrides - virtual int Read(void* pDest, int count) = 0; + virtual int Read(void* pDest, int count) = 0; virtual int Write(const void* pDest, int count) = 0; // throw(eArchive); }; @@ -137,15 +139,16 @@ class cArchive class cBidirArchive : public cArchive { public: - enum SeekFrom { + enum SeekFrom + { BEGINNING = 0, - CURRENT = 1, - END = -1 + CURRENT = 1, + END = -1 }; - virtual void Seek(int64 offset, SeekFrom from) = 0; // throw(eArchive); - virtual int64 CurrentPos() const = 0; - virtual int64 Length() const = 0; + virtual void Seek(int64 offset, SeekFrom from) = 0; // throw(eArchive); + virtual int64 CurrentPos() const = 0; + virtual int64 Length() const = 0; }; /////////////////////////////////////////////////////////////////////////////// @@ -155,29 +158,30 @@ class cBidirArchive : public cArchive class cMemMappedArchive : public cBidirArchive { public: - enum { + enum + { MAP_TO_EOF = -1 }; cMemMappedArchive(); virtual ~cMemMappedArchive(); - virtual void MapArchive(int64 offset, int64 len) = 0; // throw(eArchive); - virtual void MapArchive(int64 offset, int64 len) const = 0; // throw(eArchive); + virtual void MapArchive(int64 offset, int64 len) = 0; // throw(eArchive); + virtual void MapArchive(int64 offset, int64 len) const = 0; // throw(eArchive); // the const version of MapArchive() does not allow the archive to grow in size - int64 GetMappedOffset() const; // throw(eArchive) - int64 GetMappedLength() const; // throw(eArchive) - void* GetMap(); // throw(eArchive) - const void* GetMap() const; + int64 GetMappedOffset() const; // throw(eArchive) + int64 GetMappedLength() const; // throw(eArchive) + void* GetMap(); // throw(eArchive) + const void* GetMap() const; protected: - mutable void* mpMappedMem; - mutable int64 mMappedOffset; - mutable int64 mMappedLength; + mutable void* mpMappedMem; + mutable int64 mMappedOffset; + mutable int64 mMappedLength; // call in derived class to set above vars - void SetNewMap(void* pMap, int64 offset, int64 length) const; + void SetNewMap(void* pMap, int64 offset, int64 length) const; }; /////////////////////////////////////////////////////////////////////////////// @@ -193,27 +197,30 @@ class cMemoryArchive : public cMemMappedArchive cMemoryArchive(int maxSize = 0x8000000); // default max size == 128MB ~cMemoryArchive(); - virtual bool EndOfFile(); - virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) - virtual int64 CurrentPos() const; - virtual int64 Length() const; - virtual void MapArchive(int64 offset, int64 len); // throw(eArchive) - virtual void MapArchive(int64 offset, int64 len) const; // throw(eArchive) + virtual bool EndOfFile(); + virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) + virtual int64 CurrentPos() const; + virtual int64 Length() const; + virtual void MapArchive(int64 offset, int64 len); // throw(eArchive) + virtual void MapArchive(int64 offset, int64 len) const; // throw(eArchive) - void Truncate(); // set the length to the current pos + void Truncate(); // set the length to the current pos - int8* GetMemory() const { return mpMemory; } + int8* GetMemory() const + { + return mpMemory; + } protected: - int8* mpMemory; - int mAllocatedLen; - int mMaxAllocatedLen; - int mLogicalSize; - int mReadHead; - - virtual int Read(void* pDest, int count); - virtual int Write(const void* pDest, int count); // throw(eArchive) - virtual void AllocateMemory(int len); // throw(eArchive) + int8* mpMemory; + int mAllocatedLen; + int mMaxAllocatedLen; + int mLogicalSize; + int mReadHead; + + virtual int Read(void* pDest, int count); + virtual int Write(const void* pDest, int count); // throw(eArchive) + virtual void AllocateMemory(int len); // throw(eArchive) }; /////////////////////////////////////////////////////////////////////////////// @@ -224,30 +231,31 @@ class cFixedMemArchive : public cBidirArchive { public: cFixedMemArchive(); - cFixedMemArchive( int8* pMem, int32 size ); + cFixedMemArchive(int8* pMem, int32 size); virtual ~cFixedMemArchive(); - void Attach( int8* pMem, int32 size ); - // this method associates the archive with pMem and sets the size of the - // archive. Unlike cMemoryArchive, this may never grow or shrink in size. + void Attach(int8* pMem, int32 size); + // this method associates the archive with pMem and sets the size of the + // archive. Unlike cMemoryArchive, this may never grow or shrink in size. //----------------------------------- // cBidirArchive interface //----------------------------------- - virtual void Seek (int64 offset, SeekFrom from) ; // throw(eArchive); - virtual int64 CurrentPos () const ; - virtual int64 Length () const ; - virtual bool EndOfFile(); + virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive); + virtual int64 CurrentPos() const; + virtual int64 Length() const; + virtual bool EndOfFile(); + protected: //----------------------------------- // cArchive interface //----------------------------------- - virtual int Read(void* pDest, int count); // throw(eArchive) - virtual int Write(const void* pDest, int count); // throw(eArchive) + virtual int Read(void* pDest, int count); // throw(eArchive) + virtual int Write(const void* pDest, int count); // throw(eArchive) - int8* mpMemory; - int32 mSize; - int32 mReadHead; + int8* mpMemory; + int32 mSize; + int32 mReadHead; }; class cFileArchive : public cBidirArchive @@ -258,92 +266,74 @@ class cFileArchive : public cBidirArchive enum OpenFlags { - FA_OPEN_TEXT = 0x1, - FA_OPEN_TRUNCATE = 0x2, - FA_NONBLOCKING = 0x4 + FA_OPEN_TEXT = 0x1, + FA_OPEN_TRUNCATE = 0x2, + FA_SCANNING = 0x4, + FA_DIRECT = 0x8 }; // TODO: Open should throw - virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0 ); - virtual void OpenReadWrite(const TCHAR* filename, uint32 openFlags = FA_OPEN_TRUNCATE ); - // opens a file for reading or writing; the file is always created if it doesn't exist, - // and is truncated to zero length if truncateFile is set to true; - TSTRING GetCurrentFilename(void) const; - virtual void Close(void); - void Truncate(); // throw(eArchive) // set the length to the current pos + virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0); + virtual void OpenReadWrite(const TCHAR* filename, uint32 openFlags = FA_OPEN_TRUNCATE); + // opens a file for reading or writing; the file is always created if it doesn't exist, + // and is truncated to zero length if truncateFile is set to true; + TSTRING GetCurrentFilename(void) const; + virtual void Close(void); + void Truncate(); // throw(eArchive) // set the length to the current pos //----------------------------------- // cBidirArchive interface //----------------------------------- - virtual bool EndOfFile(); - virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) - virtual int64 CurrentPos() const; - virtual int64 Length() const; - - + virtual bool EndOfFile(); + virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) + virtual int64 CurrentPos() const; + virtual int64 Length() const; + + protected: - int64 mFileSize; //Size of FileArchive - int64 mReadHead; //Current position of read/write head + int64 mFileSize; //Size of FileArchive + int64 mReadHead; //Current position of read/write head //----------------------------------- // cArchive interface //----------------------------------- - virtual int Read(void* pDest, int count); - virtual int Write(const void* pDest, int count); //throw(eArchive) - bool isWritable; - cFile mCurrentFile; - TSTRING mCurrentFilename; //current file + virtual int Read(void* pDest, int count); + virtual int Write(const void* pDest, int count); //throw(eArchive) + bool isWritable; + cFile mCurrentFile; + TSTRING mCurrentFilename; //current file + uint32 mOpenFlags; }; /////////////////////////////////////////////////////////////// // cLockedTemporaryFileArchive -- this class uses as an archive a file // that is not accessable to any other process besides the calling one. // the file will be deleted from the filesystem on Close(); -// -// implemented by using cFileArchive and overwriting open and close +// +// implemented by using cFileArchive and overwriting open and close // functions // class cLockedTemporaryFileArchive : public cFileArchive { public: - virtual void OpenReadWrite ( const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE ); - // creates the file. filename must not exist on the file system. - // if filename is NULL, the class will create and use a temporary file. - // truncateFile has no meaning + virtual void OpenReadWrite(const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE); + // creates the file. filename must not exist on the file system. + // if filename is NULL, the class will create and use a temporary file. + // truncateFile has no meaning //virtual void OpenReadWriteThrow ( const TCHAR* filename = NULL, bool truncateFile = true ) throw (eArchive); - // this is the same as OpenReadWrite, except an exception is thrown on error (of type - // cArchive::ERR_OPEN_FAILED) + // this is the same as OpenReadWrite, except an exception is thrown on error (of type + // cArchive::ERR_OPEN_FAILED) - virtual void Close(); - // close and delete the file + virtual void Close(); + // close and delete the file private: - // open for read only makes no sense if we're always creating the file, + // open for read only makes no sense if we're always creating the file, // so disallow read only file opens - virtual void OpenRead( const TCHAR*, uint32 openFlags = 0 ) { ASSERT( false ); THROW_INTERNAL("archive.h"); } -}; - - - -/* -// TODO: fill these out - -/////////////////////////////////////////////////////////////////////////////// -// class cMMFileArchive -- -/////////////////////////////////////////////////////////////////////////////// - -class cMMFileArchive : public cMemMappedArchive -{ -public: -}; - -/////////////////////////////////////////////////////////////////////////////// -// class cNetArchive -- -/////////////////////////////////////////////////////////////////////////////// - -class cNetArchive : public cArchive -{ -public: + virtual void OpenRead(const TCHAR*, uint32 openFlags = 0) + { + ASSERT(false); + THROW_INTERNAL("archive.h"); + } }; -*/ -#endif +#endif diff --git a/src/core/charutil.cpp b/src/core/charutil.cpp index e001c9d..e9df686 100644 --- a/src/core/charutil.cpp +++ b/src/core/charutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,150 +41,111 @@ #include "charutil.h" #include "ntmbs.h" -/* NOW WE USE tss::strinc -// like mblen but also for wchar_t -int util_tlen( const TCHAR* cur, size_t count ) -{ - int nch = -2; // 'unused' value - - ASSERT( count >= 0 ); - #ifdef _UNICODE - if( count > 0 ) - nch = 1; // next char is always one TCHAR long - else - nch = 0; // no more chars - #else - nch = ::mblen( cur, count ); // here sizeof(TCHAR) == 1 - #endif - - ASSERT( nch != -2 ); // make sure nch was set - return nch; +#if IS_ANDROID +int mblen(const char* s, size_t n) +{ + return mbtowc(0, s, n); } -*/ +#endif - -// +// // finds the next whole character in string identified by ['cur'-'end') // identifies beginning of char in 'first', then end of character in 'last' // returns number of TCHARs that make up the next character // if there are no more characters, will return 0 and first = last = end // POSTCONDITIONS: -// +// // RETURNS: -// +// // THROWS: -// +// // COMPLEXITY: -// +// // /* static */ -bool cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur, - const TSTRING::const_iterator& end, - TSTRING::const_iterator& first, - TSTRING::const_iterator& last ) +bool cCharUtil::PeekNextChar(const TSTRING::const_iterator& cur, + const TSTRING::const_iterator& end, + TSTRING::const_iterator& first, + TSTRING::const_iterator& last) { // // do we have a valid string here? // - if( cur > end ) + if (cur > end) { return false; } - if( cur == end ) + if (cur == end) { first = last = end; return false; } - if( *cur == _T('\0') ) + if (*cur == _T('\0')) { first = last = cur; return false; } first = cur; -// last = tss::strinc( cur ); - last = *cur ? cur + 1 : cur; - return true; -} - - -/* OLD way of doing this... - NOW WE USE tss::strinc -int cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur, - const TSTRING::const_iterator& end, - TSTRING::const_iterator& first, - TSTRING::const_iterator& last, - bool fThrowOnError ) -{ - // - // do we have a valid string here? - // - if( cur > end ) - return -1; - // - // determine length of character in TCHARs - // - int charSizeInTCHARs = util_tlen( cur, (size_t)end - (size_t)cur ); - if( charSizeInTCHARs == -1 ) // TODO:BAM -- what if size is zero? does that make sense? + if (!(*cur)) + { + last = cur; + } + else { - if( fThrowOnError ) - throw eCharUtilUnrecognizedChar(); - else - return -1; +#if !IS_AROS + mblen(NULL, 0); + int len = mblen(&*cur, MB_CUR_MAX); + if (len < 0) //invalid multibyte sequence, but let's not blow up. + len = 1; + + last = cur + len; +#else // AROS mblen() seems broken (as of 6/2016) so don't use it. + last = cur + 1; +#endif } - // - // denote beginning and end of character - // - first = cur; // first char always starts at 'cur' - last = first + charSizeInTCHARs; - - // - // there exist more characters - // - return charSizeInTCHARs; + return true; } -*/ + //============================================================================= -// +// // /* static */ -// bool cCharUtil::PopNextChar( TSTRING::const_iterator& cur, -// const TSTRING::const_iterator& end, -// TSTRING::const_iterator& first, +// bool cCharUtil::PopNextChar( TSTRING::const_iterator& cur, +// const TSTRING::const_iterator& end, +// TSTRING::const_iterator& first, // TSTRING::const_iterator& last ) //----------------------------------------------------------------------------- // REQUIRES: -// +// // EFFECTS: -// +// // same as PeekNextChar but increments 'cur' to 'last' // // POSTCONDITIONS: -// +// // RETURNS: -// +// // THROWS: -// +// // COMPLEXITY: -// +// // /* static */ -bool cCharUtil::PopNextChar( TSTRING::const_iterator& cur, - const TSTRING::const_iterator& end, - TSTRING::const_iterator& first, - TSTRING::const_iterator& last ) +bool cCharUtil::PopNextChar(TSTRING::const_iterator& cur, + const TSTRING::const_iterator& end, + TSTRING::const_iterator& first, + TSTRING::const_iterator& last) { - bool f = PeekNextChar( cur, end, first, last ); + bool f = PeekNextChar(cur, end, first, last); - cur = last; // pop causes 'cur' to move to just beyond character ('last') + cur = last; // pop causes 'cur' to move to just beyond character ('last') return f; } - -// eof: charutil.cpp diff --git a/src/core/charutil.h b/src/core/charutil.h index 6d0c2ff..5029e57 100644 --- a/src/core/charutil.h +++ b/src/core/charutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,23 +44,20 @@ class cCharUtil { public: - - // finds the next whole character in string identified by ['cur'-'end') // identifies beginning of char in 'first', then end of character in 'last' // returns 'are there more characters in string?' // if there are no more characters, will return 0 and first = last = end - static bool PeekNextChar( const TSTRING::const_iterator& cur, - const TSTRING::const_iterator& end, - TSTRING::const_iterator& first, - TSTRING::const_iterator& last ); - + static bool PeekNextChar(const TSTRING::const_iterator& cur, + const TSTRING::const_iterator& end, + TSTRING::const_iterator& first, + TSTRING::const_iterator& last); + // same as PeekNextChar but increments 'cur' to 'last' - static bool PopNextChar( TSTRING::const_iterator& cur, - const TSTRING::const_iterator& end, - TSTRING::const_iterator& first, - TSTRING::const_iterator& last ); + static bool PopNextChar(TSTRING::const_iterator& cur, + const TSTRING::const_iterator& end, + TSTRING::const_iterator& first, + TSTRING::const_iterator& last); }; -#endif//__CHARUTIL_H - +#endif //__CHARUTIL_H diff --git a/src/core/cmdlineparser.cpp b/src/core/cmdlineparser.cpp index 7da836b..517d5ec 100644 --- a/src/core/cmdlineparser.cpp +++ b/src/core/cmdlineparser.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,9 +38,7 @@ /////////////////////////////////////////////////////////////////////////////// // ctor, dotr /////////////////////////////////////////////////////////////////////////////// -cCmdLineParser::cCmdLineParser() : - mArgTable(HASH_VERY_SMALL), - mLastArgInfo(-1, PARAM_NONE) +cCmdLineParser::cCmdLineParser() : mArgTable(HASH_VERY_SMALL), mLastArgInfo(-1, PARAM_NONE) { } @@ -51,19 +49,20 @@ cCmdLineParser::~cCmdLineParser() /////////////////////////////////////////////////////////////////////////////// // AddArg /////////////////////////////////////////////////////////////////////////////// -void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed) +void cCmdLineParser::AddArg( + int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed) { - if(arg.empty() && alias.empty()) + if (arg.empty() && alias.empty()) { // this refers to the list of parameters that comes after all the cmd line switches mLastArgInfo.mId = argId; mLastArgInfo.mNumParams = numParams; - return ; + return; } - if(! arg.empty()) - mArgTable.Insert(arg, cArgInfo(argId, numParams)); - if(! alias.empty()) + if (!arg.empty()) + mArgTable.Insert(arg, cArgInfo(argId, numParams)); + if (!alias.empty()) { // put the alias in the table with a '-' prepended to it so it matches '--' TSTRING str(_T("-")); @@ -71,62 +70,58 @@ void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias, mArgTable.Insert(str, cArgInfo(argId, numParams)); } // This argument can appear more than once on the command line. - if( multipleAllowed ) - mMultipleAllowed.insert( argId ); + if (multipleAllowed) + mMultipleAllowed.insert(argId); } /////////////////////////////////////////////////////////////////////////////// // Clear /////////////////////////////////////////////////////////////////////////////// -void cCmdLineParser::Clear() +/*void cCmdLineParser::Clear() { mLastArgInfo.mId = -1; mLastArgInfo.mNumParams = PARAM_INVALID; mArgTable.Clear(); mArgData.clear(); mMutExList.clear(); -} +}*/ /////////////////////////////////////////////////////////////////////////////// // Parse /////////////////////////////////////////////////////////////////////////////// -void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) +void cCmdLineParser::Parse(int argc, const TCHAR* const* argv) { // clear out any existing data mArgData.clear(); - const TCHAR* pCurArg = 0; - bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed + const TCHAR* pCurArg = 0; + bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed // I assume argv[0] is the executable name... - for(int i=1; i < argc; i++) + for (int i = 1; i < argc; i++) { - if(argv[i][0] == _T('-')) + if (argv[i][0] == _T('-')) { pCurArg = argv[i]; // this is a switch; find it in the table... cArgInfo argInfo; - if ( !mArgTable.Lookup( TSTRING(&argv[i][1] ), argInfo ) ) + if (!mArgTable.Lookup(TSTRING(&argv[i][1]), argInfo)) { // unknown switch! - throw eCmdLineInvalidArg( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + pCurArg ); + throw eCmdLineInvalidArg(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg); } // // make sure this hasn't been specified yet... // - if( ArgInList( argInfo.mId ) ) + if (ArgInList(argInfo.mId)) { // Make sure it isn't okay for this one to appear more than once... - std::set::iterator it = mMultipleAllowed.find( argInfo.mId ); - if( it == mMultipleAllowed.end() ) + std::set::iterator it = mMultipleAllowed.find(argInfo.mId); + if (it == mMultipleAllowed.end()) { // It wasn't in our list of allowed params, so error. - throw eCmdLineMultiArg( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + argv[i] ); + throw eCmdLineMultiArg(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + argv[i]); } } // @@ -134,24 +129,22 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) // mArgData.push_back(cArgData(argInfo.mId, TSTRING(argv[i]))); cArgData& curArg = mArgData.back(); - switch( argInfo.mNumParams ) + switch (argInfo.mNumParams) { case PARAM_NONE: - // make sure there are no parameters to this, but be careful because + // make sure there are no parameters to this, but be careful because // it is legal to start the parameters to the executable here. - if((i+1 < argc) && (argv[i+1][0] != _T('-'))) + if ((i + 1 < argc) && (argv[i + 1][0] != _T('-'))) { // search for any more parameters // TODO: In the future we may want to support a '--' switch that specifies the start // of parameters to the executable. - for (int j = i + 2; j < argc; ++j ) + for (int j = i + 2; j < argc; ++j) { if (argv[j][0] == _T('-')) { // >0 parameter passed ! - throw eCmdLineBadParam( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + pCurArg ); + throw eCmdLineBadParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg); } } } @@ -160,29 +153,27 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) case PARAM_ONE: // get the next parameter... i++; - if ( (i >= argc) || (argv[i][0] == _T('-')) ) + if ((i >= argc) || (argv[i][0] == _T('-'))) { // zero parameters passed to something that needed one param - throw eCmdLineBadParam( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + pCurArg ); + throw eCmdLineBadParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg); } - curArg.mParams.push_back( TSTRING(argv[i]) ); + curArg.mParams.push_back(TSTRING(argv[i])); break; case PARAM_MANY: i++; - while((i < argc) && (argv[i][0] != _T('-'))) + while ((i < argc) && (argv[i][0] != _T('-'))) { - curArg.mParams.push_back(TSTRING(argv[i])); + curArg.mParams.push_back(TSTRING(argv[i])); i++; } - i--; // since we have gone too far at this point + i--; // since we have gone too far at this point break; default: - ASSERTMSG( false, "Unknown number of arguments to parser" ); + ASSERTMSG(false, "Unknown number of arguments to parser"); } } else @@ -191,14 +182,14 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) // this must be the final "unnamed" arg // first, make sure it is consistent with the current info... bool bResult = true; - switch(mLastArgInfo.mNumParams) + switch (mLastArgInfo.mNumParams) { case PARAM_NONE: // this is an error; they didn't want any command line parameters... bResult = false; break; case PARAM_ONE: - if(i+1 != argc) + if (i + 1 != argc) // there is >1 final parameter; it is an error bResult = false; break; @@ -207,33 +198,28 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) break; default: ASSERT(false); - } - if(! bResult) + if (!bResult) { - throw eCmdLineBadParam( ); + throw eCmdLineBadParam(); } // ok, we can push the final parameter info onto the list... mArgData.push_back(cArgData(mLastArgInfo.mId)); cArgData& curArg = mArgData.back(); - - while ( i < argc ) + + while (i < argc) { - if ( argv[i][0] == _T('-') ) + if (argv[i][0] == _T('-')) { - if ( ! pCurArg ) + if (!pCurArg) { - throw eCmdLineBadSwitchPos( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + argv[i] ); + throw eCmdLineBadSwitchPos(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + argv[i]); } else { // there was an extra parameter passed somewhere! - throw eCmdLineBadArgParam( - TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS ) - + pCurArg ); + throw eCmdLineBadArgParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg); } } @@ -241,21 +227,18 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) curArg.mParams.push_back(TSTRING(argv[i])); i++; } - - } - } // it is possible not to process the final command line parameters in the "else" case above // (this only occurs if there are no command line parameters specified) so let's make sure that // is consistent with what we are configured with... // NOTE -- it is ok to have no cmd line parameters if they specified PARAM_NONE or PARAM_MANY - if(! bProcessedFinalParams) + if (!bProcessedFinalParams) { - if(mLastArgInfo.mNumParams == PARAM_ONE) + if (mLastArgInfo.mNumParams == PARAM_ONE) { - throw eCmdLineBadParam( ); + throw eCmdLineBadParam(); } } @@ -269,28 +252,24 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) /////////////////////////////////////////////////////////////////////////////// void cCmdLineParser::TestMutEx() { - std::list >::const_iterator i; - cCmdLineIter iter1(*this), iter2(*this); - for(i = mMutExList.begin(); i != mMutExList.end(); i++) + std::list >::const_iterator i; + cCmdLineIter iter1(*this), iter2(*this); + for (i = mMutExList.begin(); i != mMutExList.end(); i++) { //TODO -- there is a much more efficent way to do this (using cFCOPropVector, for example) // the command line is presumably small enough, tho, that it probably isn't a big // deal to do it this way. iter1.SeekToArg(i->first); - if(! iter1.Done()) + if (!iter1.Done()) { iter2.SeekToArg(i->second); - if(! iter2.Done()) + if (!iter2.Done()) { // we have a mutual exclusion violation! - throw eCmdLineMutEx( - iter1.ActualParam() - + _T(", ") - + iter2.ActualParam() ); + throw eCmdLineMutEx(iter1.ActualParam() + _T(", ") + iter2.ActualParam()); } } } - } /////////////////////////////////////////////////////////////////////////////// @@ -298,51 +277,51 @@ void cCmdLineParser::TestMutEx() /////////////////////////////////////////////////////////////////////////////// void cCmdLineParser::TestDependency() { - std::list< std::pair< std::pair< int, int>, bool > >::const_iterator i; - cCmdLineIter iter1(*this), iter2(*this); + std::list, bool> >::const_iterator i; + cCmdLineIter iter1(*this), iter2(*this); - for( i = mDependencyList.begin(); i != mDependencyList.end(); ++i) + for (i = mDependencyList.begin(); i != mDependencyList.end(); ++i) { - iter1.SeekToArg( i->first.first ); + iter1.SeekToArg(i->first.first); // was it on the command line? - if( !iter1.Done() ) + if (!iter1.Done()) { // it was, is the corresponding arg on the command line? - iter2.SeekToArg( i->first.second ); - if( iter2.Done() ) // it wasn't, dependency error + iter2.SeekToArg(i->first.second); + if (iter2.Done()) // it wasn't, dependency error { TSTRING arg1, arg2, alias1, alias2; - cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 ); - cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 ); + cCmdLineParser::LookupArgInfo(i->first.first, arg1, alias1); + cCmdLineParser::LookupArgInfo(i->first.second, arg2, alias2); // determine in which form the user passed the arguments, // and construct the error message in the same form - if ( iter1.ActualParam().length() == 2 ) - throw eCmdLineDependency( _T("The switch -") + arg1 + _T(" requires -") + arg2 +_T(".") ); + if (iter1.ActualParam().length() == 2) + throw eCmdLineDependency(_T("The switch -") + arg1 + _T(" requires -") + arg2 + _T(".")); else - throw eCmdLineDependency( _T("The switch --") + alias1 + _T(" requires --") + alias2 + _T(".") ); + throw eCmdLineDependency(_T("The switch --") + alias1 + _T(" requires --") + alias2 + _T(".")); } } - else if( i->second ) + else if (i->second) // only make this second check if the dependencies are MUTUAL, // as indicated (or not) by the bool value. { - iter2.SeekToArg( i->first.second ); - // the first arg in the pair was not on the command line, - // so just make sure the second isn't there... - if( !iter2.Done() ) + iter2.SeekToArg(i->first.second); + // the first arg in the pair was not on the command line, + // so just make sure the second isn't there... + if (!iter2.Done()) { // arg2 appeared without arg1, so dependency error. TSTRING arg1, arg2, alias1, alias2; - cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 ); - cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 ); + cCmdLineParser::LookupArgInfo(i->first.first, arg1, alias1); + cCmdLineParser::LookupArgInfo(i->first.second, arg2, alias2); // determine in which form the user passed the arguments, // and construct the error message in the same form - if ( iter1.ActualParam().length() == 2 ) - throw eCmdLineDependency( _T("The switch -") + arg2 + _T(" requires -") + arg1 +_T(".") ); + if (iter1.ActualParam().length() == 2) + throw eCmdLineDependency(_T("The switch -") + arg2 + _T(" requires -") + arg1 + _T(".")); else - throw eCmdLineDependency( _T("The switch --") + alias2 + _T(" requires --") + alias1 + _T(".") ); + throw eCmdLineDependency(_T("The switch --") + alias2 + _T(" requires --") + alias1 + _T(".")); } } @@ -364,32 +343,32 @@ void cCmdLineParser::AddMutEx(int argId1, int argId2) /////////////////////////////////////////////////////////////////////////////// // AddDependency /////////////////////////////////////////////////////////////////////////////// -void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual ) +void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual) { // again, no checking for duplicates... would a set // prove to be a better container for this operation? - std::pair< int, int > Args( argId1, argId2 ); - std::pair< std::pair< int, int >, bool > Dep( Args, mutual ); + std::pair Args(argId1, argId2); + std::pair, bool> Dep(Args, mutual); ASSERT(argId1 != argId2); - mDependencyList.push_back( Dep); + mDependencyList.push_back(Dep); } /////////////////////////////////////////////////////////////////////////////// // TraceContents /////////////////////////////////////////////////////////////////////////////// -#ifdef _DEBUG -void cCmdLineParser::TraceContents(int dl) +#ifdef DEBUG +void cCmdLineParser::TraceContents(int dl) { cDebug d("cCmdLineParser::TraceContents"); - if(dl == -1) + if (dl == -1) dl = cDebug::D_DEBUG; std::list::const_iterator i; - for(i = mArgData.begin(); i != mArgData.end(); i++) + for (i = mArgData.begin(); i != mArgData.end(); i++) { d.Trace(dl, "* Item id:%d\n", i->mId); - for(std::vector::const_iterator vi = i->mParams.begin(); vi != i->mParams.end(); vi++) + for (std::vector::const_iterator vi = i->mParams.begin(); vi != i->mParams.end(); vi++) { d.Trace(dl, "\t%s\n", vi->c_str()); } @@ -398,7 +377,7 @@ void cCmdLineParser::TraceContents(int dl) d.Trace(dl, "--- Switch id table ---\n"); cHashTableIter iter(mArgTable); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { d.Trace(dl, "[%d] %s\n", iter.Val().mId, iter.Key().c_str()); } @@ -412,16 +391,16 @@ void cCmdLineParser::TraceContents(int dl) /////////////////////////////////////////////////////////////////////////////// bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const { - arg = _T(""); - alias = _T(""); + arg = _T(""); + alias = _T(""); cHashTableIter iter(mArgTable); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - if(iter.Val().mId == argId) + if (iter.Val().mId == argId) { TSTRING str = iter.Key(); - if((str.length() > 0) && (str[0] == _T('-'))) + if ((str.length() > 0) && (str[0] == _T('-'))) { // this is the alias! alias = (str.c_str() + 1); @@ -433,7 +412,7 @@ bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) cons } } } - return ((! arg.empty()) || (! alias.empty())); + return ((!arg.empty()) || (!alias.empty())); } /////////////////////////////////////////////////////////////////////////////// @@ -442,9 +421,9 @@ bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) cons bool cCmdLineParser::ArgInList(int argId) { std::list::iterator i; - for( i = mArgData.begin(); i != mArgData.end(); i++ ) + for (i = mArgData.begin(); i != mArgData.end(); i++) { - if( i->mId == argId ) + if (i->mId == argId) return true; } return false; @@ -458,15 +437,13 @@ bool cCmdLineParser::ArgInList(int argId) /////////////////////////////////////////////////////////////////////////////// // SeekToArg /////////////////////////////////////////////////////////////////////////////// -bool cCmdLineIter::SeekToArg(int argId) const +bool cCmdLineIter::SeekToArg(int argId) const { - for(SeekBegin(); ! Done(); Next()) + for (SeekBegin(); !Done(); Next()) { - if(ArgId() == argId) + if (ArgId() == argId) return true; } return false; - } - diff --git a/src/core/cmdlineparser.h b/src/core/cmdlineparser.h index ed78009..5eef8fd 100644 --- a/src/core/cmdlineparser.h +++ b/src/core/cmdlineparser.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // cmdlineparser.h // -// cCmdLineParser.h -- class that tokenizes the command line +// cCmdLineParser.h -- class that tokenizes the command line #ifndef __CMDLINEPARSER_H #define __CMDLINEPARSER_H @@ -49,14 +49,15 @@ //============================================================================= // eCmdLine //============================================================================= -TSS_EXCEPTION( eCmdLine, eError ) -TSS_EXCEPTION( eCmdLineInvalidArg, eCmdLine ) // an arg on the command line is not recognized -TSS_EXCEPTION( eCmdLineBadArgParam, eCmdLine ) // wrong number of parameters to an argument -TSS_EXCEPTION( eCmdLineBadParam, eCmdLine ) // wrong number of paramters to the executable (not associated with any arguments) -TSS_EXCEPTION( eCmdLineBadSwitchPos,eCmdLine ) // a '-' arg appeared after the final parameter list -TSS_EXCEPTION( eCmdLineMutEx, eCmdLine ) // a mutual exclusion error has occured -TSS_EXCEPTION( eCmdLineDependency, eCmdLine ) // a dependency error has occurred. -TSS_EXCEPTION( eCmdLineMultiArg, eCmdLine ) // an arg was found twice in the command line +TSS_EXCEPTION(eCmdLine, eError) +TSS_EXCEPTION(eCmdLineInvalidArg, eCmdLine) // an arg on the command line is not recognized +TSS_EXCEPTION(eCmdLineBadArgParam, eCmdLine) // wrong number of parameters to an argument +TSS_EXCEPTION(eCmdLineBadParam, + eCmdLine) // wrong number of paramters to the executable (not associated with any arguments) +TSS_EXCEPTION(eCmdLineBadSwitchPos, eCmdLine) // a '-' arg appeared after the final parameter list +TSS_EXCEPTION(eCmdLineMutEx, eCmdLine) // a mutual exclusion error has occured +TSS_EXCEPTION(eCmdLineDependency, eCmdLine) // a dependency error has occurred. +TSS_EXCEPTION(eCmdLineMultiArg, eCmdLine) // an arg was found twice in the command line /* @@ -95,93 +96,99 @@ class cCmdLineParser enum ParamCount { - PARAM_NONE, // no parameters to arg - PARAM_ONE, // one parameter to arg - PARAM_MANY, // zero or more paramters to arg + PARAM_NONE, // no parameters to arg + PARAM_ONE, // one parameter to arg + PARAM_MANY, // zero or more paramters to arg - PARAM_INVALID // top of enum + PARAM_INVALID // top of enum }; - void AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed = false); - // this method should be called for each argument that can appear on the - // command line. - // argId -- a number that uniquely identifies the argument; no two arguments - // may have the same id (ASSERT-enforced) - // arg -- string that comes after the '-'. can be _T("") if there is only - // a string representation - // alias -- string that comes after '--' which has the same meaning. Can be _T("") - // if there is no alias. If both arg and alias are empty strings, then this arg - // represents the list of arguments that comes at the end of the command line - // numParams -- number of parameters that this argument needs + void + AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed = false); + // this method should be called for each argument that can appear on the + // command line. + // argId -- a number that uniquely identifies the argument; no two arguments + // may have the same id (ASSERT-enforced) + // arg -- string that comes after the '-'. can be _T("") if there is only + // a string representation + // alias -- string that comes after '--' which has the same meaning. Can be _T("") + // if there is no alias. If both arg and alias are empty strings, then this arg + // represents the list of arguments that comes at the end of the command line + // numParams -- number of parameters that this argument needs void AddMutEx(int argId1, int argId2); - // this adds a mutual exclusion constraint. When Parse() is called, if argId1 and - // argId2 both exist on the command line, then the parse will fail and the error - // value ERR_MUTUAL_EXCLUSION will be set. - - void AddDependency(int argId1, int argId2, bool mutual = false ); - // This adds a dependency constraint. When Parse() is called, if argId1 - // exists on the command line independent from argId2, then the parse will fail. - // If the default param mutual is true, then the command parser will check for - // argId1 if argId2 is passed. We do this, since it is possible for one arg to - // depend on another, but have the other arg alone on the command line, legally. - - void Parse(int argc, const TCHAR *const * argv); // throw eCmdLine + // this adds a mutual exclusion constraint. When Parse() is called, if argId1 and + // argId2 both exist on the command line, then the parse will fail and the error + // value ERR_MUTUAL_EXCLUSION will be set. + + void AddDependency(int argId1, int argId2, bool mutual = false); + // This adds a dependency constraint. When Parse() is called, if argId1 + // exists on the command line independent from argId2, then the parse will fail. + // If the default param mutual is true, then the command parser will check for + // argId1 if argId2 is passed. We do this, since it is possible for one arg to + // depend on another, but have the other arg alone on the command line, legally. + + void Parse(int argc, const TCHAR* const* argv); // throw eCmdLine // after AddArg() has been called for every argument that could be processed by the - // command line, call this to tokenize argv. If the return value is false, then + // command line, call this to tokenize argv. If the return value is false, then // the input was invalid in some way; the actual error can be determined by calling // GetErrorInfo() below. - void Clear(); - // clear out all information that this class contains + // void Clear(); + // clear out all information that this class contains bool LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const; - // given an argId, fill out the strings with the argument and alias strings. Returns false - // if the argId cannot be found. This method is not very fast, so don't use it often. + // given an argId, fill out the strings with the argument and alias strings. Returns false + // if the argId cannot be found. This method is not very fast, so don't use it often. - #ifdef _DEBUG - void TraceContents(int dl = -1) ; - #endif +#ifdef DEBUG + void TraceContents(int dl = -1); +#endif private: void TestMutEx(); - // tests for mutual exclusion violations; if it fails, the current error is set and false - // is returned. + // tests for mutual exclusion violations; if it fails, the current error is set and false + // is returned. void TestDependency(); - // tests for all dependency violations. + // tests for all dependency violations. bool ArgInList(int argId); - // returns true if an argument with the specified id already exists in the list; this is used - // to make sure the same arg doesn't appear >1 time on the command line + // returns true if an argument with the specified id already exists in the list; this is used + // to make sure the same arg doesn't appear >1 time on the command line // for storing information on paramers struct cArgInfo { - int mId; - ParamCount mNumParams; + int mId; + ParamCount mNumParams; - cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p) {} + cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p) + { + } }; // for storing parsed argv information struct cArgData { - int mId; - std::vector mParams; - TSTRING mActualParam; // a string representation of what was actually on the command line + int mId; + std::vector mParams; + TSTRING mActualParam; // a string representation of what was actually on the command line - cArgData(int id = -1, const TSTRING& actualParam = TSTRING(_T(""))) : mId(id), mActualParam(actualParam) {} + cArgData(int id = -1, const TSTRING& actualParam = TSTRING(_T(""))) : mId(id), mActualParam(actualParam) + { + } }; - cHashTable mArgTable; - cArgInfo mLastArgInfo; // info on the argument that comes at the end of the command line (with no associated '-x' or '--x') - std::list mArgData; - std::list > mMutExList; // all of the mutual exclusions - std::list< std::pair < std::pair, bool > > mDependencyList; // all of the dependencies - std::set< int > mMultipleAllowed; + cHashTable mArgTable; + cArgInfo + mLastArgInfo; // info on the argument that comes at the end of the command line (with no associated '-x' or '--x') + std::list mArgData; + std::list > mMutExList; // all of the mutual exclusions + std::list, bool> > mDependencyList; // all of the dependencies + std::set mMultipleAllowed; friend class cCmdLineIter; }; /////////////////////////////////////////////////////////////////////////////// -// cCmdLineIter -- used to iterate over the tokenized command line parameters; +// cCmdLineIter -- used to iterate over the tokenized command line parameters; // is only useful after cCmdLineParser::Parse() has been called. /////////////////////////////////////////////////////////////////////////////// class cCmdLineIter @@ -190,36 +197,35 @@ class cCmdLineIter cCmdLineIter(const cCmdLineParser& parser); // iteration - void SeekBegin() const; - bool Done() const; - bool IsEmpty() const; - void Next() const; + void SeekBegin() const; + bool Done() const; + bool IsEmpty() const; + void Next() const; - bool SeekToArg(int argId) const; - // seeks to the argument with the given argId. returns - // false and Done() == true if it couldn't find it. + bool SeekToArg(int argId) const; + // seeks to the argument with the given argId. returns + // false and Done() == true if it couldn't find it. // access to the argument data - int ArgId() const; - // returns the id of this arg; ASSERTs if Done() == true - int NumParams() const; - // returns the number of parameters this argument has - const TSTRING& ActualParam() const; - // returns exactly what was passed on the command line (ie -- what the user typed) - const TSTRING& ParamAt(int index) const; - // returns the parameter at the specified index. ASSERTs if - // the index is out of range. + int ArgId() const; + // returns the id of this arg; ASSERTs if Done() == true + int NumParams() const; + // returns the number of parameters this argument has + const TSTRING& ActualParam() const; + // returns exactly what was passed on the command line (ie -- what the user typed) + const TSTRING& ParamAt(int index) const; + // returns the parameter at the specified index. ASSERTs if + // the index is out of range. private: - const std::list& mList; + const std::list& mList; mutable std::list::const_iterator mIter; }; //############################################################################# // inline implementation //############################################################################# -inline cCmdLineIter::cCmdLineIter(const cCmdLineParser& parser) : - mList(parser.mArgData) +inline cCmdLineIter::cCmdLineIter(const cCmdLineParser& parser) : mList(parser.mArgData) { SeekBegin(); } @@ -241,22 +247,22 @@ inline void cCmdLineIter::Next() const } inline int cCmdLineIter::ArgId() const { - ASSERT(! Done()); + ASSERT(!Done()); return mIter->mId; } inline int cCmdLineIter::NumParams() const { - ASSERT(! Done()); + ASSERT(!Done()); return mIter->mParams.size(); } -inline const TSTRING& cCmdLineIter::ActualParam() const +inline const TSTRING& cCmdLineIter::ActualParam() const { - ASSERT(! Done()); + ASSERT(!Done()); return mIter->mActualParam; } -inline const TSTRING& cCmdLineIter::ParamAt(int index) const +inline const TSTRING& cCmdLineIter::ParamAt(int index) const { ASSERT((index >= 0) && (index < NumParams())); return mIter->mParams[index]; @@ -264,4 +270,3 @@ inline const TSTRING& cCmdLineIter::ParamAt(int index) const #endif - diff --git a/src/core/codeconvert.cpp b/src/core/codeconvert.cpp index 727c2c7..fef271e 100644 --- a/src/core/codeconvert.cpp +++ b/src/core/codeconvert.cpp @@ -1,31 +1,31 @@ -// + // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,16 +40,16 @@ /// Requirements -#include "stdcore.h" // for: pch -#include "core/codeconvert.h" // for: These classes -#include "corestrings.h" // for: Error Strings -#include "fsservices.h" // for: strerror +#include "stdcore.h" // for: pch +#include "core/codeconvert.h" // for: These classes +#include "corestrings.h" // for: Error Strings +#include "fsservices.h" // for: strerror #include "ntmbs.h" #include "errno.h" #ifdef DEBUG -#define TSS_CCONV_VERBOSE // Uncomment for verbose tracing! +# define TSS_CCONV_VERBOSE // Uncomment for verbose tracing! #endif @@ -57,21 +57,16 @@ // DEFINES //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* - * ICONV conversion seems to be broken under Linux, so until - * this is fixed, we'll wing it ourselves - 20010310 PH - */ -#if 0 -#define TSS_USE_ICONV_CCONV16 HAVE_ICONV_H -#define TSS_USE_UCS2_CCONV16 (!(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 && WCHAR_IS_16_BITS) -#define TSS_USE_UCS2_CCONV32 (!(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 && WCHAR_IS_32_BITS) +#define TSS_USE_ICONV_CCONV16 HAVE_ICONV_H +#define TSS_USE_UCS2_CCONV16 (!(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 && WCHAR_IS_16_BITS) +#define TSS_USE_UCS2_CCONV32 (!(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 && WCHAR_IS_32_BITS) + +#if ICONV_CONST_SOURCE +# define ICONV_SOURCE_TYPE const char #else -#define TSS_USE_UCS2_CCONV16 (WCHAR_REP_IS_UCS2 && WCHAR_IS_16_BITS) -#define TSS_USE_UCS2_CCONV32 (WCHAR_REP_IS_UCS2 && WCHAR_IS_32_BITS) +# define ICONV_SOURCE_TYPE char #endif - #define ICONV_SOURCE_TYPE const char - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Static Data //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -83,23 +78,23 @@ iCodeConverter* iCodeConverter::m_pInst = NULL; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // has a maximum of 512 chars of output -std::string util_output_bytes( void* p, size_t n ) +std::string util_output_bytes(void* p, size_t n) { std::ostringstream ss; - ss.imbue( std::locale::classic() ); - ss.setf( std::ios_base::hex, std::ios_base::basefield ); + ss.imbue(std::locale::classic()); + ss.setf(std::ios_base::hex, std::ios_base::basefield); - for( size_t i = 0; i < n; i++ ) + for (size_t i = 0; i < n; i++) { - ss.width( 2 ); - ss << toupper( tss::util::char_to_size( ((char*)p)[i] ) ) << " "; + ss.width(2); + ss << toupper(tss::util::char_to_size(((char*)p)[i])) << " "; } std::string s = ss.str(); - if( s.length() > 512 ) + if (s.length() > 512) { s = "truncated output: " + s; - s.resize( 512 ); + s.resize(512); } return s; @@ -107,27 +102,33 @@ std::string util_output_bytes( void* p, size_t n ) iCodeConverter* iCodeConverter::GetInstance() { - if( ! m_pInst ) + if (!m_pInst) { m_pInst = CreateConverter(); } - ASSERT( m_pInst ); + ASSERT(m_pInst); return m_pInst; } +void iCodeConverter::Finit() +{ + delete m_pInst; + m_pInst = 0; +} + iCodeConverter* iCodeConverter::CreateConverter() { cDebug d("iCodeConverter::CreateConverter()"); #if TSS_USE_ICONV_CCONV16 - if( cIconvConverter::Test() ) + if (cIconvConverter::Test()) { d.TraceDebug("using cIconvConverter\n"); return new cIconvConverter; } - else if( cDoubleIconvConverter::Test() ) + else if (cDoubleIconvConverter::Test()) { d.TraceDebug("using cDoubleIconvConverter\n"); return new cDoubleIconvConverter; @@ -155,7 +156,7 @@ iCodeConverter* iCodeConverter::CreateConverter() #endif - ASSERT( ! "reachable" ); + ASSERT(!"reachable"); } @@ -164,8 +165,8 @@ iCodeConverter* iCodeConverter::CreateGoodEnoughConverter() // // let someone know that we don't work on non-english OSs... // - cDebug d( "iCodeConverter::CreateGoodEnoughConverter()" ); - d.TraceAlways( "database WILL NOT be portable to other platforms.\n" ); + cDebug d("iCodeConverter::CreateGoodEnoughConverter()"); + d.TraceAlways("database WILL NOT be portable to other platforms.\n"); return new cGoodEnoughConverterer; } @@ -188,219 +189,197 @@ iCodeConverter* iCodeConverter::CreateGoodEnoughConverter() namespace /*Unique*/ { - void tss_dispatch_iconvopen_error() - { - cDebug d("tss_dispatch_iconvopen_error"); +void tss_dispatch_iconvopen_error() +{ + cDebug d("tss_dispatch_iconvopen_error"); - switch( errno ) - { - case EMFILE: - d.TraceDebug( "EMFILE: {OPEN_MAX} files descriptors are currently open in the calling process..\n" ); - break; - case ENFILE: - d.TraceDebug( "ENFILE: Too many files are currently open in the system.\n" ); - break; - case ENOMEM: - d.TraceDebug( "ENOMEM: Insufficient storage space is available.\n" ); - break; - case EINVAL: - d.TraceDebug( "EINVAL: The conversion specified by fromcode and tocode is not supported by the implementation.\n" ); - break; - default: - d.TraceDebug( "UNKNOWN: Unknown error.\n" ); - break; - } + switch (errno) + { + case EMFILE: + d.TraceDebug("EMFILE: {OPEN_MAX} files descriptors are currently open in the calling process..\n"); + break; + case ENFILE: + d.TraceDebug("ENFILE: Too many files are currently open in the system.\n"); + break; + case ENOMEM: + d.TraceDebug("ENOMEM: Insufficient storage space is available.\n"); + break; + case EINVAL: + d.TraceDebug("EINVAL: The conversion specified by fromcode and tocode is not supported by the " + "implementation.\n"); + break; + default: + d.TraceDebug("UNKNOWN: Unknown error.\n"); + break; } +} - int tss_dispatch_errno( cDebug& d ) +int tss_dispatch_errno(cDebug& d) +{ + // Reasons for failure: + // [EILSEQ] Input conv stopped due to an unknown input byte + // [E2BIG] Input conversion stopped due to lack of space in the output + // [EINVAL] Input conversion stopped due to an incomplete character + // [EBADF] The cd argument is not a valid open conversion descriptor. + // errno + d.TraceDebug(_T( "iconv failed with: %s\n" ), iFSServices::GetInstance()->GetErrString().c_str()); + + /// RAD: Always throw on error (Let user Catch if they want to go on) + switch (errno) { - // Reasons for failure: - // [EILSEQ] Input conv stopped due to an unknown input byte - // [E2BIG] Input conversion stopped due to lack of space in the output - // [EINVAL] Input conversion stopped due to an incomplete character - // [EBADF] The cd argument is not a valid open conversion descriptor. - // errno - d.TraceDebug( - _T( "iconv failed with: %s\n" ), - iFSServices::GetInstance()->GetErrString().c_str() ); - - /// RAD: Always throw on error (Let user Catch if they want to go on) - switch ( errno ) - { - case EILSEQ: - case EINVAL: - throw - eConverterFatal ( - TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - break; - - case E2BIG: - throw - eConverterFatal( - TSS_GetString(cCore, core::STR_ERR_OVERFLOW ) ); - break; - - case EBADF: - throw - eConverterUnknownCodepage( - TSS_GetString( cCore, core::STR_UNKNOWN ) ); - break; - - default: - throw - eConverterFatal( - TSS_GetString( cCore, core::STR_UNKNOWN ) ); - } - - return -1; + case EILSEQ: + case EINVAL: + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); + break; + + case E2BIG: + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_OVERFLOW)); + break; + + case EBADF: + throw eConverterUnknownCodepage(TSS_GetString(cCore, core::STR_UNKNOWN)); + break; + default: + throw eConverterFatal(TSS_GetString(cCore, core::STR_UNKNOWN)); } - template< class BufferT, class SourceT > - class ByteConvert + return -1; +} + +template class ByteConvert +{ +public: + bool Convert(BufferT** ppBuf, size_t* pnBufferLeft, const SourceT** ppSrc, size_t* pnSourceLeft) { - public: + cDebug d("ByteConvert::Convert< BufferT, SourceT >()"); - bool - Convert( BufferT** ppBuf, size_t* pnBufferLeft, - const SourceT** ppSrc, size_t* pnSourceLeft ) - { - cDebug d( "ByteConvert::Convert< BufferT, SourceT >()" ); - - //-- Copy manually into Buffer - **ppBuf = cConvertUtil::ConvertNonChar( **ppSrc ); - - //-- Decrement counters - *pnSourceLeft -= sizeof(SourceT); // Decrement Source Left - *pnBufferLeft -= sizeof(BufferT); // Decrement Buffer Left + //-- Copy manually into Buffer + **ppBuf = cConvertUtil::ConvertNonChar(**ppSrc); - //-- Reposition pointers - (*ppSrc)++; // Skip one SourceT fwd - (*ppBuf)++; // Skip one BufferT fwd + //-- Decrement counters + *pnSourceLeft -= sizeof(SourceT); // Decrement Source Left + *pnBufferLeft -= sizeof(BufferT); // Decrement Buffer Left - return true; - } - }; + //-- Reposition pointers + (*ppSrc)++; // Skip one SourceT fwd + (*ppBuf)++; // Skip one BufferT fwd + + return true; + } +}; - class UTF8_Util - { - public: - enum { INVALID_VALUE = 0xFF }; +class UTF8_Util +{ +public: + enum + { + INVALID_VALUE = 0xFF }; +}; - // convert to INVALID_VALUE and remember the byte value - template< class BufferT, class SourceT > - class ToUTF8Convert +// convert to INVALID_VALUE and remember the byte value +template class ToUTF8Convert +{ +public: + ToUTF8Convert(std::list& lb) : m_lb(lb) { - public: + } - ToUTF8Convert( std::list& lb ) - : m_lb( lb ) {} + bool Convert(mbchar_t** ppBuf, size_t* pnBufferLeft, const dbchar_t** ppSrc, size_t* pnSourceLeft) + { + cDebug d("ToUTF8Convert::Convert< mbchar_t, dbchar_t >()"); - bool - Convert( mbchar_t** ppBuf, size_t* pnBufferLeft, - const dbchar_t** ppSrc, size_t* pnSourceLeft ) - { - cDebug d( "ToUTF8Convert::Convert< mbchar_t, dbchar_t >()" ); - - // store the non char value - m_lb.push_back( cConvertUtil::ConvertNonChar( **ppSrc ) ); + // store the non char value + m_lb.push_back(cConvertUtil::ConvertNonChar(**ppSrc)); - // flag 'invalid char' - **ppBuf = (mbchar_t)UTF8_Util::INVALID_VALUE; - - //-- Decrement counters - *pnSourceLeft -= sizeof(dbchar_t); // Decrement Source Left - *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left + // flag 'invalid char' + **ppBuf = (mbchar_t)UTF8_Util::INVALID_VALUE; - //-- Reposition pointers - (*ppSrc)++; // Skip one SourceT fwd - (*ppBuf)++; // Skip one BufferT fwd + //-- Decrement counters + *pnSourceLeft -= sizeof(dbchar_t); // Decrement Source Left + *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left - return true; - } + //-- Reposition pointers + (*ppSrc)++; // Skip one SourceT fwd + (*ppBuf)++; // Skip one BufferT fwd - bool - Convert( mbchar_t** ppBuf, size_t* pnBufferLeft, - const mbchar_t** ppSrc, size_t* pnSourceLeft ) - { - cDebug d( "ToUTF8Convert::Convert< char, char >()" ); + return true; + } - // store non-char value - m_lb.push_back( **ppSrc ); + bool Convert(mbchar_t** ppBuf, size_t* pnBufferLeft, const mbchar_t** ppSrc, size_t* pnSourceLeft) + { + cDebug d("ToUTF8Convert::Convert< char, char >()"); - // flag 'invalid char' - **ppBuf = (char)UTF8_Util::INVALID_VALUE; - - //-- Decrement counters - *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left - *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left + // store non-char value + m_lb.push_back(**ppSrc); - //-- Reposition pointers - (*ppSrc)++; // Skip one SourceT fwd - (*ppBuf)++; // Skip one BufferT fwd + // flag 'invalid char' + **ppBuf = (char)UTF8_Util::INVALID_VALUE; - return true; - } + //-- Decrement counters + *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left + *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left - private: + //-- Reposition pointers + (*ppSrc)++; // Skip one SourceT fwd + (*ppBuf)++; // Skip one BufferT fwd - // TODO:Get rid of this guy and just use a vector and - // insert them when finished with second step - std::list& m_lb; - }; + return true; + } + +private: + // TODO:Get rid of this guy and just use a vector and + // insert them when finished with second step + std::list& m_lb; +}; - template< class BufferT, class SourceT > - class FromUTF8Convert +template class FromUTF8Convert +{ +public: + FromUTF8Convert(std::list& lb) : m_lb(lb) { - public: + } - FromUTF8Convert( std::list& lb ) - : m_lb( lb ) {} + bool Convert(dbchar_t** ppBuf, size_t* pnBufferLeft, const mbchar_t** ppSrc, size_t* pnSourceLeft) + { + cDebug d("FromUTF8Convert::Convert< dbchar_t, mbchar_t >()"); - bool - Convert( dbchar_t** ppBuf, size_t* pnBufferLeft, - const mbchar_t** ppSrc, size_t* pnSourceLeft ) - { - cDebug d( "FromUTF8Convert::Convert< dbchar_t, mbchar_t >()" ); + //-- Must be our flag char + size_t value = tss::util::char_to_size(**ppSrc); + if (value != (size_t)UTF8_Util::INVALID_VALUE) + { + d.TraceDebug("value was not flag char: %X...\n", value); + return false; + } - //-- Must be our flag char - size_t value = tss::util::char_to_size( **ppSrc ); - if ( value != (size_t)UTF8_Util::INVALID_VALUE ) - { - d.TraceDebug( "value was not flag char: %X...\n", value ); - return false; - } - - //-- Get correct character from our byte array - ASSERT( ! m_lb.empty() ); - mbchar_t newVal = (mbchar_t)tss::util::char_to_size( m_lb.front() ); - m_lb.pop_front(); + //-- Get correct character from our byte array + ASSERT(!m_lb.empty()); + mbchar_t newVal = (mbchar_t)tss::util::char_to_size(m_lb.front()); + m_lb.pop_front(); - //-- Copy character - d.TraceDebug( "converted to: %X\n", tss::util::char_to_size( newVal ) ); - **ppBuf = cConvertUtil::ConvertNonChar( newVal ); - - //-- Decrement counters - *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left - *pnBufferLeft -= sizeof(dbchar_t); // Decrement Buffer Left + //-- Copy character + d.TraceDebug("converted to: %X\n", tss::util::char_to_size(newVal)); + **ppBuf = cConvertUtil::ConvertNonChar(newVal); - //-- Reposition pointers - (*ppSrc)++; // Skip one mbchar_t fwd - (*ppBuf)++; // Skip one dbchar_t fwd + //-- Decrement counters + *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left + *pnBufferLeft -= sizeof(dbchar_t); // Decrement Buffer Left - return true; - } + //-- Reposition pointers + (*ppSrc)++; // Skip one mbchar_t fwd + (*ppBuf)++; // Skip one dbchar_t fwd - // Converts a UTF-8 value to corresponding UCS2 char (in the private - // use range) whose value is 0xE000 < x < 0xE0FF in UCS2. - // Must be of the form 11101110 100000xx 10xxxxxx - bool - Convert( mbchar_t** ppBuf, size_t* pnBufferLeft, - const mbchar_t** ppSrc, size_t* pnSourceLeft ) - { - cDebug d( "FromUTF8Convert::Convert< mbchar_t, mbchar_t >()" ); - /* + return true; + } + + // Converts a UTF-8 value to corresponding UCS2 char (in the private + // use range) whose value is 0xE000 < x < 0xE0FF in UCS2. + // Must be of the form 11101110 100000xx 10xxxxxx + bool Convert(mbchar_t** ppBuf, size_t* pnBufferLeft, const mbchar_t** ppSrc, size_t* pnSourceLeft) + { + cDebug d("FromUTF8Convert::Convert< mbchar_t, mbchar_t >()"); + /* const size_t NUM_CHARS = 3; //-- Must be our cast byte value @@ -457,279 +436,287 @@ namespace /*Unique*/ return true; */ - //-- Must be our flag char - size_t value = tss::util::char_to_size( **ppSrc ); - if ( value != (size_t)UTF8_Util::INVALID_VALUE ) - { - d.TraceDebug( "value was not flag char: %X...\n", value ); - return false; - } - - //-- Get correct character from our byte array - ASSERT( ! m_lb.empty() ); - mbchar_t newVal = (mbchar_t)tss::util::char_to_size( m_lb.front() ); - m_lb.pop_front(); - - //-- Copy character - d.TraceDebug( "converted to: %X\n", tss::util::char_to_size( newVal ) ); - **ppBuf = newVal; - - //-- Decrement counters - *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left - *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left - - //-- Reposition pointers - (*ppSrc)++; // Skip one mbchar_t fwd - (*ppBuf)++; // Skip one dbchar_t fwd - - return true; - } - - private: - - // TODO:Get rid of this guy and just use a vector and - // insert them when finished with second step - std::list& m_lb; - }; - - bool - tss_ReverseConvert( iconv_t revConv, - const char* pConvertedFrom, size_t nFrom, - char* pConvertedTo, size_t nTo ) - { - cDebug d("tss_ReverseConvert< B, S, C >()"); - d.TraceDebug( "Converted from: %s\n", util_output_bytes( (void*)pConvertedFrom, nFrom ).c_str() ); - d.TraceDebug( "Converted to: %s\n", util_output_bytes( (void*)pConvertedTo, nTo ).c_str() ); - - char aBuffer[ MB_LEN_MAX ]; -#ifdef _DEBUG - for( size_t foo = 0; foo < sizeof( aBuffer ); foo++ ) - aBuffer[ foo ] = 0xCD; -#endif - char* pBuf = &aBuffer[0]; - size_t nBuf = sizeof( aBuffer ); - - const char* pSrc = pConvertedTo; - size_t nSrc = nTo; - - size_t nConv = // NOTE: - iconv( revConv, // On return, these addresses - (ICONV_SOURCE_TYPE**)&pSrc, // are set for one past the last - &nSrc, // "item" converted successfully - &pBuf, - &nBuf ); - - if( nConv == (size_t)-1 ) + //-- Must be our flag char + size_t value = tss::util::char_to_size(**ppSrc); + if (value != (size_t)UTF8_Util::INVALID_VALUE) { - d.TraceDebug( "reverse conversion failed: iconv error\n" ); + d.TraceDebug("value was not flag char: %X...\n", value); return false; } - - d.TraceDebug( "sizeof( aBuffer ): %u, nBuf: %u, nFrom: %u\n", sizeof( aBuffer ), nBuf, nFrom ); - d.TraceDebug( "reverse conversion got: %s\n", util_output_bytes( (void*)&aBuffer[0], sizeof( aBuffer ) - nBuf ).c_str() ); - if( ( ( sizeof( aBuffer ) - nBuf ) != nFrom ) || // convertedFrom and check must be same size - ( 0 != memcmp( pConvertedFrom, &aBuffer[0], nFrom ) ) ) // must be same value, too - { - d.TraceDebug( "reverse conversion failed: converted to a different value\n" ); - return false; - } + //-- Get correct character from our byte array + ASSERT(!m_lb.empty()); + mbchar_t newVal = (mbchar_t)tss::util::char_to_size(m_lb.front()); + m_lb.pop_front(); + + //-- Copy character + d.TraceDebug("converted to: %X\n", tss::util::char_to_size(newVal)); + **ppBuf = newVal; + + //-- Decrement counters + *pnSourceLeft -= sizeof(mbchar_t); // Decrement Source Left + *pnBufferLeft -= sizeof(mbchar_t); // Decrement Buffer Left + + //-- Reposition pointers + (*ppSrc)++; // Skip one mbchar_t fwd + (*ppBuf)++; // Skip one dbchar_t fwd return true; } - template< class CharT > - bool tss_IsFlaggedCharacter( CharT ch ) +private: + // TODO:Get rid of this guy and just use a vector and + // insert them when finished with second step + std::list& m_lb; +}; + +bool tss_ReverseConvert(iconv_t revConv, const char* pConvertedFrom, size_t nFrom, char* pConvertedTo, size_t nTo) +{ + cDebug d("tss_ReverseConvert< B, S, C >()"); + d.TraceDebug("Converted from: %s\n", util_output_bytes((void*)pConvertedFrom, nFrom).c_str()); + d.TraceDebug("Converted to: %s\n", util_output_bytes((void*)pConvertedTo, nTo).c_str()); + + char aBuffer[MB_LEN_MAX]; +# ifdef DEBUG + for (size_t foo = 0; foo < sizeof(aBuffer); foo++) + aBuffer[foo] = 0xCD; +# endif + char* pBuf = &aBuffer[0]; + size_t nBuf = sizeof(aBuffer); + + const char* pSrc = pConvertedTo; + size_t nSrc = nTo; + + size_t nConv = // NOTE: + iconv(revConv, // On return, these addresses + (ICONV_SOURCE_TYPE**)&pSrc, // are set for one past the last + &nSrc, // "item" converted successfully + &pBuf, + &nBuf); + + if (nConv == (size_t)-1) { + d.TraceDebug("reverse conversion failed: iconv error\n"); return false; } - - template<> - bool tss_IsFlaggedCharacter< dbchar_t >( dbchar_t wch ) + + d.TraceDebug("sizeof( aBuffer ): %u, nBuf: %u, nFrom: %u\n", sizeof(aBuffer), nBuf, nFrom); + d.TraceDebug("reverse conversion got: %s\n", util_output_bytes((void*)&aBuffer[0], sizeof(aBuffer) - nBuf).c_str()); + + if (((sizeof(aBuffer) - nBuf) != nFrom) || // convertedFrom and check must be same size + (0 != memcmp(pConvertedFrom, &aBuffer[0], nFrom))) // must be same value, too { - return cConvertUtil::ValueInReservedRange( wch ); + d.TraceDebug("reverse conversion failed: converted to a different value\n"); + return false; } - template< class BufferT, class SourceT > - int - tss_ConvertOneCharacter( iconv_t convForward, - iconv_t convReverse, - const char** ppSource, size_t* pnSourceLeft, - char** ppBuffer, size_t* pnBufferLeft -#if ( ! SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST ) - , BufferT /*dummy*/, SourceT /*dummy*/ -#endif - ) - { - cDebug d("tss_ConvertOneCharacter< B, S, C >()"); + return true; +} - const char* pSrc = *ppSource; - char* pBuf = *ppBuffer; +template bool tss_IsFlaggedCharacter(CharT ch) +{ + return false; +} - //-- HACK!!!! BAM -- see if it is one of our reserved UCS2 characters - // TODO:BAM -- how does this affect our converters that don't use the UTF-8 step? - if( tss_IsFlaggedCharacter( **( (SourceT**)ppSource ) ) ) - { - d.TraceDebug( "Found one of our unconvertable characters in the reserved range!\n" ); - return -1; - } +template<> bool tss_IsFlaggedCharacter(dbchar_t wch) +{ + return cConvertUtil::ValueInReservedRange(wch); +} - //-- Try to find the number of items needed to get a complete character - size_t nSrcTry; - for( nSrcTry = sizeof( SourceT ); - nSrcTry <= *pnBufferLeft && nSrcTry <= MB_LEN_MAX; - nSrcTry += sizeof( SourceT ) ) - { - size_t nSrcLeft = nSrcTry; - size_t nBufLeft = *pnBufferLeft;// Try to find a character in 'n' items +template +int tss_ConvertOneCharacter(iconv_t convForward, + iconv_t convReverse, + const char** ppSource, + size_t* pnSourceLeft, + char** ppBuffer, + size_t* pnBufferLeft +# if (!SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST) + , + BufferT /*dummy*/, + SourceT /*dummy*/ +# endif +) +{ + cDebug d("tss_ConvertOneCharacter< B, S, C >()"); - // NOTE: On solaris sparc, iconv will attempt to NULL terminate the output, - // so make sure that the buffer has space for a terminating NULL - d.TraceDebug( "attempting to convert with %u items\n", nSrcTry ); - size_t nConv = // NOTE: - iconv( convForward, // On return, these addresses - (ICONV_SOURCE_TYPE**)&pSrc, // are set for one past the last - &nSrcLeft, // "item" converted successfully - &pBuf, - &nBufLeft ); - - if( nConv == (size_t)-1 ) + const char* pSrc = *ppSource; + char* pBuf = *ppBuffer; + + //-- HACK!!!! BAM -- see if it is one of our reserved UCS2 characters + // TODO:BAM -- how does this affect our converters that don't use the UTF-8 step? + if (tss_IsFlaggedCharacter(**((SourceT**)ppSource))) + { + d.TraceDebug("Found one of our unconvertable characters in the reserved range!\n"); + return -1; + } + + //-- Try to find the number of items needed to get a complete character + size_t nSrcTry; + for (nSrcTry = sizeof(SourceT); nSrcTry <= *pnBufferLeft && nSrcTry <= MB_LEN_MAX; nSrcTry += sizeof(SourceT)) + { + size_t nSrcLeft = nSrcTry; + size_t nBufLeft = *pnBufferLeft; // Try to find a character in 'n' items + + // NOTE: On solaris sparc, iconv will attempt to NULL terminate the output, + // so make sure that the buffer has space for a terminating NULL + d.TraceDebug("attempting to convert with %u items\n", nSrcTry); + size_t nConv = // NOTE: + iconv(convForward, // On return, these addresses + (ICONV_SOURCE_TYPE**)&pSrc, // are set for one past the last + &nSrcLeft, // "item" converted successfully + &pBuf, + &nBufLeft); + + if (nConv == (size_t)-1) + { + if (errno == EINVAL) { - if( errno == EINVAL ) - { - d.TraceDebug( "more items needed\n" ); - continue; - } - else - { - d.TraceDebug( "iconv failed with %d (not EINVAL)\n", errno ); - return -1; - } + d.TraceDebug("more items needed\n"); + continue; } else { - if( tss_ReverseConvert( - convReverse, - *ppSource, - pSrc - *ppSource, - *ppBuffer, - pBuf - *ppBuffer ) ) - { - // Modify source items to return + d.TraceDebug("iconv failed with %d (not EINVAL)\n", errno); + return -1; + } + } + else + { + if (tss_ReverseConvert(convReverse, *ppSource, pSrc - *ppSource, *ppBuffer, pBuf - *ppBuffer)) + { + // Modify source items to return - ASSERT( nSrcLeft == 0 ); + ASSERT(nSrcLeft == 0); - *ppSource = pSrc; - *ppBuffer = pBuf; - *pnSourceLeft -= nSrcTry; - *pnBufferLeft = nBufLeft; + *ppSource = pSrc; + *ppBuffer = pBuf; + *pnSourceLeft -= nSrcTry; + *pnBufferLeft = nBufLeft; - return nConv; - } - else - { - d.TraceDebug( "reverse conversion failed\n" ); - return -1; - } + return nConv; + } + else + { + d.TraceDebug("reverse conversion failed\n"); + return -1; } } - - //-- No valid character found in nBufferLeft or MB_LEN_MAX items - d.TraceDebug( "no valid character found after %u items.\n", nSrcTry - 1 ); - return -1; } + //-- No valid character found in nBufferLeft or MB_LEN_MAX items + d.TraceDebug("no valid character found after %u items.\n", nSrcTry - 1); + return -1; +} - // NOTE: is number of T's (as opposed to the number of Characters - // or Bytes) So for a NTWCS sequence, Item is the number of Characters - // while for a NTMBS sequence, Item is the number of char's (Bytes). - // The low-down is that n????Items represents the "Count of T's" - - // NOTE: pBuffer should really have (nBufferItems+1) buffer items, because some - // platforms use the last character to NULL terminate. - template< class BufferT, class SourceT, class ConvT > - int - tss_Converter( iconv_t convForward, - iconv_t convReverse, - BufferT* pBuffer, size_t nBufferItems, - const SourceT* pSource, size_t nSourceItems, - ConvT& ConvertByte ) - { - cDebug d( "tss_Converter< BufferT, SourceT >()" ); - -#ifdef _DEBUG - for( size_t s = nBufferItems; s; s-- ) - pBuffer[s] = 0xCD; - d.TraceDebug( "sizeof buffer: %d, sizeof source: %d\n", sizeof( BufferT ), sizeof( SourceT ) ); - d.TraceDebug( "buffer size: %d, source size: %d\n", nBufferItems, nSourceItems ); - d.TraceDebug( "source: %s\n", util_output_bytes( (void*)pSource, nSourceItems*sizeof( SourceT ) ).c_str() ); -#endif - -#ifndef HACK_FOR_SOLARIS // See NOTE above - nBufferItems++; -#endif - //--Get BYTES to process for in and out sequences - size_t nBufferLeft = nBufferItems * sizeof(BufferT); - size_t nSourceLeft = nSourceItems * sizeof(SourceT); - //--Setup BYTE iterators to in and out sequences +// NOTE: is number of T's (as opposed to the number of Characters +// or Bytes) So for a NTWCS sequence, Item is the number of Characters +// while for a NTMBS sequence, Item is the number of char's (Bytes). +// The low-down is that n????Items represents the "Count of T's" + +// NOTE: pBuffer should really have (nBufferItems+1) buffer items, because some +// platforms use the last character to NULL terminate. +template +int tss_Converter(iconv_t convForward, + iconv_t convReverse, + BufferT* pBuffer, + size_t nBufferItems, + const SourceT* pSource, + size_t nSourceItems, + ConvT& ConvertByte) +{ + cDebug d("tss_Converter< BufferT, SourceT >()"); - BufferT* pBuf = pBuffer; - const SourceT* pSrc = pSource; +# ifdef DEBUG + for (size_t s = nBufferItems; s; s--) + pBuffer[s] = 0xCD; + d.TraceDebug("sizeof buffer: %d, sizeof source: %d\n", sizeof(BufferT), sizeof(SourceT)); + d.TraceDebug("buffer size: %d, source size: %d\n", nBufferItems, nSourceItems); + d.TraceDebug("source: %s\n", util_output_bytes((void*)pSource, nSourceItems * sizeof(SourceT)).c_str()); +# endif +# ifndef HACK_FOR_SOLARIS // See NOTE above + nBufferItems++; +# endif + //--Get BYTES to process for in and out sequences + size_t nBufferLeft = nBufferItems * sizeof(BufferT); + size_t nSourceLeft = nSourceItems * sizeof(SourceT); - //--Start Iterative Conversion + //--Setup BYTE iterators to in and out sequences - while ( nSourceLeft > 0 ) - { - // Convert as much of the sequence as we can. + BufferT* pBuf = pBuffer; + const SourceT* pSrc = pSource; + while (nSourceLeft > 0) + { + // Convert as much of the sequence as we can. + SourceT* pIconvSrc = (SourceT*)pSrc; + BufferT* pIconvDest = (BufferT*)pBuf; + size_t nbIconvSrc = (size_t)nSourceLeft; + size_t nbIconvDest = (size_t)nBufferLeft; + + size_t nConv = + iconv(convForward, (ICONV_SOURCE_TYPE**)&pIconvSrc, &nbIconvSrc, (char**)&pIconvDest, &nbIconvDest); + + if (nConv == -1) + { // NOTE: On solaris sparc, iconv will attempt to NULL terminate the output, // so make sure that the buffer has space for a terminating NULL - size_t nConv = // NOTE: -#if SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST - tss_ConvertOneCharacter( -#else - tss_ConvertOneCharacter( -#endif + size_t nConv = // NOTE: +# if SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST + tss_ConvertOneCharacter( +# else + tss_ConvertOneCharacter( +# endif convForward, - convReverse, // On return, these addresses - (const char**)&pSrc, // are set for one past the last - &nSourceLeft, // "item" converted successfully - (char**)&pBuf, + convReverse, // On return, these addresses + (const char**)&pSrc, // are set for one past the last + &nSourceLeft, // "item" converted successfully + (char**)&pBuf, &nBufferLeft -#if ( ! SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST ) - , BufferT(), SourceT() -#endif - ); +# if (!SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST) + , + BufferT(), + SourceT() +# endif + ); + } + else + { + pSrc = pIconvSrc; + pBuf = pIconvDest; + nSourceLeft = nbIconvSrc; + nBufferLeft = nbIconvDest; + } - if ( nConv == (size_t)-1 ) // Indidates Conversion Error! + if (nConv == (size_t)-1) // Indidates Conversion Error! + { + if (nBufferLeft <= 0) { - if ( nBufferLeft <= 0 ) - { - d.TraceDebug( "No buffer space left\n" ); - return 0; - } - // TODO:BAM -- handle other iconv errors! + d.TraceDebug("No buffer space left\n"); + return 0; + } + // TODO:BAM -- handle other iconv errors! - //--Must attempt Manual Conversion. - ASSERT( (size_t)pSrc % sizeof( SourceT ) == 0 ); - ASSERT( (size_t)pBuf % sizeof( BufferT ) == 0 ); - - d.TraceDebug( "conversion failed: %s\n", strerror( errno ) ); - d.TraceDebug( "manually converting %X...\n", tss::util::char_to_size( *pSrc ) ); + //--Must attempt Manual Conversion. + ASSERT((size_t)pSrc % sizeof(SourceT) == 0); + ASSERT((size_t)pBuf % sizeof(BufferT) == 0); - //-- Convert characters and reposition counters and pointers - if( ! ConvertByte.Convert( &pBuf, &nBufferLeft, &pSrc, &nSourceLeft ) ) - return 0; - } - } + d.TraceDebug("conversion failed: %s\n", strerror(errno)); + d.TraceDebug("manually converting %X...\n", tss::util::char_to_size(*pSrc)); - d.TraceDebug( "buffer out: %s\n", util_output_bytes( (void*)pBuffer, nBufferItems * sizeof(BufferT) - nBufferLeft ).c_str() ); - return nBufferItems - (nBufferLeft / sizeof(BufferT)); + //-- Convert characters and reposition counters and pointers + if (!ConvertByte.Convert(&pBuf, &nBufferLeft, &pSrc, &nSourceLeft)) + return 0; + } } -}//Unique + d.TraceDebug("buffer out: %s\n", + util_output_bytes((void*)pBuffer, nBufferItems * sizeof(BufferT) - nBufferLeft).c_str()); + return nBufferItems - (nBufferLeft / sizeof(BufferT)); +} + +} // namespace //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // cIconvConverter @@ -743,33 +730,33 @@ cIconvConverter::cIconvConverter() cIconvConverter::~cIconvConverter() { // close conversion handles - cIconvUtil::CloseHandle( icFromDb ); - cIconvUtil::CloseHandle( icToDb ); + cIconvUtil::CloseHandle(icFromDb); + cIconvUtil::CloseHandle(icToDb); } /* static */ bool cIconvConverter::Test() { - bool testResult = true; - cDebug d( "cCodeConverter::Test()" ); + bool testResult = true; + cDebug d("cCodeConverter::Test()"); // // try to get the current code page id // const char* pCP = NULL; - if( ! cIconvUtil::GetCodePageID( &pCP ) ) + if (!cIconvUtil::GetCodePageID(&pCP)) { - d.TraceDebug( "No code page.\n" ); + d.TraceDebug("No code page.\n"); return false; } - d.TraceDebug( "Got code page %s.\n", pCP ); + d.TraceDebug("Got code page %s.\n", pCP); + - // // find if converters are available // - testResult &= cIconvUtil::TestConverter( pCP, cIconvUtil::GetIconvDbIdentifier() ); - testResult &= cIconvUtil::TestConverter( cIconvUtil::GetIconvDbIdentifier(), pCP ); + testResult &= cIconvUtil::TestConverter(pCP, cIconvUtil::GetIconvDbIdentifier()); + testResult &= cIconvUtil::TestConverter(cIconvUtil::GetIconvDbIdentifier(), pCP); return testResult; } @@ -778,73 +765,60 @@ void cIconvConverter::Init() { // NOTE:BAM -- if the platform doesn't have a XXX to UCS2 conversion, // you can make one with the genxlt command.... - icToDb = cIconvUtil::OpenHandle( cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetCodePageID() ); - icFromDb = cIconvUtil::OpenHandle( cIconvUtil::GetCodePageID(), cIconvUtil::GetIconvDbIdentifier() ); + icToDb = cIconvUtil::OpenHandle(cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetCodePageID()); + icFromDb = cIconvUtil::OpenHandle(cIconvUtil::GetCodePageID(), cIconvUtil::GetIconvDbIdentifier()); } -int -cIconvConverter::Convert( - ntmbs_t pbz, size_t nBytes, - const_ntdbs_t pwz, size_t nChars ) +int cIconvConverter::Convert(ntmbs_t pbz, size_t nBytes, const_ntdbs_t pwz, size_t nChars) { cDebug d("cIconvConverter::Convert( ntdbs_t -> ntmbs_t )"); - if ( pbz == 0 || ( pwz == 0 && nChars ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pbz == 0 || (pwz == 0 && nChars)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); // // reset converter // - cIconvUtil::ResetConverter( icFromDb ); + cIconvUtil::ResetConverter(icFromDb); // // do conversion // - ByteConvert< mbchar_t, dbchar_t > bc; - int nConverted = tss_Converter( icFromDb, icToDb, pbz, nBytes, pwz, nChars, bc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted < nBytes ); + ByteConvert bc; + int nConverted = tss_Converter(icFromDb, icToDb, pbz, nBytes, pwz, nChars, bc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted < nBytes); return nConverted; } -int -cIconvConverter::Convert( - ntdbs_t pwz, size_t nch, - const_ntmbs_t pbz, size_t nBytes ) -{ +int cIconvConverter::Convert(ntdbs_t pwz, size_t nch, const_ntmbs_t pbz, size_t nBytes) +{ cDebug d("cIconvConverter::Convert( ntmbs to ntdbs )"); - if ( pwz == 0 || ( pbz == 0 && nBytes ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pwz == 0 || (pbz == 0 && nBytes)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); // // reset converter // - cIconvUtil::ResetConverter( icToDb ); + cIconvUtil::ResetConverter(icToDb); // // do conversion // - ByteConvert< dbchar_t, mbchar_t > bc; - int nConverted = tss_Converter( icToDb, icFromDb, pwz, nch, pbz, nBytes, bc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted <= nch ); + ByteConvert bc; + int nConverted = tss_Converter(icToDb, icFromDb, pwz, nch, pbz, nBytes, bc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted <= nch); return nConverted; } - - - - - - - /* @@ -938,38 +912,38 @@ cDoubleIconvConverter::cDoubleIconvConverter() cDoubleIconvConverter::~cDoubleIconvConverter() { // close conversion handles - cIconvUtil::CloseHandle( icMbToUTF8 ); - cIconvUtil::CloseHandle( icUTF8ToDb ); - cIconvUtil::CloseHandle( icDbToUTF8 ); - cIconvUtil::CloseHandle( icUTF8ToMb ); + cIconvUtil::CloseHandle(icMbToUTF8); + cIconvUtil::CloseHandle(icUTF8ToDb); + cIconvUtil::CloseHandle(icDbToUTF8); + cIconvUtil::CloseHandle(icUTF8ToMb); } /* static */ bool cDoubleIconvConverter::Test() { - bool testResult = true; - cDebug d( "cDoubleIconvConverter::Test()" ); + bool testResult = true; + cDebug d("cDoubleIconvConverter::Test()"); // // try to get the current code page id // const char* pCP = NULL; - if( ! cIconvUtil::GetCodePageID( &pCP ) ) + if (!cIconvUtil::GetCodePageID(&pCP)) { - d.TraceDebug( "No code page.\n" ); + d.TraceDebug("No code page.\n"); return false; } - ASSERT( pCP && *pCP ); - d.TraceDebug( "Got code page %s.\n", pCP ); + ASSERT(pCP && *pCP); + d.TraceDebug("Got code page %s.\n", pCP); + - // // find if converters are available // - testResult &= cIconvUtil::TestConverter( cIconvUtil::GetMiddleIdentifier(), pCP ); - testResult &= cIconvUtil::TestConverter( cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetMiddleIdentifier() ); - testResult &= cIconvUtil::TestConverter( cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetIconvDbIdentifier() ); - testResult &= cIconvUtil::TestConverter( pCP, cIconvUtil::GetMiddleIdentifier() ); + testResult &= cIconvUtil::TestConverter(cIconvUtil::GetMiddleIdentifier(), pCP); + testResult &= cIconvUtil::TestConverter(cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetMiddleIdentifier()); + testResult &= cIconvUtil::TestConverter(cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetIconvDbIdentifier()); + testResult &= cIconvUtil::TestConverter(pCP, cIconvUtil::GetMiddleIdentifier()); return testResult; } @@ -977,24 +951,21 @@ bool cDoubleIconvConverter::Test() void cDoubleIconvConverter::Init() { - icMbToUTF8 = cIconvUtil::OpenHandle( cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetCodePageID() ); - icUTF8ToDb = cIconvUtil::OpenHandle( cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetMiddleIdentifier() ); - icDbToUTF8 = cIconvUtil::OpenHandle( cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetIconvDbIdentifier() ); - icUTF8ToMb = cIconvUtil::OpenHandle( cIconvUtil::GetCodePageID(), cIconvUtil::GetMiddleIdentifier() ); + icMbToUTF8 = cIconvUtil::OpenHandle(cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetCodePageID()); + icUTF8ToDb = cIconvUtil::OpenHandle(cIconvUtil::GetIconvDbIdentifier(), cIconvUtil::GetMiddleIdentifier()); + icDbToUTF8 = cIconvUtil::OpenHandle(cIconvUtil::GetMiddleIdentifier(), cIconvUtil::GetIconvDbIdentifier()); + icUTF8ToMb = cIconvUtil::OpenHandle(cIconvUtil::GetCodePageID(), cIconvUtil::GetMiddleIdentifier()); } -int -cDoubleIconvConverter::Convert( - ntmbs_t pbz, size_t nBytes, - const_ntdbs_t pwz, size_t nChars ) +int cDoubleIconvConverter::Convert(ntmbs_t pbz, size_t nBytes, const_ntdbs_t pwz, size_t nChars) { cDebug d("cDoubleIconvConverter::Convert( ntdbs_t -> ntmbs_t )"); // // initial checking // - if ( pbz == 0 || ( pwz == 0 && nChars ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pbz == 0 || (pwz == 0 && nChars)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); ////////////////////////////////////////////////// // do conversion to UTF8 @@ -1002,24 +973,24 @@ cDoubleIconvConverter::Convert( // // reset first converter // - cIconvUtil::ResetConverter( icDbToUTF8 ); + cIconvUtil::ResetConverter(icDbToUTF8); // // create middle buffer // - size_t nBufBytes = nChars * MB_LEN_MAX; - ntmbs_t pszBuffer = (ntmbs_t)::operator new( nBufBytes + 1 ); - std::auto_ptr pBuf( pszBuffer ); + size_t nBufBytes = nChars * MB_LEN_MAX; + ntmbs_t pszBuffer = (ntmbs_t)::operator new(nBufBytes + 1); + TW_UNIQUE_PTR pBuf(pszBuffer); // // do first conversion // - std::list lb; // buffer for invalid bytes - ToUTF8Convert< mbchar_t, dbchar_t > tc( lb ); - int nConverted = tss_Converter( icDbToUTF8, icUTF8ToDb, pszBuffer, nBufBytes, pwz, nChars, tc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted <= nBufBytes ); + std::list lb; // buffer for invalid bytes + ToUTF8Convert tc(lb); + int nConverted = tss_Converter(icDbToUTF8, icUTF8ToDb, pszBuffer, nBufBytes, pwz, nChars, tc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted <= nBufBytes); ////////////////////////////////////////////////// // do conversion to MB char @@ -1027,16 +998,16 @@ cDoubleIconvConverter::Convert( // // reset second converter // - cIconvUtil::ResetConverter( icUTF8ToMb ); + cIconvUtil::ResetConverter(icUTF8ToMb); // // do second conversion // - FromUTF8Convert< mbchar_t, mbchar_t > fc( lb ); - nConverted = tss_Converter( icUTF8ToMb, icMbToUTF8, pbz, nBytes, pszBuffer, nConverted, fc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted <= nBytes ); + FromUTF8Convert fc(lb); + nConverted = tss_Converter(icUTF8ToMb, icMbToUTF8, pbz, nBytes, pszBuffer, nConverted, fc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted <= nBytes); // // return number of bytes converted @@ -1044,15 +1015,12 @@ cDoubleIconvConverter::Convert( return nConverted; } -int -cDoubleIconvConverter::Convert( - ntdbs_t pwz, size_t nch, - const_ntmbs_t pbz, size_t nBytes ) -{ +int cDoubleIconvConverter::Convert(ntdbs_t pwz, size_t nch, const_ntmbs_t pbz, size_t nBytes) +{ cDebug d("cDoubleIconvConverter::Convert( ntmbs to ntdbs )"); - if ( pwz == 0 || ( pbz == 0 && nBytes ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pwz == 0 || (pbz == 0 && nBytes)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); ////////////////////////////////////////////////// // do conversion to UTF-8 char @@ -1060,24 +1028,24 @@ cDoubleIconvConverter::Convert( // // reset first converter // - cIconvUtil::ResetConverter( icMbToUTF8 ); + cIconvUtil::ResetConverter(icMbToUTF8); // // create middle buffer // - size_t nBufBytes = nBytes * MB_LEN_MAX; - ntmbs_t pszBuffer = (ntmbs_t)::operator new( nBufBytes + 1 ); - std::auto_ptr pBuf( pszBuffer ); + size_t nBufBytes = nBytes * MB_LEN_MAX; + ntmbs_t pszBuffer = (ntmbs_t)::operator new(nBufBytes + 1); + TW_UNIQUE_PTR pBuf(pszBuffer); // // do first conversion // - std::list lb; // buffer for invalid bytes - ToUTF8Convert< mbchar_t, mbchar_t > tc( lb ); - int nConverted = tss_Converter( icMbToUTF8, icUTF8ToMb, pszBuffer, nBufBytes, pbz, nBytes, tc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted <= nBufBytes ); + std::list lb; // buffer for invalid bytes + ToUTF8Convert tc(lb); + int nConverted = tss_Converter(icMbToUTF8, icUTF8ToMb, pszBuffer, nBufBytes, pbz, nBytes, tc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted <= nBufBytes); ////////////////////////////////////////////////// // do conversion to DB char @@ -1085,16 +1053,16 @@ cDoubleIconvConverter::Convert( // // reset second converter // - cIconvUtil::ResetConverter( icUTF8ToDb ); + cIconvUtil::ResetConverter(icUTF8ToDb); // // do second conversion // - FromUTF8Convert< dbchar_t, mbchar_t > fc( lb ); - nConverted = tss_Converter( icUTF8ToDb, icDbToUTF8, pwz, nch, pszBuffer, nConverted, fc ); - if ( !nConverted ) - return tss_dispatch_errno( d ); - ASSERT( nConverted <= nch ); + FromUTF8Convert fc(lb); + nConverted = tss_Converter(icUTF8ToDb, icDbToUTF8, pwz, nch, pszBuffer, nConverted, fc); + if (!nConverted) + return tss_dispatch_errno(d); + ASSERT(nConverted <= nch); return nConverted; } @@ -1104,25 +1072,25 @@ cDoubleIconvConverter::Convert( //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* static */ -iconv_t cIconvUtil::OpenHandle( const char* pTo, const char* pFrom ) +iconv_t cIconvUtil::OpenHandle(const char* pTo, const char* pFrom) { - cDebug d("cIconvUtil::OpenHandle"); + cDebug d("cIconvUtil::OpenHandle"); iconv_t ic; - - ic = iconv_open( pTo, pFrom ); - if( ic == (iconv_t)-1 ) + + ic = iconv_open(pTo, pFrom); + if (ic == (iconv_t)-1) throw eConverterUnsupportedConversion(); - d.TraceDebug( "opened %s to %s conversion\n", pFrom, pTo ); + d.TraceDebug("opened %s to %s conversion\n", pFrom, pTo); return ic; } /* static */ -bool cIconvUtil::GetCodePageID( const char** ppCP ) +bool cIconvUtil::GetCodePageID(const char** ppCP) { - *ppCP = nl_langinfo( CODESET ); + *ppCP = nl_langinfo(CODESET); - return( *ppCP && **ppCP ); + return (*ppCP && **ppCP); } /* static */ @@ -1130,8 +1098,8 @@ const char* cIconvUtil::GetCodePageID() { const char* pCurCodePage; - if( ! GetCodePageID( &pCurCodePage ) ) - throw eConverterUnknownCodepage(); + if (!GetCodePageID(&pCurCodePage)) + return NULL; return pCurCodePage; } @@ -1139,9 +1107,11 @@ const char* cIconvUtil::GetCodePageID() /* static */ const char* cIconvUtil::GetIconvDbIdentifier() { - ASSERT( false ); - throw eConverterUnknownCodepage(); - return NULL; +# ifdef WORDS_BIGENDIAN + return "UTF-16BE"; +# else + return "UTF-16LE"; +# endif } /* static */ @@ -1152,50 +1122,50 @@ const char* cIconvUtil::GetMiddleIdentifier() /* static */ -void cIconvUtil::ResetConverter( iconv_t ic ) +void cIconvUtil::ResetConverter(iconv_t ic) { - char* p = 0; + char* p = 0; size_t s = 0; - size_t i = iconv( ic, - (ICONV_SOURCE_TYPE**) &p, - &s, &p, &s ); - if ( i == (size_t)-1 ) + size_t i = iconv(ic, (ICONV_SOURCE_TYPE**)&p, &s, &p, &s); + if (i == (size_t)-1) { - ASSERT( false ); + ASSERT(false); throw eConverterReset(); } } /* static */ -void cIconvUtil::CloseHandle( iconv_t ic ) +void cIconvUtil::CloseHandle(iconv_t ic) { - int ret = iconv_close( ic ); - ASSERT( ret != -1 ); + int ret = iconv_close(ic); + ASSERT(ret != -1); } /* static */ -bool cIconvUtil::TestConverter( const char* pTo, const char* pFrom ) +bool cIconvUtil::TestConverter(const char* pTo, const char* pFrom) { - cDebug d( "cIconvUtil::TestConverter()" ); + if (!pTo || !pFrom) + return false; + + cDebug d("cIconvUtil::TestConverter()"); - iconv_t i = iconv_open( pTo, pFrom ); - if( (iconv_t)-1 == i ) - { - d.TraceDebug( "No %s to %s conversion.\n", pFrom, pTo ); + iconv_t i = iconv_open(pTo, pFrom); + if ((iconv_t)-1 == i) + { + d.TraceDebug("No %s to %s conversion.\n", pFrom, pTo); tss_dispatch_iconvopen_error(); return false; } else { - d.TraceDebug( "Valid conversion for %s to %s.\n", pFrom, pTo ); - cIconvUtil::CloseHandle( i ); + d.TraceDebug("Valid conversion for %s to %s.\n", pFrom, pTo); + cIconvUtil::CloseHandle(i); return true; } } -#endif//TSS_USE_ICONV_CCONV16 - +#endif //TSS_USE_ICONV_CCONV16 //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1203,169 +1173,159 @@ bool cIconvUtil::TestConverter( const char* pTo, const char* pFrom ) //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - namespace /*Unique*/ -{ - //-- Ensures 1-to-1 mb to wide character mapping by doing a reverse conversion - // and comparing the results - int - tss_mbtowc( wchar_t* pwch, const mbchar_t* pch, size_t nBytes ) - { - // convert forward - int nNarrow = ::mbtowc( pwch, pch, nBytes ); - if( nNarrow == -1 ) - return -1; - - // convert backwards - mbchar_t ach[ MB_LEN_MAX ]; - int nWide = ::wctomb( ach, *pwch ); - if( nWide == -1 ) - return -1; - - // compare... - if( ( nNarrow > (int)nBytes ) || - ( 0 != memcmp( ach, pch, nNarrow ) ) ) - return -1; - - // success! - return nNarrow; - } - - //-- Ensures 1-to-1 mb to wide character mapping by doing a reverse conversion - // and comparing the results - int - tss_wctomb( mbchar_t* pch, wchar_t wch ) - { - // convert forward - int nWide = ::wctomb( pch, wch ); - if( nWide == -1 ) - return -1; - - // convert backwards - wchar_t wchTest; - int nNarrow = ::mbtowc( &wchTest, pch, MB_CUR_MAX ); - if( nNarrow == -1 ) - return -1; - - // compare... - if( wchTest != wch ) - return -1; - - // success! - return nWide; - } +{ +//-- Ensures 1-to-1 mb to wide character mapping by doing a reverse conversion +// and comparing the results +int tss_mbtowc(wchar_t* pwch, const mbchar_t* pch, size_t nBytes) +{ + // convert forward + int nNarrow = ::mbtowc(pwch, pch, nBytes); + if (nNarrow == -1) + return -1; - int - tss_wcstombs( ntmbs_t pbz, const_ntwcs_t pwz, size_t nCount ) - { - cDebug d("tss_wcstombs"); + // convert backwards + mbchar_t ach[MB_LEN_MAX]; + int nWide = ::wctomb(ach, *pwch); + if (nWide == -1) + return -1; - size_t nConv; - size_t N; - for ( nConv = 0, N = 0; *pwz; ++pwz, pbz += N, ++nConv ) + // compare... + if ((nNarrow > (int)nBytes) || (0 != memcmp(ach, pch, nNarrow))) + return -1; + + // success! + return nNarrow; +} + +//-- Ensures 1-to-1 mb to wide character mapping by doing a reverse conversion +// and comparing the results +int tss_wctomb(mbchar_t* pch, wchar_t wch) +{ + // convert forward + int nWide = ::wctomb(pch, wch); + if (nWide == -1) + return -1; + + // convert backwards + wchar_t wchTest; + int nNarrow = ::mbtowc(&wchTest, pch, MB_CUR_MAX); + if (nNarrow == -1) + return -1; + + // compare... + if (wchTest != wch) + return -1; + + // success! + return nWide; +} + +int tss_wcstombs(ntmbs_t pbz, const_ntwcs_t pwz, size_t nCount) +{ + cDebug d("tss_wcstombs"); + + size_t nConv; + size_t N; + for (nConv = 0, N = 0; *pwz; ++pwz, pbz += N, ++nConv) + { + N = tss_wctomb(pbz, *pwz); + if (N == (size_t)-1) { - N = tss_wctomb( pbz, *pwz ); - if ( N == (size_t)-1 ) - { - *pbz = cConvertUtil::ConvertNonChar( (dbchar_t)*pwz ); - N = 1; - } + *pbz = cConvertUtil::ConvertNonChar((dbchar_t)*pwz); + N = 1; } - - return (int)nConv; } + return (int)nConv; +} - int - tss_mbstowcs( ntwcs_t pwz, const_ntmbs_t pbz, size_t nBytes ) - { - cDebug d("tss_mbstowcs"); - size_t N; - size_t nConv; - const_ntmbs_t end = &pbz[nBytes]; - for ( nConv = 0, N = 0; *pbz; pbz += N, ++pwz, ++nConv ) +int tss_mbstowcs(ntwcs_t pwz, const_ntmbs_t pbz, size_t nBytes) +{ + cDebug d("tss_mbstowcs"); + + size_t N; + size_t nConv; + const_ntmbs_t end = &pbz[nBytes]; + for (nConv = 0, N = 0; *pbz; pbz += N, ++pwz, ++nConv) + { + N = tss_mbtowc(pwz, pbz, end - pbz); + if (N == (size_t)-1) { - N = tss_mbtowc( pwz, pbz, end - pbz ); - if ( N == (size_t)-1 ) - { - d.TraceDebug( - "manually converting %X...\n", - cConvertUtil::ConvertNonChar( *pbz ) ); + d.TraceDebug("manually converting %X...\n", cConvertUtil::ConvertNonChar(*pbz)); - *pwz = (wchar_t)cConvertUtil::ConvertNonChar( *pbz ); - N = 1; - } + *pwz = (wchar_t)cConvertUtil::ConvertNonChar(*pbz); + N = 1; } - - return (int)nConv; } -}//Unique + + return (int)nConv; +} +} // namespace #if WCHAR_IS_32_BITS -int -cWcharIs32BitUcs2Converterer::Convert( - ntmbs_t pbz, size_t nBytes, - const_ntdbs_t pwz, size_t nCount ) +int cWcharIs32BitUcs2Converterer::Convert(ntmbs_t pbz, size_t nBytes, const_ntdbs_t pwz, size_t nCount) { - if ( pbz == 0 || ( pwz == 0 && nCount ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pbz == 0 || (pwz == 0 && nCount)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); // cast our dbchar_t to wchar_t's first - ntwcs_t pwzBuffer = new wchar_t[ nCount + 1 ]; - for( size_t n = 0; n < nCount; n++ ) + std::vector buf(nCount + 1); + wchar_t* pwzBuffer = &buf[0]; + + for (size_t n = 0; n < nCount; n++) pwzBuffer[n] = pwz[n]; pwzBuffer[nCount] = 0x00; // null terminate - int nConv = tss_wcstombs( pbz, pwzBuffer, nBytes ); - if ( (size_t)nConv == (size_t)-1 ) + int nConv = tss_wcstombs(pbz, pwzBuffer, nBytes); + if ((size_t)nConv == (size_t)-1) { cDebug d("cWcharIs32BitUcs2Converterer::Convert( ntdbs to ntmbs )"); - char* psz = new char[ nCount * 2 ]; - char* at = psz; - while ( *pwzBuffer ) + char* psz = new char[nCount * 2]; + char* at = psz; + while (*pwzBuffer) *at++ = *pwzBuffer++; *at = 0x00; - d.TraceDebug( "Invalid Input: [%s]\n", psz ); - d.TraceDebug( "%s\n", util_output_bytes( (void*)pwz, nCount*sizeof(wchar_t)).c_str() ); + d.TraceDebug("Invalid Input: [%s]\n", psz); + d.TraceDebug("%s\n", util_output_bytes((void*)pwz, nCount * sizeof(wchar_t)).c_str()); - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); } return nConv; } -int -cWcharIs32BitUcs2Converterer::Convert( - ntdbs_t pwz, size_t nCount, - const_ntmbs_t pbz, size_t nBytes ) +int cWcharIs32BitUcs2Converterer::Convert(ntdbs_t pwz, size_t nCount, const_ntmbs_t pbz, size_t nBytes) { cDebug d("cWcharIs32BitUcs2Converterer::Convert( ntmbs to ntdbs )"); // Validate Input - if ( pwz == 0 || ( pbz == 0 && nBytes ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pwz == 0 || (pbz == 0 && nBytes)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); // mb to wc to a buffer of wide chars then.... - wchar_t* pwzBuffer = new wchar_t[ nCount ]; + std::vector buf(nCount); + wchar_t* pwzBuffer = &buf[0]; - int nConv = tss_mbstowcs( pwzBuffer, pbz, nCount ); - if ( nConv == -1 ) + int nConv = tss_mbstowcs(pwzBuffer, pbz, nCount); + if (nConv == -1) { - d.TraceDebug( "Invalid Input: [%s]\n", pbz ); - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + d.TraceDebug("Invalid Input: [%s]\n", pbz); + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); } // ...cast those chars to dbchar_ts - for( size_t at = 0; at < (size_t)nConv; ++at, ++pwzBuffer ) + for (size_t at = 0; at < (size_t)nConv; ++at, ++pwzBuffer) { wchar_t wch = *pwzBuffer; - if ( wch > 0xFFFF ) + if (wch > 0xFFFF) { - d.TraceDebug("found wchar_T > 0xFFFF: %X\n", wch ); - throw eConverterFatal( _T("Cannot truncate wchar_t to dbchar_t") ); + d.TraceDebug("found wchar_T > 0xFFFF: %X\n", wch); + throw eConverterFatal(_T("Cannot truncate wchar_t to dbchar_t")); } - pwz[ at ] = (dbchar_t)wch; + pwz[at] = (dbchar_t)wch; } pwz[nConv] = 0x00; @@ -1381,164 +1341,152 @@ cWcharIs32BitUcs2Converterer::Convert( #if WCHAR_IS_16_BITS -int -cWcharIs16BitUcs2Converterer::Convert( - ntmbs_t pbz, size_t nbMB, - const_ntdbs_t pwz, size_t nch ) +int cWcharIs16BitUcs2Converterer::Convert(ntmbs_t pbz, size_t nbMB, const_ntdbs_t pwz, size_t nch) { // Validate Input - if ( pbz == 0 || ( pwz == 0 && nch ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pbz == 0 || (pwz == 0 && nch)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); - int nConverted = tss_wcstombs( pbz, pwz, nbMB ); - if ( nConverted == -1 ) + int nConverted = tss_wcstombs(pbz, pwz, nbMB); + if (nConverted == -1) { - cDebug d("cWcharIs16BitUcs2Converterer[ntdbs->ntmbs]"); - ntmbs_t psz = new char[ nch * 2 ]; - ntmbs_t at = psz; - while ( *pwz ) + cDebug d("cWcharIs16BitUcs2Converterer[ntdbs->ntmbs]"); + ntmbs_t psz = new char[nch * 2]; + ntmbs_t at = psz; + while (*pwz) *at++ = (mbchar_t)*pwz++; *at = 0x00; - d.TraceDebug( "Invalid Input: [%s]\n", psz ); - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + d.TraceDebug("Invalid Input: [%s]\n", psz); + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); } return nConverted; } -int -cWcharIs16BitUcs2Converterer::Convert( - ntdbs_t pwz, size_t nch, - const_ntmbs_t pbz, size_t nBytes ) +int cWcharIs16BitUcs2Converterer::Convert(ntdbs_t pwz, size_t nch, const_ntmbs_t pbz, size_t nBytes) { // Validate Input - if ( pbz == 0 || ( pwz == 0 && nch ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (pbz == 0 || (pwz == 0 && nch)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); - int nConverted = tss_mbstowcs( pwz, pbz, nch ); - if ( nConverted == -1 ) + int nConverted = tss_mbstowcs(pwz, pbz, nch); + if (nConverted == -1) { cDebug d("cWcharIs16BitUcs2Converterer::Convert( ntmbs to ntdbs )"); - d.TraceDebug( "Invalid Input: [%s]\n", pbz ); - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + d.TraceDebug("Invalid Input: [%s]\n", pbz); + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); } - + return nConverted; } #endif // WCHAR_IS_16_BITS - -int -cGoodEnoughConverterer::Convert( - ntmbs_t pbz, size_t nBytes, - const_ntdbs_t pwz, size_t nCount ) +int cGoodEnoughConverterer::Convert(ntmbs_t pbz, size_t nBytes, const_ntdbs_t pwz, size_t nCount) { - if ( pbz == 0 || ( pwz == 0 && nCount ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); - + if (pbz == 0 || (pwz == 0 && nCount)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); + char* at = pbz; - const dbchar_t* dat = pwz; - while ( *dat ) + + if (pwz) { - if( *dat > 0xFF ) + const dbchar_t* dat = pwz; + while (*dat) { - *at = cConvertUtil::ConvertNonChar( *dat ); - } - else - { - *at = (char)*dat; + if (*dat > 0xFF) + { + *at = cConvertUtil::ConvertNonChar(*dat); + } + else + { + *at = (char)*dat; + } + + at++; + dat++; } - - at++; - dat++; } *at = 0x00; - return( (size_t)at - (size_t)pbz ); + return ((size_t)at - (size_t)pbz); } -int -cGoodEnoughConverterer::Convert( - ntdbs_t pwz, size_t nCount, - const_ntmbs_t pbz, size_t nBytes ) +int cGoodEnoughConverterer::Convert(ntdbs_t pwz, size_t nCount, const_ntmbs_t pbz, size_t nBytes) { // Validate Input - if ( pwz == 0 || ( pbz == 0 && nBytes ) ) - throw eConverterFatal( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); - - const char* at = pbz; + if (pwz == 0 || (pbz == 0 && nBytes)) + throw eConverterFatal(TSS_GetString(cCore, core::STR_ERR_ISNULL)); + dbchar_t* dat = pwz; - while ( *at ) + + if (pbz) { - if( (unsigned char)*at > (unsigned char)0x7Fu ) + const char* at = pbz; + while (*at) { - *dat = cConvertUtil::ConvertNonChar( *at ); - } - else - { - *dat = (uint16)(unsigned char)*at; - } + if ((unsigned char)*at > (unsigned char)0x7Fu) + { + *dat = cConvertUtil::ConvertNonChar(*at); + } + else + { + *dat = (uint16)(unsigned char)*at; + } - dat++; - at++; + dat++; + at++; + } } - *dat = 0x0000; - return( ( (size_t)dat - (size_t)pwz ) / sizeof( dbchar_t ) ); + return (((size_t)dat - (size_t)pwz) / sizeof(dbchar_t)); } -dbchar_t cConvertUtil::ConvertNonChar( mbchar_t ch ) +dbchar_t cConvertUtil::ConvertNonChar(mbchar_t ch) { cDebug d("cConvertUtil::ConvertNonChar( mbchar_t to dbchar_t )"); - - if( ! ValueInReservedRange( ch ) ) + + if (!ValueInReservedRange(ch)) { - d.TraceDebug( "Invalid Input: [%X]\n", ch ); - throw eConverterFatal( _T("mbchar_t is not high ascii!") ); + d.TraceDebug("Invalid Input: [%X]\n", ch); + throw eConverterFatal(_T("mbchar_t is not high ascii!")); } - dbchar_t wch = (dbchar_t)( tss::util::char_to_size( ch ) + TSS_UCS2_RESERVED_START ); + dbchar_t wch = (dbchar_t)(tss::util::char_to_size(ch) + TSS_UCS2_RESERVED_START); - d.TraceDebug( "Converted 0x%08X to 0x%08X\n", - tss::util::char_to_size( ch ), - tss::util::char_to_size( wch ) ); + d.TraceDebug("Converted 0x%08X to 0x%08X\n", tss::util::char_to_size(ch), tss::util::char_to_size(wch)); - return( wch ); + return (wch); } -mbchar_t cConvertUtil::ConvertNonChar( dbchar_t wch ) -{ +mbchar_t cConvertUtil::ConvertNonChar(dbchar_t wch) +{ cDebug d("cConvertUtil::ConvertNonChar( dbchar_t to mbchar_t )"); - if( ! ValueInReservedRange( wch ) ) + if (!ValueInReservedRange(wch)) { - d.TraceDebug( "Invalid Input: [%X]\n", wch ); - throw eConverterFatal( _T("Cannot truncate dbchar_t to mbchar_t") ); + d.TraceDebug("Invalid Input: [%X]\n", wch); + throw eConverterFatal(_T("Cannot truncate dbchar_t to mbchar_t")); } - - mbchar_t ch = (mbchar_t)( wch - TSS_UCS2_RESERVED_START ); - d.TraceDebug( "Converted 0x%08X to 0x%08X\n", - tss::util::char_to_size( wch ), - tss::util::char_to_size( ch ) ); + mbchar_t ch = (mbchar_t)(wch - TSS_UCS2_RESERVED_START); + + d.TraceDebug("Converted 0x%08X to 0x%08X\n", tss::util::char_to_size(wch), tss::util::char_to_size(ch)); - return( ch ); + return (ch); } -bool cConvertUtil::ValueInReservedRange( dbchar_t wch ) +bool cConvertUtil::ValueInReservedRange(dbchar_t wch) { - size_t s = tss::util::char_to_size( wch ); - return( ( s >= TSS_UCS2_RESERVED_START ) && - ( s <= TSS_UCS2_RESERVED_END ) ); + size_t s = tss::util::char_to_size(wch); + return ((s >= TSS_UCS2_RESERVED_START) && (s <= TSS_UCS2_RESERVED_END)); } -bool cConvertUtil::ValueInReservedRange( mbchar_t ch ) +bool cConvertUtil::ValueInReservedRange(mbchar_t ch) { - size_t s = tss::util::char_to_size( ch ); - return( ( s >= TSS_HIGH_ASCII_START ) && - ( s <= TSS_HIGH_ASCII_END ) ); + size_t s = tss::util::char_to_size(ch); + return ((s >= TSS_HIGH_ASCII_START) && (s <= TSS_HIGH_ASCII_END)); } diff --git a/src/core/codeconvert.h b/src/core/codeconvert.h index 543d17a..f11af84 100644 --- a/src/core/codeconvert.h +++ b/src/core/codeconvert.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,17 +60,17 @@ /// Requirements -#include "platform.h" // for: Platform specific code -#include "ntmbs.h" // for: NTBS, NTMBS, NTWCS, and NTDBS types +#include "platform.h" // for: Platform specific code +#include "ntmbs.h" // for: NTBS, NTMBS, NTWCS, and NTDBS types /// Exceptions -TSS_EXCEPTION( eConverter, eError ); -TSS_EXCEPTION( eConverterReset, eConverter ); -TSS_EXCEPTION( eConverterFatal, eConverter ); -TSS_EXCEPTION( eConverterUnsupportedConversion, eConverter ); -TSS_EXCEPTION( eConverterUnknownCodepage, eConverter ); +TSS_EXCEPTION(eConverter, eError); +TSS_EXCEPTION(eConverterReset, eConverter); +TSS_EXCEPTION(eConverterFatal, eConverter); +TSS_EXCEPTION(eConverterUnsupportedConversion, eConverter); +TSS_EXCEPTION(eConverterUnknownCodepage, eConverter); /// Classes @@ -90,43 +90,38 @@ TSS_EXCEPTION( eConverterUnknownCodepage, eConverter ); */ class iCodeConverter { - public: - - static iCodeConverter* GetInstance(); // Singleton - +public: + static iCodeConverter* GetInstance(); // Singleton + static void Finit(); - /// Subclass Responsibilities - virtual - int - Convert( - ntmbs_t, // NTMBS buffer - size_t, // Capacity in mbchar_t's (bytes) - const_ntdbs_t, // null terminated two-byte wide character (UCS2 rep) - size_t nCount ) = 0; // Amount to convert in dbchar_t's - // returns number of buffer items converted, -1 on error - - virtual - int - Convert( - ntdbs_t, // NTDBS (Null-terminated two byte sequence) buf - size_t, // Capacity in dbchar_t's - const_ntmbs_t, // Null-terminated multi-byte sequence - size_t ) = 0; // Capacity in mbchar_t's (bytes) - // returns number of buffer items converted, -1 on error + /// Subclass Responsibilities + virtual int Convert(ntmbs_t, // NTMBS buffer + size_t, // Capacity in mbchar_t's (bytes) + const_ntdbs_t, // null terminated two-byte wide character (UCS2 rep) + size_t nCount) = 0; // Amount to convert in dbchar_t's + // returns number of buffer items converted, -1 on error - protected: - iCodeConverter() {} - virtual ~iCodeConverter() {} - - private: + virtual int Convert(ntdbs_t, // NTDBS (Null-terminated two byte sequence) buf + size_t, // Capacity in dbchar_t's + const_ntmbs_t, // Null-terminated multi-byte sequence + size_t) = 0; // Capacity in mbchar_t's (bytes) + // returns number of buffer items converted, -1 on error - static iCodeConverter* CreateConverter(); - static iCodeConverter* CreateGoodEnoughConverter(); +protected: + iCodeConverter() + { + } + virtual ~iCodeConverter() + { + } - static iCodeConverter* m_pInst; +private: + static iCodeConverter* CreateConverter(); + static iCodeConverter* CreateGoodEnoughConverter(); + static iCodeConverter* m_pInst; }; @@ -137,74 +132,70 @@ class iCodeConverter #ifdef HAVE_ICONV_H #include -#ifdef HAVE_LANGINFO_H -#ifndef __USE_XOPEN -#define __USE_XOPEN 1 -#endif -#include -#endif +# ifdef HAVE_LANGINFO_H +# ifndef __USE_XOPEN +# define __USE_XOPEN 1 +# endif +# include +# endif class cIconvUtil { - public: - - static const char* GetCodePageID(); // gets code page id for current locale, throws if error - static bool GetCodePageID( const char** ppCP ); - static const char* GetIconvDbIdentifier(); - static const char* GetMiddleIdentifier(); - static void ResetConverter( iconv_t ); - static bool TestConverter( const char* pTo, const char* pFrom ); - static iconv_t OpenHandle( const char* pTo, const char* pFrom ); // throws - static void CloseHandle( iconv_t ic ); +public: + static const char* GetCodePageID(); // gets code page id for current locale, throws if error + static bool GetCodePageID(const char** ppCP); + static const char* GetIconvDbIdentifier(); + static const char* GetMiddleIdentifier(); + static void ResetConverter(iconv_t); + static bool TestConverter(const char* pTo, const char* pFrom); + static iconv_t OpenHandle(const char* pTo, const char* pFrom); // throws + static void CloseHandle(iconv_t ic); }; class cIconvConverter : public iCodeConverter { - public: +public: + static bool Test(); // is there a conversion for the current codepage? - static bool Test(); // is there a conversion for the current codepage? + virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t); + virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t); - virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); - virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); + cIconvConverter(); + virtual ~cIconvConverter(); - cIconvConverter(); - virtual ~cIconvConverter(); +private: + void Init(); - private: - void Init(); - - iconv_t icToDb; - iconv_t icFromDb; + iconv_t icToDb; + iconv_t icFromDb; }; class cDoubleIconvConverter : public iCodeConverter { - public: +public: + static bool Test(); // is there a conversion for the current codepage? - static bool Test(); // is there a conversion for the current codepage? + virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t); + virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t); - virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); - virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); + cDoubleIconvConverter(); + virtual ~cDoubleIconvConverter(); - cDoubleIconvConverter(); - virtual ~cDoubleIconvConverter(); +private: + void Init(); - private: + iconv_t icMbToUTF8; + iconv_t icUTF8ToDb; - void Init(); - - iconv_t icMbToUTF8; - iconv_t icUTF8ToDb; - - iconv_t icDbToUTF8; - iconv_t icUTF8ToMb; + iconv_t icDbToUTF8; + iconv_t icUTF8ToMb; }; #endif // HAVE_ICONV_H -/// QUESTION:RAD -- Why not just have one platform-specific of the below +/// QUESTION:RAD -- Why not just have one platform-specific of the below //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // cWcharIs32BitUcs2Converterer @@ -212,16 +203,18 @@ class cDoubleIconvConverter : public iCodeConverter #if WCHAR_IS_32_BITS -// TODO:BAM -- this is not really correct! Convert will not honor nSource!! +// TODO:BAM -- this is not really correct! Convert will not honor nSource!! // it looks for the first null char! class cWcharIs32BitUcs2Converterer : public iCodeConverter { -public: - virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); - virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); - - virtual ~cWcharIs32BitUcs2Converterer() {} +public: + virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t); + virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t); + + virtual ~cWcharIs32BitUcs2Converterer() + { + } }; #endif // WCHAR_IS_32_BITS @@ -232,16 +225,18 @@ class cWcharIs32BitUcs2Converterer : public iCodeConverter #if WCHAR_IS_16_BITS -// TODO:BAM -- this is not really correct! Convert will not honor nSource!! +// TODO:BAM -- this is not really correct! Convert will not honor nSource!! // it looks for the first null char! class cWcharIs16BitUcs2Converterer : public iCodeConverter { -public: - virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); - virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); - - virtual ~cWcharIs16BitUcs2Converterer() {} +public: + virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t); + virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t); + + virtual ~cWcharIs16BitUcs2Converterer() + { + } }; #endif // WCHAR_IS_16_BITS @@ -250,31 +245,33 @@ class cWcharIs16BitUcs2Converterer : public iCodeConverter // converts mbchars > 0x7F to our reserved space class cGoodEnoughConverterer : public iCodeConverter { -public: - virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); - virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); - - virtual ~cGoodEnoughConverterer() {} +public: + virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t); + virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t); + + virtual ~cGoodEnoughConverterer() + { + } }; class cConvertUtil { - enum - { + enum + { TSS_UCS2_RESERVED_START = 0xE800u, // E000-E8FF is private use range, but TSS_UCS2_RESERVED_END = 0xE8FFu, // SJIS and EUC use E000-E757 TSS_HIGH_ASCII_START = 0x0080u, TSS_HIGH_ASCII_END = 0x00FFu }; + public: - static dbchar_t ConvertNonChar( mbchar_t ch ); - static mbchar_t ConvertNonChar( dbchar_t ch ); + static dbchar_t ConvertNonChar(mbchar_t ch); + static mbchar_t ConvertNonChar(dbchar_t ch); - static bool ValueInReservedRange( mbchar_t ch ); - static bool ValueInReservedRange( dbchar_t ch ); + static bool ValueInReservedRange(mbchar_t ch); + static bool ValueInReservedRange(dbchar_t ch); }; #endif //__CODECONVERT_H - diff --git a/src/core/core.cpp b/src/core/core.cpp index 453b509..7196bf2 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,26 +39,28 @@ #include "core.h" #include "coreerrors.h" -#include "codeconvert.h" // for: iCodeConverter::GetInstance -#include "twlocale.h" // for: cTWLocale::InitGlobalLocale +#include "codeconvert.h" // for: iCodeConverter::GetInstance +#include "twlocale.h" // for: cTWLocale::InitGlobalLocale -TSS_ImplementPackage( cCore ) +TSS_ImplementPackage(cCore) cCore::cCore() { - TSS_REGISTER_PKG_ERRORS( core ); + TSS_REGISTER_PKG_ERRORS(core); // NOTE: Initialize code converter when cCore is a dependency // of another package (created on first call to GetInstance(), // forcing creation here to hasten the display of any errors) - cDebug::SetDebugLevel( cDebug::D_DEBUG ); - cDebug::AddOutTarget( cDebug::OUT_STDOUT ); + cDebug::SetDebugLevel(cDebug::D_DEBUG); + cDebug::AddOutTarget(cDebug::OUT_STDOUT); cTWLocale::InitGlobalLocale(); iCodeConverter::GetInstance(); } - -// eof: core.cpp +cCore::~cCore() +{ + iCodeConverter::Finit(); +} diff --git a/src/core/core.h b/src/core/core.h index ce629da..fd2cf92 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,19 +43,18 @@ //--Requirements -#include "package.h" // for: Packaging Abstraction +#include "package.h" // for: Packaging Abstraction //--Classes -TSS_BeginPackage( cCore ) +TSS_BeginPackage(cCore) TSS_DECLARE_STRINGTABLE; - public: - - cCore(); +public: +cCore(); +~cCore(); -TSS_EndPackage( cCore ) +TSS_EndPackage(cCore) #endif //__CORE_H - diff --git a/src/core/coreerrors.cpp b/src/core/coreerrors.cpp index 2df59aa..b4490a7 100644 --- a/src/core/coreerrors.cpp +++ b/src/core/coreerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,120 +49,118 @@ #include "ntmbs.h" #include "displayencoder.h" -TSS_BEGIN_ERROR_REGISTRATION( core ) +TSS_BEGIN_ERROR_REGISTRATION(core) /// Internal -TSS_REGISTER_ERROR( eInternal(), _T("Internal error.") ) +TSS_REGISTER_ERROR(eInternal(), _T("Internal error.")) /// General -TSS_REGISTER_ERROR( eErrorGeneral(), _T("General Error") ); -TSS_REGISTER_ERROR( eOpen(), _T("File could not be opened.") ); -TSS_REGISTER_ERROR( eOpenRead(), _T("File could not be opened for reading.") ); -TSS_REGISTER_ERROR( eOpenWrite(), _T("File could not be opened for writing.") ); -TSS_REGISTER_ERROR( eBadModeSwitch(), _T("Unknown mode specified.") ); -TSS_REGISTER_ERROR( eBadCmdLine(), _T("Command line error.") ); +TSS_REGISTER_ERROR(eErrorGeneral(), _T("General Error")); +TSS_REGISTER_ERROR(eOpen(), _T("File could not be opened.")); +TSS_REGISTER_ERROR(eOpenRead(), _T("File could not be opened for reading.")); +TSS_REGISTER_ERROR(eOpenWrite(), _T("File could not be opened for writing.")); +TSS_REGISTER_ERROR(eBadModeSwitch(), _T("Unknown mode specified.")); +TSS_REGISTER_ERROR(eBadCmdLine(), _T("Command line error.")); -/// Archive +/// Archive -TSS_REGISTER_ERROR( eArchive(), _T("Archive error.") ) -TSS_REGISTER_ERROR( eArchiveOpen(), _T("File could not be opened.") ) -TSS_REGISTER_ERROR( eArchiveWrite(), _T("File could not be written.") ) -TSS_REGISTER_ERROR( eArchiveRead(), _T("File could not be read.") ) -TSS_REGISTER_ERROR( eArchiveEOF(), _T("End of file reached.") ) -TSS_REGISTER_ERROR( eArchiveSeek(), _T("File seek failed.") ) -TSS_REGISTER_ERROR( eArchiveMemmap(), _T("Memory mapped archive file invalid.") ) -TSS_REGISTER_ERROR( eArchiveOutOfMem(), _T("Archive ran out of memory.") ) -TSS_REGISTER_ERROR( eArchiveInvalidOp(),_T("Archive logic error.") ) -TSS_REGISTER_ERROR( eArchiveFormat(), _T("Archive file format invalid.") ) -TSS_REGISTER_ERROR( eArchiveNotRegularFile(), _T("File is not a regular file.") ) -TSS_REGISTER_ERROR( eArchiveCrypto(), _T("File could not be decrypted.") ) -TSS_REGISTER_ERROR( eArchiveStringTooLong(), _T("String was too long.") ) +TSS_REGISTER_ERROR(eArchive(), _T("Archive error.")) +TSS_REGISTER_ERROR(eArchiveOpen(), _T("File could not be opened.")) +TSS_REGISTER_ERROR(eArchiveWrite(), _T("File could not be written.")) +TSS_REGISTER_ERROR(eArchiveRead(), _T("File could not be read.")) +TSS_REGISTER_ERROR(eArchiveEOF(), _T("End of file reached.")) +TSS_REGISTER_ERROR(eArchiveSeek(), _T("File seek failed.")) +TSS_REGISTER_ERROR(eArchiveMemmap(), _T("Memory mapped archive file invalid.")) +TSS_REGISTER_ERROR(eArchiveOutOfMem(), _T("Archive ran out of memory.")) +TSS_REGISTER_ERROR(eArchiveInvalidOp(), _T("Archive logic error.")) +TSS_REGISTER_ERROR(eArchiveFormat(), _T("Archive file format invalid.")) +TSS_REGISTER_ERROR(eArchiveNotRegularFile(), _T("File is not a regular file.")) +TSS_REGISTER_ERROR(eArchiveCrypto(), _T("File could not be decrypted.")) +TSS_REGISTER_ERROR(eArchiveStringTooLong(), _T("String was too long.")) /// File -TSS_REGISTER_ERROR( eFile(), _T("File error.") ) -TSS_REGISTER_ERROR( eFileOpen(), _T("File could not be opened.") ) -TSS_REGISTER_ERROR( eFileWrite(), _T("File could not be written.") ) -TSS_REGISTER_ERROR( eFileRead(), _T("File could not be read.") ) -TSS_REGISTER_ERROR( eFileEOF(), _T("End of file reached.") ) -TSS_REGISTER_ERROR( eFileSeek(), _T("File seek failed.") ) -TSS_REGISTER_ERROR( eFileInvalidOp(), _T("File logic error.") ) -TSS_REGISTER_ERROR( eFileTrunc(), _T("File could not be truncated.") ) -TSS_REGISTER_ERROR( eFileClose(), _T("File could not be closed.") ) -TSS_REGISTER_ERROR( eFileFlush(), _T("File could not be flushed.") ) -TSS_REGISTER_ERROR( eFileRewind(), _T("File could not be rewound.") ) +TSS_REGISTER_ERROR(eFile(), _T("File error.")) +TSS_REGISTER_ERROR(eFileOpen(), _T("File could not be opened.")) +TSS_REGISTER_ERROR(eFileWrite(), _T("File could not be written.")) +TSS_REGISTER_ERROR(eFileRead(), _T("File could not be read.")) +TSS_REGISTER_ERROR(eFileEOF(), _T("End of file reached.")) +TSS_REGISTER_ERROR(eFileSeek(), _T("File seek failed.")) +TSS_REGISTER_ERROR(eFileInvalidOp(), _T("File logic error.")) +TSS_REGISTER_ERROR(eFileTrunc(), _T("File could not be truncated.")) +TSS_REGISTER_ERROR(eFileClose(), _T("File could not be closed.")) +TSS_REGISTER_ERROR(eFileFlush(), _T("File could not be flushed.")) +TSS_REGISTER_ERROR(eFileRewind(), _T("File could not be rewound.")) -/// Win32 +/// General API failures +TSS_REGISTER_ERROR(eUnix(), _T("Unix API failure.")) -#if IS_UNIX -TSS_REGISTER_ERROR(eUnix(), _T("Unix API failure.") ) -#endif /// FSServices -TSS_REGISTER_ERROR( eFSServices(), _T("File system error.") ) -TSS_REGISTER_ERROR( eFSServicesGeneric(),_T("File system error.") ) +TSS_REGISTER_ERROR(eFSServices(), _T("File system error.")) +TSS_REGISTER_ERROR(eFSServicesGeneric(), _T("File system error.")) /// Serializer -TSS_REGISTER_ERROR( eSerializerUnknownType(), _T("Unknown type encountered in file.\nFile format may not be valid for this platform.") ) -TSS_REGISTER_ERROR( eSerializerInputStreamFmt(), _T("Invalid input stream format.") ) -TSS_REGISTER_ERROR( eSerializerOutputStreamFmt(), _T("Invalid output stream format.") ) -TSS_REGISTER_ERROR( eSerializerInputStremTypeArray(), _T("A bad index was encountered in file.") ) -TSS_REGISTER_ERROR( eSerializerArchive(), _T("File read encountered an archive error.") ) -TSS_REGISTER_ERROR( eSerializerVersionMismatch(), _T("File version mismatch.") ) -TSS_REGISTER_ERROR( eSerializerEncryption(), _T("File encryption error.") ) -TSS_REGISTER_ERROR( eSerializer(), _T("File format error.") ) +TSS_REGISTER_ERROR(eSerializerUnknownType(), + _T("Unknown type encountered in file.\nFile format may not be valid for this platform.")) +TSS_REGISTER_ERROR(eSerializerInputStreamFmt(), _T("Invalid input stream format.")) +TSS_REGISTER_ERROR(eSerializerOutputStreamFmt(), _T("Invalid output stream format.")) +TSS_REGISTER_ERROR(eSerializerInputStremTypeArray(), _T("A bad index was encountered in file.")) +TSS_REGISTER_ERROR(eSerializerArchive(), _T("File read encountered an archive error.")) +TSS_REGISTER_ERROR(eSerializerVersionMismatch(), _T("File version mismatch.")) +TSS_REGISTER_ERROR(eSerializerEncryption(), _T("File encryption error.")) +TSS_REGISTER_ERROR(eSerializer(), _T("File format error.")) /// Command Line -TSS_REGISTER_ERROR( eCmdLine(), _T("Command line parsing error.") ) -TSS_REGISTER_ERROR( eCmdLineInvalidArg(), _T("Invalid argument passed on command line.") ) -TSS_REGISTER_ERROR( eCmdLineBadArgParam(), _T("Incorrect number of parameters to a command line argument.") ) -TSS_REGISTER_ERROR( eCmdLineBadParam(), _T("Incorrect number of parameters on command line.") ) -TSS_REGISTER_ERROR( eCmdLineBadSwitchPos(), _T("Switch appears after final command line parameter.") ) -TSS_REGISTER_ERROR( eCmdLineMutEx(), _T("Specified command line switches are mutually exclusive.") ) -TSS_REGISTER_ERROR( eCmdLineDependency(), _T("Command line parameter missing.") ) -TSS_REGISTER_ERROR( eCmdLineMultiArg(), _T("Command line argument specified more than once.") ) +TSS_REGISTER_ERROR(eCmdLine(), _T("Command line parsing error.")) +TSS_REGISTER_ERROR(eCmdLineInvalidArg(), _T("Invalid argument passed on command line.")) +TSS_REGISTER_ERROR(eCmdLineBadArgParam(), _T("Incorrect number of parameters to a command line argument.")) +TSS_REGISTER_ERROR(eCmdLineBadParam(), _T("Incorrect number of parameters on command line.")) +TSS_REGISTER_ERROR(eCmdLineBadSwitchPos(), _T("Switch appears after final command line parameter.")) +TSS_REGISTER_ERROR(eCmdLineMutEx(), _T("Specified command line switches are mutually exclusive.")) +TSS_REGISTER_ERROR(eCmdLineDependency(), _T("Command line parameter missing.")) +TSS_REGISTER_ERROR(eCmdLineMultiArg(), _T("Command line argument specified more than once.")) /// TWLocale -TSS_REGISTER_ERROR( eTWLocale(), _T("Localization error.") ) -TSS_REGISTER_ERROR( eTWLocaleBadNumFormat(),_T("Bad number format.") ) +TSS_REGISTER_ERROR(eTWLocale(), _T("Localization error.")) +TSS_REGISTER_ERROR(eTWLocaleBadNumFormat(), _T("Bad number format.")) /// Character Handling (defined in ntmbs.h) -TSS_REGISTER_ERROR( eCharacter(), _T("General Character Handling Error.") ) -TSS_REGISTER_ERROR( eCharacterEncoding(), _T("Character Encoding Error.") ) +TSS_REGISTER_ERROR(eCharacter(), _T("General Character Handling Error.")) +TSS_REGISTER_ERROR(eCharacterEncoding(), _T("Character Encoding Error.")) /// Character Conversion Handling (defined in ) -TSS_REGISTER_ERROR( eConverter(), _T("General conversion error.") ) -TSS_REGISTER_ERROR( eConverterReset(), _T("Converter handle could not be reset.") ) -TSS_REGISTER_ERROR( eConverterFatal(), _T("Catastrophic conversion error.") ) -TSS_REGISTER_ERROR( eConverterUnsupportedConversion(), _T("Unsupported character conversion.") ) -TSS_REGISTER_ERROR( eConverterUnknownCodepage(), _T("Could not identify code page.") ) +TSS_REGISTER_ERROR(eConverter(), _T("General conversion error.")) +TSS_REGISTER_ERROR(eConverterReset(), _T("Converter handle could not be reset.")) +TSS_REGISTER_ERROR(eConverterFatal(), _T("Catastrophic conversion error.")) +TSS_REGISTER_ERROR(eConverterUnsupportedConversion(), _T("Unsupported character conversion.")) +TSS_REGISTER_ERROR(eConverterUnknownCodepage(), _T("Could not identify code page.")) // // Display Encoder // -TSS_REGISTER_ERROR( eEncoder(), _T("Display encoder error.") ) -TSS_REGISTER_ERROR( eBadDecoderInput(), _T("Bad input to display encoder.") ) -TSS_REGISTER_ERROR( eBadHexConversion(), _T("Bad hex conversion in display encoder.") ) -TSS_REGISTER_ERROR( eUnknownEscapeEncoding(), _T("Unknown encoding in display encoder input.") ) +TSS_REGISTER_ERROR(eEncoder(), _T("Display encoder error.")) +TSS_REGISTER_ERROR(eBadDecoderInput(), _T("Bad input to display encoder.")) +TSS_REGISTER_ERROR(eBadHexConversion(), _T("Bad hex conversion in display encoder.")) +TSS_REGISTER_ERROR(eUnknownEscapeEncoding(), _T("Unknown encoding in display encoder input.")) TSS_END_ERROR_REGISTRATION() - diff --git a/src/core/coreerrors.h b/src/core/coreerrors.h index 19dd721..be5fdcb 100644 --- a/src/core/coreerrors.h +++ b/src/core/coreerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,8 +41,7 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( core ) - +TSS_DECLARE_ERROR_REGISTRATION(core) -#endif//__COREERRORS_H +#endif //__COREERRORS_H diff --git a/src/core/corestrings.cpp b/src/core/corestrings.cpp index 18d7648..a930b31 100644 --- a/src/core/corestrings.cpp +++ b/src/core/corestrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,39 +35,35 @@ // Creator.: Robert DiFalco (rdifalco) // -#include "stdcore.h" // for: pch (required by all core source modules) -#include "corestrings.h" // for: cCore and core::STR_IDS +#include "stdcore.h" // for: pch (required by all core source modules) +#include "corestrings.h" // for: cCore and core::STR_IDS -TSS_BeginStringtable( cCore ) +TSS_BeginStringtable(cCore) - TSS_StringEntry( core::STR_ERR2_ARCH_CRYPTO_ERR, _T("File could not be decrypted.") ), - TSS_StringEntry( core::STR_ERR2_BAD_ARG_PARAMS, _T("Argument: ") ), - TSS_StringEntry( core::STR_ERROR_ERROR, _T("### Error") ), - TSS_StringEntry( core::STR_ERROR_WARNING, _T("### Warning") ), - TSS_StringEntry( core::STR_ERROR_COLON, _T(":") ), - TSS_StringEntry( core::STR_ERROR_HEADER, _T("### ") ), - TSS_StringEntry( core::STR_ERROR_EXITING, _T("Exiting...") ), - TSS_StringEntry( core::STR_ERROR_CONTINUING, _T("Continuing...") ), - TSS_StringEntry( core::STR_ERR2_FILENAME, _T("Filename: ") ), - TSS_StringEntry( core::STR_ERROR_FILENAME, _T("Filename: ") ), - TSS_StringEntry( core::STR_UNKNOWN, _T("Unknown") ), - TSS_StringEntry( core::STR_NUMBER_TOO_BIG, _T("Number too big") ), - TSS_StringEntry( core::STR_SIGNAL, _T("Software interrupt forced exit:") ), - TSS_StringEntry( core::STR_NEWLINE, _T("\n") ), - TSS_StringEntry( core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file") ), - TSS_StringEntry( core::STR_MEMARCHIVE_ERRSTR, _T("") ), - TSS_StringEntry( core::STR_ENDOFTIME, _T("Tripwire is not designed to run past the year 2038.\nNow exiting...") ), - TSS_StringEntry( core::STR_UNKNOWN_TIME, _T("Unknown time") ), - TSS_StringEntry( core::STR_BAD_TEMPDIRECTORY, _T("Solution: Check existence/permissions for directory specified by TEMPDIRECTORY in config file") ), + TSS_StringEntry(core::STR_ERR2_ARCH_CRYPTO_ERR, _T("File could not be decrypted.")), + TSS_StringEntry(core::STR_ERR2_BAD_ARG_PARAMS, _T("Argument: ")), + TSS_StringEntry(core::STR_ERROR_ERROR, _T("### Error")), + TSS_StringEntry(core::STR_ERROR_WARNING, _T("### Warning")), TSS_StringEntry(core::STR_ERROR_COLON, _T(":")), + TSS_StringEntry(core::STR_ERROR_HEADER, _T("### ")), TSS_StringEntry(core::STR_ERROR_EXITING, _T("Exiting...")), + TSS_StringEntry(core::STR_ERROR_CONTINUING, _T("Continuing...")), + TSS_StringEntry(core::STR_ERR2_FILENAME, _T("Filename: ")), + TSS_StringEntry(core::STR_ERROR_FILENAME, _T("Filename: ")), TSS_StringEntry(core::STR_UNKNOWN, _T("Unknown")), + TSS_StringEntry(core::STR_NUMBER_TOO_BIG, _T("Number too big")), + TSS_StringEntry(core::STR_SIGNAL, _T("Software interrupt forced exit:")), + TSS_StringEntry(core::STR_NEWLINE, _T("\n")), + TSS_StringEntry(core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file")), + TSS_StringEntry(core::STR_MEMARCHIVE_ERRSTR, _T("")), + TSS_StringEntry(core::STR_ENDOFTIME, _T("Tripwire is not designed to run past the year 2038.\nNow exiting...")), + TSS_StringEntry(core::STR_UNKNOWN_TIME, _T("Unknown time")), + TSS_StringEntry( + core::STR_BAD_TEMPDIRECTORY, + _T("Solution: Check existence/permissions for directory specified by TEMPDIRECTORY in config file")), /// Particularly useful for eCharacter and eCharacterEncoding - TSS_StringEntry( core::STR_ERR_ISNULL, _T("Argument cannot be null.") ), - TSS_StringEntry( core::STR_ERR_OVERFLOW, _T("An overflow has been detected.") ), - TSS_StringEntry( core::STR_ERR_UNDERFLOW, _T("An underflow has been detected.") ), - TSS_StringEntry( core::STR_ERR_BADCHAR, _T("Input contained an invalid character.") ) - -TSS_EndStringtable( cCore ) - + TSS_StringEntry(core::STR_ERR_ISNULL, _T("Argument cannot be null.")), + TSS_StringEntry(core::STR_ERR_OVERFLOW, _T("An overflow has been detected.")), + TSS_StringEntry(core::STR_ERR_UNDERFLOW, _T("An underflow has been detected.")), + TSS_StringEntry(core::STR_ERR_BADCHAR, _T("Input contained an invalid character.")) -// eof: corestrings.cpp + TSS_EndStringtable(cCore) diff --git a/src/core/corestrings.h b/src/core/corestrings.h index 3071203..e6c78a1 100644 --- a/src/core/corestrings.h +++ b/src/core/corestrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,42 +40,24 @@ #define __CORESTRINGS_H -#include "core.h" // for: STRINGTABLE syntax +#include "core.h" // for: STRINGTABLE syntax //--Message Keys -TSS_BeginStringIds( core ) - +TSS_BeginStringIds(core) + STR_ERR2_ARCH_CRYPTO_ERR, - STR_ERR2_BAD_ARG_PARAMS, - STR_ERROR_ERROR, - STR_ERROR_WARNING, - STR_ERROR_COLON, - STR_ERROR_HEADER, - STR_ERROR_EXITING, - STR_ERROR_CONTINUING, - STR_ERR2_FILENAME, - STR_ERROR_FILENAME, - STR_NUMBER_TOO_BIG, - STR_UNKNOWN, - STR_SIGNAL, - STR_NEWLINE, - STR_MEMARCHIVE_FILENAME, - STR_MEMARCHIVE_ERRSTR, - STR_ENDOFTIME, - STR_UNKNOWN_TIME, - STR_BAD_TEMPDIRECTORY, + STR_ERR2_BAD_ARG_PARAMS, STR_ERROR_ERROR, STR_ERROR_WARNING, STR_ERROR_COLON, STR_ERROR_HEADER, STR_ERROR_EXITING, + STR_ERROR_CONTINUING, STR_ERR2_FILENAME, STR_ERROR_FILENAME, STR_NUMBER_TOO_BIG, STR_UNKNOWN, STR_SIGNAL, + STR_NEWLINE, STR_MEMARCHIVE_FILENAME, STR_MEMARCHIVE_ERRSTR, STR_ENDOFTIME, STR_UNKNOWN_TIME, STR_BAD_TEMPDIRECTORY, /// Particularly useful for eCharacterSet and eCharacterEncoding - STR_ERR_ISNULL, - STR_ERR_OVERFLOW, - STR_ERR_UNDERFLOW, + STR_ERR_ISNULL, STR_ERR_OVERFLOW, STR_ERR_UNDERFLOW, STR_ERR_BADCHAR -TSS_EndStringIds( core ) + TSS_EndStringIds(core) #endif //__CORESTRINGS_H - diff --git a/src/core/crc32.cpp b/src/core/crc32.cpp index 4c357c9..25a3261 100644 --- a/src/core/crc32.cpp +++ b/src/core/crc32.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/core/crc32.h b/src/core/crc32.h index 4b3bf67..c2fbeb9 100644 --- a/src/core/crc32.h +++ b/src/core/crc32.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/core/debug.cpp b/src/core/debug.cpp index 6a6fbc2..0082694 100644 --- a/src/core/debug.cpp +++ b/src/core/debug.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,17 +37,17 @@ #ifdef DEBUG -#ifndef va_start -#include -#endif +# ifndef va_start +# include +# endif #include #include #include -int cDebug::mDebugLevel(10); -uint32 cDebug::mOutMask(cDebug::OUT_TRACE); +int cDebug::mDebugLevel(10); +uint32 cDebug::mOutMask(cDebug::OUT_TRACE); std::ofstream cDebug::logfile; - //mDebugLevel default == 10, mOutMask default == OUT_TRACE. +//mDebugLevel default == 10, mOutMask default == OUT_TRACE. /////////////////////////////////////////////////////////////////////////////// // Constructors and Destructor @@ -61,45 +61,33 @@ cDebug::cDebug(const char* label) mLabel[cnt] = '\0'; } -cDebug::cDebug(const cDebug &rhs) +cDebug::cDebug(const cDebug& rhs) { - strcpy(mLabel, rhs.mLabel); + strncpy(mLabel, rhs.mLabel, MAX_LABEL); } cDebug::~cDebug() { - if(logfile) + if (logfile) logfile.close(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Trace -- Outputs a format string only if the passed integer value is <= -// the "global debug level" (indicated by mDebugLevel). +// the "global debug level" (indicated by mDebugLevel). /////////////////////////////////////////////////////////////////////////////// void cDebug::Trace(int levelNum, const char* format, ...) { if (levelNum > mDebugLevel) return; - // create the output buffer + // create the output buffer va_list args; va_start(args, format); DoTrace(format, args); va_end(args); - } -void cDebug::Trace(int levelNum, const wchar_t* format, ...) -{ - if (levelNum > mDebugLevel) - return; - // create the output buffer - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); - -} /////////////////////////////////////////////////////////////////////////////// // DoTrace() @@ -107,13 +95,13 @@ void cDebug::Trace(int levelNum, const wchar_t* format, ...) // console, etc... /////////////////////////////////////////////////////////////////////////////// -void cDebug::DoTrace(const char *format, va_list &args) +void cDebug::DoTrace(const char* format, va_list& args) { size_t guard1 = 0xBABABABA; - char out[2048]; + char out[2048]; size_t guard2 = 0xBABABABA; - vsprintf(out, format, args); + vsnprintf(out, 2048, format, args); ASSERT(guard1 == 0xBABABABA && guard2 == 0xBABABABA); // string was too long ASSERT(strlen(out) < 1024); @@ -146,136 +134,14 @@ void cDebug::DoTrace(const char *format, va_list &args) logfile.flush(); } } - -void cDebug::DoTrace(const wchar_t *format, va_list &args) -{ -#if IS_UNIX - // we don't support vswprintf on UNIX - ASSERT(false); - THROW_INTERNAL("debug.cpp"); -#else - - size_t guard1 = 0xBABABABA; - wchar_t out[2048]; - size_t guard2 = 0xBABABABA; - - vswprintf(out, format, args); - - ASSERT(guard1 == 0xBABABABA && guard2 == 0xBABABABA); // string was too long - char nout[1024]; - if (wcstombs(nout, out, 1024) == -1) - strcpy(nout, "XXX Unconvertable wide char detected in cDebug::DoTrace()\n"); - - std::ostringstream ostr; - ostr.setf(std::ios::left); - ostr.width(40); - ostr << mLabel; - ostr.width(0); - ostr << nout; - - - if ((mOutMask & OUT_STDOUT) != 0) - { - std::cout << ostr.str().c_str(); - std::cout.flush(); - } - - // - //make it output to log file! - // - if ((mOutMask & OUT_FILE) != 0) - { - // the logfile is narrow chars only... - logfile.setf(std::ios::left); - logfile.width(40); - logfile << mLabel; - logfile.width(0); - logfile << out; - logfile.flush(); - } -#endif // IS_UNIX -} - -#ifdef DEBUG +# ifdef DEBUG // // wrappers around Trace() that requires less typing // TODO: this is quick and dirty, but lets me check in all these files right away. --ghk // -void cDebug::TraceAlways(const char *format, ...) -{ - if (D_ALWAYS > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceError(const char *format, ...) -{ - if (D_ERROR > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceWarning(const char *format, ...) -{ - if (D_WARNING > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceDebug(const char *format, ...) -{ - if (D_DEBUG > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceDetail(const char *format, ...) -{ - if (D_DETAIL > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceNever(const char *format, ...) -{ - if (D_NEVER > mDebugLevel) - return; - - // fill up arglist, and pass to printing routine - va_list args; - va_start(args, format); - DoTrace(format, args); - va_end(args); -} - -void cDebug::TraceAlways(const wchar_t *format, ...) +void cDebug::TraceAlways(const char* format, ...) { if (D_ALWAYS > mDebugLevel) return; @@ -287,7 +153,7 @@ void cDebug::TraceAlways(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceError(const wchar_t *format, ...) +void cDebug::TraceError(const char* format, ...) { if (D_ERROR > mDebugLevel) return; @@ -299,7 +165,7 @@ void cDebug::TraceError(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceWarning(const wchar_t *format, ...) +void cDebug::TraceWarning(const char* format, ...) { if (D_WARNING > mDebugLevel) return; @@ -311,7 +177,7 @@ void cDebug::TraceWarning(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceDebug(const wchar_t *format, ...) +void cDebug::TraceDebug(const char* format, ...) { if (D_DEBUG > mDebugLevel) return; @@ -323,7 +189,7 @@ void cDebug::TraceDebug(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceDetail(const wchar_t *format, ...) +void cDebug::TraceDetail(const char* format, ...) { if (D_DETAIL > mDebugLevel) return; @@ -335,7 +201,7 @@ void cDebug::TraceDetail(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceNever(const wchar_t *format, ...) +void cDebug::TraceNever(const char* format, ...) { if (D_NEVER > mDebugLevel) return; @@ -347,22 +213,15 @@ void cDebug::TraceNever(const wchar_t *format, ...) va_end(args); } -void cDebug::TraceVaArgs( int iDebugLevel, const char *format, va_list &args ) -{ - if ( iDebugLevel <= mDebugLevel ) - DoTrace( format, args); -} - -void cDebug::TraceVaArgs( int iDebugLevel, const wchar_t *format, va_list &args ) +void cDebug::TraceVaArgs(int iDebugLevel, const char* format, va_list& args) { - if ( iDebugLevel <= mDebugLevel ) - DoTrace( format, args ); + if (iDebugLevel <= mDebugLevel) + DoTrace(format, args); } - -#endif // DEBUG +# endif // DEBUG /////////////////////////////////////////////////////////////////////////////// -// AddOutTarget -- Attempts to add a new target for trace/debug output. +// AddOutTarget -- Attempts to add a new target for trace/debug output. // FAILS ONLY IF caller attempts to SET OUT_FILE via this function. /////////////////////////////////////////////////////////////////////////////// bool cDebug::AddOutTarget(OutTarget target) @@ -371,7 +230,8 @@ bool cDebug::AddOutTarget(OutTarget target) mOutMask |= OUT_STDOUT; if (target == OUT_TRACE) mOutMask |= OUT_TRACE; - if (target == OUT_FILE) { + if (target == OUT_FILE) + { mOutMask |= OUT_FILE; return false; } @@ -399,7 +259,7 @@ bool cDebug::RemoveOutTarget(OutTarget target) /////////////////////////////////////////////////////////////////////////////// bool cDebug::HasOutTarget(OutTarget target) { - + if (target == OUT_STDOUT) return ((mOutMask & OUT_STDOUT) != 0); else if (target == OUT_TRACE) @@ -411,25 +271,27 @@ bool cDebug::HasOutTarget(OutTarget target) } /////////////////////////////////////////////////////////////////////////////// -// SetOutputFile -- Attempts to set the output file for Logfile member to +// SetOutputFile -- Attempts to set the output file for Logfile member to // the string passed in. /////////////////////////////////////////////////////////////////////////////// bool cDebug::SetOutputFile(const char* filename) { - // TODO -- make sure this does the right thing if a log file is + // TODO -- make sure this does the right thing if a log file is // already open! - // TODO -- make this work with wide chars + // TODO -- make this work with wide chars if (!logfile) logfile.open(filename, std::ios_base::out | std::ios_base::ate | std::ios_base::app); else logfile.setf(std::ios_base::hex, std::ios_base::basefield); - //make sure info. will not be clobbered. + //make sure info. will not be clobbered. //Should be open now- if not, abort. - if (!logfile) { + if (!logfile) + { mOutMask ^= OUT_FILE; return false; - } else + } + else mOutMask |= OUT_FILE; return true; } @@ -438,91 +300,23 @@ bool cDebug::SetOutputFile(const char* filename) // DebugOut -- Works just like TRACE. note: there is an internal buffer size // of 1024; traces larger than that will have unpredictable results. ////////////////////////////////////////////////////////////////////////////// -void cDebug::DebugOut( const char* lpOutputString, ... ) +void cDebug::DebugOut(const char* lpOutputString, ...) { char buf[2048]; - // create the output buffer + // create the output buffer va_list args; va_start(args, lpOutputString); - vsprintf(buf, lpOutputString, args); + vsnprintf(buf, 2048, lpOutputString, args); va_end(args); - -#ifdef _UNICODE - wchar_t wbuf[2048]; - if (mbstowcs(wbuf, buf, strlen(buf)+1) == -1) - wcscpy(wbuf, _T("XXX Unconvertable mb character detected in cDebug::DebugOut()\n") ); - - #if !USE_OUTPUT_DEBUG_STRING - #ifdef _DEBUG - TCERR << wbuf; - #endif //_DEBUG - #else // USE_OUTPUT_DEBUG_STRING - ::OutputDebugString(wbuf); - #endif // USE_OUTPUT_DEBUG_STRING -#else // _UNICODE - #if !USE_OUTPUT_DEBUG_STRING - #ifdef _DEBUG - TCERR << buf; - #endif //_DEBUG - #else // USE_OUTPUT_DEBUG_STRING - ::OutputDebugString(buf); - #endif // USE_OUTPUT_DEBUG_STRING -#endif // _UNICODE - TCOUT.flush(); -} - -void cDebug::DebugOut( const wchar_t* lpOutputString, ... ) -{ - va_list args; - va_start(args, lpOutputString); - -#if IS_UNIX - char mbformatbuf[1024]; - char buf[1024]; -// if (wcstombs(mbformatbuf, lpOutputString, wcslen(lpOutputString)) == -1) -// strcpy(mbformatbuf, "XXX Unconvertable wide char detected in cDebug::DebugOut()\n"); - - vsprintf(buf, mbformatbuf, args); -#else - - wchar_t buf[1024]; - vswprintf(buf, lpOutputString, args); -#endif - va_end(args); - -#ifdef _UNICODE - #if !USE_OUTPUT_DEBUG_STRING - #ifdef _DEBUG - TCERR << buf; - #endif //_DEBUG - #else // USE_OUTPUT_DEBUG_STRING - ::OutputDebugString(buf); - #endif // USE_OUTPUT_DEBUG_STRING -#else - char nbuf[1024]; - #if IS_UNIX - strcpy(nbuf, buf); - #else - if (wcstombs(nbuf, buf, wcslen(buf)+1) == -1) - strcpy(nbuf, "XXX Unconvertable wide char detected in cDebug::DebugOut()\n"); -#endif - -#if !USE_OUTPUT_DEBUG_STRING - #ifdef _DEBUG - TCERR << nbuf; - #endif //_DEBUG -#else // USE_OUTPUT_DEBUG_STRING - ::OutputDebugString(nbuf); -#endif // USE_OUTPUT_DEBUG_STRING - #endif +# ifdef DEBUG + TCERR << buf; +# endif //_DEBUG TCOUT.flush(); } - #endif // DEBUG ////////////////////////////////////////////////////////////////////////////////// // ASSERT macro support function ////////////////////////////////////////////////////////////////////////////////// - diff --git a/src/core/debug.h b/src/core/debug.h index 18310f5..5ffdae0 100644 --- a/src/core/debug.h +++ b/src/core/debug.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,19 +40,17 @@ #include - - #include /* Do it in this order, because autoconf checks for * first i.e. if HAVE_VARARGS_H is defined, it is only because * couldn't be found. */ #ifdef HAVE_VARARGS_H -# include +#include #else -# ifdef HAVE_STDARG_H -# include -# endif +# ifdef HAVE_STDARG_H +# include +# endif #endif #include "types.h" @@ -69,8 +67,8 @@ // // IMPORTANT: // -// strings outputted as trace statements are printed as narrow characters. -// passing trace messages with wide characters will have odd results, since +// strings outputted as trace statements are printed as narrow characters. +// passing trace messages with wide characters will have odd results, since // they will be used as arugments to sprintf(), etc... // @@ -80,19 +78,19 @@ class cDebug public: enum OutTarget { - OUT_STDOUT = 1, - OUT_TRACE = 2, - OUT_FILE = 4 + OUT_STDOUT = 1, + OUT_TRACE = 2, + OUT_FILE = 4 }; enum DebugLevel { D_ALWAYS = 0, - D_ERROR = 1, - D_WARNING = 4, - D_DEBUG = 8, - D_DETAIL = 16, - D_NEVER = 1000 + D_ERROR = 1, + D_WARNING = 4, + D_DEBUG = 8, + D_DETAIL = 16, + D_NEVER = 1000 }; cDebug(const char* pLabel); @@ -101,75 +99,68 @@ class cDebug // These are the preferred tracing interfaces, because you don't need to know // the DebugLevel enums. - // Wide/Narrow Chars Issues: If you include a %s in your format string and you + // Wide/Narrow Chars Issues: If you include a %s in your format string and you // wish to print out a TCHAR (which might be a natural thing to do) you should // encompas the format string with a _T("") macro, i.e. make it a TSTRING. // The wide character overloads of these functions will expect wide strings // for %s options. // - void TraceAlways (const char *format, ...); - void TraceError (const char *format, ...); - void TraceWarning (const char *format, ...); - void TraceDebug (const char *format, ...); - void TraceDetail (const char *format, ...); - void TraceNever (const char *format, ...); - void TraceAlways (const wchar_t *format, ...); - void TraceError (const wchar_t *format, ...); - void TraceWarning (const wchar_t *format, ...); - void TraceDebug (const wchar_t *format, ...); - void TraceDetail (const wchar_t *format, ...); - void TraceNever (const wchar_t *format, ...); + void TraceAlways(const char* format, ...); + void TraceError(const char* format, ...); + void TraceWarning(const char* format, ...); + void TraceDebug(const char* format, ...); + void TraceDetail(const char* format, ...); + void TraceNever(const char* format, ...); + // these are of use if you are inside a function with a "..." as an argument // and you want to trace those args - void TraceVaArgs (int iDebugLevel, const char *format, va_list &args); - void TraceVaArgs (int iDebugLevel, const wchar_t *format, va_list &args); + void TraceVaArgs(int iDebugLevel, const char* format, va_list& args); // ...but you can still choose to use this interface... void Trace(int levelNum, const char* format, ...); - void Trace(int levelNum, const wchar_t* format, ...); - // Outputs based on levelnum. If levelnum <= global debug, print. + // Outputs based on levelnum. If levelnum <= global debug, print. public: - - static bool AddOutTarget (OutTarget target); - static bool RemoveOutTarget (OutTarget target); - // used to specify the out target.... - static bool HasOutTarget (OutTarget target); - - static bool SetOutputFile (const char* filename); - // specifies the output file name used when OUT_FILE is set - static void SetDebugLevel (int level); - static int GetDebugLevel (void); - // gets and sets the global debug level. Trace output at or below this - // level will be output. - - static void DebugOut ( const char* lpOutputString, ... ); - static void DebugOut ( const wchar_t* lpOutputString, ... ); - // Works just like TRACE - // note: there is an internal buffer size of 1024; traces larger - // than that will have unpredictable and probably bad results + static bool AddOutTarget(OutTarget target); + static bool RemoveOutTarget(OutTarget target); + // used to specify the out target.... + static bool HasOutTarget(OutTarget target); + + static bool SetOutputFile(const char* filename); + // specifies the output file name used when OUT_FILE is set + static void SetDebugLevel(int level); + static int GetDebugLevel(void); + // gets and sets the global debug level. Trace output at or below this + // level will be output. + + static void DebugOut(const char* lpOutputString, ...); + // Works just like TRACE + // note: there is an internal buffer size of 1024; traces larger + // than that will have unpredictable and probably bad results private: #ifdef DEBUG - enum { MAX_LABEL = 128 }; + enum + { + MAX_LABEL = 128 + }; - static int mDebugLevel; - static uint32 mOutMask; - static std::ofstream logfile; - char mLabel[MAX_LABEL]; + static int mDebugLevel; + static uint32 mOutMask; + static std::ofstream logfile; + char mLabel[MAX_LABEL]; // helper functions - void DoTrace(const char *format, va_list &args); - void DoTrace(const wchar_t *format, va_list &args); + void DoTrace(const char* format, va_list& args); #endif }; -#ifdef _DEBUG -#define TRACE cDebug::DebugOut +#ifdef DEBUG +# define TRACE cDebug::DebugOut #else -#define TRACE 1 ? (void)0 : cDebug::DebugOut -#endif // _DEBUG +# define TRACE 1 ? (void)0 : cDebug::DebugOut +#endif // DEBUG ////////////////////////////////////////////////////////////////////////////////// // inline implementation @@ -188,66 +179,90 @@ inline int cDebug::GetDebugLevel() return mDebugLevel; } -#else // DEBUG - -inline cDebug::cDebug (const char *) {} -inline cDebug::~cDebug () {} -inline cDebug::cDebug (const cDebug&) {} -inline void cDebug::TraceAlways (const char *, ...) {} -inline void cDebug::TraceError (const char *, ...) {} -inline void cDebug::TraceWarning (const char *, ...) {} -inline void cDebug::TraceDebug (const char *, ...) {} -inline void cDebug::TraceDetail (const char *, ...) {} -inline void cDebug::TraceNever (const char *, ...) {} -inline void cDebug::TraceAlways (const wchar_t *, ...) {} -inline void cDebug::TraceError (const wchar_t *, ...) {} -inline void cDebug::TraceWarning (const wchar_t *, ...) {} -inline void cDebug::TraceDebug (const wchar_t *, ...) {} -inline void cDebug::TraceDetail (const wchar_t *, ...) {} -inline void cDebug::TraceNever (const wchar_t *, ...) {} -inline void cDebug::TraceVaArgs (int, const char *, va_list &) {} -inline void cDebug::TraceVaArgs (int, const wchar_t *, va_list &) {} -inline void cDebug::Trace (int, const char*, ...) {} -inline void cDebug::Trace (int, const wchar_t*, ...) {} -inline bool cDebug::AddOutTarget (OutTarget) { return false; } -inline bool cDebug::RemoveOutTarget (OutTarget) { return false; } -inline bool cDebug::HasOutTarget (OutTarget) { return false; } -inline bool cDebug::SetOutputFile (const char*) { return false; } -inline void cDebug::SetDebugLevel (int) {} -inline int cDebug::GetDebugLevel (void) { return 0; } -inline void cDebug::DebugOut ( const char*, ... ) {} -inline void cDebug::DebugOut ( const wchar_t*, ... ) {} +# else // DEBUG -#endif // DEBUG +inline cDebug::cDebug(const char*) +{ +} +inline cDebug::~cDebug() +{ +} +inline cDebug::cDebug(const cDebug&) +{ +} +inline void cDebug::TraceAlways(const char*, ...) +{ +} +inline void cDebug::TraceError(const char*, ...) +{ +} +inline void cDebug::TraceWarning(const char*, ...) +{ +} +inline void cDebug::TraceDebug(const char*, ...) +{ +} +inline void cDebug::TraceDetail(const char*, ...) +{ +} +inline void cDebug::TraceNever(const char*, ...) +{ +} +inline void cDebug::TraceVaArgs(int, const char*, va_list&) +{ +} +inline void cDebug::Trace(int, const char*, ...) +{ +} +inline bool cDebug::AddOutTarget(OutTarget) +{ + return false; +} +inline bool cDebug::RemoveOutTarget(OutTarget) +{ + return false; +} +inline bool cDebug::HasOutTarget(OutTarget) +{ + return false; +} +inline bool cDebug::SetOutputFile(const char*) +{ + return false; +} +inline void cDebug::SetDebugLevel(int) +{ +} +inline int cDebug::GetDebugLevel(void) +{ + return 0; +} +inline void cDebug::DebugOut(const char*, ...) +{ +} +# endif // DEBUG ////////////////////////////////////////////////////////////////////////////////// // ASSERT macro ////////////////////////////////////////////////////////////////////////////////// +# define ASSERTMSG(exp, s) assert((exp) != 0) +# define ASSERT(exp) assert((exp) != 0) + // if we are not windows we will just use the standard assert() +# define TSS_DebugBreak() ASSERT(false); -#if IS_UNIX - - #define ASSERTMSG( exp, s ) assert( (exp) != 0 ) - #define ASSERT( exp ) assert( (exp) != 0 ) - // if we are not windows we will just use the standard assert() - #define TSS_DebugBreak() ASSERT( false ); +# ifndef ASSERT +# error ASSERT did not get defined!!! +# endif -#endif// IS_UNIX +# ifndef ASSERTMSG +# error ASSERTMSG did not get defined!!! +# endif - -#ifndef ASSERT -#error ASSERT did not get defined!!! -#endif - -#ifndef ASSERTMSG -#error ASSERTMSG did not get defined!!! -#endif - -#ifndef TSS_DebugBreak -#error TSS_DebugBreak did not get defined!!! -#endif +# ifndef TSS_DebugBreak +# error TSS_DebugBreak did not get defined!!! +# endif #endif //__DEBUG_H - diff --git a/src/core/displayencoder.cpp b/src/core/displayencoder.cpp index 1453d03..eac1c16 100644 --- a/src/core/displayencoder.cpp +++ b/src/core/displayencoder.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -66,10 +66,9 @@ ////////////////////////////////////////////////////////////////////////////// -inline bool IsSingleTCHAR( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +inline bool IsSingleTCHAR(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( first + 1 == last ); + return (first + 1 == last); } ////////////////////////////////////////////////////////////////////////////// @@ -80,130 +79,133 @@ inline bool IsSingleTCHAR( TSTRING::const_iterator first, class iCharEncoder { - public: - virtual bool NeedsEncoding( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const = 0; - // Determines if character identified by [first,last) needs encoding. - // Returns true if it does. +public: + virtual ~iCharEncoder(){}; - virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, - TSTRING::const_iterator last ) const = 0; - // Encodes character identified by [first,last) in such a way that it - // can be decoded by Decode(). Returns encoded character sequence. + virtual bool NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const = 0; + // Determines if character identified by [first,last) needs encoding. + // Returns true if it does. - virtual TSTRING EncodePretty( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const = 0; - // Encodes character identified by [first,last) in a manner that is not roundtrip, - // but looks good. Returns encoded character sequence. + virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const = 0; + // Encodes character identified by [first,last) in such a way that it + // can be decoded by Decode(). Returns encoded character sequence. - virtual TSTRING Decode( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) const = 0; - // Decodes character sequence beginning with '*pcur' and ending before 'end'. - // Returns decoded character or sequence of characters. Advances *pcur beyond - // the last character decoded. + virtual TSTRING EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const = 0; + // Encodes character identified by [first,last) in a manner that is not roundtrip, + // but looks good. Returns encoded character sequence. + virtual TSTRING Decode(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) const = 0; + // Decodes character sequence beginning with '*pcur' and ending before 'end'. + // Returns decoded character or sequence of characters. Advances *pcur beyond + // the last character decoded. - virtual TCHAR Identifier() const = 0; - static TCHAR EscapeChar() { return char_escape; } + virtual TCHAR Identifier() const = 0; - protected: + static TCHAR EscapeChar() + { + return char_escape; + } - static TCHAR char_escape; +protected: + static TCHAR char_escape; }; class cNonNarrowableCharEncoder : public iCharEncoder { - public: - virtual bool NeedsEncoding( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; +public: + virtual ~cNonNarrowableCharEncoder() + { + } + + virtual bool NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const; + + virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodePretty( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING Decode(TSTRING::const_iterator* cur, const TSTRING::const_iterator end) const; - virtual TSTRING Decode( TSTRING::const_iterator* cur, - const TSTRING::const_iterator end ) const; + virtual TCHAR Identifier() const; - virtual TCHAR Identifier() const; - private: - static TCHAR char_identifier; - static TCHAR char_replace; +private: + static TCHAR char_identifier; + static TCHAR char_replace; }; class cNonPrintableCharEncoder : public iCharEncoder { - public: - cNonPrintableCharEncoder( bool f_allowWS ) - : m_allowWS( f_allowWS ) {}; +public: + cNonPrintableCharEncoder(bool f_allowWS) : m_allowWS(f_allowWS){}; + + virtual ~cNonPrintableCharEncoder() + { + } - virtual bool NeedsEncoding( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual bool NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodePretty( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING Decode( TSTRING::const_iterator* cur, - const TSTRING::const_iterator end ) const; + virtual TSTRING Decode(TSTRING::const_iterator* cur, const TSTRING::const_iterator end) const; - virtual TCHAR Identifier() const; - private: - static TCHAR char_identifier; - static TCHAR char_replace; + virtual TCHAR Identifier() const; - bool m_allowWS; +private: + static TCHAR char_identifier; + static TCHAR char_replace; + + bool m_allowWS; }; class cQuoteCharEncoder : public iCharEncoder { - public: - virtual bool NeedsEncoding( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; +public: + virtual ~cQuoteCharEncoder() + { + } + + virtual bool NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodePretty( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING Decode( TSTRING::const_iterator* cur, - const TSTRING::const_iterator end ) const; + virtual TSTRING Decode(TSTRING::const_iterator* cur, const TSTRING::const_iterator end) const; - virtual TCHAR Identifier() const; - private: - static TCHAR char_test; - static TCHAR char_identifier; - static TCHAR char_replace; + virtual TCHAR Identifier() const; + +private: + static TCHAR char_test; + static TCHAR char_identifier; + static TCHAR char_replace; }; class cBackslashCharEncoder : public iCharEncoder { - public: - virtual bool NeedsEncoding( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; +public: + virtual ~cBackslashCharEncoder() + { + } - virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual bool NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING EncodePretty( TSTRING::const_iterator first, - TSTRING::const_iterator last ) const; + virtual TSTRING EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TSTRING Decode( TSTRING::const_iterator* cur, - const TSTRING::const_iterator end ) const; + virtual TSTRING EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const; - virtual TCHAR Identifier() const; - private: - static TCHAR char_test; - static TCHAR char_identifier; - static TCHAR char_replace; + virtual TSTRING Decode(TSTRING::const_iterator* cur, const TSTRING::const_iterator end) const; + + virtual TCHAR Identifier() const; + +private: + static TCHAR char_test; + static TCHAR char_identifier; + static TCHAR char_replace; }; @@ -211,63 +213,33 @@ class cBackslashCharEncoder : public iCharEncoder // CHARACTER SPECIALIZATIONS ////////////////////////////////////////////////////////////////////////////// -TCHAR iCharEncoder::char_escape = _T('\\'); +TCHAR iCharEncoder::char_escape = _T('\\'); -TCHAR cNonNarrowableCharEncoder::char_identifier = _T('x'); -TCHAR cNonPrintableCharEncoder::char_identifier = _T('x'); -TCHAR cQuoteCharEncoder::char_identifier = _T('\"'); -TCHAR cBackslashCharEncoder::char_identifier = _T('\\'); +TCHAR cNonNarrowableCharEncoder::char_identifier = _T('x'); +TCHAR cNonPrintableCharEncoder::char_identifier = _T('x'); +TCHAR cQuoteCharEncoder::char_identifier = _T('\"'); +TCHAR cBackslashCharEncoder::char_identifier = _T('\\'); -TCHAR cBackslashCharEncoder::char_test = cBackslashCharEncoder::char_identifier; -TCHAR cQuoteCharEncoder::char_test = cQuoteCharEncoder::char_identifier; +TCHAR cBackslashCharEncoder::char_test = cBackslashCharEncoder::char_identifier; +TCHAR cQuoteCharEncoder::char_test = cQuoteCharEncoder::char_identifier; -TCHAR cBackslashCharEncoder::char_replace = cBackslashCharEncoder::char_identifier; -TCHAR cQuoteCharEncoder::char_replace = cQuoteCharEncoder::char_identifier; +TCHAR cBackslashCharEncoder::char_replace = cBackslashCharEncoder::char_identifier; +TCHAR cQuoteCharEncoder::char_replace = cQuoteCharEncoder::char_identifier; -TCHAR cNonNarrowableCharEncoder::char_replace = _T('?'); -TCHAR cNonPrintableCharEncoder::char_replace = _T('?'); +TCHAR cNonNarrowableCharEncoder::char_replace = _T('?'); +TCHAR cNonPrintableCharEncoder::char_replace = _T('?'); ////////////////////////////////////////////////////////////////////////////// // TESTS ////////////////////////////////////////////////////////////////////////////// -bool cNonNarrowableCharEncoder::NeedsEncoding( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +bool cNonNarrowableCharEncoder::NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - -#ifdef _UNICODE - - ASSERT( IsSingleTCHAR( first, last ) ); - - char amb[ MB_LEN_MAX ]; - TCHAR awch[] = { *first, 0 }; - - // TODO:BAM -- this is not really correct! Convert will not honor nSource!! - // it looks for the first null char! - try - { - int ret = iCodeConverter::GetInstance()->Convert( amb, sizeof( amb ), awch, 1 ); - return( -1 == ret ); - } - catch( eError& ) - { - return true; - } - -#else - return false; // all chars are narrow - -#endif - } - -bool cNonPrintableCharEncoder::NeedsEncoding( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +bool cNonPrintableCharEncoder::NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const { // TODO:BAM -- handle this with mb chars // std::isprint does a wctob() on the wchar!!?!?! @@ -287,38 +259,26 @@ bool cNonPrintableCharEncoder::NeedsEncoding( // #else // return( ! isprint( ch ) ); // #endif - // + // // assuming all unprintable chars are one TCHAR long - if( ! IsSingleTCHAR( first, last ) ) + if (!IsSingleTCHAR(first, last)) return false; - if( m_allowWS && cCharEncoderUtil::IsWhiteSpace( *first ) ) + if (m_allowWS && cCharEncoderUtil::IsWhiteSpace(*first)) return false; - return cCharEncoderUtil::IsPrintable( *first ); + return cCharEncoderUtil::IsPrintable(*first); } -bool cQuoteCharEncoder::NeedsEncoding( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +bool cQuoteCharEncoder::NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - return( - IsSingleTCHAR( first, last ) - && - ( *first == char_test ) - ); + return (IsSingleTCHAR(first, last) && (*first == char_test)); } -bool cBackslashCharEncoder::NeedsEncoding( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +bool cBackslashCharEncoder::NeedsEncoding(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - return( - IsSingleTCHAR( first, last ) - && - ( *first == char_test ) - ); + return (IsSingleTCHAR(first, last) && (*first == char_test)); } ////////////////////////////////////////////////////////////////////////////// @@ -326,46 +286,40 @@ bool cBackslashCharEncoder::NeedsEncoding( ////////////////////////////////////////////////////////////////////////////// -TSTRING cNonNarrowableCharEncoder::EncodeRoundtrip( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cNonNarrowableCharEncoder::EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const { TSTRING str; str += char_escape; str += char_identifier; - str += cCharEncoderUtil::CharStringToHexValue( TSTRING( first, last ) ); + str += cCharEncoderUtil::CharStringToHexValue(TSTRING(first, last)); return str; } -TSTRING cNonPrintableCharEncoder::EncodeRoundtrip( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cNonPrintableCharEncoder::EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - ASSERT( IsSingleTCHAR( first, last ) ); // non-prints are single char (see NOTE above) + ASSERT(IsSingleTCHAR(first, last)); // non-prints are single char (see NOTE above) TSTRING str; str += char_escape; str += char_identifier; - str += cCharEncoderUtil::CharStringToHexValue( TSTRING( first, last ) ); + str += cCharEncoderUtil::CharStringToHexValue(TSTRING(first, last)); return str; } -TSTRING cQuoteCharEncoder::EncodeRoundtrip( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cQuoteCharEncoder::EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const { // should just be a quote - ASSERT( IsSingleTCHAR( first, last ) ); - ASSERT( *first == char_test ); + ASSERT(IsSingleTCHAR(first, last)); + ASSERT(*first == char_test); TSTRING str; - + str += char_escape; str += char_identifier; @@ -373,17 +327,14 @@ TSTRING cQuoteCharEncoder::EncodeRoundtrip( } - -TSTRING cBackslashCharEncoder::EncodeRoundtrip( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cBackslashCharEncoder::EncodeRoundtrip(TSTRING::const_iterator first, TSTRING::const_iterator last) const { // should just be a backslash - ASSERT( IsSingleTCHAR( first, last ) ); - ASSERT( *first == char_test ); + ASSERT(IsSingleTCHAR(first, last)); + ASSERT(*first == char_test); TSTRING str; - + str += char_escape; str += char_identifier; @@ -395,43 +346,35 @@ TSTRING cBackslashCharEncoder::EncodeRoundtrip( ////////////////////////////////////////////////////////////////////////////// -TSTRING cNonNarrowableCharEncoder::EncodePretty( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cNonNarrowableCharEncoder::EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - return EncodeRoundtrip( first, last ); + return EncodeRoundtrip(first, last); } -TSTRING cNonPrintableCharEncoder::EncodePretty( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cNonPrintableCharEncoder::EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const { - return EncodeRoundtrip( first, last ); + return EncodeRoundtrip(first, last); } -TSTRING cQuoteCharEncoder::EncodePretty( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cQuoteCharEncoder::EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const { // should just be a quote - ASSERT( IsSingleTCHAR( first, last ) ); - ASSERT( *first == char_test ); - - return TSTRING( 1, char_replace ); + ASSERT(IsSingleTCHAR(first, last)); + ASSERT(*first == char_test); + + return TSTRING(1, char_replace); } -TSTRING cBackslashCharEncoder::EncodePretty( - TSTRING::const_iterator first, - TSTRING::const_iterator last ) const +TSTRING cBackslashCharEncoder::EncodePretty(TSTRING::const_iterator first, TSTRING::const_iterator last) const { // should just be a backslash - ASSERT( IsSingleTCHAR( first, last ) ); - ASSERT( *first == char_test ); + ASSERT(IsSingleTCHAR(first, last)); + ASSERT(*first == char_test); - return TSTRING( 1, char_replace ); + return TSTRING(1, char_replace); } ////////////////////////////////////////////////////////////////////////////// @@ -439,49 +382,45 @@ TSTRING cBackslashCharEncoder::EncodePretty( ////////////////////////////////////////////////////////////////////////////// -TSTRING cNonNarrowableCharEncoder::Decode( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) const +TSTRING cNonNarrowableCharEncoder::Decode(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) const { // check preconditions - if( (*pcur) >= end || *(*pcur) != Identifier() ) - ThrowAndAssert( eBadDecoderInput() ); + if ((*pcur) >= end || *(*pcur) != Identifier()) + ThrowAndAssert(eBadDecoderInput()); - return( cCharEncoderUtil::DecodeHexToChar( pcur, end ) ); + return (cCharEncoderUtil::DecodeHexToChar(pcur, end)); } -TSTRING cNonPrintableCharEncoder::Decode( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) const +TSTRING cNonPrintableCharEncoder::Decode(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) const { // check preconditions - if( (*pcur) >= end || *(*pcur) != Identifier() ) - ThrowAndAssert( eBadDecoderInput() ); + if ((*pcur) >= end || *(*pcur) != Identifier()) + ThrowAndAssert(eBadDecoderInput()); - return( cCharEncoderUtil::DecodeHexToChar( pcur, end ) ); + return (cCharEncoderUtil::DecodeHexToChar(pcur, end)); } -TSTRING cQuoteCharEncoder::Decode( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) const +TSTRING cQuoteCharEncoder::Decode(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) const { - if( (*pcur) >= end || *(*pcur) != Identifier() ) - ThrowAndAssert( eBadDecoderInput() ); + if ((*pcur) >= end || *(*pcur) != Identifier()) + ThrowAndAssert(eBadDecoderInput()); (*pcur)++; // advance past part decoded - return TSTRING( 1, Identifier() ); + return TSTRING(1, Identifier()); } -TSTRING cBackslashCharEncoder::Decode( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) const +TSTRING cBackslashCharEncoder::Decode(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) const { - if( (*pcur) >= end || *(*pcur) != Identifier() ) - ThrowAndAssert( eBadDecoderInput() ); + if ((*pcur) >= end || *(*pcur) != Identifier()) + ThrowAndAssert(eBadDecoderInput()); (*pcur)++; // advance past part decoded - return TSTRING( 1, Identifier() ); + return TSTRING(1, Identifier()); } ////////////////////////////////////////////////////////////////////////////// @@ -515,120 +454,107 @@ TCHAR cBackslashCharEncoder::Identifier() const // UTILITIES ////////////////////////////////////////////////////////////////////////////// -bool cCharEncoderUtil::IsWhiteSpace( TCHAR ch ) +bool cCharEncoderUtil::IsWhiteSpace(TCHAR ch) { - return ( ch == '\r' || - ch == '\n' || - ch == '\t' || - ch == '\v' || - ch == ' ' ); + return (ch == '\r' || ch == '\n' || ch == '\t' || ch == '\v' || ch == ' '); } -bool cCharEncoderUtil::IsPrintable( TCHAR ch ) +bool cCharEncoderUtil::IsPrintable(TCHAR ch) { #if USE_CLIB_LOCALE && !defined(__APPLE__) - return( ! isprint( ch ) ); // kludge for KAI + return (!isprint(ch)); // kludge for KAI #else // USE_CLIB_LOCALE - -#if IS_UNIX - return( ! std::isprint( ch, std::locale() ) ); - #endif + return (!std::isprint(ch, std::locale())); #endif // USE_CLIB_LOCALE } -TSTRING cCharEncoderUtil::CharStringToHexValue( const TSTRING& str ) +TSTRING cCharEncoderUtil::CharStringToHexValue(const TSTRING& str) { - TSTRING strOut; + TSTRING strOut; TSTRING::const_iterator at; - for( at = str.begin(); at < str.end(); at++ ) + for (at = str.begin(); at < str.end(); at++) { - strOut += char_to_hex( *at ); + strOut += char_to_hex(*at); } return strOut; } -TSTRING cCharEncoderUtil::HexValueToCharString( const TSTRING& str ) +TSTRING cCharEncoderUtil::HexValueToCharString(const TSTRING& str) { - TSTRING strOut; - TSTRING::const_iterator at; + TSTRING strOut; + TSTRING::const_iterator at; - for( at = str.begin(); at < str.end(); at += TCHAR_AS_HEX__IN_TCHARS ) + for (at = str.begin(); at < str.end(); at += TCHAR_AS_HEX__IN_TCHARS) { - strOut += hex_to_char( at, at + TCHAR_AS_HEX__IN_TCHARS ); + strOut += hex_to_char(at, at + TCHAR_AS_HEX__IN_TCHARS); } return strOut; } -TCHAR cCharEncoderUtil::hex_to_char( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +TCHAR cCharEncoderUtil::hex_to_char(TSTRING::const_iterator first, TSTRING::const_iterator last) { static const TCHAR max_char = std::numeric_limits::max(); static const TCHAR min_char = std::numeric_limits::min(); - if( first + TCHAR_AS_HEX__IN_TCHARS != last ) - ThrowAndAssert( eBadHexConversion() ); + if (first + TCHAR_AS_HEX__IN_TCHARS != last) + ThrowAndAssert(eBadHexConversion()); - TISTRINGSTREAM ss( TSTRING( first, last ) ); - ss.imbue( std::locale::classic() ); - ss.fill ( _T('0') ); - ss.setf( std::ios_base::hex, std::ios_base::basefield ); + TISTRINGSTREAM ss(TSTRING(first, last)); + ss.imbue(std::locale::classic()); + ss.fill(_T('0')); + ss.setf(std::ios_base::hex, std::ios_base::basefield); unsigned long ch; ss >> ch; - - if( ss.bad() || ss.fail() ) - ThrowAndAssert( eBadHexConversion( TSTRING( first, last ) ) ); - if( (TCHAR)ch > max_char || (TCHAR)ch < min_char ) - ThrowAndAssert( eBadHexConversion( TSTRING( first, last ) ) ); + + if (ss.bad() || ss.fail()) + ThrowAndAssert(eBadHexConversion(TSTRING(first, last))); + if ((TCHAR)ch > max_char || (TCHAR)ch < min_char) + ThrowAndAssert(eBadHexConversion(TSTRING(first, last))); return (TCHAR)ch; } -TSTRING cCharEncoderUtil::char_to_hex( TCHAR ch ) +TSTRING cCharEncoderUtil::char_to_hex(TCHAR ch) { TOSTRINGSTREAM ss; - ss.imbue( std::locale::classic() ); - ss.fill ( _T('0') ); - ss.width( TCHAR_AS_HEX__IN_TCHARS ); - ss.setf( std::ios_base::hex, std::ios_base::basefield ); + ss.imbue(std::locale::classic()); + ss.fill(_T('0')); + ss.width(TCHAR_AS_HEX__IN_TCHARS); + ss.setf(std::ios_base::hex, std::ios_base::basefield); - ss << tss::util::char_to_size( ch ); + ss << tss::util::char_to_size(ch); - if( ss.bad() || ss.fail() || - ss.str().length() != TCHAR_AS_HEX__IN_TCHARS ) - ThrowAndAssert( eBadHexConversion( TSTRING( 1, ch ) ) ); + if (ss.bad() || ss.fail() || ss.str().length() != TCHAR_AS_HEX__IN_TCHARS) + ThrowAndAssert(eBadHexConversion(TSTRING(1, ch))); return ss.str(); } -TSTRING cCharEncoderUtil::DecodeHexToChar( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ) +TSTRING cCharEncoderUtil::DecodeHexToChar(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end) { // get hex numbers -- 2 chars TSTRING str; - size_t n = 0; - for( (*pcur)++; - n < TCHAR_AS_HEX__IN_TCHARS && - (*pcur) != end; - n++, (*pcur)++ ) + size_t n = 0; + for ((*pcur)++; n < TCHAR_AS_HEX__IN_TCHARS && (*pcur) != end; n++, (*pcur)++) { str += *(*pcur); } - if( n != TCHAR_AS_HEX__IN_TCHARS ) - ThrowAndAssert( eBadDecoderInput() ); + if (n != TCHAR_AS_HEX__IN_TCHARS) + ThrowAndAssert(eBadDecoderInput()); // convert hex numbers - return HexValueToCharString( str ); + return HexValueToCharString(str); } ////////////////////////////////////////////////////////////////////////////// @@ -636,91 +562,86 @@ TSTRING cCharEncoderUtil::DecodeHexToChar( TSTRING::const_iterator* pcur, ////////////////////////////////////////////////////////////////////////////// -cEncoder::cEncoder( int e, int f ) - : m_fFlags( f ) +cEncoder::cEncoder(int e, int f) : m_fFlags(f) { // add encodings - if( e & NON_NARROWABLE ) - m_encodings.push_back( new cNonNarrowableCharEncoder ); - if( e & NON_PRINTABLE ) - m_encodings.push_back( new cNonPrintableCharEncoder( AllowWhiteSpace() ) ); - if( e & BACKSLASH ) - m_encodings.push_back( new cBackslashCharEncoder ); - if( e & DBL_QUOTE ) - m_encodings.push_back( new cQuoteCharEncoder ); - + if (e & NON_NARROWABLE) + m_encodings.push_back(new cNonNarrowableCharEncoder); + if (e & NON_PRINTABLE) + m_encodings.push_back(new cNonPrintableCharEncoder(AllowWhiteSpace())); + if (e & BACKSLASH) + m_encodings.push_back(new cBackslashCharEncoder); + if (e & DBL_QUOTE) + m_encodings.push_back(new cQuoteCharEncoder); + // assert that we weren't passed anything freaky - ASSERT( 0 == ( e & ~( NON_NARROWABLE | - NON_PRINTABLE | - BACKSLASH | - DBL_QUOTE ) ) ); + ASSERT(0 == (e & ~(NON_NARROWABLE | NON_PRINTABLE | BACKSLASH | DBL_QUOTE))); // add flags - ASSERT( ! ( ( m_fFlags & ROUNDTRIP ) && - ( m_fFlags & NON_ROUNDTRIP ) ) ); - + ASSERT(!((m_fFlags & ROUNDTRIP) && (m_fFlags & NON_ROUNDTRIP))); + #ifdef TSS_DO_SCHEMA_VALIDATION // check assumptions about encodings ValidateSchema(); #endif - } -cEncoder::~cEncoder() +cEncoder::~cEncoder() { + sack_type::iterator itr; + for (itr = m_encodings.begin(); itr != m_encodings.end(); ++itr) + delete *itr; } bool cEncoder::RoundTrip() const { - return( 0 != ( m_fFlags & ROUNDTRIP ) ); + return (0 != (m_fFlags & ROUNDTRIP)); } bool cEncoder::AllowWhiteSpace() const { - return( 0 != ( m_fFlags & ALLOW_WHITESPACE ) ); + return (0 != (m_fFlags & ALLOW_WHITESPACE)); } ////////////////////////////////////////////////////////////////////////////// // ENCODER BASIC FUNCTIONALITY ////////////////////////////////////////////////////////////////////////////// -void cEncoder::Encode( TSTRING& strIn ) const +void cEncoder::Encode(TSTRING& strIn) const { // TODO:BAM -- reserve space for strOut as an optimization? - TSTRING strOut; // encoded string we will build up + TSTRING strOut; // encoded string we will build up - TSTRING::const_iterator cur = strIn.begin(); // pointer to working position in strIn - const TSTRING::const_iterator end = strIn.end(); // end of strIn - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character + TSTRING::const_iterator cur = strIn.begin(); // pointer to working position in strIn + const TSTRING::const_iterator end = strIn.end(); // end of strIn + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character // while get next char (updates cur) - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { - bool fCharEncoded = false; // answers: did char need encoding? + bool fCharEncoded = false; // answers: did char need encoding? sack_type::const_iterator atE; // for all encoders - for( atE = m_encodings.begin(); - atE != m_encodings.end(); - atE++ ) + for (atE = m_encodings.begin(); atE != m_encodings.end(); atE++) { // does char need encoding? - if( (*atE)->NeedsEncoding( first, last ) ) + if ((*atE)->NeedsEncoding(first, last)) { - strOut += Encode( first, last, atE ); + strOut += Encode(first, last, atE); fCharEncoded = true; - break; // each char should only fail at most one - // encoding test, so it should be cool to quit + break; // each char should only fail at most one + // encoding test, so it should be cool to quit } } - if( ! fCharEncoded ) + if (!fCharEncoded) { - strOut.append( first, last ); // simply add current char to output since it needed no encoding + strOut.append(first, last); // simply add current char to output since it needed no encoding } } @@ -728,74 +649,70 @@ void cEncoder::Encode( TSTRING& strIn ) const strIn = strOut; } -TSTRING cEncoder::Encode( TSTRING::const_iterator first, - TSTRING::const_iterator last, - sack_type::const_iterator encoding ) const +TSTRING +cEncoder::Encode(TSTRING::const_iterator first, TSTRING::const_iterator last, sack_type::const_iterator encoding) const { - // encode it - if( RoundTrip() ) - return (*encoding)->EncodeRoundtrip( first, last ); + // encode it + if (RoundTrip()) + return (*encoding)->EncodeRoundtrip(first, last); else - return (*encoding)->EncodePretty( first, last ); + return (*encoding)->EncodePretty(first, last); } -void cEncoder::Decode( TSTRING& strIn ) const +void cEncoder::Decode(TSTRING& strIn) const { // TODO:BAM -- reserve space for strOut as an optimization? - TSTRING strOut; // decoded string we will build up + TSTRING strOut; // decoded string we will build up + + TSTRING::const_iterator cur = strIn.begin(); // pointer to working position in strIn + const TSTRING::const_iterator end = strIn.end(); // end of strIn + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character - TSTRING::const_iterator cur = strIn.begin(); // pointer to working position in strIn - const TSTRING::const_iterator end = strIn.end(); // end of strIn - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character - // while get next char (updates cur) - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { // is this char the escape character? - if( IsSingleTCHAR( first, last ) && - *first == iCharEncoder::EscapeChar() ) + if (IsSingleTCHAR(first, last) && *first == iCharEncoder::EscapeChar()) { // get to identifier - if( ! cCharUtil::PopNextChar( cur, end, first, last ) ) - ThrowAndAssert( eBadDecoderInput() ); - + if (!cCharUtil::PopNextChar(cur, end, first, last)) + ThrowAndAssert(eBadDecoderInput()); + // this algorithm assumes that all identifiers are single char - // so anything following the escape char should be a + // so anything following the escape char should be a // single-char identifier - if( ! IsSingleTCHAR( first, last ) ) - THROW_INTERNAL( "displayencoder.cpp" ); + if (!IsSingleTCHAR(first, last)) + THROW_INTERNAL("displayencoder.cpp"); // determine to which encoding the identifier belongs - bool fFoundEncoding = false; + bool fFoundEncoding = false; sack_type::const_iterator atE; - for( atE = m_encodings.begin(); - atE != m_encodings.end(); - atE++ ) + for (atE = m_encodings.begin(); atE != m_encodings.end(); atE++) { // is this the right encoding? - if( *first == (*atE)->Identifier() ) + if (*first == (*atE)->Identifier()) { // this is the correct encoding.... fFoundEncoding = true; // ...so decode char - strOut += (*atE)->Decode( &first, end ); // should modify cur - + strOut += (*atE)->Decode(&first, end); // should modify cur + cur = first; // advance current char pointer - break; // no need to run other tests after - // this because all identifiers should be unique + break; // no need to run other tests after + // this because all identifiers should be unique } } - if( ! fFoundEncoding ) - ThrowAndAssert( eUnknownEscapeEncoding( TSTRING( 1, *first ) ) ); + if (!fFoundEncoding) + ThrowAndAssert(eUnknownEscapeEncoding(TSTRING(1, *first))); } else - { - strOut.append( first, last ); + { + strOut.append(first, last); } } @@ -808,8 +725,8 @@ void cEncoder::Decode( TSTRING& strIn ) const void cEncoder::ValidateSchema() const { - ASSERT( OnlyOneCatagoryPerChar() ); - ASSERT( AllIdentifiersUnique() ); + ASSERT(OnlyOneCatagoryPerChar()); + ASSERT(AllIdentifiersUnique()); } @@ -817,29 +734,28 @@ void cEncoder::ValidateSchema() const bool cEncoder::OnlyOneCatagoryPerChar() const { // TODO:BAM - man, is there a better way to do this? - TCHAR ch = std::numeric_limits::min(); - TSTRING ach(1,ch); + TCHAR ch = std::numeric_limits::min(); + TSTRING ach(1, ch); - if( ch != std::numeric_limits::max() ) + if (ch != std::numeric_limits::max()) { do { bool fFailedATest = false; ach[0] = ch; - for( sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++ ) + for (sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++) { - if( (*atE)->NeedsEncoding( ach.begin(), ach.end() ) ) + if ((*atE)->NeedsEncoding(ach.begin(), ach.end())) { - if( fFailedATest ) + if (fFailedATest) return false; // each char can only fail one test else fFailedATest = true; } } ch++; - } - while( ch != std::numeric_limits::max() ); + } while (ch != std::numeric_limits::max()); } return true; } @@ -848,10 +764,10 @@ bool cEncoder::OnlyOneCatagoryPerChar() const bool cEncoder::AllIdentifiersUnique() const { TSTRING chars; - for( sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++ ) + for (sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++) { TCHAR chID = (*atE)->Identifier(); - if( chars.find( chID ) == TSTRING::npos ) + if (chars.find(chID) == TSTRING::npos) chars += chID; else return false; @@ -860,23 +776,21 @@ bool cEncoder::AllIdentifiersUnique() const } -bool cEncoder::AllTestsRunOnEncodedString( const TSTRING& s ) const +bool cEncoder::AllTestsRunOnEncodedString(const TSTRING& s) const { - TSTRING::const_iterator cur = s.begin(); // pointer to working position in s - const TSTRING::const_iterator end = s.end(); // end of s - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character - + TSTRING::const_iterator cur = s.begin(); // pointer to working position in s + const TSTRING::const_iterator end = s.end(); // end of s + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character + // while get next char (updates cur) - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { sack_type::const_iterator atE; - for( atE = m_encodings.begin(); - atE != m_encodings.end(); - atE++ ) + for (atE = m_encodings.begin(); atE != m_encodings.end(); atE++) { - if( (*atE)->NeedsEncoding( first, last ) ) + if ((*atE)->NeedsEncoding(first, last)) { return false; } @@ -892,25 +806,17 @@ bool cEncoder::AllTestsRunOnEncodedString( const TSTRING& s ) const ////////////////////////////////////////////////////////////////////////////// -cDisplayEncoder::cDisplayEncoder( Flags f ) - : cEncoder( - NON_NARROWABLE | - NON_PRINTABLE | - BACKSLASH | - DBL_QUOTE, - f - ) +cDisplayEncoder::cDisplayEncoder(Flags f) : cEncoder(NON_NARROWABLE | NON_PRINTABLE | BACKSLASH | DBL_QUOTE, f) { } -void cDisplayEncoder::Encode( TSTRING& str ) const +void cDisplayEncoder::Encode(TSTRING& str) const { - cEncoder::Encode( str ); + cEncoder::Encode(str); } -bool cDisplayEncoder::Decode( TSTRING& str ) const +bool cDisplayEncoder::Decode(TSTRING& str) const { - cEncoder::Decode( str ); + cEncoder::Decode(str); return true; // TODO:BAM -- throw error! } - diff --git a/src/core/displayencoder.h b/src/core/displayencoder.h index fb8a775..8971fdc 100644 --- a/src/core/displayencoder.h +++ b/src/core/displayencoder.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,10 +40,10 @@ // EXCEPTION DECLARATION //========================================================================= -TSS_EXCEPTION( eEncoder, eError ); -TSS_EXCEPTION( eBadDecoderInput, eEncoder ); -TSS_EXCEPTION( eBadHexConversion, eEncoder ); -TSS_EXCEPTION( eUnknownEscapeEncoding, eEncoder ); +TSS_EXCEPTION(eEncoder, eError); +TSS_EXCEPTION(eBadDecoderInput, eEncoder); +TSS_EXCEPTION(eBadHexConversion, eEncoder); +TSS_EXCEPTION(eUnknownEscapeEncoding, eEncoder); //========================================================================= // DECLARATION OF CLASSES @@ -55,106 +55,101 @@ TSS_EXCEPTION( eUnknownEscapeEncoding, eEncoder ); class iCharEncoder; -// TODO:BAM -- i don't think that the order of encodings is important +// TODO:BAM -- i don't think that the order of encodings is important // as long as AllIdentifiersUnique and OnlyOneCatagoryPerChar are true class cEncoder { - public: - enum Encodings - { - NON_NARROWABLE = 0x01, // WC -> MB, MB alway narrowable: - NON_PRINTABLE = 0x02, - BACKSLASH = 0x04, - DBL_QUOTE = 0x08 - }; - - enum Flags - { - ROUNDTRIP = 0x01, - NON_ROUNDTRIP = 0x02, - ALLOW_WHITESPACE = 0x04 - }; - - cEncoder( int e, int f ); // mask of Encodings - virtual ~cEncoder(); - - void Encode( TSTRING& str ) const; - void Decode( TSTRING& str ) const; // TODO:BAM -- throw error! - - void ValidateSchema() const; - bool OnlyOneCatagoryPerChar() const; - bool AllIdentifiersUnique() const; - bool AllTestsRunOnEncodedString( const TSTRING& str ) const; - - private: - typedef std::vector< iCharEncoder* > sack_type; - - TSTRING Encode( TSTRING::const_iterator first, - TSTRING::const_iterator last, - sack_type::const_iterator encoding ) const; - - bool RoundTrip() const; - bool AllowWhiteSpace() const; - - sack_type m_encodings; - int m_fFlags; +public: + enum Encodings + { + NON_NARROWABLE = 0x01, // WC -> MB, MB alway narrowable: + NON_PRINTABLE = 0x02, + BACKSLASH = 0x04, + DBL_QUOTE = 0x08 + }; + + enum Flags + { + ROUNDTRIP = 0x01, + NON_ROUNDTRIP = 0x02, + ALLOW_WHITESPACE = 0x04 + }; + + cEncoder(int e, int f); // mask of Encodings + virtual ~cEncoder(); + + void Encode(TSTRING& str) const; + void Decode(TSTRING& str) const; // TODO:BAM -- throw error! + + void ValidateSchema() const; + bool OnlyOneCatagoryPerChar() const; + bool AllIdentifiersUnique() const; + bool AllTestsRunOnEncodedString(const TSTRING& str) const; + +private: + typedef std::vector sack_type; + + TSTRING + Encode(TSTRING::const_iterator first, TSTRING::const_iterator last, sack_type::const_iterator encoding) const; + + bool RoundTrip() const; + bool AllowWhiteSpace() const; + + sack_type m_encodings; + int m_fFlags; }; // encodes ( BACKSLASH | DBL_QUOTE | NON_NARROWABLE | NON_PRINTABLE ) class cDisplayEncoder : public cEncoder { - public: - cDisplayEncoder( Flags f = NON_ROUNDTRIP ); - - void Encode( TSTRING& str ) const; - bool Decode( TSTRING& str ) const; - - static TSTRING EncodeInline( const TSTRING& sIn ) - { - TSTRING sOut = sIn; - cDisplayEncoder e; - e.Encode( sOut ); - return sOut; - } - - static TSTRING EncodeInlineAllowWS( const TSTRING& sIn ) - { - TSTRING sOut = sIn; - cDisplayEncoder e( (Flags)( NON_ROUNDTRIP | ALLOW_WHITESPACE ) ); - e.Encode( sOut ); - return sOut; - } +public: + cDisplayEncoder(Flags f = NON_ROUNDTRIP); + + void Encode(TSTRING& str) const; + bool Decode(TSTRING& str) const; + + static TSTRING EncodeInline(const TSTRING& sIn) + { + TSTRING sOut = sIn; + cDisplayEncoder e; + e.Encode(sOut); + return sOut; + } + + static TSTRING EncodeInlineAllowWS(const TSTRING& sIn) + { + TSTRING sOut = sIn; + cDisplayEncoder e((Flags)(NON_ROUNDTRIP | ALLOW_WHITESPACE)); + e.Encode(sOut); + return sOut; + } }; - class cCharEncoderUtil { - public: - - static bool IsPrintable( TCHAR ch ); - static bool IsWhiteSpace( TCHAR ch ); +public: + static bool IsPrintable(TCHAR ch); + static bool IsWhiteSpace(TCHAR ch); - static TSTRING CharStringToHexValue( const TSTRING& str ); + static TSTRING CharStringToHexValue(const TSTRING& str); - static TSTRING HexValueToCharString( const TSTRING& str ); + static TSTRING HexValueToCharString(const TSTRING& str); - static TCHAR hex_to_char( TSTRING::const_iterator first, - TSTRING::const_iterator last ); + static TCHAR hex_to_char(TSTRING::const_iterator first, TSTRING::const_iterator last); - static TSTRING char_to_hex( TCHAR ch ); + static TSTRING char_to_hex(TCHAR ch); - static TSTRING DecodeHexToChar( TSTRING::const_iterator* pcur, - const TSTRING::const_iterator end ); + static TSTRING DecodeHexToChar(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end); - enum - { - BYTE_AS_HEX__IN_TCHARS = 2, - BYTES_PER_TCHAR = sizeof( TCHAR ), - TCHAR_AS_HEX__IN_TCHARS = BYTE_AS_HEX__IN_TCHARS * BYTES_PER_TCHAR - }; + enum + { + BYTE_AS_HEX__IN_TCHARS = 2, + BYTES_PER_TCHAR = sizeof(TCHAR), + TCHAR_AS_HEX__IN_TCHARS = BYTE_AS_HEX__IN_TCHARS * BYTES_PER_TCHAR + }; }; #endif //__DISPLAYENCODER_H @@ -241,4 +236,3 @@ typedef cDisplayEncoder_ cDisplayEncoder; #endif //__DISPLAYENCODER_H */ - diff --git a/src/core/displayutil.cpp b/src/core/displayutil.cpp index aa45571..a005446 100644 --- a/src/core/displayutil.cpp +++ b/src/core/displayutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,29 +40,29 @@ #include "ntmbs.h" #include -TSTRING cDisplayUtil::FormatMultiLineString( const TSTRING& str, int nOffset, int nWidth ) +TSTRING cDisplayUtil::FormatMultiLineString(const TSTRING& str, int nOffset, int nWidth) { TOSTRINGSTREAM sstr; - TSTRING strT; - bool fFirstLine = true; - for( TSTRING::const_iterator i = str.begin(); i != str.end(); i = *i ? i + 1 : i ) + TSTRING strT; + bool fFirstLine = true; + for (TSTRING::const_iterator i = str.begin(); i != str.end(); i = *i ? i + 1 : i) { // return found -- add line to output string - if( _T('\n') == *i ) + if (_T('\n') == *i) { // only do offset for strings after the first - if( fFirstLine ) + if (fFirstLine) { fFirstLine = false; } else - { + { // add offset - for( int j = 0; j < nOffset; j++ ) + for (int j = 0; j < nOffset; j++) sstr << _T(" "); // set width - sstr << std::setw( nWidth ); + sstr << std::setw(nWidth); } // add to stringstream @@ -73,28 +73,26 @@ TSTRING cDisplayUtil::FormatMultiLineString( const TSTRING& str, int nOffset, in } else { - // add char to string - strT.append( i, (TSTRING::const_iterator)(*i ? i + 1 : i) ); + // add char to string + strT.append(i, (TSTRING::const_iterator)(*i ? i + 1 : i)); } - } - - // add last portion -- no endl + } + + // add last portion -- no endl // we want our client to be able to say "out << PropAsString() << endl;" // add offset - if( ! fFirstLine ) + if (!fFirstLine) { - for( int j = 0; j < nOffset; j++ ) + for (int j = 0; j < nOffset; j++) sstr << _T(" "); } // set width - sstr << std::setw( nWidth ); + sstr << std::setw(nWidth); // now add last string sstr << strT; - return( sstr.str() ); + return (sstr.str()); } - -// eof: displayutil.cpp diff --git a/src/core/displayutil.h b/src/core/displayutil.h index e9ab6a6..fc24804 100644 --- a/src/core/displayutil.h +++ b/src/core/displayutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,7 @@ class cDisplayUtil { public: - static TSTRING FormatMultiLineString( const TSTRING& str, int nOffset, int nWidth ); + static TSTRING FormatMultiLineString(const TSTRING& str, int nOffset, int nWidth); }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -61,18 +61,18 @@ class cDisplayUtil // // What happens is that you get output like: // " First Line" -// ^ ^^ ^ +// ^ ^^ ^ // |--10 sp-||---15 width--| // "Second Line" -// ^ +// ^ // | 0 sp, 0 width // // When you really wanted: // " First Line" -// ^ ^^ ^ +// ^ ^^ ^ // |--10 sp-||---15 width--| // " Second Line" -// ^ ^^ ^ +// ^ ^^ ^ // |--10 sp-||---15 width--| // // @@ -84,13 +84,13 @@ class cDisplayUtil // So you can output a multiline string and have each line be formatted // like the first one was. // -// So, for the preceeding example, +// So, for the preceeding example, // // change: // TCOUT << szTenSpaceMargin << setw(15) << szMessage; // // to: -// TCOUT << szTenSpaceMargin << setw(15) +// TCOUT << szTenSpaceMargin << setw(15) // << cDisplayUtil::FormatMultiLineString( szMessage, 10, 15 ); // // Comprende? It's crazy but it works. @@ -98,4 +98,3 @@ class cDisplayUtil // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #endif // #ifndef __DISPLAYUTIL_H - diff --git a/src/core/timebomb.cpp b/src/core/epoch.cpp similarity index 68% rename from src/core/timebomb.cpp rename to src/core/epoch.cpp index 5d023eb..53efb6f 100644 --- a/src/core/timebomb.cpp +++ b/src/core/epoch.cpp @@ -1,80 +1,57 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// timebomb.h +// epoch.h #include "stdcore.h" -#include "timebomb.h" +#include "epoch.h" #include #include #include "timeconvert.h" #include "corestrings.h" /////////////////////////////////////////////////////////////////////////////// -// TimeBombExploded() -- Call from main(). Prints out timebomb message and -// returns true if main() should exit. -// -bool TimeBombExploded() +bool CheckEpoch() { - struct tm time_struct; +#if SIZEOF_TIME_T == 4 - /* - memset(&time_struct, 0, sizeof(time_struct)); - time_struct.tm_mday = 25; - time_struct.tm_mon = 0; - time_struct.tm_year = 99; - int64 begin = cTimeUtil::DateToTime( &time_struct ); - - memset(&time_struct, 0, sizeof(time_struct)); - time_struct.tm_mday = 1; - time_struct.tm_mon = 4; - time_struct.tm_year = 99; - int64 end = cTimeUtil::DateToTime( &time_struct ); - - int64 now = time(0); - - if (now < begin || now > end) - { - std::cerr << "This beta version of Tripwire(R) has expired.\n"; - return true; - } - */ + struct tm time_struct; // Many functions will fail as we approach the end of the epoch // Rather than crashing, we will exit with a nice message memset(&time_struct, 0, sizeof(time_struct)); time_struct.tm_mday = 1; - time_struct.tm_mon = 0; + time_struct.tm_mon = 0; time_struct.tm_year = 138; - int64 endoftime = cTimeUtil::DateToTime( &time_struct ); + int64 endoftime = cTimeUtil::DateToTime(&time_struct); if (time(0) > endoftime) { @@ -83,5 +60,7 @@ bool TimeBombExploded() } return false; +#else + return false; +#endif } - diff --git a/src/core/timebomb.h b/src/core/epoch.h similarity index 86% rename from src/core/timebomb.h rename to src/core/epoch.h index b9030bc..196b5e4 100644 --- a/src/core/timebomb.h +++ b/src/core/epoch.h @@ -1,45 +1,44 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// timebomb.h +// epoch.h -#ifndef __TIMEBOMB_H -#define __TIMEBOMB_H +#ifndef __EPOCH_H +#define __EPOCH_H /////////////////////////////////////////////////////////////////////////////// -// TimeBombExploded() -- Call from main(). Prints out timebomb message and +// CheckEpoch() -- Call from main(). Prints out timebomb message and // returns true if main() should exit. // -bool TimeBombExploded(); +bool CheckEpoch(); #endif - diff --git a/src/core/error.cpp b/src/core/error.cpp index 5c20c23..0c3d5d1 100644 --- a/src/core/error.cpp +++ b/src/core/error.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,13 +39,11 @@ /////////////////////////////////////////////////////////////////////////////// // CalcHash /////////////////////////////////////////////////////////////////////////////// -uint32 eError::CalcHash( const char* name ) +uint32 eError::CalcHash(const char* name) { CRC_INFO crc; - crcInit( crc ); - crcUpdate( crc, (const uint8*)name, strlen( name ) ); - crcFinit( crc ); + crcInit(crc); + crcUpdate(crc, (const uint8*)name, strlen(name)); + crcFinit(crc); return crc.crc; } - - diff --git a/src/core/error.h b/src/core/error.h index bb73cbd..a6a3437 100644 --- a/src/core/error.h +++ b/src/core/error.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,14 +42,13 @@ class eError { public: - //------------------------------------------------------------------------- // Construction and Assignment //------------------------------------------------------------------------- - eError( const TSTRING& msg, uint32 flags = 0 ); - explicit eError( const eError& rhs ); - explicit eError(); - void operator=( const eError& rhs ); + eError(const TSTRING& msg, uint32 flags = 0); + explicit eError(const eError& rhs); + explicit eError(); + void operator=(const eError& rhs); //------------------------------------------------------------------------- // Destruction @@ -60,54 +59,54 @@ class eError // Data Access //------------------------------------------------------------------------- virtual uint32 GetID() const = 0; - // returns a system wide unique identifier for this exception. See the - // macro below for the typical implementation of this method. - // This is used to associate the error with a string description of the - // error via the global error table. + // returns a system wide unique identifier for this exception. See the + // macro below for the typical implementation of this method. + // This is used to associate the error with a string description of the + // error via the global error table. virtual TSTRING GetMsg() const; - // returns specific information about the error that occured. Provides - // additional information about the error described by GetID(). It should - // not provide any information redundant with GetID(). - // - // The string passed to the constructor should be formated properly to - // be displayed as the "Second" part of an error message, or the derived - // class should override GetMsg() and return a string appropriate for display. - + // returns specific information about the error that occured. Provides + // additional information about the error described by GetID(). It should + // not provide any information redundant with GetID(). + // + // The string passed to the constructor should be formated properly to + // be displayed as the "Second" part of an error message, or the derived + // class should override GetMsg() and return a string appropriate for display. + uint32 GetFlags() const; - // Flags are defined below. Currently, these only have an impact on how errors are - // displayed. + // Flags are defined below. Currently, these only have an impact on how errors are + // displayed. //------------------------------------------------------------------------- // Flags //------------------------------------------------------------------------- enum Flag { - NON_FATAL = 0x00000001, // displays "Error" or "Warning" ? - SUPRESS_THIRD_MSG = 0x00000002 // supresses the "continuing" or "exiting" message + NON_FATAL = 0x00000001, // displays "Error" or "Warning" ? + SUPRESS_THIRD_MSG = 0x00000002 // supresses the "continuing" or "exiting" message }; - void SetFlags( uint32 flags ); + void SetFlags(uint32 flags); //------------------------------------------------------------------------- // Flag Convenience Methods //------------------------------------------------------------------------- - void SetFatality(bool fatal); - bool IsFatal() const; - // Fatality is set to true by default when eError is constructed. But when an error - // it is put in an cErrorBucket chain it the code doing so may wish to set the fatality - // to non-fatal to indicate that the error is actually a warning and program flow - // is going to continue. - void SetSupressThird(bool supressThird); - bool SupressThird() const; + void SetFatality(bool fatal); + bool IsFatal() const; + // Fatality is set to true by default when eError is constructed. But when an error + // it is put in an cErrorBucket chain it the code doing so may wish to set the fatality + // to non-fatal to indicate that the error is actually a warning and program flow + // is going to continue. + void SetSupressThird(bool supressThird); + bool SupressThird() const; //------------------------------------------------------------------------- // Utility Methods //------------------------------------------------------------------------- - static uint32 CalcHash( const char* name ); - // calculates the CRC32 of the string passed in as name. This methods - // asserts that name is non null. This is used to generate unique IDs - // for errors. + static uint32 CalcHash(const char* name); + // calculates the CRC32 of the string passed in as name. This methods + // asserts that name is non null. This is used to generate unique IDs + // for errors. //------------------------------------------------------------------------- // Private Implementation @@ -124,62 +123,69 @@ class eError /////////////////////////////////////////////////////////////////////////////// // TSS_BEGIN_EXCEPTION / TSS_END_EXCEPTION // -// Serves the same purpose as TSS_EXCEPTION but allows custom data and methods +// Serves the same purpose as TSS_EXCEPTION but allows custom data and methods // to be added to the exception class. /////////////////////////////////////////////////////////////////////////////// #if HAVE_GCC -#define TSS_BEGIN_EXCEPTION_EXPLICIT +# define TSS_BEGIN_EXCEPTION_EXPLICIT #else -#define TSS_BEGIN_EXCEPTION_EXPLICIT explicit +# define TSS_BEGIN_EXCEPTION_EXPLICIT explicit #endif -#define TSS_BEGIN_EXCEPTION( except, base ) \ - class except : public base \ - {\ - public:\ - except( const TSTRING& msg, uint32 flags = 0 ) \ - : base( msg, flags ) {} \ - TSS_BEGIN_EXCEPTION_EXPLICIT except( const except& rhs ) \ - : base( rhs ) {} \ - explicit except() : base() {} \ - \ - virtual uint32 GetID() const \ - {\ - return CalcHash( #except ); \ - }\ - -#define TSS_END_EXCEPTION( ) \ - }; +#define TSS_BEGIN_EXCEPTION(except, base) \ + class except : public base \ + { \ + public: \ + except(const TSTRING& msg, uint32 flags = 0) : base(msg, flags) \ + { \ + } \ + TSS_BEGIN_EXCEPTION_EXPLICIT except(const except& rhs) : base(rhs) \ + { \ + } \ + explicit except() : base() \ + { \ + } \ + \ + virtual uint32 GetID() const \ + { \ + return CalcHash(#except); \ + } + +#define TSS_END_EXCEPTION() \ + } \ + ; /////////////////////////////////////////////////////////////////////////////// // TSS_BEGIN_EXCEPTION_NO_CTOR // // Same as TSS_BEGIN_EXCEPTION, but doesn't define any ctors. /////////////////////////////////////////////////////////////////////////////// -#define TSS_BEGIN_EXCEPTION_NO_CTOR( except, base ) \ - class except : public base \ - {\ - public:\ - explicit except() : base() {} \ - \ - virtual uint32 GetID() const \ - {\ - return CalcHash( #except ); \ - }\ +#define TSS_BEGIN_EXCEPTION_NO_CTOR(except, base) \ + class except : public base \ + { \ + public: \ + explicit except() : base() \ + { \ + } \ + \ + virtual uint32 GetID() const \ + { \ + return CalcHash(#except); \ + } /////////////////////////////////////////////////////////////////////////////// // TSS_EXCEPTION // // This is a convenience define for quickly defining an exception class. After -// defining a new exception, don't forget to add it to the package's error +// defining a new exception, don't forget to add it to the package's error // string file! // -// TODO (mdb) -- do we want to cache the CRC? if we store it in a class static +// TODO (mdb) -- do we want to cache the CRC? if we store it in a class static // variable, then we will need to define it in the cpp file as well ... /////////////////////////////////////////////////////////////////////////////// -#define TSS_EXCEPTION( except, base ) \ - TSS_BEGIN_EXCEPTION( except, base ) \ +#define TSS_EXCEPTION(except, base) \ + TSS_BEGIN_EXCEPTION(except, base) \ TSS_END_EXCEPTION() //----------------------------------------------------------------------------- @@ -189,41 +195,32 @@ class eError /////////////////////////////////////////////////////////////////////////////// // eError /////////////////////////////////////////////////////////////////////////////// -inline eError::eError( const TSTRING& msg, uint32 flags ) -: mMsg ( msg ), - mFlags ( flags ) +inline eError::eError(const TSTRING& msg, uint32 flags) : mMsg(msg), mFlags(flags) { - } /////////////////////////////////////////////////////////////////////////////// // eError /////////////////////////////////////////////////////////////////////////////// -inline eError::eError( const eError& rhs ) -: mMsg ( rhs.mMsg ), - mFlags ( rhs.mFlags ) +inline eError::eError(const eError& rhs) : mMsg(rhs.mMsg), mFlags(rhs.mFlags) { - } /////////////////////////////////////////////////////////////////////////////// // eError /////////////////////////////////////////////////////////////////////////////// -inline eError::eError( ) -: mMsg ( _T("") ), - mFlags ( 0 ) +inline eError::eError() : mMsg(_T("")), mFlags(0) { - } /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -inline void eError::operator=( const eError& rhs ) +inline void eError::operator=(const eError& rhs) { - mMsg = rhs.mMsg; - mFlags = rhs.mFlags; + mMsg = rhs.mMsg; + mFlags = rhs.mFlags; } /////////////////////////////////////////////////////////////////////////////// @@ -231,7 +228,6 @@ inline void eError::operator=( const eError& rhs ) /////////////////////////////////////////////////////////////////////////////// inline eError::~eError() { - } /////////////////////////////////////////////////////////////////////////////// @@ -239,7 +235,7 @@ inline eError::~eError() /////////////////////////////////////////////////////////////////////////////// inline TSTRING eError::GetMsg() const { - return mMsg; + return mMsg; } /////////////////////////////////////////////////////////////////////////////// @@ -253,9 +249,9 @@ inline uint32 eError::GetFlags() const /////////////////////////////////////////////////////////////////////////////// // SetFlags /////////////////////////////////////////////////////////////////////////////// -inline void eError::SetFlags( uint32 flags ) +inline void eError::SetFlags(uint32 flags) { - mFlags = flags; + mFlags = flags; } /////////////////////////////////////////////////////////////////////////////// @@ -275,7 +271,6 @@ inline void eError::SetFatality(bool fatal) inline bool eError::IsFatal() const { return (mFlags & (uint32)NON_FATAL) == 0; - } /////////////////////////////////////////////////////////////////////////////// @@ -298,6 +293,4 @@ inline bool eError::SupressThird() const } - #endif //__ERROR_H - diff --git a/src/core/errorbucket.h b/src/core/errorbucket.h index d9f5ac6..8f2385e 100644 --- a/src/core/errorbucket.h +++ b/src/core/errorbucket.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,32 +46,34 @@ class eError; /////////////////////////////////////////////////////////////////////////////// -// cErrorBucket -- contains an interface that handles error reporting, and -// contains a link to a child bucket. Each concrete implementation of the +// cErrorBucket -- contains an interface that handles error reporting, and +// contains a link to a child bucket. Each concrete implementation of the // cErrorBucket interface will perform its own specific task related to the // error's occurence (print to stderr, store in a queue, etc) and then forward -// the error on to its child link. The parent bucket does not own the destruction +// the error on to its child link. The parent bucket does not own the destruction // of the pointer to the child bucket. /////////////////////////////////////////////////////////////////////////////// class cErrorBucket { public: cErrorBucket(); - virtual ~cErrorBucket() {} + virtual ~cErrorBucket() + { + } virtual void AddError(const eError& error); - // add an error to the bucket + // add an error to the bucket cErrorBucket* GetChild(); - // returns the bucket that the current bucket is chained to, or - // NULL if nothing is attached to it. + // returns the bucket that the current bucket is chained to, or + // NULL if nothing is attached to it. cErrorBucket* SetChild(cErrorBucket* pNewChild); - // sets the child link of this bucket; returns the old link value + // sets the child link of this bucket; returns the old link value protected: virtual void HandleError(const eError& error) = 0; - // override this to implement error handling functionality specific to - // the derived class + // override this to implement error handling functionality specific to + // the derived class cErrorBucket* mpChild; }; @@ -81,8 +83,7 @@ class cErrorBucket /////////////////// // cErrorBucket /////////////////// -inline cErrorBucket::cErrorBucket() : - mpChild(0) +inline cErrorBucket::cErrorBucket() : mpChild(0) { } @@ -94,9 +95,8 @@ inline cErrorBucket* cErrorBucket::GetChild() inline cErrorBucket* cErrorBucket::SetChild(cErrorBucket* pNewChild) { cErrorBucket* pOldChild = mpChild; - mpChild = pNewChild; + mpChild = pNewChild; return pOldChild; } #endif - diff --git a/src/core/errorbucketimpl.cpp b/src/core/errorbucketimpl.cpp index 523720d..15298d3 100644 --- a/src/core/errorbucketimpl.cpp +++ b/src/core/errorbucketimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,7 +43,7 @@ void cErrorBucket::AddError(const eError& error) { HandleError(error); - if(mpChild) + if (mpChild) mpChild->AddError(error); } @@ -52,10 +52,8 @@ void cErrorBucket::AddError(const eError& error) //############################################################################# void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) { - cDisplayEncoder e( - (cDisplayEncoder::Flags) ( cDisplayEncoder::NON_ROUNDTRIP | - cDisplayEncoder::ALLOW_WHITESPACE ) ); - TSTRING errStr; + cDisplayEncoder e((cDisplayEncoder::Flags)(cDisplayEncoder::NON_ROUNDTRIP | cDisplayEncoder::ALLOW_WHITESPACE)); + TSTRING errStr; // // if the ID is zero, just return. @@ -68,19 +66,18 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) // point is when we throw ePoly() with no constructor arguments. At some point we want // to stop using the mechanism have non-printing errors, thus we leave in the ASSERT below. // But we don't want to break any release code, thus we return on the next line - June 2, 1999 DMB. - ASSERT( error.GetID() != 0 ); + ASSERT(error.GetID() != 0); - if( error.GetID() == 0 ) + if (error.GetID() == 0) return; // "First Part" header - errStr = TSS_GetString( cCore, error.IsFatal() ? core::STR_ERROR_ERROR - : core::STR_ERROR_WARNING ); + errStr = TSS_GetString(cCore, error.IsFatal() ? core::STR_ERROR_ERROR : core::STR_ERROR_WARNING); if (errStr.empty()) { TOSTRINGSTREAM strm; - ASSERT( sizeof( uint32 ) == sizeof(unsigned int) ); // for cast on next line + ASSERT(sizeof(uint32) == sizeof(unsigned int)); // for cast on next line strm << _T("Unknown Error ID ") << (unsigned int)error.GetID(); errStr = strm.str(); } @@ -91,10 +88,10 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) // "First Part" error string TSTRING prependToSecond; -// #pragma message("errorbucketimpl.cpp needs a little help in the mb arena, with the findfirst/last and such") + // #pragma message("errorbucketimpl.cpp needs a little help in the mb arena, with the findfirst/last and such") - errStr = cErrorTable::GetInstance()->Get( error.GetID() ); - if(! errStr.empty()) + errStr = cErrorTable::GetInstance()->Get(error.GetID()); + if (!errStr.empty()) { // If the first part has a '\n' in it, we take everything following and prepend it to the // second part. This was added to allow specifing a verbose string as the second part @@ -108,7 +105,7 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) ASSERT(errStr.length() + len + 6 < 80); // line too big for terminal? // Add 6 to account for "### ' and ': ' - TCERR << TSS_GetString( cCore, core::STR_ERROR_COLON ) << _T(" ") << errStr; + TCERR << TSS_GetString(cCore, core::STR_ERROR_COLON) << _T(" ") << errStr; TCERR << std::endl; } @@ -117,14 +114,14 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) const TCHAR SPACE = _T(' '); errStr = prependToSecond + error.GetMsg() + strExtra; - e.Encode( errStr ); - if (! errStr.empty()) + e.Encode(errStr); + if (!errStr.empty()) { - do + do { // look for newline chars TSTRING::size_type firstNewLine; - TSTRING currentStr = errStr.substr(0, (firstNewLine = errStr.find_first_of(_T('\n')))); + TSTRING currentStr = errStr.substr(0, (firstNewLine = errStr.find_first_of(_T('\n')))); errStr.erase(0, (firstNewLine < errStr.length() ? firstNewLine + 1 : firstNewLine)); // break up the error string in case it is larger than screen width @@ -132,11 +129,12 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) { if (currentStr.length() <= (unsigned int)WIDTH) { - TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER ) << currentStr << std::endl; + TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER) << currentStr << std::endl; break; } - TSTRING::size_type lastSpace = currentStr.find_last_of(SPACE, currentStr.length() >= WIDTH - 1 ? WIDTH - 1 : TSTRING::npos); + TSTRING::size_type lastSpace = + currentStr.find_last_of(SPACE, currentStr.length() >= WIDTH - 1 ? WIDTH - 1 : TSTRING::npos); if (lastSpace == TSTRING::npos) { // can't find space to break at so this string will just have to be longer than screen width. @@ -148,28 +146,21 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) lastSpace = currentStr.length(); } - TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER ) - << currentStr.substr( 0, lastSpace ) - << std::endl; + TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER) << currentStr.substr(0, lastSpace) << std::endl; - currentStr.erase( 0, lastSpace + 1 ); - } - while ( !currentStr.empty() ); - } - while ( !errStr.empty() ); + currentStr.erase(0, lastSpace + 1); + } while (!currentStr.empty()); + } while (!errStr.empty()); } // "Third Part" print 'exiting' or 'continuing' // note that we supress this part if the appropriate flag is set... // - if( (error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0 ) + if ((error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0) { - TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER) - << TSS_GetString( - cCore, - error.IsFatal() - ? core::STR_ERROR_EXITING - : core::STR_ERROR_CONTINUING ) << std::endl; + TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER) + << TSS_GetString(cCore, error.IsFatal() ? core::STR_ERROR_EXITING : core::STR_ERROR_CONTINUING) + << std::endl; } } @@ -185,9 +176,7 @@ void cErrorTracer::HandleError(const eError& error) { cDebug d("cErrorTracer::HandleError"); - d.TraceError( _T("%s : %s\n"), - cErrorTable::GetInstance()->Get( error.GetID() ).c_str(), - error.GetMsg().c_str() ); + d.TraceError(_T("%s : %s\n"), cErrorTable::GetInstance()->Get(error.GetID()).c_str(), error.GetMsg().c_str()); } //############################################################################# @@ -207,17 +196,15 @@ int cErrorQueue::GetNumErrors() const void cErrorQueue::HandleError(const eError& error) { - mList.push_back( ePoly( error ) ); + mList.push_back(ePoly(error)); } -cErrorQueueIter::cErrorQueueIter(cErrorQueue& queue) : - mList(queue.mList) +cErrorQueueIter::cErrorQueueIter(cErrorQueue& queue) : mList(queue.mList) { SeekBegin(); } -cErrorQueueIter::cErrorQueueIter(const cErrorQueue& queue) -: mList( ((cErrorQueue*)&queue)->mList ) +cErrorQueueIter::cErrorQueueIter(const cErrorQueue& queue) : mList(((cErrorQueue*)&queue)->mList) { SeekBegin(); } @@ -240,7 +227,7 @@ bool cErrorQueueIter::Done() const const ePoly& cErrorQueueIter::GetError() const { - ASSERT(! Done()); + ASSERT(!Done()); return (*mIter); } @@ -255,19 +242,18 @@ void cErrorQueue::Read(iSerializer* pSerializer, int32 version) int32 size; mList.clear(); pSerializer->ReadInt32(size); - for(int i = 0; i < size; ++i) + for (int i = 0; i < size; ++i) { int32 errorNumber; TSTRING errorString; int32 flags; - pSerializer->ReadInt32 (errorNumber); - pSerializer->ReadString (errorString); - pSerializer->ReadInt32 (flags); + pSerializer->ReadInt32(errorNumber); + pSerializer->ReadString(errorString); + pSerializer->ReadInt32(flags); - mList.push_back( ePoly( errorNumber, errorString, flags ) ); + mList.push_back(ePoly(errorNumber, errorString, flags)); } - } /////////////////////////////////////////////////////////////////////////////// @@ -277,13 +263,12 @@ void cErrorQueue::Write(iSerializer* pSerializer) const { pSerializer->WriteInt32(mList.size()); ListType::const_iterator i; - for( i = mList.begin(); i != mList.end(); ++i) + for (i = mList.begin(); i != mList.end(); ++i) { - pSerializer->WriteInt32 ((*i).GetID()); + pSerializer->WriteInt32((*i).GetID()); pSerializer->WriteString((*i).GetMsg()); - pSerializer->WriteInt32 ((*i).GetFlags()); + pSerializer->WriteInt32((*i).GetFlags()); } - } @@ -292,15 +277,14 @@ void cErrorQueue::Write(iSerializer* pSerializer) const /////////////////////////////////////////////////////////////////////////////// void cErrorQueue::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; - - cDebug d("cFCOErrorQueue::TraceContents"); + + cDebug d("cFCOErrorQueue::TraceContents"); ListType::const_iterator i; - int counter = 0; - for(i = mList.begin(); i != mList.end(); i++, counter++) + int counter = 0; + for (i = mList.begin(); i != mList.end(); i++, counter++) { - d.Trace(dl, _T("Error[%d]: num = %x string = %s\n") , counter, (*i).GetID(), (*i).GetMsg().c_str()); + d.Trace(dl, _T("Error[%d]: num = %x string = %s\n"), counter, (*i).GetID(), (*i).GetMsg().c_str()); } } - diff --git a/src/core/errorbucketimpl.h b/src/core/errorbucketimpl.h index f714e46..8a543df 100644 --- a/src/core/errorbucketimpl.h +++ b/src/core/errorbucketimpl.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // errorbucketimpl.h -// +// // This component contains classes derived from cErrorBucket and helper classes. // They were broken out of errorbucket.h becuase many components will only need to // know about cErrorBucket, so we reduce system dependencies by keeping these classes @@ -60,22 +60,22 @@ #endif ////////////////////////////////////////////////////// -// cErrorReporter -- sends all error messages to +// cErrorReporter -- sends all error messages to // stderr ////////////////////////////////////////////////////// class cErrorReporter : public cErrorBucket { public: static void PrintErrorMsg(const eError& error, const TSTRING& strExtra = _T("")); - // function that HandleError() uses to print the error messages to stderr. - // this function uses the current authoritative format for error reporting, so - // other functions needing to display errors to the user should use this. - // + // function that HandleError() uses to print the error messages to stderr. + // this function uses the current authoritative format for error reporting, so + // other functions needing to display errors to the user should use this. + // - // NOTE:bam 5/7/99 -- I don't think the below is true anymore? - // NOTE:mdb -- if the error has an ID of zero, nothing will be printed. This - // is a way to throw a fatal error where the error reporting has already - // occurred. + // NOTE:bam 5/7/99 -- I don't think the below is true anymore? + // NOTE:mdb -- if the error has an ID of zero, nothing will be printed. This + // is a way to throw a fatal error where the error reporting has already + // occurred. protected: virtual void HandleError(const eError& error); @@ -100,17 +100,18 @@ class cErrorTracer : public cErrorBucket class cErrorQueue : public cErrorBucket, public iTypedSerializable { friend class cErrorQueueIter; + public: - void Clear(); - // remove all errors from the queue + void Clear(); + // remove all errors from the queue int GetNumErrors() const; - // returns how many errors are in the queue + // returns how many errors are in the queue // // iSerializable interface // - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) // // Debugging @@ -119,9 +120,10 @@ class cErrorQueue : public cErrorBucket, public iTypedSerializable protected: virtual void HandleError(const eError& error); + private: typedef std::list ListType; - ListType mList; + ListType mList; DECLARE_TYPEDSERIALIZABLE() }; @@ -131,7 +133,9 @@ class cErrorQueueIter public: cErrorQueueIter(cErrorQueue& queue); cErrorQueueIter(const cErrorQueue& queue); - ~cErrorQueueIter() {} + ~cErrorQueueIter() + { + } // iteration methods void SeekBegin(); @@ -139,9 +143,9 @@ class cErrorQueueIter bool Done() const; // access to the error - const ePoly& GetError() const; - // both of these return results are undefined if the iterator - // is not valid (ie - IsDone() == true) + const ePoly& GetError() const; + // both of these return results are undefined if the iterator + // is not valid (ie - IsDone() == true) private: cErrorQueue::ListType& mList; cErrorQueue::ListType::iterator mIter; @@ -153,9 +157,14 @@ class cErrorQueueIter ////////////////////////////////////////////////////// class cErrorBucketNull : public cErrorBucket { - virtual void AddError(const eError& ) {} + virtual void AddError(const eError&) + { + } + protected: - virtual void HandleError(const eError& ) {} + virtual void HandleError(const eError&) + { + } }; ////////////////////////////////////////////////////// @@ -165,10 +174,10 @@ class cErrorBucketNull : public cErrorBucket class cErrorBucketPassThru : public cErrorBucket { protected: - virtual void HandleError(const eError& ) {} + virtual void HandleError(const eError&) + { + } }; - #endif - diff --git a/src/core/errorgeneral.h b/src/core/errorgeneral.h index c78b285..e284705 100644 --- a/src/core/errorgeneral.h +++ b/src/core/errorgeneral.h @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// errorgeneral.h -- +// errorgeneral.h -- // #ifndef __ERRORGENERAL_H @@ -38,12 +38,11 @@ #include "error.h" -TSS_EXCEPTION( eErrorGeneral, eError ); -TSS_EXCEPTION( eOpen, eErrorGeneral ); -TSS_EXCEPTION( eOpenRead, eErrorGeneral ); -TSS_EXCEPTION( eOpenWrite, eErrorGeneral ); -TSS_EXCEPTION( eBadCmdLine, eErrorGeneral ); -TSS_EXCEPTION( eBadModeSwitch, eErrorGeneral ); +TSS_EXCEPTION(eErrorGeneral, eError); +TSS_EXCEPTION(eOpen, eErrorGeneral); +TSS_EXCEPTION(eOpenRead, eErrorGeneral); +TSS_EXCEPTION(eOpenWrite, eErrorGeneral); +TSS_EXCEPTION(eBadCmdLine, eErrorGeneral); +TSS_EXCEPTION(eBadModeSwitch, eErrorGeneral); #endif //#ifndef __ERRORGENERAL_H - diff --git a/src/core/errortable.cpp b/src/core/errortable.cpp index 6c7a24c..0673ee3 100644 --- a/src/core/errortable.cpp +++ b/src/core/errortable.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,7 +35,7 @@ #include "stdcore.h" #include "errortable.h" -#ifdef _DEBUG +#ifdef DEBUG #include "package.h" #include "corestrings.h" #endif @@ -52,7 +52,7 @@ cErrorTable* cErrorTable::GetInstance() /////////////////////////////////////////////////////////////////////////////// // AssertMsgValidity /////////////////////////////////////////////////////////////////////////////// -#ifdef _DEBUG +#ifdef DEBUG void cErrorTable::AssertMsgValidity(const TCHAR* msg) { // Check to see that the first part of this error message is not too long. @@ -64,18 +64,18 @@ void cErrorTable::AssertMsgValidity(const TCHAR* msg) if (errSize == TSTRING::npos) errSize = errStr.length(); - #if 0 //TODO: Figure out how to do this properly. +# if 0 //TODO: Figure out how to do this properly. TSTRING::size_type errorSize = TSS_GetString( cCore, core::STR_ERROR_ERROR ).length(); TSTRING::size_type warningSize = TSS_GetString( cCore, core::STR_ERROR_WARNING ).length(); TSTRING::size_type maxHeaderSize = (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': ' - #else +# else // Sunpro got stuck in an infinite loop when we called GetString from this func; - TSTRING::size_type errorSize = 9; + TSTRING::size_type errorSize = 9; TSTRING::size_type warningSize = 10; - TSTRING::size_type maxHeaderSize = (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': ' - #endif + TSTRING::size_type maxHeaderSize = + (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': ' +# endif ASSERT(maxHeaderSize + errSize < 80); } #endif - diff --git a/src/core/errortable.h b/src/core/errortable.h index dbd0632..687d27b 100644 --- a/src/core/errortable.h +++ b/src/core/errortable.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,7 +34,7 @@ // Date: 30 April 99 // Creator: mdb // -// cErrorTable -- singleton derived from Resource_<> that serves as the global +// cErrorTable -- singleton derived from Resource_<> that serves as the global // error id to string mapping // #ifndef __ERRORTABLE_H @@ -59,36 +59,36 @@ class cErrorTable : public cMessages_ // // Convenience Methods // - void Put( const eError& e, const TCHAR* msg ); + void Put(const eError& e, const TCHAR* msg); // // Singleton Interface // static cErrorTable* GetInstance(); private: - #ifdef _DEBUG +#ifdef DEBUG static void AssertMsgValidity(const TCHAR* msg); - #endif +#endif }; -inline void cErrorTable::Put( const eError& e, const TCHAR* msg ) +inline void cErrorTable::Put(const eError& e, const TCHAR* msg) { - #ifdef _DEBUG +#ifdef DEBUG AssertMsgValidity(msg); - #endif +#endif - inherited::Put( e.GetID(), msg ); + inherited::Put(e.GetID(), msg); } //----------------------------------------------------------------------------- // Convenience Macros //----------------------------------------------------------------------------- // -// These macros make it easy for a module to register errors with the global +// These macros make it easy for a module to register errors with the global // error table. Them like this: // // // animalerrors.h -// // +// // // TSS_DECLARE_ERROR_REGISTRATION( animal ) // // // animalerrors.cpp @@ -109,32 +109,27 @@ inline void cErrorTable::Put( const eError& e, const TCHAR* msg ) //=================== // cpp file macros //=================== -#define TSS_BEGIN_ERROR_REGISTRATION( pkgName ) \ - RegisterErrors##pkgName::RegisterErrors##pkgName() \ - { +# define TSS_BEGIN_ERROR_REGISTRATION(pkgName) \ + RegisterErrors##pkgName::RegisterErrors##pkgName() \ + { -#define TSS_REGISTER_ERROR( err, str ) \ - cErrorTable::GetInstance()->Put \ - ( err, str ); +# define TSS_REGISTER_ERROR(err, str) cErrorTable::GetInstance()->Put(err, str); -#define TSS_END_ERROR_REGISTRATION() \ - } +# define TSS_END_ERROR_REGISTRATION() } //=================== // h file macros //=================== -#define TSS_DECLARE_ERROR_REGISTRATION( pkgName ) \ - struct RegisterErrors##pkgName \ - {\ - RegisterErrors##pkgName(); \ - }; +# define TSS_DECLARE_ERROR_REGISTRATION(pkgName) \ + struct RegisterErrors##pkgName \ + { \ + RegisterErrors##pkgName(); \ + }; //=================== // package init macros //=================== -#define TSS_REGISTER_PKG_ERRORS( pkgName ) \ - RegisterErrors##pkgName register##pkgName; +# define TSS_REGISTER_PKG_ERRORS(pkgName) RegisterErrors##pkgName register##pkgName; #endif //__ERRORTABLE_H - diff --git a/src/core/errorutil.cpp b/src/core/errorutil.cpp index 65f5099..34160ac 100644 --- a/src/core/errorutil.cpp +++ b/src/core/errorutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,31 +37,26 @@ #include "corestrings.h" //============================================================================= -// class eInternal +// class eInternal //============================================================================= -#if IS_UNIX namespace //unique { - TCHAR* tw_itot( int value, TCHAR* string, int radix) - { - _stprintf( string, "%d", value ); - return string; - } +TCHAR* tw_itot(int value, TCHAR* string, int radix, int size) +{ + snprintf(string, size, "%d", value); + return string; } -#else - #define tw_itot _itot -#endif //IS_UNIX +} // namespace -eInternal::eInternal(TCHAR* sourceFile, int lineNum) -: eError(_T("")) +eInternal::eInternal(TCHAR* sourceFile, int lineNum) : eError(_T("")) { TCHAR buf[256]; mMsg = _T("File: "); mMsg += sourceFile; mMsg += _T(" Line: "); - mMsg += tw_itot(lineNum, buf, 10); + mMsg += tw_itot(lineNum, buf, 10, 256); } //============================================================================= @@ -71,18 +66,17 @@ eInternal::eInternal(TCHAR* sourceFile, int lineNum) /////////////////////////////////////////////////////////////////////////////// // MakeFileError /////////////////////////////////////////////////////////////////////////////// -TSTRING cErrorUtil::MakeFileError( const TSTRING& msg, const TSTRING& fileName ) +TSTRING cErrorUtil::MakeFileError(const TSTRING& msg, const TSTRING& fileName) { TSTRING ret; - ret = TSS_GetString( cCore, core::STR_ERR2_FILENAME ); - ret.append( fileName ); - ret.append( 1, _T('\n') ); + ret = TSS_GetString(cCore, core::STR_ERR2_FILENAME); + ret.append(fileName); + ret.append(1, _T('\n')); - if ( msg.length() > 0 ) + if (msg.length() > 0) { ret.append(msg); } - + return ret; } - diff --git a/src/core/errorutil.h b/src/core/errorutil.h index 4b95b6f..6c0f39c 100644 --- a/src/core/errorutil.h +++ b/src/core/errorutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,7 +39,7 @@ // eInternal -- internal logic errors ( ie -- programming mistakes ) // ePoly -- "polymorphic" error that takes its ID as input instead // of from its class name -// ThrowAndAssert -- asserts false and throws the specified exception +// ThrowAndAssert -- asserts false and throws the specified exception // #ifndef __ERRORUTIL_H #define __ERRORUTIL_H @@ -58,27 +58,27 @@ class ePoly : public eError //------------------------------------------------------------------------- // Construction and Assignment //------------------------------------------------------------------------- - ePoly( uint32 id, const TSTRING& msg, uint32 flags = 0 ); - explicit ePoly( const eError& rhs ); - explicit ePoly(); - void operator=( const eError& rhs ); + ePoly(uint32 id, const TSTRING& msg, uint32 flags = 0); + explicit ePoly(const eError& rhs); + explicit ePoly(); + void operator=(const eError& rhs); //------------------------------------------------------------------------- // ID manipulation //------------------------------------------------------------------------- - virtual uint32 GetID() const; - void SetID( uint32 id ); + virtual uint32 GetID() const; + void SetID(uint32 id); private: - uint32 mID; + uint32 mID; }; //----------------------------------------------------------------------------- // eInternal //----------------------------------------------------------------------------- -TSS_BEGIN_EXCEPTION( eInternal, eError ) +TSS_BEGIN_EXCEPTION(eInternal, eError) public: - eInternal( TCHAR* file, int lineNum ); +eInternal(TCHAR* file, int lineNum); TSS_END_EXCEPTION() //----------------------------------------------------------------------------- @@ -87,28 +87,32 @@ TSS_END_EXCEPTION() class cErrorUtil { public: - static TSTRING MakeFileError( const TSTRING& msg, const TSTRING& fileName ); - // constructs an error message of the form: - // File: \n - // This is useful for constructing strings to pass as the msg parameter - // to eError constructors. + static TSTRING MakeFileError(const TSTRING& msg, const TSTRING& fileName); + // constructs an error message of the form: + // File: \n + // This is useful for constructing strings to pass as the msg parameter + // to eError constructors. }; //----------------------------------------------------------------------------- // Convenience Macros //----------------------------------------------------------------------------- // -// NOTE -- we require the developer to supply the file name instead of using +// NOTE -- we require the developer to supply the file name instead of using // __FILE__ because that includes the full path to the file, which we // would not like to display to the user. // -#define INTERNAL_ERROR(filename) eInternal((TCHAR*)_T(filename), __LINE__) -#define THROW_INTERNAL(filename) throw eInternal((TCHAR*)_T(filename), __LINE__) +#define INTERNAL_ERROR(filename) eInternal((TCHAR*)_T(filename), __LINE__) +#define THROW_INTERNAL(filename) throw eInternal((TCHAR*)_T(filename), __LINE__) // TODO: ASSERT is always fatal in Unix, perhaps we could #ifdef the ASSERT // to echo to cout the line number the exception occured at? -#define ThrowAndAssert(exception) { ASSERT(false); throw exception; } +#define ThrowAndAssert(exception) \ + { \ + ASSERT(false); \ + throw exception; \ + } //----------------------------------------------------------------------------- @@ -118,17 +122,14 @@ class cErrorUtil /////////////////////////////////////////////////////////////////////////////// // ePoly /////////////////////////////////////////////////////////////////////////////// -inline ePoly::ePoly( uint32 id, const TSTRING& msg, uint32 flags ) -: eError( msg, flags ), - mID( id ) +inline ePoly::ePoly(uint32 id, const TSTRING& msg, uint32 flags) : eError(msg, flags), mID(id) { - } /////////////////////////////////////////////////////////////////////////////// // ePoly /////////////////////////////////////////////////////////////////////////////// -inline ePoly::ePoly( const eError& rhs ) +inline ePoly::ePoly(const eError& rhs) { *this = rhs; } @@ -136,21 +137,18 @@ inline ePoly::ePoly( const eError& rhs ) /////////////////////////////////////////////////////////////////////////////// // ePoly /////////////////////////////////////////////////////////////////////////////// -inline ePoly::ePoly() -: eError( _T("") ), - mID( 0 ) +inline ePoly::ePoly() : eError(_T("")), mID(0) { - } /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -inline void ePoly::operator=( const eError& rhs ) +inline void ePoly::operator=(const eError& rhs) { - mMsg = rhs.GetMsg(); + mMsg = rhs.GetMsg(); mFlags = rhs.GetFlags(); - mID = rhs.GetID(); + mID = rhs.GetID(); } /////////////////////////////////////////////////////////////////////////////// @@ -164,10 +162,9 @@ inline uint32 ePoly::GetID() const /////////////////////////////////////////////////////////////////////////////// // SetID /////////////////////////////////////////////////////////////////////////////// -inline void ePoly::SetID( uint32 id ) +inline void ePoly::SetID(uint32 id) { - mID = id; + mID = id; } #endif //__ERRORUTIL_H - diff --git a/src/core/file.h b/src/core/file.h index ebdba9d..154ccd3 100644 --- a/src/core/file.h +++ b/src/core/file.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,7 +47,7 @@ #include "fileerror.h" #endif -#ifdef __MINT__ // for off_t +#if IS_MINT // for off_t #include #endif @@ -55,102 +55,133 @@ // eFile exception class //============================================================================= -TSS_FILE_EXCEPTION( eFile, eFileError ); -TSS_FILE_EXCEPTION( eFileOpen, eFile ); -TSS_FILE_EXCEPTION( eFileWrite, eFile ); -TSS_FILE_EXCEPTION( eFileRead, eFile ); -TSS_FILE_EXCEPTION( eFileEOF, eFile ); // never used! -TSS_FILE_EXCEPTION( eFileSeek, eFile ); -TSS_FILE_EXCEPTION( eFileInvalidOp, eFile ); // never used! -TSS_FILE_EXCEPTION( eFileTrunc, eFile ); -TSS_FILE_EXCEPTION( eFileClose, eFile ); // never used! -TSS_FILE_EXCEPTION( eFileFlush, eFile ); -TSS_FILE_EXCEPTION( eFileRewind, eFile ); +TSS_FILE_EXCEPTION(eFile, eFileError); +TSS_FILE_EXCEPTION(eFileOpen, eFile); +TSS_FILE_EXCEPTION(eFileWrite, eFile); +TSS_FILE_EXCEPTION(eFileRead, eFile); +TSS_FILE_EXCEPTION(eFileEOF, eFile); // never used! +TSS_FILE_EXCEPTION(eFileSeek, eFile); +TSS_FILE_EXCEPTION(eFileInvalidOp, eFile); // never used! +TSS_FILE_EXCEPTION(eFileTrunc, eFile); +TSS_FILE_EXCEPTION(eFileClose, eFile); // never used! +TSS_FILE_EXCEPTION(eFileFlush, eFile); +TSS_FILE_EXCEPTION(eFileRewind, eFile); //============================================================================= // cFile //============================================================================= struct cFile_i; -class cFile +class cFile { public: -#if IS_UNIX typedef off_t File_t; -#else //WIN32 - typedef int64 File_t; - -#endif // IS_UNIX - enum SeekFrom + enum SeekFrom { - SEEK_BEGIN = 0, - SEEK_CURRENT, - SEEK_EOF + SEEK_BEGIN = 0, + SEEK_CURRENT, + SEEK_EOF }; enum OpenFlags { - // note that reading from the file is implicit - OPEN_READ = 0x00000001, // not needed, but makes calls nice... - OPEN_WRITE = 0x00000002, // we will be writing to the file - OPEN_LOCKED_TEMP = 0x00000004, // the file should not be readable by other processes and should be removed when closed - OPEN_TRUNCATE = 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE - OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set - OPEN_TEXT = 0x00000020, - OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL - OPEN_NONBLOCKING = 0x00000080, // Use non-blocking i/o [Unix] + // note that reading from the file is implicit + OPEN_READ = 0x00000001, // not needed, but makes calls nice... + OPEN_WRITE = 0x00000002, // we will be writing to the file + OPEN_LOCKED_TEMP = + 0x00000004, // the file should not be readable by other processes and should be removed when closed + OPEN_TRUNCATE = + 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE + OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set + OPEN_TEXT = 0x00000020, + OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL + OPEN_SCANNING = 0x00000080, // Open for scanning; set nonblocking & caching accordingly, where available + OPEN_DIRECT = 0x00000100 // Use O_DIRECT or platform equivalent }; //Ctor, Dtor, CpyCtor, Operator=: - cFile ( void ); - ~cFile ( void ); + cFile(void); + ~cFile(void); /************ User Interface **************************/ // Both Open methods ALWAYS open files in BINARY mode! - void Open ( const TSTRING& sFileName, uint32 flags = OPEN_READ ); //throw(eFile) - void Close ( void ); //throw(eFile) - bool IsOpen ( void ) const; + void Open(const TSTRING& sFileName, uint32 flags = OPEN_READ); //throw(eFile) + void Close(void); //throw(eFile) + bool IsOpen(void) const; - File_t Seek ( File_t offset, SeekFrom From ) const; //throw(eFile) + File_t Seek(File_t offset, SeekFrom From) const; //throw(eFile) // Seek returns the current offset after completion - File_t Read ( void* buffer, File_t nBytes ) const; //throw(eFile) + File_t Read(void* buffer, File_t nBytes) const; //throw(eFile) // Read returns the number of bytes that are actually read. If the nBytes // parameter is 0, 0 bytes will be read and buffer will remain untouched. // If the read head is at EOF, no bytes will be read and 0 will be returned. - File_t Write ( const void* buffer, File_t nBytes ); //throw(eFile) + File_t Write(const void* buffer, File_t nBytes); //throw(eFile) // Write returns the number of bytes that are actually written. - File_t Tell ( void ) const; - // Tell returns the current offset. - bool Flush ( void ); //throw(eFile) + File_t Tell(void) const; + // Tell returns the current offset. + bool Flush(void); //throw(eFile) // Flush returns 0 if the currently defined stream is successfully flushed. - void Rewind ( void ) const; //throw(eFile) + void Rewind(void) const; //throw(eFile) // Sets the offset to 0. - File_t GetSize ( void ) const; - // Returns the size of the current file in bytes. Returns -1 if no file is defined. - void Truncate ( File_t offset ); // throw(eFile) + File_t GetSize(void) const; + // Returns the size of the current file in bytes. Returns -1 if no file is defined. + void Truncate(File_t offset); // throw(eFile) private: - cFile ( const cFile& rhs ); //not impl. - cFile& operator= ( const cFile& rhs); //not impl. + cFile(const cFile& rhs); //not impl. + cFile& operator=(const cFile& rhs); //not impl. //Pointer to the insulated implementation - cFile_i* mpData; + cFile_i* mpData; public: - bool isWritable; + bool isWritable; }; -#ifdef __AROS__ +class cDosPath +{ +public: + static TSTRING AsPosix(const TSTRING& in); + static TSTRING AsNative(const TSTRING& in); + static bool IsAbsolutePath(const TSTRING& in); + static TSTRING BackupName(const TSTRING& in); +}; + class cArosPath { public: static TSTRING AsPosix(const TSTRING& in); static TSTRING AsNative(const TSTRING& in); + static bool IsAbsolutePath(const TSTRING& in); }; -#endif +class cRiscosPath +{ +public: + static TSTRING AsPosix(const TSTRING& in); + static TSTRING AsNative(const TSTRING& in); + static bool IsAbsolutePath(const TSTRING& in); +}; -#endif //__FILE_H +class cRedoxPath +{ +public: + static TSTRING AsPosix(const TSTRING& in); + static TSTRING AsNative(const TSTRING& in); + static bool IsAbsolutePath(const TSTRING& in); +}; +# if IS_DOS_DJGPP +# define cDevicePath cDosPath +# elif IS_AROS +# define cDevicePath cArosPath +# elif IS_RISCOS +# define cDevicePath cRiscosPath +# elif IS_REDOX +# define cDevicePath cRedoxPath +# endif + + +#endif //__FILE_H diff --git a/src/core/file_unix.cpp b/src/core/file_unix.cpp index 22c259e..286de9a 100644 --- a/src/core/file_unix.cpp +++ b/src/core/file_unix.cpp @@ -1,40 +1,47 @@ -// + // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // file_unix.cpp : Specific implementation of file operations for Unix. + +/* On GNU/Hurd, need to define _GNU_SOURCE in order to use O_NOATIME + which technically is still a nonstandard extension to open() */ +#if IS_HURD +# define _GNU_SOURCE +#endif + #include "core/stdcore.h" #if !IS_UNIX -#error Need to be unix to use unixfsservices +# error Need to be unix to use unixfsservices #endif #include "core/file.h" @@ -46,27 +53,19 @@ #include #include +#if HAVE_SYS_FS_VX_IOCTL_H +#include +#endif + #include "core/debug.h" #include "core/corestrings.h" #include "core/fsservices.h" #include "core/errorutil.h" -/////////////////////////////////////////////////////////////////////////////// -// util_GetErrnoString -- return the result of strerror(errno) as a tstring -/////////////////////////////////////////////////////////////////////////////// -/*static TSTRING util_GetErrnoString() -{ - TSTRING ret; - char* pErrorStr = strerror(errno); -#ifdef _UNICODE -#error We dont currently support unicode on unix -#else - ret = pErrorStr; +#if IS_RISCOS +#include #endif - return ret; -}*/ -/////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // cFile_i : Insulated implementation for cFile objects. /////////////////////////////////////////////////////////////////////////// @@ -76,23 +75,36 @@ struct cFile_i cFile_i(); ~cFile_i(); - FILE* mpCurrStream; //currently defined file stream - TSTRING mFileName; //the name of the file we are currently referencing. + int m_fd; //underlying file descriptor + FILE* mpCurrStream; //currently defined file stream + TSTRING mFileName; //the name of the file we are currently referencing. + uint32 mFlags; //Flags used to open the file }; //Ctor -cFile_i::cFile_i() : - mpCurrStream(NULL) -{} +cFile_i::cFile_i() : m_fd(-1), mpCurrStream(NULL), mFlags(0) +{ +} //Dtor cFile_i::~cFile_i() { if (mpCurrStream != NULL) - fclose( mpCurrStream ); - mpCurrStream = NULL; + { + fclose(mpCurrStream); + mpCurrStream = NULL; - mFileName.empty(); +#if !CAN_UNLINK_WHILE_OPEN // so unlink after close instead + if (mFlags & cFile::OPEN_LOCKED_TEMP) + { + // unlink this file + if (0 != unlink(mFileName.c_str())) + { + throw(eFileOpen(mFileName, iFSServices::GetInstance()->GetErrString())); + } + } +#endif + } } /////////////////////////////////////////////////////////////////////////// @@ -101,15 +113,14 @@ cFile_i::~cFile_i() /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// -cFile::cFile() : - mpData(NULL), isWritable(false) +cFile::cFile() : mpData(NULL), isWritable(false) { mpData = new cFile_i; } cFile::~cFile() { - if( mpData != NULL) + if (mpData != NULL) { delete mpData; mpData = NULL; @@ -120,31 +131,33 @@ cFile::~cFile() // Open /////////////////////////////////////////////////////////////////////////////// -#ifndef __AROS -void cFile::Open( const TSTRING& sFileName, uint32 flags ) +#if !USES_DEVICE_PATH +void cFile::Open(const TSTRING& sFileName, uint32 flags) { #else -void cFile::Open( const TSTRING& sFileNameC, uint32 flags ) +void cFile::Open(const TSTRING& sFileNameC, uint32 flags) { - TSTRING sFileName = cArosPath::AsNative(sFileNameC); + TSTRING sFileName = cDevicePath::AsNative(sFileNameC); #endif mode_t openmode = 0664; - if ( mpData->mpCurrStream != NULL ) + if (mpData->mpCurrStream != NULL) Close(); - + + mpData->mFlags = flags; + // - // set up the sopen permissions + // set up the open permissions // int perm = 0; TSTRING mode; - if( flags & OPEN_WRITE ) + if (flags & OPEN_WRITE) { - perm |= O_RDWR; - isWritable = true; - mode = _T("rb"); - if( flags & OPEN_TRUNCATE ) + perm |= O_RDWR; + isWritable = true; + mode = _T("rb"); + if (flags & OPEN_TRUNCATE) { perm |= O_TRUNC; perm |= O_CREAT; @@ -155,41 +168,56 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags ) } else { - perm |= O_RDONLY; - isWritable = false; - mode = _T("rb"); + perm |= O_RDONLY; + isWritable = false; + mode = _T("rb"); } - if ( flags & OPEN_EXCLUSIVE ) { + if (flags & OPEN_EXCLUSIVE) + { perm |= O_CREAT | O_EXCL; - openmode = (mode_t) 0600; // Make sure only root can read the file + openmode = (mode_t)0600; // Make sure only root can read the file } - if ( flags & OPEN_CREATE ) - perm |= O_CREAT; + if (flags & OPEN_CREATE) + perm |= O_CREAT; #ifdef O_NONBLOCK - if( flags & OPEN_NONBLOCKING ) - perm |= O_NONBLOCK; + if (flags & OPEN_SCANNING) + perm |= O_NONBLOCK; #endif + +#ifdef O_NOATIME + if (flags & OPEN_SCANNING) + perm |= O_NOATIME; +#endif + +#ifdef O_DIRECT + //Only use O_DIRECT for scanning, since cfg/policy/report reads + // don't happen w/ a nice round block size. + if ((flags & OPEN_DIRECT) && (flags & OPEN_SCANNING)) + perm |= O_DIRECT; +#endif + // // actually open the file // - int fh = _topen( sFileName.c_str(), perm, openmode ); - if( fh == -1 ) + int fh = _topen(sFileName.c_str(), perm, openmode); + if (fh == -1) { - throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) ); + throw(eFileOpen(sFileName, iFSServices::GetInstance()->GetErrString())); } + mpData->m_fd = fh; -#ifndef __AROS__ - if( flags & OPEN_LOCKED_TEMP ) +#if CAN_UNLINK_WHILE_OPEN + if (flags & OPEN_LOCKED_TEMP) { - // unlink this file - if( 0 != unlink( sFileName.c_str() ) ) + // unlink this file + if (0 != unlink(sFileName.c_str())) { // we weren't able to unlink file, so close handle and fail - close( fh ); - throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) ); + close(fh); + throw(eFileOpen(sFileName, iFSServices::GetInstance()->GetErrString())); } } #endif @@ -199,9 +227,36 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags ) // mpData->mpCurrStream = _tfdopen(fh, mode.c_str()); - mpData->mFileName = sFileName; //Set mFileName to the newly opened file. - + mpData->mFileName = sFileName; //Set mFileName to the newly opened file. + cFile::Rewind(); + +#ifdef F_NOCACHE //OSX + if ((flags & OPEN_DIRECT) && (flags & OPEN_SCANNING)) + fcntl(fh, F_NOCACHE, 1); +#endif + +#if IS_SOLARIS + if ((flags & OPEN_DIRECT) && (flags & OPEN_SCANNING)) + directio(fh, DIRECTIO_ON); +#endif + +#if HAVE_POSIX_FADVISE + if (flags & OPEN_SCANNING && !(flags & OPEN_DIRECT)) + { + posix_fadvise(fh, 0, 0, POSIX_FADV_SEQUENTIAL); + posix_fadvise(fh, 0, 0, POSIX_FADV_NOREUSE); + } + +#elif HAVE_SYS_FS_VX_IOCTL_H + if (flags & OPEN_SCANNING) + { + if (flags & OPEN_DIRECT) + ioctl(fh, VX_SETCACHE, VX_DIRECT); + else + ioctl(fh, VX_SETCACHE, VX_SEQ | VX_NOREUSE); + } +#endif } @@ -210,31 +265,37 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags ) /////////////////////////////////////////////////////////////////////////// void cFile::Close() //throw(eFile) { - if(mpData->mpCurrStream != NULL) + if (mpData->mpCurrStream != NULL) { - fclose( mpData->mpCurrStream ); +#ifdef HAVE_POSIX_FADVISE + posix_fadvise(fileno(mpData->mpCurrStream), 0, 0, POSIX_FADV_DONTNEED); +#endif + + fclose(mpData->mpCurrStream); mpData->mpCurrStream = NULL; } + + mpData->mFileName.empty(); } -bool cFile::IsOpen( void ) const +bool cFile::IsOpen(void) const { - return( mpData->mpCurrStream != NULL ); + return (mpData->mpCurrStream != NULL); } /////////////////////////////////////////////////////////////////////////// // Seek -- Positions the read/write offset in mpCurrStream. Returns the // current offset upon completion. Returns 0 if no stream is defined. /////////////////////////////////////////////////////////////////////////// -cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile) +cFile::File_t cFile::Seek(File_t offset, SeekFrom From) const //throw(eFile) { //Check to see if a file as been opened yet... - ASSERT( mpData->mpCurrStream != 0); + ASSERT(mpData->mpCurrStream != 0); int apiFrom; - switch( From ) + switch (From) { case cFile::SEEK_BEGIN: apiFrom = SEEK_SET; @@ -247,11 +308,11 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile) break; default: //An invalid SeekFrom parameter was passed. - throw( eInternal( _T("file_unix") ) ); + throw(eInternal(_T("file_unix"))); } - // this is a hack to simulate running out of disk space - #if 0 +// this is a hack to simulate running out of disk space +#if 0 static int blowupCount = 1; if (++blowupCount == 1075) { @@ -260,14 +321,14 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile) throw std::bad_alloc(); } fprintf(stderr, "%d\n", blowupCount); - #endif +#endif - if (fseeko( mpData->mpCurrStream, offset, apiFrom ) != 0) + if (fseeko(mpData->mpCurrStream, offset, apiFrom) != 0) { - #ifdef _DEBUG +#ifdef DEBUG cDebug d("cFile::Seek"); d.TraceDebug("Seek failed!\n"); - #endif +#endif throw eFileSeek(); } @@ -278,39 +339,51 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile) // Read -- Returns the actual bytes read from mpCurrStream. Returns 0 if // mpCurrStream is undefined. /////////////////////////////////////////////////////////////////////////// -cFile::File_t cFile::Read( void* buffer, File_t nBytes ) const //throw(eFile) +cFile::File_t cFile::Read(void* buffer, File_t nBytes) const //throw(eFile) { File_t iBytesRead; // Has a file been opened? - ASSERT( mpData->mpCurrStream != NULL ); + ASSERT(mpData->mpCurrStream != NULL); // Is the nBytes parameter 0? If so, return without touching buffer: - if( nBytes == 0 ) + if (nBytes == 0) return 0; - iBytesRead = fread( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ); - - if( ferror( mpData->mpCurrStream ) != 0 ) - throw eFileRead( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ; + if (mpData->mFlags & OPEN_DIRECT) + { + iBytesRead = read(mpData->m_fd, buffer, nBytes); + if (iBytesRead < 0) + { + throw eFileRead(mpData->mFileName, iFSServices::GetInstance()->GetErrString()); + } + } else - return iBytesRead; + { + iBytesRead = fread(buffer, sizeof(byte), nBytes, mpData->mpCurrStream); + if (ferror(mpData->mpCurrStream) != 0) + { + throw eFileRead(mpData->mFileName, iFSServices::GetInstance()->GetErrString()); + } + } + + return iBytesRead; } /////////////////////////////////////////////////////////////////////////// // Write -- Returns the actual number of bytes written to mpCurrStream // Returns 0 if no file has been opened. /////////////////////////////////////////////////////////////////////////// -cFile::File_t cFile::Write( const void* buffer, File_t nBytes ) //throw(eFile) +cFile::File_t cFile::Write(const void* buffer, File_t nBytes) //throw(eFile) { File_t actual_count = 0; // Has a file been opened? Is it writable? - ASSERT( mpData->mpCurrStream != NULL ); - ASSERT( isWritable ); + ASSERT(mpData->mpCurrStream != NULL); + ASSERT(isWritable); - if( ( actual_count = fwrite( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ) ) < nBytes ) - throw eFileWrite( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ); + if ((actual_count = fwrite(buffer, sizeof(byte), nBytes, mpData->mpCurrStream)) < nBytes) + throw eFileWrite(mpData->mFileName, iFSServices::GetInstance()->GetErrString()); else return actual_count; } @@ -321,9 +394,9 @@ cFile::File_t cFile::Write( const void* buffer, File_t nBytes ) //throw(eFil /////////////////////////////////////////////////////////////////////////// cFile::File_t cFile::Tell() const { - ASSERT( mpData->mpCurrStream != 0); + ASSERT(mpData->mpCurrStream != 0); - return ftell( mpData->mpCurrStream ); + return ftell(mpData->mpCurrStream); } /////////////////////////////////////////////////////////////////////////// @@ -331,23 +404,23 @@ cFile::File_t cFile::Tell() const /////////////////////////////////////////////////////////////////////////// bool cFile::Flush() //throw(eFile) { - if ( mpData->mpCurrStream == NULL ) - throw eFileFlush( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ); - - return ( fflush( mpData->mpCurrStream) == 0 ); + if (mpData->mpCurrStream == NULL) + throw eFileFlush(mpData->mFileName, iFSServices::GetInstance()->GetErrString()); + + return (fflush(mpData->mpCurrStream) == 0); } /////////////////////////////////////////////////////////////////////////// // Rewind -- Sets the offset to the beginning of the file. If mpCurrStream // is NULL, this method returns false. If the rewind operation fails, // an exception is thrown. /////////////////////////////////////////////////////////////////////////// -void cFile::Rewind() const //throw(eFile) +void cFile::Rewind() const //throw(eFile) { - ASSERT( mpData->mpCurrStream != 0); + ASSERT(mpData->mpCurrStream != 0); - rewind( mpData->mpCurrStream ); - if( ftell( mpData->mpCurrStream ) != 0 ) - throw( eFileRewind( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ); + rewind(mpData->mpCurrStream); + if (ftell(mpData->mpCurrStream) != 0) + throw(eFileRewind(mpData->mFileName, iFSServices::GetInstance()->GetErrString())); } /////////////////////////////////////////////////////////////////////////// @@ -360,12 +433,12 @@ cFile::File_t cFile::GetSize() const File_t ret; //Has a file been opened? If not, return -1 - if( mpData->mpCurrStream == NULL ) + if (mpData->mpCurrStream == NULL) return -1; - ret = Seek( 0, cFile::SEEK_EOF ); - Seek( vCurrentOffset, cFile::SEEK_BEGIN ); - //return the offset to it's position prior to GetSize call. + ret = Seek(0, cFile::SEEK_EOF); + Seek(vCurrentOffset, cFile::SEEK_BEGIN); + //return the offset to it's position prior to GetSize call. return ret; } @@ -373,41 +446,240 @@ cFile::File_t cFile::GetSize() const ///////////////////////////////////////////////////////////////////////// // Truncate ///////////////////////////////////////////////////////////////////////// -void cFile::Truncate( File_t offset ) // throw(eFile) +void cFile::Truncate(File_t offset) // throw(eFile) { - ASSERT( mpData->mpCurrStream != 0); - ASSERT( isWritable ); + ASSERT(mpData->mpCurrStream != 0); + ASSERT(isWritable); - ftruncate( fileno(mpData->mpCurrStream), offset ); - if( GetSize() != offset ) - throw( eFileTrunc( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ); + ftruncate(fileno(mpData->mpCurrStream), offset); + if (GetSize() != offset) + throw(eFileTrunc(mpData->mFileName, iFSServices::GetInstance()->GetErrString())); } -#ifdef __AROS__ -TSTRING cArosPath::AsPosix( const TSTRING& in ) +///////////////////////////////////////////////////////////////////////// +// Platform path conversion methods +///////////////////////////////////////////////////////////////////////// + +bool cDosPath::IsAbsolutePath(const TSTRING& in) { + if (in.empty()) + return false; + if (in[0] == '/') + return true; + + if (in.length() >= 2 && in[1] == ':') + return true; + + return false; +} + +// For paths of type C:\DOS +TSTRING cDosPath::AsPosix(const TSTRING& in) +{ + if (in[0] == '/') + { return in; + } - TSTRING out = '/' + in; - std::replace(out.begin(), out.end(), ':', '/'); + TSTRING out = (cDosPath::IsAbsolutePath(in)) ? ("/dev/" + in) : in; + std::replace(out.begin(), out.end(), '\\', '/'); + out.erase(std::remove(out.begin(), out.end(), ':'), out.end()); return out; } -TSTRING cArosPath::AsNative( const TSTRING& in ) +TSTRING cDosPath::AsNative(const TSTRING& in) { if (in[0] != '/') + { + return in; + } + + if (in.find("/dev") != 0 || in.length() < 6) return in; - int x; - for (x=1; in[x] == '/' && x= 8) + out.append(in.substr(7)); - TSTRING out = in.substr(x); - TSTRING::size_type t = out.find_first_of('/'); - out[t] = ':'; + std::replace(out.begin(), out.end(), '/', '\\'); return out; -} +} + +TSTRING cDosPath::BackupName(const TSTRING& in) +{ + TSTRING out = in; + std::string::size_type pos = out.find_last_of("\\"); + if (std::string::npos == pos) + return in; + + TSTRING path = in.substr(0, pos); + TSTRING name = in.substr(pos, 9); + std::replace(name.begin(), name.end(), '.', '_'); + path.append(name); + + return path; +} + +///////////////////////////////////////////////////////////////////////// +bool cArosPath::IsAbsolutePath(const TSTRING& in) +{ + if (in.empty()) + return false; + + if (in[0] == '/') + return true; + + if (in.find(":") != std::string::npos) + return true; + + return false; +} + +// For paths of type DH0:dir/file +TSTRING cArosPath::AsPosix(const TSTRING& in) +{ + if (in[0] == '/') + { + return in; + } + + TSTRING out = IsAbsolutePath(in) ? '/' + in : in; + std::replace(out.begin(), out.end(), ':', '/'); + + return out; +} + +TSTRING cArosPath::AsNative(const TSTRING& in) +{ + if (in[0] != '/') + { + return in; + } + + std::string::size_type drive = in.find_first_not_of("/"); + TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in; + TSTRING::size_type t = out.find_first_of('/'); + if (t != std::string::npos) + out[t] = ':'; + else + out.append(":"); + + return out; +} + +///////////////////////////////////////////////////////////////////////// +bool cRiscosPath::IsAbsolutePath(const TSTRING& in) +{ + if (in.empty()) + return false; + + if (in[0] == '/') + return true; + + if (in.find("$") != std::string::npos) + return true; + + return false; +} + +// For paths of type SDFS::Volume.$.dir.file +TSTRING cRiscosPath::AsPosix(const TSTRING& in) +{ +#if IS_RISCOS + if (in[0] == '/') + { + return in; + } + + TSTRING out; + char* unixified = __unixify(in.c_str(), 0, 0, 0, 0); + if (unixified) + { + out.assign(unixified); + free(unixified); + return out; + } + return in; + +#else + return in; +#endif +} + +TSTRING cRiscosPath::AsNative(const TSTRING& in) +{ +#if IS_RISCOS + if (in[0] != '/') + { + return in; + } + + TSTRING out; + int buf_size = in.length() + 100; // examples pad by 100 + std::vector buf(buf_size); + __riscosify(in.c_str(), 0, 0, &buf[0], buf_size, 0); + if (buf[0]) + { + out.assign(&buf[0]); + return out; + } + return in; +#else + return in; #endif +} + + +///////////////////////////////////////////////////////////////////////// +bool cRedoxPath::IsAbsolutePath(const TSTRING& in) +{ + if (in.empty()) + return false; + + if (in[0] == '/') + return true; + + if (in.find(":") != std::string::npos) + return true; + + return false; +} + +// For paths of type file:/dir/file +TSTRING cRedoxPath::AsPosix(const TSTRING& in) +{ + if (in[0] == '/') + { + return in; + } + + TSTRING out = IsAbsolutePath(in) ? '/' + in : in; + std::string::size_type colon = out.find_first_of(":"); + if (colon != std::string::npos) + out.erase(colon, 1); + return out; +} + +TSTRING cRedoxPath::AsNative(const TSTRING& in) +{ + if (in[0] != '/') + { + return in; + } + + std::string::size_type drive = in.find_first_not_of("/"); + TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in; + TSTRING::size_type slash = out.find_first_of('/'); + if (slash != std::string::npos) + out.insert(slash, ":"); + else + out.append(":/"); + + return out; +} diff --git a/src/core/fileerror.cpp b/src/core/fileerror.cpp index e925e13..244418d 100644 --- a/src/core/fileerror.cpp +++ b/src/core/fileerror.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,11 +37,10 @@ #include "corestrings.h" // TODO: Make this use MakeFileError() for consistency -eFileError::eFileError( const TSTRING& filename, const TSTRING& description, uint32 flags ) -: eError( _T(""), flags ) +eFileError::eFileError(const TSTRING& filename, const TSTRING& description, uint32 flags) : eError(_T(""), flags) { mFilename = filename; - mMsg = description; + mMsg = description; } TSTRING eFileError::GetFilename() const @@ -58,14 +57,14 @@ TSTRING eFileError::GetDescription() const { TSTRING ret; - if( ! mFilename.empty() ) + if (!mFilename.empty()) { - ret = TSS_GetString( cCore, core::STR_ERROR_FILENAME ) + mFilename; + ret = TSS_GetString(cCore, core::STR_ERROR_FILENAME) + mFilename; } - if( ! mMsg.empty() ) + if (!mMsg.empty()) { - if ( ! mFilename.empty() ) + if (!mFilename.empty()) ret += _T("\n"); ret += mMsg; @@ -73,4 +72,3 @@ TSTRING eFileError::GetDescription() const return ret; } - diff --git a/src/core/fileerror.h b/src/core/fileerror.h index 48b54b6..c9f7c48 100644 --- a/src/core/fileerror.h +++ b/src/core/fileerror.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,30 +51,33 @@ // ### Insufficient permission to open file. <-- constructor parameter "msg" // ### Exiting... <-- appropriate third message //============================================================================= -TSS_BEGIN_EXCEPTION_NO_CTOR( eFileError, eError ) +TSS_BEGIN_EXCEPTION_NO_CTOR(eFileError, eError) private: - TSTRING mFilename; +TSTRING mFilename; public: - eFileError( const TSTRING& filename, const TSTRING& description, uint32 flags = 0 ); +eFileError(const TSTRING& filename, const TSTRING& description, uint32 flags = 0); - explicit eFileError( const eFileError& rhs ) - : eError( rhs ) { mFilename = rhs.mFilename; } - eFileError( const TSTRING& msg, uint32 flags = 0 ) - : eError( msg, flags ) {} +explicit eFileError(const eFileError& rhs) : eError(rhs) +{ + mFilename = rhs.mFilename; +} +eFileError(const TSTRING& msg, uint32 flags = 0) : eError(msg, flags) +{ +} - TSTRING GetFilename() const; - TSTRING GetDescription() const; - virtual TSTRING GetMsg() const; +TSTRING GetFilename() const; +TSTRING GetDescription() const; +virtual TSTRING GetMsg() const; TSS_END_EXCEPTION() -#define TSS_FILE_EXCEPTION( except, base ) \ - TSS_BEGIN_EXCEPTION( except, base ) \ - except( const TSTRING& filename, const TSTRING& msg, uint32 flags = 0 ) \ - : base( filename, msg, flags ) {} \ - TSS_END_EXCEPTION() +# define TSS_FILE_EXCEPTION(except, base) \ + TSS_BEGIN_EXCEPTION(except, base) \ + except(const TSTRING& filename, const TSTRING& msg, uint32 flags = 0) : base(filename, msg, flags) \ + { \ + } \ + TSS_END_EXCEPTION() #endif - diff --git a/src/core/fileheader.cpp b/src/core/fileheader.cpp index b3574a1..21c3623 100644 --- a/src/core/fileheader.cpp +++ b/src/core/fileheader.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,10 +38,10 @@ #include "ntmbs.h" // A magic number to put at top of file headers -// I changed this magic number in 2.1 since we now support versioning in the file header. +// I changed this magic number in 2.1 since we now support versioning in the file header. // (the old magic number was 0x00202039) // I generated the random number using the random.org web site. -const uint32 FILE_HEADER_MAGIC_NUMBER = 0x78f9beb3; +const uint32 FILE_HEADER_MAGIC_NUMBER = 0x78f9beb3; /////////////////////////////////////////////////////////////////////////////// // class cFileHeaderID @@ -50,11 +50,11 @@ cFileHeaderID::~cFileHeaderID() { } -void cFileHeaderID::operator=( const TCHAR* pszId ) +void cFileHeaderID::operator=(const TCHAR* pszId) { // RAD:10/1/99 -- Not Needed // TODO:BAM -- I'm pretty sure that there's a bug hiding here... - //size_t len = _tcslen(id); + //size_t len = _tcslen(id); //if (len >= 256) //{ // ASSERT(false); @@ -62,62 +62,34 @@ void cFileHeaderID::operator=( const TCHAR* pszId ) // return; //} -#ifdef _UNICODE - - size_t N = (::wcslen( pszId ) * MB_CUR_MAX); // Try the easy way! - if ( !(N < cFileHeaderID::MAXBYTES) ) - { - N = ::wcstombs( 0, pszId, (size_t)-1 ); // Try again! - if ( N == (size_t)-1 ) - { - throw - eCharacterEncoding( - TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - } - else if ( !(N < cFileHeaderID::MAXBYTES) ) - { - throw - eCharacter( - TSS_GetString( cCore, core::STR_ERR_OVERFLOW ) ); - } - } - - mIDLen = (int16)(::wcstombs( mID, pszId, N )); // Do it + size_t N = ::strlen(pszId); + if (!(N < cFileHeaderID::MAXBYTES)) + throw eCharacter(TSS_GetString(cCore, core::STR_ERR_OVERFLOW)); -#else - - size_t N = ::strlen( pszId ); - if ( !(N < cFileHeaderID::MAXBYTES) ) - throw eCharacter( TSS_GetString( cCore, core::STR_ERR_OVERFLOW ) ); - - mIDLen = static_cast( N ); // know len is less than MAXBYTES - ::memcpy( mID, pszId, N * sizeof(char) ); - -#endif + mIDLen = static_cast(N); // know len is less than MAXBYTES + ::memcpy(mID, pszId, N * sizeof(char)); } -void cFileHeaderID::operator=( const cFileHeaderID& rhs ) +void cFileHeaderID::operator=(const cFileHeaderID& rhs) { - ASSERT( rhs.mIDLen < cFileHeaderID::MAXBYTES ); + ASSERT(rhs.mIDLen < cFileHeaderID::MAXBYTES); mIDLen = rhs.mIDLen; memcpy(mID, rhs.mID, mIDLen * sizeof(char)); } -int cFileHeaderID::operator==( const cFileHeaderID& rhs ) const +int cFileHeaderID::operator==(const cFileHeaderID& rhs) const { - return - ( mIDLen == rhs.mIDLen ) && - ( ::memcmp( mID, rhs.mID, mIDLen * sizeof(char) ) == 0 ); + return (mIDLen == rhs.mIDLen) && (::memcmp(mID, rhs.mID, mIDLen * sizeof(char)) == 0); } -void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/ ) // throw (eSerializer, eArchive) +void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eSerializer, eArchive) { int16 len; - pSerializer->ReadInt16( len ); - if ( (len < 0) || (len >= cFileHeaderID::MAXBYTES )) + pSerializer->ReadInt16(len); + if ((len < 0) || (len >= cFileHeaderID::MAXBYTES)) { // this is invalid! - throw eSerializerInputStreamFmt( _T("File Header ID invalid") ); + throw eSerializerInputStreamFmt(_T("File Header ID invalid")); } pSerializer->ReadBlob(mID, len * sizeof(char)); mIDLen = len; @@ -125,19 +97,18 @@ void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/ ) // throw void cFileHeaderID::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) { - ASSERT( mIDLen >= 0 && mIDLen < cFileHeaderID::MAXBYTES ); - - pSerializer->WriteInt16( mIDLen ); - pSerializer->WriteBlob( mID, mIDLen * sizeof(char) ); + ASSERT(mIDLen >= 0 && mIDLen < cFileHeaderID::MAXBYTES); + + pSerializer->WriteInt16(mIDLen); + pSerializer->WriteBlob(mID, mIDLen * sizeof(char)); } /////////////////////////////////////////////////////////////////////////////// // class cFileHeader -cFileHeader::cFileHeader() -: mVersion(0) +cFileHeader::cFileHeader() : mVersion(0) { -#ifdef _DEBUG +#ifdef DEBUG mEncoding = LAST_ENCODING; // set to invalid value so we can assert on write #else mEncoding = NO_ENCODING; @@ -145,20 +116,14 @@ cFileHeader::cFileHeader() } cFileHeader::cFileHeader(const cFileHeader& rhs) -: iSerializable(), - mID(rhs.mID), - mVersion(rhs.mVersion), - mEncoding(rhs.mEncoding) + : iSerializable(), mID(rhs.mID), mVersion(rhs.mVersion), mEncoding(rhs.mEncoding) { if (rhs.mBaggage.Length() > 0) { mBaggage.MapArchive(0, rhs.mBaggage.Length()); rhs.mBaggage.MapArchive(0, rhs.mBaggage.Length()); - - ::memcpy( - mBaggage.GetMap(), - rhs.mBaggage.GetMap(), - static_cast( rhs.mBaggage.Length() ) ); + + ::memcpy(mBaggage.GetMap(), rhs.mBaggage.GetMap(), static_cast(rhs.mBaggage.Length())); mBaggage.MapArchive(0, 0); rhs.mBaggage.MapArchive(0, 0); @@ -197,18 +162,18 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS if ((unsigned int)magicNumber != FILE_HEADER_MAGIC_NUMBER) { d.TraceDebug("Bad magic number"); - throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); + throw eSerializerInputStreamFmt(pSerializer->GetFileName()); } // Note this version refers to the format of this data structure in the - // file image. mVersion refers to the version of data that accompanies + // file image. mVersion refers to the version of data that accompanies // this cFileHeader, for example the database or report format. pSerializer->ReadInt32(version); if (version > 1) { // don't understand the version d.TraceDebug("Bad version"); - throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); + throw eSerializerInputStreamFmt(pSerializer->GetFileName()); } mID.Read(pSerializer); @@ -222,7 +187,7 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS pSerializer->ReadInt32(len); if (len < 0 || len > 0xffff) - throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); + throw eSerializerInputStreamFmt(pSerializer->GetFileName()); mBaggage.MapArchive(0, len); @@ -239,19 +204,19 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS void cFileHeader::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) { -#ifdef _DEBUG +#ifdef DEBUG // check that we set some values cFileHeaderID id; ASSERT(mID != id); ASSERT(mEncoding != LAST_ENCODING); #endif - // we need to have our own versioning since we are not + // we need to have our own versioning since we are not // a iTypedSerializable object. pSerializer->WriteInt32(FILE_HEADER_MAGIC_NUMBER); // Note this version refers to the format of this data structure in the - // file image. mVersion refers to the version of data that accompanies + // file image. mVersion refers to the version of data that accompanies // this cFileHeader, for example the database or report format. pSerializer->WriteInt32(1); // version @@ -259,21 +224,20 @@ void cFileHeader::Write(iSerializer* pSerializer) const // throw (eSerializer, e pSerializer->WriteInt32(mVersion); - pSerializer->WriteInt16( static_cast(mEncoding) ); + pSerializer->WriteInt16(static_cast(mEncoding)); - int32 len = static_cast( mBaggage.Length() ); + int32 len = static_cast(mBaggage.Length()); ASSERT(len >= 0); ASSERT(len <= 0xFFFF); - if ( len < 0 || len > 0xFFFF ) + if (len < 0 || len > 0xFFFF) throw eSerializerOutputStreamFmt(); pSerializer->WriteInt32(len); if (len > 0) - { + { mBaggage.MapArchive(0, len); pSerializer->WriteBlob(mBaggage.GetMap(), len); } } - diff --git a/src/core/fileheader.h b/src/core/fileheader.h index cb5806c..78b723d 100644 --- a/src/core/fileheader.h +++ b/src/core/fileheader.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -54,13 +54,13 @@ class cFileHeaderID : public iSerializable cFileHeaderID(const cFileHeaderID& rhs); virtual ~cFileHeaderID(); - void operator = (const TCHAR* id); - void operator = (const cFileHeaderID& rhs); - int operator == (const cFileHeaderID& rhs) const; - int operator != (const cFileHeaderID& rhs) const; + void operator=(const TCHAR* id); + void operator=(const cFileHeaderID& rhs); + int operator==(const cFileHeaderID& rhs) const; + int operator!=(const cFileHeaderID& rhs) const; - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) private: // For now we will store the id as a string. @@ -68,10 +68,13 @@ class cFileHeaderID : public iSerializable // the way we implemented cFCONames. // Note: We store the string as narrow chars, since // the program is the only person who will see them. - int16 mIDLen; + int16 mIDLen; - enum { MAXBYTES = 256 }; - char mID[ MAXBYTES ]; + enum + { + MAXBYTES = 256 + }; + char mID[MAXBYTES]; }; inline cFileHeaderID::cFileHeaderID() @@ -84,14 +87,12 @@ inline cFileHeaderID::cFileHeaderID(const TCHAR* id) *this = id; } -inline -cFileHeaderID::cFileHeaderID( const cFileHeaderID& rhs ) : - iSerializable(), mIDLen( rhs.mIDLen ) +inline cFileHeaderID::cFileHeaderID(const cFileHeaderID& rhs) : iSerializable(), mIDLen(rhs.mIDLen) { - memcpy( mID, rhs.mID, MAXBYTES ); + memcpy(mID, rhs.mID, MAXBYTES); } -inline int cFileHeaderID::operator != (const cFileHeaderID& rhs) const +inline int cFileHeaderID::operator!=(const cFileHeaderID& rhs) const { return !(*this == rhs); } @@ -115,26 +116,26 @@ class cFileHeader : public iSerializable LAST_ENCODING }; - void SetID(const cFileHeaderID& id); - const cFileHeaderID& GetID() const; + void SetID(const cFileHeaderID& id); + const cFileHeaderID& GetID() const; - void SetVersion(uint32 v); - uint32 GetVersion() const; + void SetVersion(uint32 v); + uint32 GetVersion() const; - void SetEncoding(Encoding e); - Encoding GetEncoding() const; + void SetEncoding(Encoding e); + Encoding GetEncoding() const; - cMemoryArchive& GetBaggage(); - const cMemoryArchive& GetBaggage() const; + cMemoryArchive& GetBaggage(); + const cMemoryArchive& GetBaggage() const; - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: - cFileHeaderID mID; - uint32 mVersion; - Encoding mEncoding; - cMemoryArchive mBaggage; // items that have been serialized to this object + cFileHeaderID mID; + uint32 mVersion; + Encoding mEncoding; + cMemoryArchive mBaggage; // items that have been serialized to this object }; inline const cFileHeaderID& cFileHeader::GetID() const @@ -163,4 +164,3 @@ inline const cMemoryArchive& cFileHeader::GetBaggage() const } #endif - diff --git a/src/core/fixedfilebuf.h b/src/core/fixedfilebuf.h index adf7d00..f646801 100644 --- a/src/core/fixedfilebuf.h +++ b/src/core/fixedfilebuf.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,8 +34,8 @@ // Date....: 8/12/99 // Creator.: Brian McFeely (bmcfeely) // -// Plauger's 'basic_filebuf::overflow' had a bug, -// so I had to reimplement the entire class. +// Plauger's 'basic_filebuf::overflow' had a bug, +// so I had to reimplement the entire class. // // Plauger had a line: "fwrite(_Str->begin(), _N, 1, _File)" // that should have been: "fwrite(_Str->begin(), 1, _N, _File)" @@ -45,10 +45,6 @@ #define __FIXED_FILEBUF_H #include - -#if IS_UNIX #define fixed_basic_ofstream std::basic_ofstream -#endif // IS_WIN32/IS_UNIX - -#endif//__FIXED_FILEBUF_H +#endif //__FIXED_FILEBUF_H diff --git a/src/core/fsservices.cpp b/src/core/fsservices.cpp index 7f68d62..3817582 100644 --- a/src/core/fsservices.cpp +++ b/src/core/fsservices.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,5 +43,3 @@ iFSServices* iFSServices::mpInstance = 0; //############################################################################# // eFSServices //############################################################################# - - diff --git a/src/core/fsservices.h b/src/core/fsservices.h index 0f8ad2f..43ce5e6 100644 --- a/src/core/fsservices.h +++ b/src/core/fsservices.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,7 +36,7 @@ // // objective: // abstract all file system calls, except for reading/writing -// to elaborate: this class does not handle any file I/O -- we +// to elaborate: this class does not handle any file I/O -- we // intend to use streams to abstract out file I/O // abstract case sensitivity of underlying file system // @@ -65,38 +65,41 @@ // STANDARD LIBRARY INCLUDES //========================================================================= -#if IS_UNIX - #if HAVE_SYS_PARAM_H - #include - #endif +#if HAVE_SYS_PARAM_H +#include #endif +#if HAVE_SYS_STAT_H +#include +#endif + + //========================================================================= // DEFINES AND MACROS //========================================================================= -// macros for extracting the major and minor portions of int64's: +// macros for extracting the major and minor portions of int64's: #if !defined(major) -#if !USES_GLIBC -#define major(x) ((int)((x) >> 8) & 0xff) -#define minor(x) ((int)((x) & 0xff)) -#else -#ifdef WORDS_BIGENDIAN -#define major(x) (int)(((char*)&(x))[2]) -#define minor(x) (int)(((char*)&(x))[3]) -#else -#define major(x) (int)(((char*)&(x))[1]) -#define minor(x) (int)(((char*)&(x))[0]) -#endif -#endif +# if !USES_GLIBC +# define major(x) ((int)((x) >> 8) & 0xff) +# define minor(x) ((int)((x)&0xff)) +# else +# ifdef WORDS_BIGENDIAN +# define major(x) (int)(((char*)&(x))[2]) +# define minor(x) (int)(((char*)&(x))[3]) +# else +# define major(x) (int)(((char*)&(x))[1]) +# define minor(x) (int)(((char*)&(x))[0]) +# endif +# endif #endif /* !major */ //========================================================================= // TYPEDEFS //========================================================================= -typedef int64 cFSTime; -typedef int64 cFSType; +typedef int64 cFSTime; +typedef int64 cFSType; //========================================================================= // GLOBALS @@ -111,280 +114,232 @@ typedef int64 cFSType; //========================================================================= // filesystem access control lists -// it is the union of MAX(elem) for all the file systems that we support -class cACLElem { +// it is the union of MAX(elem) for all the file systems that we support +/*class cACLElem { // TODO this is just a place holder // uint32 mUid; -}; +};*/ // this class is used only to pass arguments to iFSServices -// it is the union of MAX(elem) for all the file systems that we support -struct cFSStatArgs { - enum FileType { - TY_INVALID, // lazy evaluation - TY_FILE, - TY_DIR, - TY_BLOCKDEV, - TY_CHARDEV, - TY_SYMLINK, - TY_FIFO, - TY_SOCK, - TY_DOOR, - TY_PORT - }; - - // attr is fs dependent? - uint64 dev; // dep - int64 ino; // dep - int64 mode; // dep - int64 nlink; // indep - int64 uid; // dep - int64 gid; // dep - uint64 rdev; // dep - int64 size; // indep - cFSTime atime; // indep - cFSTime mtime; // indep - cFSTime ctime; // indep - int64 blksize; // indep - int64 blocks; // dep - int64 fstype; // dep - TSTRING usid; // dep - TSTRING gsid; // dep -// int64 mFileType; // Matt's addition... - - FileType mFileType; // redundant with other information in this struct, but - // broken out for convenience - - // access control list should go here, too - std::list mACL; // indep +// it is the union of MAX(elem) for all the file systems that we support +struct cFSStatArgs +{ + enum FileType + { + TY_INVALID, // lazy evaluation + TY_FILE, + TY_DIR, + TY_BLOCKDEV, + TY_CHARDEV, + TY_SYMLINK, + TY_FIFO, + TY_SOCK, + TY_DOOR, + TY_PORT, + TY_NAMED + }; + + // attr is fs dependent? + uint64 dev; // dep + int64 ino; // dep + int64 mode; // dep + int64 nlink; // indep + int64 uid; // dep + int64 gid; // dep + uint64 rdev; // dep + int64 size; // indep + cFSTime atime; // indep + cFSTime mtime; // indep + cFSTime ctime; // indep + int64 blksize; // indep + int64 blocks; // dep + int64 fstype; // dep + TSTRING usid; // dep + TSTRING gsid; // dep + // int64 mFileType; // Matt's addition... + + FileType mFileType; // redundant with other information in this struct, but + // broken out for convenience + + //TODO: access control list should go here, too + //std::list mACL; // indep }; - //========================================================================= // // eFSServices -- exception class // //========================================================================= -TSS_FILE_EXCEPTION( eFSServices, eFileError ); -TSS_FILE_EXCEPTION( eFSServicesGeneric, eFSServices ); +TSS_FILE_EXCEPTION(eFSServices, eFileError); +TSS_FILE_EXCEPTION(eFSServicesGeneric, eFSServices); //========================================================================= // // iFSServices -- abstracts all file system calls, except for opening, reading, -// and writing, which will be handled by standard c++. +// and writing, which will be handled by standard c++. // NOTE -- all paths returned from this class will be delimited with a '/' // //========================================================================= -class iFSServices +class iFSServices { - public: - virtual ~iFSServices() {} - /////////////////////////////////////////////////////////////// - // ENUMS - /////////////////////////////////////////////////////////////// - - //////////////////////////////////////// - // file creation modes - //////////////////////////////////////// - enum Mode - { - MODE_DEFAULT = 0, - MODE_READ = 1, - MODE_WRITE = 2, - MODE_SHARE_DELETE = 4, - MODE_SHARE_READ = 8, - MODE_SHARE_WRITE = 16, - MODE_CREATE_EXCL = 32, - MODE_CREATE_TRUNCATE = 64 - }; - - //////////////////////////////////////// - // maximum path length on platform - //////////////////////////////////////// - enum - { -#if IS_UNIX - #ifdef MAXPATHLEN - TW_MAX_PATH = MAXPATHLEN - #else - TW_MAX_PATH = 1024 - #endif +public: + virtual ~iFSServices() + { + } + /////////////////////////////////////////////////////////////// + // ENUMS + /////////////////////////////////////////////////////////////// + + //////////////////////////////////////// + // file creation modes + //////////////////////////////////////// + enum Mode + { + MODE_DEFAULT = 0, + MODE_READ = 1, + MODE_WRITE = 2, + MODE_SHARE_DELETE = 4, + MODE_SHARE_READ = 8, + MODE_SHARE_WRITE = 16, + MODE_CREATE_EXCL = 32, + MODE_CREATE_TRUNCATE = 64 + }; + + //////////////////////////////////////// + // maximum path length on platform + //////////////////////////////////////// + enum + { +#ifdef MAXPATHLEN + TW_MAX_PATH = MAXPATHLEN +#else + TW_MAX_PATH = 1024 #endif - }; - - /////////////////////////////////////////////////////////////// - // MEMBER FUNCTIONS - /////////////////////////////////////////////////////////////// - - - //////////////////////////////////////// - // platform specific functions - //////////////////////////////////////// - virtual bool IsCaseSensitive() const = 0; - // returns true if the file system is case sensitive - virtual TCHAR GetPathSeparator() const = 0; - // returns "/" for unix and "\\" for win32 - virtual const TCHAR* GetStandardBackupExtension() const = 0; - // returns normal string to append to backup files for this os. - - //////////////////////////////////////// - // process functions - //////////////////////////////////////// - virtual void Sleep( int nSeconds ) const = 0; - // makes the current process sleep for the specified number of seconds - - - //////////////////////////////////////// - // major filesystem functions - //////////////////////////////////////// - virtual void Stat( const TSTRING& strFileName, cFSStatArgs& pStat ) const throw( eFSServices ) = 0; - // fills out the cFSStatArgs structure with the stat info for the named file - virtual void GetTempDirName( TSTRING& strName ) const throw( eFSServices ) = 0; - // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) - - virtual void SetTempDirName( TSTRING& tmpName ) = 0; - - virtual TSTRING& MakeTempFilename( TSTRING& strName ) const throw( eFSServices ) = 0; - // create temporary file - // TSTRING must have the form ("baseXXXXXX"), where the X's are replaced with - // characters to make it a unique file. There must be at least 6 Xs. - - // TODO: remove this function - // Matt theorized that this is no longer used - dmb Aug 23 1999 - // virtual int CreateLockedTemporaryFile( const TCHAR* szFilename, int perm ) const = 0; - // creates a temporary file to which only the current process has read or write access. - // returns an open C file descriptor on success and -1 on error. Returns error if filename already exists on the filesystem. - // the file will automatically be deleted when the file descriptor is closed. - // perm should be zero or more of: - // O_WRONLY: create with read write only permission - // O_RDWR: create with read and write permission - - - //////////////////////////////////////// - // minor filesystem functions - //////////////////////////////////////// - virtual void GetHostID( TSTRING& name ) const = 0; - - virtual void GetMachineName( TSTRING& name ) const throw(eFSServices) = 0; - - virtual void GetMachineNameFullyQualified( TSTRING& name ) const = 0; - - virtual bool GetCurrentUserName( TSTRING& tstrName ) const = 0; - - virtual bool GetIPAddress( uint32& uiIPAddress ) = 0; - - - //////////////////////////////////////// - // directory specific functions - //////////////////////////////////////// - virtual void ReadDir( const TSTRING& strName, std::vector &vDirContents, bool bFullPaths = true ) const throw( eFSServices ) = 0; - // puts the contents of the specified directory, except for . and .., into the supplied vector. - // if bFullPaths is true, then the vector contains fully qualified path names; otherwise, it only contains the - // short names. - virtual void GetCurrentDir( TSTRING& strCurDir ) const throw( eFSServices ) = 0; - // returns the current working directory - virtual void ChangeDir( const TSTRING& strName ) const throw( eFSServices ) = 0; - // sets the current working directory - virtual void Mkdir( const TSTRING& strName ) const throw( eFSServices ) = 0; - - virtual bool Rmdir( const TSTRING& strName ) const = 0; - - - //////////////////////////////////////// - // file specific functions - //////////////////////////////////////// - virtual bool FileDelete( const TSTRING& name ) const = 0; - - - //////////////////////////////////////// - // directory and file functions - //////////////////////////////////////// - virtual bool Rename( const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true ) const = 0; - // rename a file - virtual bool GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tstrUser ) const = 0; - - virtual bool GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tstrGroup ) const = 0; - - - //////////////////////////////////////// - // miscellaneous utility functions - //////////////////////////////////////// - virtual void ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const = 0; - // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) - virtual bool FullPath( TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("") ) const = 0; - // converts relPath into a fully qualified path, storing it in FullPath. If this - // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. - // TODO: In some places we have depended on the behaviour that if relPath.empty() == true then we - // fail or return an empty string. Should we add this behaviour to the interface? - virtual bool GetExecutableFilename( TSTRING& strFullPath, const TSTRING& strFilename ) const = 0; - // get the path to the current executable file - virtual bool IsRoot( const TSTRING& strPath ) const = 0; - // returns true if strPath denotes a root path - - - //////////////////////////////////////// - // error functions - //////////////////////////////////////// - virtual TSTRING GetErrString() const = 0; - // Returns an error string that is appropriate for the system, (e.g. errorstr(errno) - // on UNIX and FormatError( ..., GetLastError(), ...) in Win32 - // Call this immediately after a failed system call to get a string - // representation of the error event. - - - //////////////////////////////////////// - // singleton manipulation - //////////////////////////////////////// - static iFSServices* GetInstance(); - static void SetInstance( iFSServices* pInst ); - - - /////////////////////////////////////////////////////////////// - // PRIVATE DATA - /////////////////////////////////////////////////////////////// - private: - static iFSServices* mpInstance; - - //virtual cFSStatArgs::FileType GetFileType(const cFCOName &filename) throw(eFSServices) = 0; - // returns the type of the file specified by filename. Separated from Stat() for convenience - // and potential efficiency (if a file system doesn't need to do a stat to get the file type) - - //virtual char*& MakeTempFile( char*& name) throw(eFSServices) = 0; - //virtual wchar_t*& MakeTempFile( wchar_t*& name) throw(eFSServices) = 0; - - // - // file ops - // - // these are commented out for timeliness reasons; we should uncomment and implement as needed... - // -- mdb - /* - virtual int Create(cFSName &name, Mode mode = MODE_DEFAULT) = 0; - virtual bool Mkdir(cFSName &name, Mode mode = MODE_DEFAULT) = 0; - virtual bool Delete(cFSName &name) = 0; - virtual bool Link(cFSName &src, cFSName &dest) = 0; - - virtual bool Chmod(cFSName &name, Mode mode) = 0; - virtual Mode Umask(Mode mode) = 0; - // file system types (e.g., "FAT", "NTFS", "UFS", "NFS") - virtual bool FSTypeAsString(cFSName &name, TSTRING &str) = 0; - // file type (e.g., "file", "symbolic link", "block device") - // TODO -- this should either be static or in another utility class, since it does not rely on the - // instance of the class (there is a global enumeration of file types; this fn should take a - // cFSStatArgs::FileType instead of a name. - virtual bool FileTypeAsString(cFSName &filename, TSTRING &str) = 0; - // TODO -- does this beling here? Is it always true that st_dev defines the file system? If not, then the - // Stat() call should add some extra piece of data that identifies the file system. - virtual bool IsSameFileSystem(cFSStatArgs &file1, cFSStatArgs &file2) = 0; - // to determine whether to recurse - musn't traverse mount points - - // capabilities - virtual bool IsUnicodeFilename(cFSName &name) = 0; - virtual bool IsACLCapable(cFSName &name) = 0; - virtual bool Is8bitFilename(cFSName &name) = 0; - */ + }; + + /////////////////////////////////////////////////////////////// + // MEMBER FUNCTIONS + /////////////////////////////////////////////////////////////// + + + //////////////////////////////////////// + // platform specific functions + //////////////////////////////////////// + virtual bool IsCaseSensitive() const = 0; + // returns true if the file system is case sensitive + virtual TCHAR GetPathSeparator() const = 0; + // returns "/" for unix and "\\" for win32 + virtual const TCHAR* GetStandardBackupExtension() const = 0; + // returns normal string to append to backup files for this os. + + //////////////////////////////////////// + // process functions + //////////////////////////////////////// + virtual void Sleep(int nSeconds) const = 0; + // makes the current process sleep for the specified number of seconds + + + //////////////////////////////////////// + // major filesystem functions + //////////////////////////////////////// + virtual void Stat(const TSTRING& strFileName, cFSStatArgs& pStat) const = 0; + // fills out the cFSStatArgs structure with the stat info for the named file + virtual void GetTempDirName(TSTRING& strName) const = 0; + // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) + + virtual void SetTempDirName(TSTRING& tmpName) = 0; + + virtual TSTRING& MakeTempFilename(TSTRING& strName) const = 0; + // create temporary file + // TSTRING must have the form ("baseXXXXXX"), where the X's are replaced with + // characters to make it a unique file. There must be at least 6 Xs. + + + //////////////////////////////////////// + // minor filesystem functions + //////////////////////////////////////// + virtual void GetHostID(TSTRING& name) const = 0; + + virtual void GetMachineName(TSTRING& name) const = 0; + + virtual void GetMachineNameFullyQualified(TSTRING& name) const = 0; + + virtual bool GetCurrentUserName(TSTRING& tstrName) const = 0; + + virtual bool GetIPAddress(uint32& uiIPAddress) = 0; + + + //////////////////////////////////////// + // directory specific functions + //////////////////////////////////////// + virtual void ReadDir(const TSTRING& strName, std::vector& vDirContents, bool bFullPaths = true) const = 0; + // puts the contents of the specified directory, except for . and .., into the supplied vector. + // if bFullPaths is true, then the vector contains fully qualified path names; otherwise, it only contains the + // short names. + virtual void GetCurrentDir(TSTRING& strCurDir) const = 0; + // returns the current working directory + + + //////////////////////////////////////// + // file specific functions + //////////////////////////////////////// + virtual bool FileDelete(const TSTRING& name) const = 0; + + //////////////////////////////////////// + // directory and file functions + //////////////////////////////////////// + virtual bool Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true) const = 0; + // rename a file + + virtual bool GetUserName(uid_t user_id, TSTRING& tstrUser) const = 0; + virtual bool GetGroupName(gid_t group_id, TSTRING& tstrGroup) const = 0; + + //Set whether we try to resolve uid/gid to a name, since Linux static binaries can + //have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup. + //This defaults to true if not specified. + virtual void SetResolveNames(bool resolve) = 0; + + //////////////////////////////////////// + // miscellaneous utility functions + //////////////////////////////////////// + virtual void ConvertModeToString(uint64 perm, TSTRING& tstrPerm) const = 0; + // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) + virtual bool FullPath(TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("")) const = 0; + // converts relPath into a fully qualified path, storing it in FullPath. If this + // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. + // TODO: In some places we have depended on the behaviour that if relPath.empty() == true then we + // fail or return an empty string. Should we add this behaviour to the interface? + virtual bool GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const = 0; + // get the path to the current executable file + virtual bool IsRoot(const TSTRING& strPath) const = 0; + // returns true if strPath denotes a root path + + + //////////////////////////////////////// + // error functions + //////////////////////////////////////// + virtual TSTRING GetErrString() const = 0; + // Returns an error string that is appropriate for the system, (e.g. errorstr(errno) + // on UNIX and FormatError( ..., GetLastError(), ...) in Win32 + // Call this immediately after a failed system call to get a string + // representation of the error event. + + + //////////////////////////////////////// + // singleton manipulation + //////////////////////////////////////// + static iFSServices* GetInstance(); + static void SetInstance(iFSServices* pInst); + + + /////////////////////////////////////////////////////////////// + // PRIVATE DATA + /////////////////////////////////////////////////////////////// +private: + static iFSServices* mpInstance; }; @@ -393,16 +348,15 @@ class iFSServices //========================================================================= inline iFSServices* iFSServices::GetInstance() { - ASSERT(mpInstance != 0); + ASSERT(mpInstance != 0); - return mpInstance; + return mpInstance; } -inline void iFSServices::SetInstance( iFSServices* pInst ) +inline void iFSServices::SetInstance(iFSServices* pInst) { - mpInstance = pInst; + mpInstance = pInst; } #endif - diff --git a/src/core/growheap.cpp b/src/core/growheap.cpp index e1142ff..b6d384a 100644 --- a/src/core/growheap.cpp +++ b/src/core/growheap.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,48 +44,51 @@ class cGrowHeap_i class cHeap { public: - size_t mSize; - int8* mpData; - - cHeap( size_t size ) : mSize( size ), mpData( new int8[size] ) { ASSERT(mpData != 0); } - // Note: The above ASSERT should never occur! If the new failed we should have thrown a bad_alloc(). + size_t mSize; + int8* mpData; + + cHeap(size_t size) : mSize(size), mpData(new int8[size]) + { + ASSERT(mpData != 0); + } + // Note: The above ASSERT should never occur! If the new failed we should have thrown a bad_alloc(). }; typedef std::vector HeapList; - size_t mInitialSize; - size_t mGrowBy; - HeapList mHeaps; - TSTRING mName; - size_t mCurOff; - - cGrowHeap_i( size_t initialSize, size_t growBy, const TCHAR* name ); - ~cGrowHeap_i() { Clear(); } - - size_t AlignSizeRequest( size_t size, size_t alignSize ); - void* Malloc( size_t size ); - void Clear(); + size_t mInitialSize; + size_t mGrowBy; + HeapList mHeaps; + TSTRING mName; + size_t mCurOff; + + cGrowHeap_i(size_t initialSize, size_t growBy, const TCHAR* name); + ~cGrowHeap_i() + { + Clear(); + } + + size_t AlignSizeRequest(size_t size, size_t alignSize); + void* Malloc(size_t size); + void Clear(); }; -cGrowHeap_i::cGrowHeap_i( size_t initialSize, size_t growBy, const TCHAR* name ) -: mInitialSize( initialSize ), - mGrowBy ( growBy ), - mName ( name ), - mCurOff ( 0 ) +cGrowHeap_i::cGrowHeap_i(size_t initialSize, size_t growBy, const TCHAR* name) + : mInitialSize(initialSize), mGrowBy(growBy), mName(name), mCurOff(0) { // assure that initial size and growby are aligned - ASSERT( 0 == ( initialSize % BYTE_ALIGN ) ); - ASSERT( 0 == ( growBy % BYTE_ALIGN ) ); + ASSERT(0 == (initialSize % BYTE_ALIGN)); + ASSERT(0 == (growBy % BYTE_ALIGN)); } size_t cGrowHeap::TotalMemUsage() const { size_t usage = 0; - for( cGrowHeap_i::HeapList::const_iterator i = mpData->mHeaps.begin(); i != mpData->mHeaps.end(); i++ ) + for (cGrowHeap_i::HeapList::const_iterator i = mpData->mHeaps.begin(); i != mpData->mHeaps.end(); i++) { usage += i->mSize; } - if( ! mpData->mHeaps.empty() ) + if (!mpData->mHeaps.empty()) { // take off the unused portion... usage -= (mpData->mHeaps.back().mSize - mpData->mCurOff); @@ -94,23 +97,23 @@ size_t cGrowHeap::TotalMemUsage() const } -void* cGrowHeap_i::Malloc( size_t size ) +void* cGrowHeap_i::Malloc(size_t size) { - size = AlignSizeRequest( size, BYTE_ALIGN ); + size = AlignSizeRequest(size, BYTE_ALIGN); - ASSERT( ( size > 0 ) && ( size < mGrowBy ) ); + ASSERT((size > 0) && (size < mGrowBy)); - if( size >= mGrowBy ) + if (size >= mGrowBy) return NULL; - if( mHeaps.empty() ) + if (mHeaps.empty()) { - mHeaps.push_back( cHeap( mInitialSize ) ); + mHeaps.push_back(cHeap(mInitialSize)); ASSERT(mHeaps.back().mpData != 0); - mCurOff = 0; + mCurOff = 0; } - - if( mCurOff + size < mHeaps.back().mSize ) + + if (mCurOff + size < mHeaps.back().mSize) { // we have room to add this to the current heap. // @@ -122,43 +125,43 @@ void* cGrowHeap_i::Malloc( size_t size ) } else { - mHeaps.push_back( cHeap( mGrowBy ) ); + mHeaps.push_back(cHeap(mGrowBy)); ASSERT(mHeaps.back().mpData != 0); mCurOff = 0; - #ifdef _DEUBG - void* ret = Malloc( size ); - ASSERT(ret != 0); - return ret; - #else - return Malloc( size ); - #endif +#ifdef _DEUBG + void* ret = Malloc(size); + ASSERT(ret != 0); + return ret; +#else + return Malloc(size); +#endif } } -size_t cGrowHeap_i::AlignSizeRequest( size_t size, size_t alignSize ) +size_t cGrowHeap_i::AlignSizeRequest(size_t size, size_t alignSize) { // The two's complement algorithm requires a non-zero size request size, // so make make all requests require it so that this function // acts the same no matter what the integer representation - if( 0 == size ) + if (0 == size) size = 1; #if USES_2S_COMPLEMENT - // This efficient algorithm assumes alignSize is power of two AND a + // This efficient algorithm assumes alignSize is power of two AND a // 2's complement representation. Requires non-zero size request - ASSERT( 0 == ( alignSize % 2 ) ); - ASSERT( size > 0 ); - return( ( size + alignSize - 1 ) & ~( alignSize - 1 ) ); + ASSERT(0 == (alignSize % 2)); + ASSERT(size > 0); + return ((size + alignSize - 1) & ~(alignSize - 1)); #else // this makes no assumption about BYTE_ALIGN or hardware integer representation - return( ( ( size / alignSize ) + ( ( size % alignSize ) ? 1 : 0 ) ) * alignSize ); + return (((size / alignSize) + ((size % alignSize) ? 1 : 0)) * alignSize); #endif } void cGrowHeap_i::Clear() { - for( HeapList::iterator i = mHeaps.begin(); i != mHeaps.end(); i++ ) + for (HeapList::iterator i = mHeaps.begin(); i != mHeaps.end(); i++) { delete [] i->mpData; } @@ -168,27 +171,25 @@ void cGrowHeap_i::Clear() //----------------------------------------------------------------------------- // cGrowHeap //----------------------------------------------------------------------------- -cGrowHeap::cGrowHeap( size_t initialSize, size_t growBy, const TCHAR* name ) : - mpData( new cGrowHeap_i( initialSize, growBy, name ) ) +cGrowHeap::cGrowHeap(size_t initialSize, size_t growBy, const TCHAR* name) + : mpData(new cGrowHeap_i(initialSize, growBy, name)) { - } cGrowHeap::~cGrowHeap() { cDebug d("FCO name heap stats"); - d.TraceDebug( _T("Total heap memory usage for %s: %d\n"), mpData->mName.c_str(), TotalMemUsage() ); - + d.TraceDebug(_T("Total heap memory usage for %s: %d\n"), mpData->mName.c_str(), TotalMemUsage()); + delete mpData; } -void* cGrowHeap::Malloc( size_t size ) +void* cGrowHeap::Malloc(size_t size) { - return mpData->Malloc( size ); + return mpData->Malloc(size); } void cGrowHeap::Clear() { mpData->Clear(); } - diff --git a/src/core/growheap.h b/src/core/growheap.h index d255480..11b0b11 100644 --- a/src/core/growheap.h +++ b/src/core/growheap.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,24 +49,23 @@ //----------------------------------------------------------------------------- class cGrowHeap_i; -class cGrowHeap +class cGrowHeap { public: - cGrowHeap( size_t initialSize, size_t growby, const TCHAR* name ); - // creates a heap that is initially initialSize big, and increases the - // size by growBy every time there is no more room. - // initialSize and growby must be a multiple of BYTE_ALIGN + cGrowHeap(size_t initialSize, size_t growby, const TCHAR* name); + // creates a heap that is initially initialSize big, and increases the + // size by growBy every time there is no more room. + // initialSize and growby must be a multiple of BYTE_ALIGN ~cGrowHeap(); - void* Malloc( size_t size ); - void Clear(); - // resets the grow heap's state. - size_t TotalMemUsage() const; - // returns the total memory usage of this heap + void* Malloc(size_t size); + void Clear(); + // resets the grow heap's state. + size_t TotalMemUsage() const; + // returns the total memory usage of this heap private: - cGrowHeap_i* mpData; + cGrowHeap_i* mpData; }; #endif - diff --git a/src/core/hashtable.cpp b/src/core/hashtable.cpp index dfe3ad6..bdffb59 100644 --- a/src/core/hashtable.cpp +++ b/src/core/hashtable.cpp @@ -1,36 +1,34 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // //hashtable.cpp : implementation for hashtable which maps const TCHAR*'s to void*'s #include "stdcore.h" #include "hashtable.h" - - diff --git a/src/core/hashtable.h b/src/core/hashtable.h index 658905e..9804994 100644 --- a/src/core/hashtable.h +++ b/src/core/hashtable.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,9 +34,9 @@ // implements cHashTable, which maps a key of arbitrary type to a value // of arbitrary type. The key data type MUST have the const byte*() // operator overloaded in order for this to work. TSTRINGS will always -// work as the key value because of the overloaded-template-function +// work as the key value because of the overloaded-template-function // -// Note: Any overloaded const byte*() operator must return an +// Note: Any overloaded const byte*() operator must return an // length of key as well. see cDefaultConvert // // IMPORTANT -- cDefaultConvert only works for pointers to objects @@ -63,12 +63,11 @@ /////////////////////////////////////////////////////////////////////////////// // Comparison function objects ... these are used by the hash table to determine -// equality. The one defined should work for objects that use op== to define +// equality. The one defined should work for objects that use op== to define // equality. There is also a specialization for TSTRINGS. If neither of these // fit your needs, you must pass the hash table your own fn pointer or class /////////////////////////////////////////////////////////////////////////////// -template -class cDefaultCompare +template class cDefaultCompare { public: bool operator()(const T& lhs, const T& rhs) @@ -79,19 +78,17 @@ class cDefaultCompare ///////////////////////////////////////////////////////// // specialization for TSTRINGS ///////////////////////////////////////////////////////// -template<> -inline bool cDefaultCompare::operator()(const TSTRING& lhs, const TSTRING& rhs) +template<> inline bool cDefaultCompare::operator()(const TSTRING& lhs, const TSTRING& rhs) { return (lhs.compare(rhs) == 0); } /////////////////////////////////////////////////////////////////////////////// // Conversion function objects ... used by the hash table to locate the key in KEY_TYPE -// into a byte* and a key length (for hashing purposes). The default implementation +// into a byte* and a key length (for hashing purposes). The default implementation // just does a cast. A specialization is also provided for TSTRINGs. /////////////////////////////////////////////////////////////////////////////// -template -class cDefaultConvert +template class cDefaultConvert { public: const byte* operator()(const T& obj, int* const pcbKeyLen) @@ -104,8 +101,7 @@ class cDefaultConvert ///////////////////////////////////////////////////////// // specialization for TSTRINGS ///////////////////////////////////////////////////////// -template<> -inline const byte* cDefaultConvert::operator()(const TSTRING& obj, int* const pcbKeyLen ) +template<> inline const byte* cDefaultConvert::operator()(const TSTRING& obj, int* const pcbKeyLen) { *pcbKeyLen = sizeof(TCHAR) * obj.length(); return (byte*)obj.c_str(); @@ -113,7 +109,7 @@ inline const byte* cDefaultConvert::operator()(const TSTRING& obj, int* /////////////////////////////////////////////////////////////////////////////// // cHashTable -// KEY -- the key you are hashing on +// KEY -- the key you are hashing on // VAL -- the value you want associated with that key // CMP -- a function object that takes (KEY, KEY) and returns true if they // are equal. @@ -123,7 +119,8 @@ inline const byte* cDefaultConvert::operator()(const TSTRING& obj, int* /////////////////////////////////////////////////////////////////////////////// // these were moved outside of the class because it sucks to have to name the class with template parameters // ie -- mTable(cHashTable::MEDIUM -enum cHashTable_TableSize { +enum cHashTable_TableSize +{ HASH_VERY_SMALL = 17, HASH_SMALL = 2007, HASH_MEDIUM = 6007, @@ -132,151 +129,165 @@ enum cHashTable_TableSize { }; // forward declaration -template , class CONVERTER = cDefaultConvert > +template, + class CONVERTER = cDefaultConvert > class cHashTableIter; //General version of cHashTable template: -template , class CONVERTER = cDefaultConvert > -class cHashTable +template, + class CONVERTER = cDefaultConvert > +class cHashTable { -friend class cHashTableIter; + friend class cHashTableIter; + public: //structure for hash table nodes. - struct node { + struct node + { KEY_TYPE nKey; VAL_TYPE nData; - node* next; + node* next; }; cHashTable(int tblSize = HASH_MEDIUM); ~cHashTable(); bool Insert(KEY_TYPE key, VAL_TYPE data_in); - // The pointer, data_in, is stored in a node based on string_in's hashing. - // - // if (key) already exists in the table, then it's value is replaced by (data_in) - // returns true if (key) already existed in table. otherwise, returns false - + // The pointer, data_in, is stored in a node based on string_in's hashing. + // + // if (key) already exists in the table, then it's value is replaced by (data_in) + // returns true if (key) already existed in table. otherwise, returns false + bool Lookup(KEY_TYPE key, VAL_TYPE& data_out) const; //bool Lookup(TSTRING key, VAL_TYPE& data_out) const; - //Lookup returns true if a match is found for string_check. A reference - //to the node in the table that matches string_check is passed back (by ref). + //Lookup returns true if a match is found for string_check. A reference + //to the node in the table that matches string_check is passed back (by ref). bool Remove(KEY_TYPE key); - //The node that matches string_out is de-allocated. + //The node that matches string_out is de-allocated. bool Clear(void); - //Clears the entire table and sets all node pointers to NULL - bool IsEmpty(void) const; - uint32 Hash( const KEY_TYPE& key ) const; - //The hashing function, taken from old Tripwire - int32 GetNumValues() const { return mValuesInTable; }; + //Clears the entire table and sets all node pointers to NULL + bool IsEmpty(void) const; + uint32 Hash(const KEY_TYPE& key) const; + //The hashing function, taken from old Tripwire + int32 GetNumValues() const + { + return mValuesInTable; + }; // returns number of table entries filled -#ifdef _DEBUG +#ifdef DEBUG void TraceDiagnostics() const; - // traces hash table statistics + // traces hash table statistics #endif private: - cHashTable(const cHashTable& rhs); // not impl - void operator=(const cHashTable& rhs); // not impl - + cHashTable(const cHashTable& rhs); // not impl + void operator=(const cHashTable& rhs); // not impl + node** mTable; - int mTableSize; - int32 mValuesInTable; + int mTableSize; + int32 mValuesInTable; }; /////////////////////////////////////////////////////////////////////////////// // cHashTableIter /////////////////////////////////////////////////////////////////////////////// -template -class cHashTableIter +template class cHashTableIter { public: cHashTableIter(const cHashTable& hashTbl); - void SeekBegin() const; - bool Done() const; - void Next() const; + void SeekBegin() const; + bool Done() const; + void Next() const; - const KEY_TYPE& Key() const; - const VAL_TYPE& Val() const; - VAL_TYPE& Val(); + const KEY_TYPE& Key() const; + const VAL_TYPE& Val() const; + VAL_TYPE& Val(); private: - mutable int mCurIndex; + mutable int mCurIndex; mutable typename cHashTable::node* mpCurNode; - const cHashTable& mHashTable; + const cHashTable& mHashTable; // helper function void SeekNextValid() const; }; - //############################################################################# // implementation /////////////////////////////////////////////////////////////////////////////// // iterator /////////////////////////////////////////////////////////////////////////////// -template -inline cHashTableIter::cHashTableIter( const cHashTable& hashTbl) : - mHashTable(hashTbl) +template +inline cHashTableIter::cHashTableIter( + const cHashTable& hashTbl) + : mHashTable(hashTbl) { SeekBegin(); } -template +template inline void cHashTableIter::SeekBegin() const { mCurIndex = 0; mpCurNode = mHashTable.mTable[0]; - if(! mpCurNode) + if (!mpCurNode) SeekNextValid(); } -template -inline bool cHashTableIter::Done() const +template +inline bool cHashTableIter::Done() const { return ((mCurIndex < 0) || (mCurIndex >= mHashTable.mTableSize)); } -template -inline void cHashTableIter::Next() const +template +inline void cHashTableIter::Next() const { SeekNextValid(); } -template +template inline void cHashTableIter::SeekNextValid() const { - if(mpCurNode) + if (mpCurNode) mpCurNode = mpCurNode->next; - //mCurIndex++; - while((! mpCurNode) && (mCurIndex < mHashTable.mTableSize)) + + // if we're out of range, bail out w/o incrementing index + if (mCurIndex >= mHashTable.mTableSize) + return; + + while ((!mpCurNode) && (++mCurIndex < mHashTable.mTableSize)) { - mpCurNode = mHashTable.mTable[++mCurIndex]; + mpCurNode = mHashTable.mTable[mCurIndex]; } } -template +template inline const KEY_TYPE& cHashTableIter::Key() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpCurNode->nKey; } -template -inline const VAL_TYPE& cHashTableIter::Val() const +template +inline const VAL_TYPE& cHashTableIter::Val() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpCurNode->nData; } -template +template inline VAL_TYPE& cHashTableIter::Val() { - ASSERT(! Done()); + ASSERT(!Done()); return mpCurNode->nData; } @@ -285,37 +296,38 @@ inline VAL_TYPE& cHashTableIter::Val( /////////////////////////////////////////////////////////////////////////////// //Default value for tblSize == 6007 -template +template cHashTable::cHashTable(int tblSize) { mValuesInTable = 0; - mTableSize = tblSize; - mTable = new node*[mTableSize]; + mTableSize = tblSize; + mTable = new node*[mTableSize]; - for (int i=0; i < mTableSize; ++i) + for (int i = 0; i < mTableSize; ++i) mTable[i] = NULL; } //Destructor steps through table and deallocates all dynamic memory -template +template cHashTable::~cHashTable() { - for (int i=0; inext; + del = curr; + curr = curr->next; delete del; } } } + delete [] mTable; } //////////////////////////////////////////////////////////////////////////////// @@ -323,17 +335,18 @@ cHashTable::~cHashTable() // using seperate chaining (link lists). //////////////////////////////////////////////////////////////////////////////// // General Version: -template +template bool cHashTable::Insert(KEY_TYPE key, VAL_TYPE d_in) { - COMPARE_OP compare; + COMPARE_OP compare; - int hindex = Hash( key ); - if (mTable[hindex] == NULL) { + int hindex = Hash(key); + if (mTable[hindex] == NULL) + { //open index, perform insert - mTable[hindex] = new node; - (mTable[hindex])->nKey = key; - (mTable[hindex])->next = NULL; + mTable[hindex] = new node; + (mTable[hindex])->nKey = key; + (mTable[hindex])->next = NULL; (mTable[hindex])->nData = d_in; mValuesInTable++; @@ -343,13 +356,13 @@ bool cHashTable::Insert(KEY_TYPE key, { // case 1: key already exists in list -- replace existing one // case 2: key does not exist -- add to end of list - + node* nodeptr = mTable[hindex]; bool found = false; - while (true) + while (true) { - if ( compare(nodeptr->nKey, key)) + if (compare(nodeptr->nKey, key)) { // we found a duplicate! found = true; @@ -357,24 +370,24 @@ bool cHashTable::Insert(KEY_TYPE key, } // break if this is the last node in the list - if(! nodeptr->next) + if (!nodeptr->next) break; // otherwise, keep traversing nodeptr = nodeptr->next; } - + // add a node if the key was not found - if (! found) + if (!found) { - node *prev = nodeptr; - nodeptr = new node; - nodeptr->nKey = key; - nodeptr->next = NULL; - prev->next = nodeptr; - + node* prev = nodeptr; + nodeptr = new node; + nodeptr->nKey = key; + nodeptr->next = NULL; + prev->next = nodeptr; + mValuesInTable++; - } + } // whether it is a new node or not, set the data to this new value nodeptr->nData = d_in; @@ -387,52 +400,55 @@ bool cHashTable::Insert(KEY_TYPE key, // Lookup -- Attempts to find 'string' in the hash table. //////////////////////////////////////////////////////////////////////////////// // General Version: -template -bool -cHashTable::Lookup(KEY_TYPE key, VAL_TYPE& d_out) const +template +bool cHashTable::Lookup(KEY_TYPE key, VAL_TYPE& d_out) const { COMPARE_OP compare; - int hindex = Hash( key ); + int hindex = Hash(key); if (mTable[hindex] == NULL) return false; - else { + else + { node* nodeptr = mTable[hindex]; while (nodeptr != NULL) { - if( compare(nodeptr->nKey, key)) { + if (compare(nodeptr->nKey, key)) + { d_out = nodeptr->nData; return true; } nodeptr = nodeptr->next; } } - return false; //mTable entries exhausted without a match + return false; //mTable entries exhausted without a match } //////////////////////////////////////////////////////////////////////////////// -// Remove -- Removes a single entry from the hash table. Returns false if +// Remove -- Removes a single entry from the hash table. Returns false if // the nKey is not found in the table. //////////////////////////////////////////////////////////////////////////////// -// General Version - -template -bool -cHashTable::Remove(KEY_TYPE key) +// General Version - +template +bool cHashTable::Remove(KEY_TYPE key) { COMPARE_OP compare; - int hindex = Hash( key ); - if (mTable[hindex] == NULL) { + int hindex = Hash(key); + if (mTable[hindex] == NULL) + { delete (mTable[hindex]); mTable[hindex] = NULL; return true; } - else { + else + { node* nodeptr = mTable[hindex]; node* prev; - while(nodeptr != NULL) { + while (nodeptr != NULL) + { prev = nodeptr; - if(compare(mTable[hindex]->nKey, key)) + if (compare(mTable[hindex]->nKey, key)) { prev->next = nodeptr->next; delete nodeptr; @@ -440,48 +456,48 @@ cHashTable::Remove(KEY_TYPE key) mTable[hindex] = NULL; nodeptr = NULL; return true; - }//end if + } //end if nodeptr = nodeptr->next; - }//end while - }//end else + } //end while + } //end else return false; //match was not found, no node deleted } //////////////////////////////////////////////////////////////////////////////// // Clear -- Clears entire hash table so that all indices are NULL //////////////////////////////////////////////////////////////////////////////// -template -bool -cHashTable::Clear(void) +template +bool cHashTable::Clear(void) { - for (int i=0; inext; + while (curr != NULL) + { + del = curr; + curr = curr->next; delete del; if (del == mTable[i]) mTable[i] = NULL; del = NULL; - - }//end delete chain loop - }//end if mTable[i]!= NULL - }//end for + + } //end delete chain loop + } //end if mTable[i]!= NULL + } //end for return (IsEmpty()); } //////////////////////////////////////////////////////////////////////////////// // IsEmpty -- //////////////////////////////////////////////////////////////////////////////// -template -bool -cHashTable::IsEmpty(void) const +template +bool cHashTable::IsEmpty(void) const { bool ret = true; - for(int i=0; i< mTableSize; ++i) + for (int i = 0; i < mTableSize; ++i) ret &= (mTable[i] == NULL); return ret; } @@ -489,13 +505,13 @@ cHashTable::IsEmpty(void) const //////////////////////////////////////////////////////////////////////////////// // Hash -- performs hashing on key, returns an integer index val. //////////////////////////////////////////////////////////////////////////////// -template -uint32 cHashTable::Hash( const KEY_TYPE& key ) const +template +uint32 cHashTable::Hash(const KEY_TYPE& key) const { - CONVERTER converter; - int len; - const byte* pb = converter( key, &len ); //locates key - uint32 hindex; + CONVERTER converter; + int len; + const byte* pb = converter(key, &len); //locates key + uint32 hindex; hindex = *pb; while (len-- > 0) @@ -503,26 +519,26 @@ uint32 cHashTable::Hash( const KEY_TY return hindex; } -#ifdef _DEBUG +#ifdef DEBUG -template +template void cHashTable::TraceDiagnostics() const { cDebug d("cHashTable::Diagnostics"); - int slotsFilled = 0, numItems = 0, numMultiSlot = 0; + int slotsFilled = 0, numItems = 0, numMultiSlot = 0; node* pNode; - for(int i=0; i < mTableSize; i++) + for (int i = 0; i < mTableSize; i++) { - if(mTable[i] != NULL) + if (mTable[i] != NULL) { slotsFilled++; numItems++; pNode = (mTable[i])->next; - if(pNode != NULL) + if (pNode != NULL) numMultiSlot++; - while(pNode) + while (pNode) { numItems++; pNode = pNode->next; @@ -531,14 +547,17 @@ void cHashTable::TraceDiagnostics() c } d.TraceDebug("---------------Hash Table Statisics---------------\n"); - d.TraceDebug("-- Number of slots: %d\n", mTableSize); - d.TraceDebug("-- Number of items: %d\n", numItems); - d.TraceDebug("-- Slots filled: %d (%lf %%)\n",slotsFilled, ((double)slotsFilled / (double)mTableSize) * 100.0); - d.TraceDebug("-- Slots with >1 item: %d (%lf %%)\n",numMultiSlot, ((double)numMultiSlot / (double)slotsFilled) * 100.0); + d.TraceDebug("-- Number of slots: %d\n", mTableSize); + d.TraceDebug("-- Number of items: %d\n", numItems); + d.TraceDebug("-- Slots filled: %d (%lf %%)\n", + slotsFilled, + ((double)slotsFilled / (double)mTableSize) * 100.0); + d.TraceDebug("-- Slots with >1 item: %d (%lf %%)\n", + numMultiSlot, + ((double)numMultiSlot / (double)slotsFilled) * 100.0); d.TraceDebug("--------------------------------------------------\n"); } -#endif // _DEBUG +# endif // DEBUG #endif //__HASHTABLE_H - diff --git a/src/core/haval.cpp b/src/core/haval.cpp index cffc303..207a4b4 100644 --- a/src/core/haval.cpp +++ b/src/core/haval.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -275,6 +275,7 @@ static uint8 padding[128] = { /* constants for padding */ } \ } +#if 0 //unused in OST /* hash a string */ void haval_string (char *string, uint8 fingerprint[FPTLEN >> 3]) @@ -330,6 +331,7 @@ void haval_stdin () putchar(fingerprint[i]); } } +#endif /* initialization */ void haval_start (haval_state *state) diff --git a/src/core/haval.h b/src/core/haval.h index e9489dd..d89cdf2 100644 --- a/src/core/haval.h +++ b/src/core/haval.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -117,10 +117,12 @@ typedef struct { #define P_(s) s //Old prototyping stuff... I will ignore it for now. - +#if 0 //unused in OST void haval_string P_((char *, uint8 *)); /* hash a string */ int haval_file P_((char *, uint8 *)); /* hash a file */ void haval_stdin P_((void)); /* filter -- hash input from stdin */ +#endif + void haval_start P_((haval_state *)); /* initialization */ void haval_hash P_((haval_state* state, uint8* str, int str_len)); void haval_end P_((haval_state *, uint8 *)); /* finalization */ diff --git a/src/core/md5.cpp b/src/core/md5.cpp index 1a265b7..d37e168 100644 --- a/src/core/md5.cpp +++ b/src/core/md5.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/core/md5.h b/src/core/md5.h index d82b54b..34b907b 100644 --- a/src/core/md5.h +++ b/src/core/md5.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/core/msystem.cpp b/src/core/msystem.cpp index c0158e4..53d6ed9 100644 --- a/src/core/msystem.cpp +++ b/src/core/msystem.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -66,21 +66,19 @@ #include "stdcore.h" -#if IS_UNIX - /* * set, reset environment to be passed to mpopem */ #include "config.h" #include #include -#ifndef _SORTIX_SOURCE +#if !IS_SORTIX # include #endif #include #include #include -#if defined(HAVE_MALLOC_H) +#if HAVE_MALLOC_H && !IS_AROS #include #endif #include @@ -96,6 +94,13 @@ #include #include "msystem.h" +#if IS_REDOX +#define setuid(x) sleep(0) +#define setgid(x) sleep(0) +#endif + + + /* * signal type */ @@ -209,6 +214,7 @@ char *getenv(); /* get variable from environment */ * on some systems, this is a library function, so define STRDUP * if it is on yours */ +#if 0 #ifdef STRDUP # ifndef __STDC__ char *strdup(); @@ -226,13 +232,14 @@ char *getenv(); /* get variable from environment */ /* * allocate space for the string, and copy if successful */ - if ((p = (char*)malloc((unsigned)((strlen(str)+1)*sizeof(char)))) + size_t p_size = (strlen(str)+1)*sizeof(char); + if ((p = (char*)malloc((unsigned)(p_size))) != NULL) - (void) strcpy(p, str); + (void) strncpy(p, str, p_size); return(p); } #endif - +#endif //0 /* * allocate space for an array of pointers, OR @@ -382,7 +389,7 @@ char *env; register int n; /* where a previous definition is */ /* - * seeif youneed to create the environment list + * see if you need to create the environment list */ if (sz_envp == 0){ if ((envp = c2alloc((const char**)envp, &sz_envp)) == NULL){ @@ -403,21 +410,26 @@ char *env; * just include it from the current environment * (if not defined there, don't define it here) */ - if (strchr(env, '=') == NULL){ + if (strchr(env, '=') == NULL) { + + q = getenv(env); + /* is it defined locally? */ - if ((q = getenv(env)) == NULL){ + if (NULL == q) { /* no -- don't define it here */ return(SE_NONE); } - else if ((p = (char*)malloc((unsigned) (strlen(env)+strlen(q)+2))) - == NULL){ + + size_t p_size = strlen(env) + strlen(q) + 2; + + if ((p = (char*)malloc((unsigned)(p_size))) == NULL) { ERMSG("ran out of memory"); return(SE_NOMEM); } - else{ - (void) strcpy(p, env); - (void) strcat(p, "="); - (void) strcat(p, q); + else { + (void) strncpy(p, env, p_size); + (void) strncat(p, "=", p_size); + (void) strncat(p, q, p_size); } } else if ((p = strdup(env)) == NULL){ @@ -871,7 +883,7 @@ FILE *fp[]; return(mfpclose(indx, fp)); } -#ifdef __AROS__ +#if IS_AROS #define fork() vfork() #endif @@ -1038,6 +1050,3 @@ int pid; */ return(status); } - -#endif //#if IS_UNIX - diff --git a/src/core/msystem.h b/src/core/msystem.h index 09aee38..b6caa43 100644 --- a/src/core/msystem.h +++ b/src/core/msystem.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -54,6 +54,9 @@ /* * forward declarations */ + +#include "platform.h" + #ifdef __STDC__ void le_clobber(void); int le_set(const char*); @@ -114,7 +117,7 @@ int echild(); # define GID_RESET -2 /* reset EGID to RGID */ #endif #ifndef DEF_PATH -# ifdef __FreeBSD_cc_version +# if IS_FREEBSD # define DEF_PATH "PATH=/sbin:/usr/sbin:/bin:/usr/bin" /* default search path */ # else # define DEF_PATH "PATH=/bin:/usr/bin:/usr/ucb" /* default search path */ diff --git a/src/core/ntdbs.h b/src/core/ntdbs.h index 81ae8f2..fc219b8 100644 --- a/src/core/ntdbs.h +++ b/src/core/ntdbs.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,13 +51,13 @@ #include "ntmbs.h" #if IS_KAI - #define IS_STDLIB_MODENA 1 // Has special char_traits req's! - #ifdef MSIPL_WCHART - #define MBSTATE_T_DEFINED - #endif +# define IS_STDLIB_MODENA 1 // Has special char_traits req's! +# ifdef MSIPL_WCHART +# define MBSTATE_T_DEFINED +# endif #else - #define IS_STDLIB_MODENA 0 - #define MBSTATE_T_DEFINED +# define IS_STDLIB_MODENA 0 +# define MBSTATE_T_DEFINED #endif @@ -65,15 +65,24 @@ // Char traits for WCHAR16 (aka dbchar_t) and NTMBCS (mctype_t) //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#if ( WCHAR_IS_16_BITS ) - namespace tss { typedef std::wstring dbstring; } +#if (WCHAR_IS_16_BITS) +namespace tss +{ +typedef std::wstring dbstring; +} -#elif ( WCHAR_IS_32_BITS ) - namespace std { template <> struct char_traits< dbchar_t >; } - namespace tss { typedef std::basic_string dbstring; } +#elif (WCHAR_IS_32_BITS) +namespace std +{ +template<> struct char_traits; +} +namespace tss +{ +typedef std::basic_string dbstring; +} #else - #error "wchar_t is not correctly factored!" +# error "wchar_t is not correctly factored!" #endif @@ -84,151 +93,140 @@ // specialize *std*::char_traits!!! -template<> -struct std::char_traits< dbchar_t > +template<> struct std::char_traits { - typedef dbchar_t char_type; - typedef wint_t int_type; - typedef streampos pos_type; - typedef streamoff off_type; - -#ifdef MBSTATE_T_DEFINED - typedef mbstate_t state_type; -#else - typedef int state_type; // Shame on you KAI! This is ANSI-C! -#endif - - static - void assign( char_type& lhs, const char_type& rhs ) { + typedef dbchar_t char_type; + typedef wint_t int_type; + typedef streampos pos_type; + typedef streamoff off_type; + +# ifdef MBSTATE_T_DEFINED + typedef mbstate_t state_type; +# else + typedef int state_type; // Shame on you KAI! This is ANSI-C! +# endif + + static void assign(char_type& lhs, const char_type& rhs) + { lhs = rhs; } - static - bool eq( const char_type& lhs, const char_type& rhs ) { + static bool eq(const char_type& lhs, const char_type& rhs) + { return lhs == rhs; } - static - bool lt( const char_type& lhs, const char_type& rhs ) { - return lhs < rhs; + static bool lt(const char_type& lhs, const char_type& rhs) + { + return lhs < rhs; } - static - int compare( const char_type* lhs, const char_type* rhs, size_t N ) + static int compare(const char_type* lhs, const char_type* rhs, size_t N) { - for ( ; N; ++lhs, ++rhs, --N ) - if ( *lhs != *rhs ) - return ( *lhs < *rhs ) ? -1 : +1; + for (; N; ++lhs, ++rhs, --N) + if (*lhs != *rhs) + return (*lhs < *rhs) ? -1 : +1; return 0; } - static - size_t length( const char_type* psz ) + static size_t length(const char_type* psz) { - if ( psz == 0 ) + if (psz == 0) return 0; else { const char_type* end; - for ( end = psz; *end; end++ ); - return (size_t)( end - psz ); + for (end = psz; *end; end++) + ; + return (size_t)(end - psz); } } - static - char_type* copy( char_type* lhs, const char_type* rhs, size_t N ) + static char_type* copy(char_type* lhs, const char_type* rhs, size_t N) { - for ( char_type* at = lhs; N; ++at, ++rhs, --N ) + for (char_type* at = lhs; N; ++at, ++rhs, --N) *at = *rhs; return lhs; } - static - const char_type* - find( const char_type* psz, size_t N, const char_type& ch ) + static const char_type* find(const char_type* psz, size_t N, const char_type& ch) { - for ( ; N; ++psz, --N ) - if ( *psz == ch ) + for (; N; ++psz, --N) + if (*psz == ch) return psz; return 0; } - static - char_type* move( char_type* lhs, const char_type* rhs, size_t N ) { - return (char_type*)memmove( lhs, rhs, N * sizeof(char_type) ); + static char_type* move(char_type* lhs, const char_type* rhs, size_t N) + { + return (char_type*)memmove(lhs, rhs, N * sizeof(char_type)); } - static - char_type* assign( char_type* lhs, size_t N, char_type ch ) + static char_type* assign(char_type* lhs, size_t N, char_type ch) { - for ( char_type* at = lhs; N; ++at, --N ) + for (char_type* at = lhs; N; ++at, --N) *at = ch; return lhs; } - static - int_type not_eof( const int_type& ch ) { - return int_type( !eq( ch, eof() ) ? ch : ~ch ); + static int_type not_eof(const int_type& ch) + { + return int_type(!eq(ch, eof()) ? ch : ~ch); } - static - char_type to_char_type( const int_type& ch ) + static char_type to_char_type(const int_type& ch) { - return - eq_int_type( ch, to_int_type( ch ) ) - ? ch - : char_type(0); + return eq_int_type(ch, to_int_type(ch)) ? ch : char_type(0); } - static - int_type to_int_type( const char_type& ch ) { + static int_type to_int_type(const char_type& ch) + { return (int_type)ch; } - static - bool eq_int_type( const int_type& lhs, const int_type& rhs ) { + static bool eq_int_type(const int_type& lhs, const int_type& rhs) + { return lhs == rhs; } -#if IS_STDLIB_MODENA +# if IS_STDLIB_MODENA // CAUTION:RAD -- Extra members required by Modena!! -#ifdef MBSTATE_T_DEFINED // This is ANSI-C *not* ANSI-C++!! - static - state_type get_state( pos_type pos ) { +# ifdef MBSTATE_T_DEFINED // This is ANSI-C *not* ANSI-C++!! + static state_type get_state(pos_type pos) + { return pos.state(); } - static - pos_type get_pos( pos_type pos, state_type state ) { - return pos_type( pos.offset(), state ); + static pos_type get_pos(pos_type pos, state_type state) + { + return pos_type(pos.offset(), state); } -#endif//MBSTATE_T_DEFINED +# endif //MBSTATE_T_DEFINED - static - char_type newline() { + static char_type newline() + { return L'\n'; } - static - char_type eos() { + static char_type eos() + { return 0; } -#endif//IS_STDLIB_MODENA +# endif //IS_STDLIB_MODENA - static - int_type eof() { + static int_type eof() + { return (wint_t)(0xFFFF); } }; -#endif//WCHAR_IS_16_BITS // We already have a dbstring implicitly in wstring!!! - +# endif //WCHAR_IS_16_BITS // We already have a dbstring implicitly in wstring!!! -#endif//__NTDBS_H +#endif //__NTDBS_H diff --git a/src/core/ntmbs.cpp b/src/core/ntmbs.cpp index 97202cf..e7ddd5b 100644 --- a/src/core/ntmbs.cpp +++ b/src/core/ntmbs.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,27 +38,25 @@ * Routines to make NTMBS processing easier. */ -#include "stdcore.h" // for: pch -#include "ntmbs.h" // for: These Declarations +#include "stdcore.h" // for: pch +#include "ntmbs.h" // for: These Declarations //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Module-wide Helpers //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#ifndef TSS_Raise // Should add file and line info in _DEBUG mode!!!! - #define TSS_Raise( Xcpt, pkg, ids ) \ - throw Xcpt( TSS_GetString( pkg, ids ) ) - -#endif//TSS_Raise +#ifndef TSS_Raise // Should add file and line info in DEBUG mode!!!! +# define TSS_Raise(Xcpt, pkg, ids) throw Xcpt(TSS_GetString(pkg, ids)) +#endif //TSS_Raise //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // NTMBS Utils -- Definition //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +#if 0 /* * TSS::mbsdec * @@ -96,7 +94,7 @@ tss::mbsdec( const_ntmbs_t beg, const_ntmbs_t curr ) const_ntmbs_t prev = curr - 1; for ( ; prev > beg && ::mblen( (char*)prev, curr - prev ) == -1; --prev ); - if ( curr - prev > MB_CUR_MAX ) + if ( (size_t)(curr - prev) > MB_CUR_MAX ) { prev = (curr - 1); @@ -117,7 +115,7 @@ tss::mbsdec( const_ntmbs_t beg, const_ntmbs_t curr ) return (ntmbs_t)prev; } - +#endif /* * TSS::mbsinc @@ -134,32 +132,28 @@ tss::mbsdec( const_ntmbs_t beg, const_ntmbs_t curr ) * POSTCONDITIONS: * Returns non-const pointer after moving it. */ -ntmbs_t -tss::mbsinc( const_ntmbs_t psz ) +ntmbs_t tss::mbsinc(const_ntmbs_t psz) { - cDebug dbg( "tss::mbsinc -" ); + cDebug dbg("tss::mbsinc -"); - if ( psz == 0 ) - throw eCharacter( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (psz == 0) + throw eCharacter(TSS_GetString(cCore, core::STR_ERR_ISNULL)); - int nBytes = ::mblen( (char*)psz, MB_CUR_MAX ); - if ( nBytes == -1 ) + int nBytes = ::mblen((char*)psz, MB_CUR_MAX); + if (nBytes == -1) { - dbg.TraceDebug( "Character Fault: %c\n", *psz ); - if ( (unsigned char)*psz > 0x7F ) + dbg.TraceDebug("Character Fault: %c\n", *psz); + if ((unsigned char)*psz > 0x7F) { - dbg.TraceDebug( "Normalizing.\n" ); - return (((ntmbs_t)psz) + 1 ); + dbg.TraceDebug("Normalizing.\n"); + return (((ntmbs_t)psz) + 1); } - dbg.TraceDebug( "Incorrectly Formed, Cannot Normalize!\n" ); - TSS_Raise( - eCharacterEncoding, - cCore, - core::STR_ERR_BADCHAR ); + dbg.TraceDebug("Incorrectly Formed, Cannot Normalize!\n"); + TSS_Raise(eCharacterEncoding, cCore, core::STR_ERR_BADCHAR); } - return ( ((ntmbs_t)psz) + nBytes ); + return (((ntmbs_t)psz) + nBytes); } @@ -180,33 +174,30 @@ tss::mbsinc( const_ntmbs_t psz ) * POSTCONDITIONS: * Returns size_t value indicating bytes in the range of [0,nCount). */ -size_t -tss::mbsbytes( const_ntmbs_t psz, size_t nCount ) +size_t tss::mbsbytes(const_ntmbs_t psz, size_t nCount) { const_ntmbs_t at = psz; - while ( nCount-- ) - at = tss::mbsinc( at ); + while (nCount--) + at = tss::mbsinc(at); return (size_t)((char*)at - (char*)psz); } /// To Null terminator -size_t -tss::mbsbytes( const_ntmbs_t psz ) +size_t tss::mbsbytes(const_ntmbs_t psz) { - if ( psz == 0 ) - throw eCharacter( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); + if (psz == 0) + throw eCharacter(TSS_GetString(cCore, core::STR_ERR_ISNULL)); const_ntmbs_t at; - for ( at = psz; *at; ++at ); + for (at = psz; *at; ++at) + ; return (size_t)((char*)at - (char*)psz); } - - /* * TSS::mbscount * @@ -224,25 +215,22 @@ tss::mbsbytes( const_ntmbs_t psz ) * POSTCONDITIONS: * Returns size_t value indicating characters in the range of [psz + 0, psz + nBytes). */ -size_t -tss_mbscount( const_ntmbs_t psz, size_t nBytes ) +size_t tss_mbscount(const_ntmbs_t psz, size_t nBytes) { - size_t nCount = 0; - const_ntmbs_t at = psz; - const_ntmbs_t end = psz + nBytes; - for ( ; at < end; nCount++, at = tss::mbsinc( at ) ); + size_t nCount = 0; + const_ntmbs_t at = psz; + const_ntmbs_t end = psz + nBytes; + for (; at < end; nCount++, at = tss::mbsinc(at)) + ; return nCount; } /// To Null terminator -size_t -tss::mbscount( const_ntmbs_t psz ) +size_t tss::mbscount(const_ntmbs_t psz) { size_t nCount = 0; - for ( ; *psz; psz = tss::mbsinc( psz ), nCount++ ); + for (; *psz; psz = tss::mbsinc(psz), nCount++) + ; return nCount; } - -// eof: ntmbs.cpp - diff --git a/src/core/ntmbs.h b/src/core/ntmbs.h index d3cc036..5d45d82 100644 --- a/src/core/ntmbs.h +++ b/src/core/ntmbs.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,9 +45,9 @@ /// Requirements. -#include "error.h" // for: TSS_EXCEPTION -#include "package.h" // for: TSS_GetString -#include "corestrings.h" // for: Utility Strings +#include "error.h" // for: TSS_EXCEPTION +#include "package.h" // for: TSS_GetString +#include "corestrings.h" // for: Utility Strings /// Type Definitions for Multiple (?), Double (16), and Wide Characters (32) @@ -55,28 +55,27 @@ //--Null-terminated Multibyte Character Sequence #ifndef NTMBS_T_DEFINED -#define NTMBS_T_DEFINED - #ifdef TSS_NTMBS_IS_UNSIGNED // Natural-sign by default - typedef unsigned char mbchar_t; - typedef unsigned char* ntmbs_t; - typedef const unsigned char* const_ntmbs_t; - #else //TSS_NTMBS_IS_UNSIGNED - typedef char mbchar_t; - typedef char* ntmbs_t; - typedef const char* const_ntmbs_t; - #endif//TSS_NTMBS_IS_UNSIGNED -#endif//NTMBS_T_DEFINED +# define NTMBS_T_DEFINED +# ifdef TSS_NTMBS_IS_UNSIGNED // Natural-sign by default +typedef unsigned char mbchar_t; +typedef unsigned char* ntmbs_t; +typedef const unsigned char* const_ntmbs_t; +# else //TSS_NTMBS_IS_UNSIGNED +typedef char mbchar_t; +typedef char* ntmbs_t; +typedef const char* const_ntmbs_t; +# endif //TSS_NTMBS_IS_UNSIGNED +#endif //NTMBS_T_DEFINED //--Null-terminated Wide Character Sequence (Could be double or quad byte) #ifndef NTWCS_T_DEFINED -#define NTWCS_T_DEFINED - //typedef wchar_t wchar_t; - typedef wchar_t* ntwcs_t; - typedef const wchar_t* const_ntwcs_t; -#endif//NTWCS_T_DEFINED - +# define NTWCS_T_DEFINED +//typedef wchar_t wchar_t; +typedef wchar_t* ntwcs_t; +typedef const wchar_t* const_ntwcs_t; +#endif //NTWCS_T_DEFINED /// NOTE: Size Specific (2 [double] or 4 [quad] byte wide characters) @@ -84,56 +83,57 @@ //--Null-terminated double(2)-byte Character Sequence #ifndef NTDBS_T_DEFINED -#define NTDBS_T_DEFINED - #if WCHAR_IS_16_BITS - typedef wchar_t dbchar_t; // Same size but use NT's type - #else - typedef uint16 dbchar_t; - #endif - typedef dbchar_t* ntdbs_t; - typedef const dbchar_t* const_ntdbs_t; -#endif//NTDBS_T_DEFINED +# define NTDBS_T_DEFINED +# if WCHAR_IS_16_BITS +typedef wchar_t dbchar_t; // Same size but use NT's type +# else +typedef uint16 dbchar_t; +# endif +typedef dbchar_t* ntdbs_t; +typedef const dbchar_t* const_ntdbs_t; +#endif //NTDBS_T_DEFINED //--Internal, "size-specific" types for type dispatched specializations #ifndef NTQBS_T_DEFINED -#define NTQBS_T_DEFINED - #if WCHAR_IS_32_BITS - typedef wchar_t qbchar_t; // Same size but use NT's type - #else - typedef uint32 qbchar_t; - #endif - typedef qbchar_t* ntqbs_t; - typedef const qbchar_t* const_ntqbs_t; -#endif//NTQBS_T_DEFINED - +# define NTQBS_T_DEFINED +# if WCHAR_IS_32_BITS +typedef wchar_t qbchar_t; // Same size but use NT's type +# else +typedef uint32 qbchar_t; +# endif +typedef qbchar_t* ntqbs_t; +typedef const qbchar_t* const_ntqbs_t; +#endif //NTQBS_T_DEFINED //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // NTMBS Manipulators //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -TSS_EXCEPTION( eCharacter, eError ); -TSS_EXCEPTION( eCharacterEncoding, eCharacter ); +TSS_EXCEPTION(eCharacter, eError); +TSS_EXCEPTION(eCharacterEncoding, eCharacter); + namespace tss { - /// Specific Routines (Add as needed) +/// Specific Routines (Add as needed) - ntmbs_t mbsdec( const_ntmbs_t, const_ntmbs_t ); - ntmbs_t mbsinc( const_ntmbs_t ); +//ntmbs_t mbsdec( const_ntmbs_t, const_ntmbs_t ); +ntmbs_t mbsinc(const_ntmbs_t); - size_t mbsbytes( const_ntmbs_t, size_t ); - size_t mbscount( const_ntmbs_t, size_t ); +size_t mbsbytes(const_ntmbs_t, size_t); +size_t mbscount(const_ntmbs_t, size_t); - size_t mbsbytes( const_ntmbs_t ); - size_t mbscount( const_ntmbs_t ); +size_t mbsbytes(const_ntmbs_t); +size_t mbscount(const_ntmbs_t); - inline size_t mbslen( const_ntmbs_t psz ) { // RAD: Yeesh! - return tss::mbscount( psz ); - } -}//tss:: +inline size_t mbslen(const_ntmbs_t psz) +{ // RAD: Yeesh! + return tss::mbscount(psz); +} +} // namespace tss //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -144,15 +144,14 @@ namespace tss namespace tss { - /// Increment and Decrement Pointers by (N) +/// Increment and Decrement Pointers by (N) - //--DEC +//--DEC - template< class CT > - inline - CT* strdec( const CT*, const CT* psz ) { - return const_cast( psz - 1 ); - } +template inline CT* strdec(const CT*, const CT* psz) +{ + return const_cast(psz - 1); +} #if 0 template<> @@ -163,96 +162,86 @@ namespace tss #endif - //--INC +//--INC - template< class CT > - inline - CT* strinc( const CT* psz ) - { - ASSERT( psz ); - return const_cast( ( *psz ? psz + 1 : psz ) ); - } +template inline CT* strinc(const CT* psz) +{ + ASSERT(psz); + return const_cast((*psz ? psz + 1 : psz)); +} - template< class CT, class SIZET > - inline - CT* strinc( const CT* psz, SIZET N ) - { - ASSERT( psz ); - return const_cast( ( *psz ? psz + N : psz ) ); - } +template inline CT* strinc(const CT* psz, SIZET N) +{ + ASSERT(psz); + return const_cast((*psz ? psz + N : psz)); +} - - template<> - inline - ntmbs_t strinc( const_ntmbs_t psz ) - { - return tss::mbsinc( psz ); - } - template<> - inline - ntmbs_t strinc( const_ntmbs_t psz, size_t N ) - { - ntmbs_t at = const_cast( psz ); - while ( N-- ) - at = tss::mbsinc( at ); - return at; - } +template<> inline ntmbs_t strinc(const_ntmbs_t psz) +{ + return tss::mbsinc(psz); +} +template<> inline ntmbs_t strinc(const_ntmbs_t psz, size_t N) +{ + ntmbs_t at = const_cast(psz); + while (N--) + at = tss::mbsinc(at); + return at; +} - /// Byte and Character Count Mappings +/// Byte and Character Count Mappings - //--BYTES - template< class CT > - size_t strsize( const CT* psz ) - { - const CT* at = psz; - while ( *at ) at++; - return (size_t)((char*)at - (char*)psz); - } +//--BYTES - template< class CT > - size_t strsize( const CT*, size_t N ) - { - return N * sizeof(CT); - } +template size_t strsize(const CT* psz) +{ + const CT* at = psz; + while (*at) + at++; + return (size_t)((char*)at - (char*)psz); +} - template<> - inline size_t strsize( const_ntmbs_t psz ) { - return mbsbytes( psz ); - } - template<> - inline size_t strsize( const_ntmbs_t psz, size_t N ) { - return mbsbytes( psz, N ); - } +template size_t strsize(const CT*, size_t N) +{ + return N * sizeof(CT); +} +template<> inline size_t strsize(const_ntmbs_t psz) +{ + return mbsbytes(psz); +} +template<> inline size_t strsize(const_ntmbs_t psz, size_t N) +{ + return mbsbytes(psz, N); +} - //--COUNT - template< class CT > - size_t strcount( const CT* psz ) - { - const CT* at = psz; - while ( *at ) at++; - return (size_t)(at - psz); - } +//--COUNT - template< class CT > - size_t strcount( const CT*, size_t N ) - { - return N; - } - - template<> - inline size_t strcount( const_ntmbs_t psz ) { - return mbscount( psz ); - } - template<> - inline size_t strcount( const_ntmbs_t psz, size_t N ) { - return mbscount( psz, N ); - } +template size_t strcount(const CT* psz) +{ + const CT* at = psz; + while (*at) + at++; + return (size_t)(at - psz); +} + +template size_t strcount(const CT*, size_t N) +{ + return N; +} + +template<> inline size_t strcount(const_ntmbs_t psz) +{ + return mbscount(psz); +} +template<> inline size_t strcount(const_ntmbs_t psz, size_t N) +{ + return mbscount(psz, N); +} /* These are needed! However, it would be better to just create @@ -261,7 +250,7 @@ done with it */ #ifdef TSS_NTMBS_AWARE_SEACH_COMPLETE - /* CAUTION:RAD -- I changed the traversal logic from "!=" to +/* CAUTION:RAD -- I changed the traversal logic from "!=" to "<" to accomodate a basic_string whose end() member does not correctly point after the last valid trail-byte in a string. Really, at != end should be correct, but I don't want to leave @@ -269,243 +258,209 @@ done with it */ under unit test and have all occurances of "at < end" changed to the "more on-purpose" "at != end". */ - /// Various MULTIBYTE aware string searching routines.. +/// Various MULTIBYTE aware string searching routines.. - //--FIND_FIRST: ITER +//--FIND_FIRST: ITER - template< class InputT, class E > - InputT - find_first( InputT beg, InputT end, const E& item ) - { - for ( ; beg < end && *beg != item; beg = (InputT)tss::strinc( beg ) ); - return beg; - } +template InputT find_first(InputT beg, InputT end, const E& item) +{ + for (; beg < end && *beg != item; beg = (InputT)tss::strinc(beg)) + ; + return beg; +} - - //--FIND_LAST: ITER - template< class InputT, class E > - InputT - find_last( InputT beg, InputT end, const E& item ) - { - InputT at = end; - for ( ; beg < end ; beg = (InputT)tss::strinc( beg ) ); - if ( *beg == item ) - at = beg; +//--FIND_LAST: ITER - return at; - } +template InputT find_last(InputT beg, InputT end, const E& item) +{ + InputT at = end; + for (; beg < end; beg = (InputT)tss::strinc(beg)) + ; + if (*beg == item) + at = beg; + return at; +} - //--FIND_FIRST: STRING - template< class StrT > - StrT::size_type - find_first( const StrT& sin, StrT::const_reference item ) - { - StrT::const_iterator - beg = sin.begin(); - end = sin.end(); +//--FIND_FIRST: STRING - StrT::size_type N; - for ( N = 0; beg < end; ++N, beg = (InputT)tss::strinc( beg ) ) - if ( *beg == item ) - return N; +template StrT::size_type find_first(const StrT& sin, StrT::const_reference item) +{ + StrT::const_iterator beg = sin.begin(); + end = sin.end(); - return StrT::npos; - } + StrT::size_type N; + for (N = 0; beg < end; ++N, beg = (InputT)tss::strinc(beg)) + if (*beg == item) + return N; - - //--FIND_LAST: STRING + return StrT::npos; +} - template< class StrT > - StrT::size_type - find_last( const StrT& sin, StrT::const_reference item ) - { - StrT::size_type N = 0; - StrT::size_type nResult = StrT::npos; - StrT::const_iterator - beg = sin.begin(); - end = sin.end(); - for ( ; beg < end ; beg = (InputT)tss::strinc( beg ) ); - if ( *beg == item ) - nResult = N; +//--FIND_LAST: STRING - return N; - } +template StrT::size_type find_last(const StrT& sin, StrT::const_reference item) +{ + StrT::size_type N = 0; + StrT::size_type nResult = StrT::npos; + StrT::const_iterator beg = sin.begin(); + end = sin.end(); + for (; beg < end; beg = (InputT)tss::strinc(beg)) + ; + if (*beg == item) + nResult = N; - //--FIND_FIRST_OF: ITER + return N; +} - template< class InputT > - InputT - find_first_of( - InputT beg, - InputT end, - InputT setbeg, - InputT setend ) - { - InputT at; - for ( ; beg < end; beg = (InputT)tss::strinc( beg ) ); - for ( at = setbeg; setbeg < setend; at = (InputT)tss::strinc( at ) ) - if ( *beg == *at ) - return beg; - - return end; - } +//--FIND_FIRST_OF: ITER - //--FIND_FIRST_OF: STRING (SAFE!!!) +template InputT find_first_of(InputT beg, InputT end, InputT setbeg, InputT setend) +{ + InputT at; + for (; beg < end; beg = (InputT)tss::strinc(beg)) + ; + for (at = setbeg; setbeg < setend; at = (InputT)tss::strinc(at)) + if (*beg == *at) + return beg; - template< class StrT > - StrT::size_type - find_first_of( const StrT& sin, StrT::const_iterator set ) - { - // Point to beg of input - StrT::iterator beg = sin.begin(); + return end; +} - // Start Search - StrT::size_type N = 0; - for ( ; beg < sin.end(); ++N, beg = tss::strinc( beg ) ) - for ( StrT::const_iterator at = set; *at; at = tss::strinc( at ) ) - if ( *beg == *at ) - return N; - - return StrT::npos; - } +//--FIND_FIRST_OF: STRING (SAFE!!!) - //--FIND_FIRST_OF: STRING (NOT SAFE!!!) +template StrT::size_type find_first_of(const StrT& sin, StrT::const_iterator set) +{ + // Point to beg of input + StrT::iterator beg = sin.begin(); + + // Start Search + StrT::size_type N = 0; + for (; beg < sin.end(); ++N, beg = tss::strinc(beg)) + for (StrT::const_iterator at = set; *at; at = tss::strinc(at)) + if (*beg == *at) + return N; - template< class StrT > - StrT::size_type - find_first_of( - const StrT& sin, - StrT::const_iterator set, - StrT::size_type nPos, - StrT::size_type nCount ) - { + return StrT::npos; +} + + +//--FIND_FIRST_OF: STRING (NOT SAFE!!!) + +template +StrT::size_type find_first_of(const StrT& sin, StrT::const_iterator set, StrT::size_type nPos, StrT::size_type nCount) +{ ASSERT( nPos < tss::strcount( sin.begin() ); if ( nCount > 0 && nPos < sin.size() ) { - ASSERT( nCount > tss::strcount( set ) ); - StrT::const_iterator endset; // Get end of set - while ( nCount-- ) endset++; - - // Advance to nPos - StrT::const_iterator at = tss::strinc( sin.begin(), nPos ); - StrT::const_iterator end = sin.end(); - - // Start Search - StrT::size_type N = 0; - for ( ; at < end; ++N, at = tss::strinc( at ) ) - { - if ( tss::find( set, endset, *at ) != 0 ) - return N; - } + ASSERT(nCount > tss::strcount(set)); + StrT::const_iterator endset; // Get end of set + while (nCount--) + endset++; + + // Advance to nPos + StrT::const_iterator at = tss::strinc(sin.begin(), nPos); + StrT::const_iterator end = sin.end(); + + // Start Search + StrT::size_type N = 0; + for (; at < end; ++N, at = tss::strinc(at)) + { + if (tss::find(set, endset, *at) != 0) + return N; + } } return StrT::npos; - } +} - //--FIND_LAST_OF: ITER +//--FIND_LAST_OF: ITER - template< class InputT1, class InputT2 > - InputT - find_last_of( - const InputT1 beg, const InputT1 end, - const InputT2 setbeg, const InputT2 setend ) - { - const InputT1 ans = end; - for ( ; beg < end; beg = tss::strinc( beg ) ); - for ( InputT2 at = setbeg; setbeg != setend; at = tss::strinc( at ) ) - if ( *beg == *at ) - ans = beg; - - return ans; - } +template +InputT find_last_of(const InputT1 beg, const InputT1 end, const InputT2 setbeg, const InputT2 setend) +{ + const InputT1 ans = end; + for (; beg < end; beg = tss::strinc(beg)) + ; + for (InputT2 at = setbeg; setbeg != setend; at = tss::strinc(at)) + if (*beg == *at) + ans = beg; + return ans; +} - //--FIND_LAST_OF: STRING (SAFE!!!) - template< class StrT > - StrT::size_type - find_last_of( const StrT& sin, StrT::const_iterator set ) - { - StrT::size_type nResult = StrT::npos; - StrT::size_type N = 0; - for ( ; at < end; ++N, at = tss::strinc( at ) ) - { - for ( StrT::const_iterator at = set; *at; at = tss::strinc( at ) ) - if ( *beg == *at ) - nResult = N; - } +//--FIND_LAST_OF: STRING (SAFE!!!) - return nResult; +template StrT::size_type find_last_of(const StrT& sin, StrT::const_iterator set) +{ + StrT::size_type nResult = StrT::npos; + StrT::size_type N = 0; + for (; at < end; ++N, at = tss::strinc(at)) + { + for (StrT::const_iterator at = set; *at; at = tss::strinc(at)) + if (*beg == *at) + nResult = N; } + return nResult; +} - template< class StrT > - StrT::size_type - find_last_of( - const StrT& sin, - StrT::const_iterator set, - StrT::size_type nStart, - StrT::size_type nCount ) - { - if ( nCount > 0 && sin.size() ) - { - for ( StrT::const_iterator at = sin.begin() - + (nStart < _Len ? nStart : _Len - 1); ; --_U) - if (_Tr::find(set, nCount, *_U) != 0) - return (_U - _Ptr); - else if (_U == _Ptr) - break; - } - return StrT::npos; +template +StrT::size_type find_last_of(const StrT& sin, StrT::const_iterator set, StrT::size_type nStart, StrT::size_type nCount) +{ + if (nCount > 0 && sin.size()) + { + for (StrT::const_iterator at = sin.begin() + (nStart < _Len ? nStart : _Len - 1);; --_U) + if (_Tr::find(set, nCount, *_U) != 0) + return (_U - _Ptr); + else if (_U == _Ptr) + break; } - // TODO:RAD -- find_first_not_of; - // TODO:RAD -- find_last_not_of; + return StrT::npos; +} -#endif//TSS_NTMBS_AWARE_SEACH_COMPLETE +// TODO:RAD -- find_first_not_of; +// TODO:RAD -- find_last_not_of; - namespace util - { - // Preserves bit values when enlarging a type to a size_t - // Good for preventing sign extension - template< class E > - inline - size_t - char_to_size( E ch ) - { - // if this fails, 'ch' can't be cast to a - // size_t and preserve bit values - // if this fails, then you must find another way - ASSERT( sizeof( size_t ) >= sizeof( E ) ); +#endif //TSS_NTMBS_AWARE_SEACH_COMPLETE - // assert that either 'ch' is an unsigned value (no sign extension possible) - // or that 'ch' is the same size as a size_t (no sign extension is possible as well) - // if this fails, then you must specialize this function like we did for 'char' - ASSERT( (int)(E)-1 > (int)0 || sizeof( size_t ) == sizeof( E ) ); +namespace util +{ +// Preserves bit values when enlarging a type to a size_t +// Good for preventing sign extension +template inline size_t char_to_size(E ch) +{ + // if this fails, 'ch' can't be cast to a + // size_t and preserve bit values + // if this fails, then you must find another way + ASSERT(sizeof(size_t) >= sizeof(E)); - return (size_t)ch; - } + // assert that either 'ch' is an unsigned value (no sign extension possible) + // or that 'ch' is the same size as a size_t (no sign extension is possible as well) + // if this fails, then you must specialize this function like we did for 'char' + ASSERT((int)(E)-1 > (int)0 || sizeof(size_t) == sizeof(E)); + + return (size_t)ch; +} - - inline - size_t - char_to_size( char ch ) - { - return (size_t)(unsigned char)ch; - } - } -}//tss:: +inline size_t char_to_size(char ch) +{ + return (size_t)(unsigned char)ch; +} +} // namespace util +} // namespace tss -#endif//__NTMBS_H +#endif //__NTMBS_H diff --git a/src/core/objectpool.cpp b/src/core/objectpool.cpp deleted file mode 100644 index 86c0ba9..0000000 --- a/src/core/objectpool.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -// objectpool.cpp -#include "stdcore.h" -#include "objectpool.h" -#include "debug.h" - -//----------------------------------------------------------------------------- -// cBlockLink -//----------------------------------------------------------------------------- -class cBlockLink -{ -public: - cBlockLink(cBlockLink* pNext) : mpNext(pNext) {} - cBlockLink* Next() { return mpNext; } -private: - cBlockLink* mpNext; // pointer to the next link, or NULL -}; - - -//----------------------------------------------------------------------------- -// cBlockList -//----------------------------------------------------------------------------- - -/////////////////////////////////////////////////////////////////////////////// -// ctor, dtor -/////////////////////////////////////////////////////////////////////////////// -cBlockList::cBlockList() : - mpBlocks(0) -{ -} - -cBlockList::~cBlockList() -{ - Clear(); -} - -/////////////////////////////////////////////////////////////////////////////// -// Allocate -/////////////////////////////////////////////////////////////////////////////// -void* cBlockList::Allocate(int size) -{ - char* mem = new char[size + sizeof(cBlockLink)]; - mpBlocks = new(mem) cBlockLink(mpBlocks); - return mem + sizeof(cBlockLink); -} - -/////////////////////////////////////////////////////////////////////////////// -// Clear -/////////////////////////////////////////////////////////////////////////////// -void cBlockList::Clear() -{ - while(mpBlocks) - { - cBlockLink* pLink = mpBlocks; - mpBlocks = mpBlocks->Next(); - pLink->~cBlockLink(); - delete [] (char*)(pLink); - } -} - -//----------------------------------------------------------------------------- -// cObjectPoolBase -//----------------------------------------------------------------------------- - -/////////////////////////////////////////////////////////////////////////////// -// ctor, dtor -/////////////////////////////////////////////////////////////////////////////// -cObjectPoolBase::cObjectPoolBase(int objSize, int chunkSize) : - mObjectSize(objSize), - mChunkSize(chunkSize), - mpNextFree(0) -{ -} - -cObjectPoolBase::~cObjectPoolBase() -{ - //TODO -- assert that the number of instances left are 0. - Clear(); -} - -/////////////////////////////////////////////////////////////////////////////// -// AllocNewChunk -/////////////////////////////////////////////////////////////////////////////// -void cObjectPoolBase::AllocNewChunk() -{ - ASSERT(mpNextFree == 0); - - int size = mObjectSize * mChunkSize; - char* pBlock = (char*)mBlockList.Allocate(size); - - char* pLast = pBlock + size - mObjectSize; - for(char* pc = pBlock; pc < pLast; pc += mObjectSize) - { - ((cLink*)pc)->mpNext = (cLink*)(pc + mObjectSize); - } - ((cLink*)pLast)->mpNext = 0; - - mpNextFree = (cLink*)pBlock; -} - - diff --git a/src/core/objectpool.h b/src/core/objectpool.h deleted file mode 100644 index 6877b34..0000000 --- a/src/core/objectpool.h +++ /dev/null @@ -1,140 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// objectpool.h -// -// cBlockList -- a linked list of blocks of memory -// cObjectPoolBase -- a pool of equal-sized objects; constant time allocation -#ifndef __OBJECTPOOL_H -#define __OBJECTPOOL_H - -class cBlockLink; - -//----------------------------------------------------------------------------- -// cBlockList -//----------------------------------------------------------------------------- -class cBlockList -{ -public: - cBlockList(); - ~cBlockList(); - - void* Allocate(int size); - void Clear(); // releases everything in the block list -private: - cBlockLink* mpBlocks; // linked list of blocks -}; - -//----------------------------------------------------------------------------- -// cObjectPoolBase -//----------------------------------------------------------------------------- -class cObjectPoolBase -{ -public: - cObjectPoolBase(int objSize, int chunkSize); - ~cObjectPoolBase(); - // NOTE -- dtor is not virtual; therefore it is potentially dangerous to delete a pointer to - // this class unless you know for sure the dynamic class type has nothing to clean up. - - void* Alloc (); - void Free (void* pObj); - void Clear (); - //TODO -- add IsPointerValid() -private: - void AllocNewChunk(); // get another chunk to use... - - struct cLink - { - cLink* mpNext; - }; - - cBlockList mBlockList; - const int mObjectSize; // how big are the objects? - const int mChunkSize; // how big are the chunks we are allocating? - cLink* mpNextFree; // the next free object - //int mInstanceCount; // number of objects that are currently allocated but not freed. -}; - -//----------------------------------------------------------------------------- -// cObjectPool -// Note -- this template only works for classes that are constructed with their -// default ctor; I don't know how to extend this model to work for non-default -// ctors... -//----------------------------------------------------------------------------- -template -class cObjectPool : public cObjectPoolBase -{ -public: - cObjectPool(int chunkSize) : cObjectPoolBase(sizeof(T), chunkSize) {} - - T* New () { return new(cObjectPoolBase::Alloc()) T(); } - void Delete (T* pObj) { pObj->~T(); Free(pObj); } -}; - -//############################################################################# -// inline implementation -//############################################################################# -/////////////////////////////////////////////////////////////////////////////// -// Alloc -/////////////////////////////////////////////////////////////////////////////// -inline void* cObjectPoolBase::Alloc() -{ - if(! mpNextFree) - AllocNewChunk(); - - cLink* pRtn = mpNextFree; - mpNextFree = mpNextFree->mpNext; - return pRtn; -} - -/////////////////////////////////////////////////////////////////////////////// -// Free -/////////////////////////////////////////////////////////////////////////////// -inline void cObjectPoolBase::Free(void* pObj) -{ - cLink* pNew = (cLink*)pObj; - pNew->mpNext = mpNextFree; - mpNextFree = pNew; -} - -/////////////////////////////////////////////////////////////////////////////// -// Clear -/////////////////////////////////////////////////////////////////////////////// -inline void cObjectPoolBase::Clear() -{ - mBlockList.Clear(); - mpNextFree = 0; -} - - -#endif //__OBJECTPOOL_H - diff --git a/src/core/package.cpp b/src/core/package.cpp deleted file mode 100644 index f9ddae8..0000000 --- a/src/core/package.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// - diff --git a/src/core/package.h b/src/core/package.h index ac5e6a8..0639f82 100644 --- a/src/core/package.h +++ b/src/core/package.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,7 +52,7 @@ // themselves singletons or shared. Using the package interface // guarantees that all shared resources will be properely // initialized before they are used. When creating a package -// representation you can declare other packages that your +// representation you can declare other packages that your // package depends on, ensuring that predicate packages and their // resources will be initialized before the package that uses // those resources. @@ -60,8 +60,8 @@ // Contents of this File // // TSS_Package( cPackage ) -// TSS_BeginPackage( cPackage ) -// TSS_EndPackage( cPackage ) +// TSS_BeginPackage( cPackage ) +// TSS_EndPackage( cPackage ) // TSS_ImplementPackage( cPackage ) // TSS_Dependency( cPackage ) // @@ -71,7 +71,7 @@ // TSS_BeginStringtable( cPackage ) // TSS_StringEntry( IDS, "message" ) // TSS_EndStringtable( cPackage ) -// +// // TSS_BeginStringIds( package_namespace ) // TSS_EndStringIds( package_namespace ) // @@ -82,7 +82,7 @@ #ifndef __PACKAGE_H #define __PACKAGE_H -#include "resources.h" // for: cMessage_ +#include "resources.h" // for: cMessage_ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -91,90 +91,92 @@ //--PACKAGE Helpers -#define TSS_Package( pkg ) \ - pkg::GetInstance() // Access "the" Package obj - -#define TSS_Dependency( pkg ) \ - TSS_Package( pkg ) // Declare a Package Depend. +#define TSS_Package(pkg) pkg::GetInstance() // Access "the" Package obj +#define TSS_Dependency(pkg) TSS_Package(pkg) // Declare a Package Depend. -#define TSS_BeginPackage( pkg ) \ - class pkg : public cPackageBase_< TCHAR > \ - { \ - public: \ +#define TSS_BeginPackage(pkg) \ + class pkg : public cPackageBase_ \ + { \ + public: \ static pkg& GetInstance(); -#define TSS_EndPackage( pkg ) \ - }; +#define TSS_EndPackage(pkg) \ + } \ + ; -#define TSS_ImplementPackage( pkg ) \ - pkg& pkg::GetInstance() \ - { \ +#define TSS_ImplementPackage(pkg) \ + pkg& pkg::GetInstance() \ + { \ static bool bConstructed = false; \ - static pkg x; \ - if ( !bConstructed ) \ - { \ - bConstructed = true; \ - x.LoadStrings(); \ - } \ - return x; \ + static pkg x; \ + if (!bConstructed) \ + { \ + bConstructed = true; \ + x.LoadStrings(); \ + } \ + return x; \ } - - //--STRINGTABLE Helperfs -#define TSS_GetString( pkg, id ) \ - TSS_Package( pkg ).GetString( id ) // Access the Message String +#define TSS_GetString(pkg, id) TSS_Package(pkg).GetString(id) // Access the Message String -#define TSS_DECLARE_STRINGTABLE \ - public: \ - Messages::String \ - GetString( \ - Messages::ConstKeyRef id ) const { \ - return m_messages.Get( id ); } \ - void LoadStrings(); \ - private: \ - Messages m_messages // Decare a Stringtable +#define TSS_DECLARE_STRINGTABLE \ +public: \ + Messages::String GetString(Messages::ConstKeyRef id) const \ + { \ + return m_messages.Get(id); \ + } \ + void LoadStrings(); \ + \ +private: \ + Messages m_messages // Decare a Stringtable -#ifdef _DEBUG -#define TSS_BeginStringtable( pkg ) \ - void pkg::LoadStrings() \ - { cDebug d( #pkg "::LoadStrings()" ); \ - d.TraceDebug("Loading strings for " #pkg " package.\n"); \ - Messages::Pair astr[] = { // Define a Stringtable -#else // _DEBUG -#define TSS_BeginStringtable( pkg ) \ - void pkg::LoadStrings() \ - { Messages::Pair astr[] = { // Define a Stringtable -#endif // _DEBUG +#ifdef DEBUG +# define TSS_BeginStringtable(pkg) \ + void pkg::LoadStrings() \ + { \ + cDebug d(#pkg "::LoadStrings()"); \ + d.TraceDebug("Loading strings for " #pkg " package.\n"); \ + Messages::Pair astr[] = { // Define a Stringtable +#else // DEBUG +# define TSS_BeginStringtable(pkg) \ + void pkg::LoadStrings() \ + { \ + Messages::Pair astr[] = { // Define a Stringtable +#endif // DEBUG -#define TSS_EndStringtable( pkg ) \ - }; m_messages.Put( \ - astr, astr + countof(astr) ); } // End define Strintable +#define TSS_EndStringtable(pkg) \ + } \ + ; \ + m_messages.Put(astr, astr + countof(astr)); \ + } // End define Strintable -#define TSS_StringEntry( id, s ) \ - Messages::Pair( id, s ) // Stringtable Entry +#define TSS_StringEntry(id, s) Messages::Pair(id, s) // Stringtable Entry -#define TSS_BeginStringIds( pns ) \ - namespace pns { \ - enum { // Define String IDs - -#define TSS_EndStringIds( pns ) \ - }; } // End define String IDs +#define TSS_BeginStringIds(pns) \ + namespace pns \ + { \ + enum \ + { // Define String IDs +#define TSS_EndStringIds(pns) \ + } \ + ; \ + } // End define String IDs //============================================================================= // cPackageBase_ -- Base class for all Package Resources //----------------------------------------------------------------------------- -// SYNOPSIS: +// SYNOPSIS: // This class is the base class for all package representations // and, thus, establishes the package contract. It's interface // is relied on by the Package singleton wrapper, TSS_Package. @@ -184,28 +186,25 @@ // be called once. // // CONSTRAINTS: -// A Package representation template must be instantiated with a +// A Package representation template must be instantiated with a // "character concept" that is a valid STDCPP NTCTS. // This will most often be char (for NTBS), wchar_t (for NTWCS), // but may also be unsigned char (for NTMBCS). // // INVARIANTS: // m_nInstances <= 1 -// +// // -template< class CharT > -class cPackageBase_ +template class cPackageBase_ { - public: +public: + typedef cMessages_ Messages; - typedef cMessages_< int, CharT > Messages; - - void LoadStrings() - { - } + void LoadStrings() + { + } }; -#endif//__PACKAGE_H - +#endif //__PACKAGE_H diff --git a/src/core/platform.h b/src/core/platform.h index 01abde9..78f7765 100644 --- a/src/core/platform.h +++ b/src/core/platform.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,35 +34,72 @@ // #ifdef HAVE_CONFIG_H -# include +#include #endif #ifndef __PLATFORM_H -#define __PLATFORM_H +# define __PLATFORM_H + +//NOTE: Autoconf is strongly preferred as the Right Way to detect platform-specific features/behaviors. +// These macros should really only be used when autoconf can't get the job done. //============================================================================= // Enumerations -// +// // For each of these "enumerations" we create unique integers identifying each // variation. We group similar items together, such as OS_REDHAT and OS_SLACKWARE -#define OS_UNKNOWN 0 -#define OS_WIN32 0x0101 -#define OS_AIX 0x0401 -#define OS_HPUX 0x0501 -#define OS_IRIX 0x0601 -#define OS_OSF1 0x0701 - -#define COMP_UNKNOWN 0 -#define COMP_MSVC 0x0101 -#define COMP_KAI_GCC 0x0201 -#define COMP_KAI_SUNPRO 0x0202 -#define COMP_KAI_GLIBC 0x0203 -#define COMP_KAI_VISUALAGE 0x0204 -#define COMP_KAI_HPANSIC 0x0205 -#define COMP_KAI_IRIX 0x0206 -#define COMP_KAI_OSF1ALPHA 0x0207 -#define COMP_SUNPRO 0x0301 +# define OS_UNKNOWN 0 + +# define OS_WIN32 0x0101 +# define OS_CYGWIN 0x0102 +# define OS_DOS_DJGPP 0x0103 + +# define OS_LINUX 0x0201 +# define OS_ANDROID 0x0202 + +# define OS_FREEBSD 0x0301 +# define OS_NETBSD 0x0302 +# define OS_OPENBSD 0x0303 +# define OS_DARWIN 0x0304 +# define OS_DRAGONFLYBSD 0x0305 +# define OS_MIDNIGHTBSD 0x0306 +# define OS_MIRBSD 0x0307 +# define OS_BITRIG 0x0308 +# define OS_LIBERTYBSD 0x0309 + +# define OS_SOLARIS 0x0400 +# define OS_AIX 0x0401 +# define OS_HPUX 0x0402 +# define OS_IRIX 0x0403 +# define OS_OSF1 0x0404 + +# define OS_MINIX 0x0501 +# define OS_HURD 0x0502 +# define OS_HAIKU 0x0503 +# define OS_SYLLABLE 0x0504 +# define OS_SKYOS 0x0505 +# define OS_SORTIX 0x0506 +# define OS_MINT 0x0507 +# define OS_AROS 0x0508 +# define OS_RTEMS 0x0509 +# define OS_RISCOS 0x050A +# define OS_REDOX 0x050B +# define OS_QNX 0x050C + +# define COMP_UNKNOWN 0 +# define COMP_GCC 0x0001 +# define COMP_CLANG 0x0002 + +# define COMP_MSVC 0x0101 +# define COMP_KAI_GCC 0x0201 +# define COMP_KAI_SUNPRO 0x0202 +# define COMP_KAI_GLIBC 0x0203 +# define COMP_KAI_VISUALAGE 0x0204 +# define COMP_KAI_HPANSIC 0x0205 +# define COMP_KAI_IRIX 0x0206 +# define COMP_KAI_OSF1ALPHA 0x0207 +# define COMP_SUNPRO 0x0301 //============================================================================= // Platform detection @@ -75,40 +112,143 @@ // OS The OS // COMP The compiler // -// PLEASE NOTE: Do not set any preprocessor variable other than the above three in this +// PLEASE NOTE: Do not set any preprocessor variable other than the above three in this // section. Use the following sections for anything that does not fall into // the above catagories. -#if defined(_WIN32) - #define OS OS_WIN32 +# if defined(_WIN32) +# define OS OS_WIN32 +# define IS_WIN32 1 - #if defined(_MSC_VER) - #define COMP COMP_MSVC - #else - #error _MSC_VER not defined. MSVC is currently the only supported compiler - #endif +# elif defined(__CYGWIN__) +# define OS OS_CYGWIN +# define IS_CYGWIN 1 -#elif defined(_IRIX) - #define OS OS_IRIX - #define COMP COMP_KAI_IRIX +# elif defined(__DJGPP__) +# define OS OS_DOS_DJGPP +# define IS_DOS_DJGPP 1 -#elif defined(_ALPHA) - #define OS OS_OSF1 - #define COMP COMP_KAI_OSF1ALPHA -#elif defined (_HPUX) - #define OS OS_HPUX - #define COMP COMP_KAI_HPANSIC +# elif defined(__ANDROID__) +# define OS OS_ANDROID +# define IS_ANDROID 1 + +# elif defined(__linux__) +# define OS OS_LINUX +# define IS_LINUX 1 + + +// A herd of BSDs. Have to detect MidnightBSD before FreeBSD, and MirOS & Bitrig before OpenBSD +// because they also define symbols for their ancestor BSDs. +# elif defined(__DragonFly__) +# define OS OS_DRAGONFLYBSD +# define IS_DRAGONFLYBSD 1 + +# elif defined(__MidnightBSD__) +# define OS OS_MIDNIGHTBSD +# define IS_MIDNIGHTBSD 1 + +# elif defined(__FreeBSD__) +# define OS OS_FREEBSD +# define IS_FREEBSD 1 + +# elif defined(__NetBSD__) +# define OS OS_NETBSD +# define IS_NETBSD 1 + +# elif defined(__MirBSD__) +# define OS OS_MIRBSD +# define IS_MIRBSD 1 + +# elif defined(__Bitrig__) +# define OS OS_BITRIG +# define IS_BITRIG 1 + +# elif defined(TW_LibertyBSD) +# define OS OS_LIBERTYBSD +# define IS_LIBERTYBSD 1 + +# elif defined(__OpenBSD__) +# define OS OS_OPENBSD +# define IS_OPENBSD 1 + +# elif defined(__APPLE__) +# define OS OS_DARWIN +# define IS_DARWIN 1 + + +# elif defined(__sun) +# define OS OS_SOLARIS +# define IS_SOLARIS 1 + +# elif defined(_AIX) +# define OS OS_AIX +# define IS_AIX 1 + +# elif defined(__hpux) +# define OS OS_HPUX +# define IS_HPUX 1 + +# elif defined(__sgi) +# define OS OS_IRIX +# define IS_IRIX 1 + +# elif defined(TRU64) || defined(__OSF1__) +# define OS OS_OSF1 +# define IS_OSF1 1 + + +# elif defined(__minix__) +# define OS OS_MINIX +# define IS_MINIX 1 + +# elif defined(__gnu_hurd__) +# define OS OS_HURD +# define IS_HURD 1 + +# elif defined(__HAIKU__) +# define OS OS_HAIKU +# define IS_HAIKU 1 + +# elif defined(__SYLLABLE__) +# define OS OS_SYLLABLE +# define IS_SYLLABLE 1 + +# elif defined(SKYOS) +# define OS OS_SKYOS +# define IS_SKYOS 1 + +# elif defined(_SORTIX_SOURCE) +# define OS OS_SORTIX +# define IS_SORTIX 1 + +# elif defined(__MINT__) +# define OS OS_MINT +# define IS_MINT 1 + +# elif defined(__AROS__) +# define OS OS_AROS +# define IS_AROS 1 + +# elif defined(__rtems__) +# define OS OS_RTEMS +# define IS_RTEMS 1 + +# elif defined(__riscos__) +# define OS OS_RISCOS +# define IS_RISCOS 1 + +# elif defined(__redox__) +# define OS OS_REDOX +# define IS_REDOX 1 + +# elif defined(__QNX__) +# define OS OS_QNX +# define IS_QNX 1 + +# endif -#else -// OK for OS not to resolve, it's being phased out. -// #error Unknown OS -#endif -#if !defined(OS) -// OK for OS not to resolve, it's being phased out. -// #error OS definition did not resolve. Check "platform.h". -#endif /* XXX: COMP may now not resolve, because autoconf may * detect GCC. This is done in the hopes that all * COMP detections, and indeed both OS & COMP detechtions @@ -121,9 +261,9 @@ * * PH - 20010311 */ -#if !defined(COMP) && !defined(HAVE_GCC) - #error COMP definition did not resolve. Check "platform.h". -#endif +# if !defined(COMP) && !defined(HAVE_GCC) +# error COMP definition did not resolve. Check "platform.h". +# endif //============================================================================= // Platform Macros (a.k.a. "IS_" macros) @@ -132,7 +272,7 @@ // these macros rather than comparing PLATFORM to the unique IDs by hand. // // NB: Programmers are STRONGLY ENCOURAGED not to use the OS detection macros -// or compiler detection marcros directly. Instead they should create +// or compiler detection marcros directly. Instead they should create // macros specific to the task at hand. For example Win32 and Solaris support // extended permissions for their files. Rather than check IS_WIN32 || IS_SOLARIS, // create a new macro called "HAS_EXTENDED_FILE_PERMISSIONS" and use that. @@ -148,77 +288,95 @@ // int network_order = swap(machine_order); // #endif -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// OS detection -// Note: Avoid using these if possible (see above) -#define IS_WIN32 (OS == OS_WIN32) -#define IS_AIX (OS == OS_AIX) -#define IS_HPUX (OS == OS_HPUX) -#define IS_IRIX (OS == OS_IRIX) -#define IS_OSF1 (OS == OS_OSF1) // complier detection -#define IS_KAI (COMP == COMP_KAI_GCC || COMP == COMP_KAI_SUNPRO || COMP == COMP_KAI_GLIBC || COMP == COMP_KAI_VISUALAGE || COMP == COMP_KAI_HPANSIC || COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA) -#define IS_MSVC (COMP == COMP_MSVC) -#define IS_SUNPRO (COMP == COMP_SUNPRO) +# define IS_KAI \ + (COMP == COMP_KAI_GCC || COMP == COMP_KAI_SUNPRO || COMP == COMP_KAI_GLIBC || COMP == COMP_KAI_VISUALAGE || \ + COMP == COMP_KAI_HPANSIC || COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA) +# define IS_MSVC (COMP == COMP_MSVC) +# define IS_SUNPRO (COMP == COMP_SUNPRO) -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Unicode -#define SUPPORTS_UNICODE IS_WIN32 // The OS supports Unicode +# define SUPPORTS_UNICODE IS_WIN32 // The OS supports Unicode // KAI 3.4 uses a much improved stl -#define IS_KAI_3_4 (IS_KAI && (COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA || COMP == COMP_KAI_GLIBC)) +# define IS_KAI_3_4 (IS_KAI && (COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA || COMP == COMP_KAI_GLIBC)) // Used in twlocale -#define USE_STD_CPP_LOCALE_WORKAROUND (IS_SUNPRO || (IS_KAI && !IS_KAI_3_4)) // TODO:BAM -- name this something more general. -#define USE_CLIB_LOCALE IS_KAI || HAVE_GCC -#define USES_CLIB_DATE_FUNCTION ( USE_CLIB_LOCALE || IS_SUNPRO || IS_MSVC ) // if we use clib, can't use C++ time_put, and SUNPRO and MSVC add characters +# define USE_STD_CPP_LOCALE_WORKAROUND \ + (IS_SUNPRO || (IS_KAI && !IS_KAI_3_4)) // TODO:BAM -- name this something more general. +# define USE_CLIB_LOCALE IS_KAI || HAVE_GCC +# define USES_CLIB_DATE_FUNCTION \ + (USE_CLIB_LOCALE || IS_SUNPRO || \ + IS_MSVC) // if we use clib, can't use C++ time_put, and SUNPRO and MSVC add characters //#define USE_CLIB_LOCALE (IS_ALPHA || IS_IRIX || (IS_KAI && !IS_KAI_3_4)) // Threading API -// TODO:mdb -- this is not complete or rigorous on the unix side!!! -#define SUPPORTS_WIN32_THREADS IS_WIN32 -#define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS) +// TODO:mdb -- this is not complete or rigorous on the unix side!!! +# define SUPPORTS_WIN32_THREADS IS_WIN32 +# define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS) // Miscellaneous -#define FSEEK_TAKES_INT32 IS_UNIX // True if fseek takes 32-bit offsets -#define USE_OUTPUT_DEBUG_STRING IS_WIN32 // Use the Win32 OutputDebugString() for debug messages. -#define SUPPORTS_MAPI IS_WIN32 -#define WCHAR_IS_16_BITS IS_WIN32 -#define WCHAR_IS_32_BITS IS_UNIX -#define WCHAR_REP_IS_UCS2 IS_WIN32 -#define USES_MPOPEN IS_UNIX -#define USES_WINSOCK IS_WIN32 -#define SUPPORTS_WCHART IS_WIN32 // TODO: Remove after getting new ver of KAI -#define USES_GLIBC ((COMP == COMP_KAI_GLIBC) || HAVE_GCC) -#define SUPPORTS_EVENTLOG IS_WIN32 -#define SUPPORTS_MEMBER_TEMPLATES ( ! IS_SUNPRO ) -#define SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST ( ! IS_SUNPRO ) +# define WCHAR_IS_16_BITS IS_WIN32 +# define WCHAR_IS_32_BITS IS_UNIX +# define WCHAR_REP_IS_UCS2 IS_WIN32 +// msystem+mpopen fail on Syllable, so use the libc equivalents until we figure out why. +// TODO: Figure out why. +# define USES_MPOPEN (IS_UNIX && !IS_SYLLABLE) +# define USES_MSYSTEM (IS_UNIX && !IS_SYLLABLE) +# define SUPPORTS_WCHART IS_WIN32 // TODO: Remove after getting new ver of KAI +# define USES_GLIBC ((COMP == COMP_KAI_GLIBC) || HAVE_GCC) +# define SUPPORTS_MEMBER_TEMPLATES (!IS_SUNPRO) +# define SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST (!IS_SUNPRO) + +# define SUPPORTS_POSIX_SIGNALS (!IS_DOS_DJGPP) +# define SUPPORTS_NETWORKING (!IS_SORTIX && !IS_DOS_DJGPP && !IS_REDOX) +# define SUPPORTS_SYSLOG (HAVE_SYSLOG_H && !IS_SKYOS && !IS_RISCOS) +# define NEEDS_SWAB_IMPL (IS_CYGWIN || IS_SYLLABLE || IS_ANDROID || IS_SORTIX) +# define USES_MBLEN (!IS_ANDROID && !IS_AROS) +# define USES_DEVICE_PATH (IS_AROS || IS_DOS_DJGPP || IS_RISCOS || IS_REDOX) +# define ICONV_CONST_SOURCE (IS_MINIX) +# define SUPPORTS_DIRECT_IO (IS_LINUX) +// Linux is the only platform where direct i/o hashing has been tested & works properly so far. + +# define SUPPORTS_TERMIOS (!IS_RTEMS && !IS_REDOX) +// RTEMS errors are probably just a buildsys issue & this will change or go away. +// Redox will probably implement this in the future. + +# define CAN_UNLINK_WHILE_OPEN (!IS_AROS && !IS_RISCOS && !IS_REDOX && !IS_DOS_DJGPP) + +# define SUPPORTS_DOUBLE_SLASH_PATH (IS_CYGWIN) +// POSIX standard says paths beginning with 2 slashes are "implementation defined" +// (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 ) +// The only platform OST works on (afaik) that actually defines a double-slash behavior is Cygwin +// which uses this syntax for UNC paths. So we'll allow leading double slashes there, but +// continue removing them on all other platforms + +# define USE_DEV_URANDOM (HAVE_DEV_URANDOM && ENABLE_DEV_URANDOM) //============================================================================= // Miscellaneous // -// Put all items that are not an "IS_" macro here. +// Put all items that are not an "IS_" macro here. -#if IS_BYTE_ALIGNED - #define BYTE_ALIGN 8 -#else - #error Unknown Byte alignment -#endif +# if IS_BYTE_ALIGNED +# define BYTE_ALIGN 8 +# else +# error Unknown Byte alignment +# endif // A scalar that matches the sizeof a pointer -typedef unsigned long ptr_size_type; // true for all of our current platforms - // TODO: I would like to use a XXXX_t like name +typedef unsigned long ptr_size_type; // true for all of our current platforms + // TODO: I would like to use a XXXX_t like name // Check integer representation -#if !(USES_2S_COMPLEMENT) - #error "Tripwire will only work on a 2's complement CPU. Check \"platform.h\"." -#endif - - +# if !(USES_2S_COMPLEMENT) +# error "Tripwire will only work on a 2's complement CPU. Check \"platform.h\"." +# endif #endif // __PLATFORM_H - diff --git a/src/core/refcountobj.cpp b/src/core/refcountobj.cpp index 209f03d..cadd5ac 100644 --- a/src/core/refcountobj.cpp +++ b/src/core/refcountobj.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,15 +41,15 @@ #include "errorutil.h" -#ifdef _DEBUG -int cRefCountObj::objectCounter = 0; +#ifdef DEBUG +int cRefCountObj::objectCounter = 0; int cRefCountObj::referenceCounter = 0; #include // ok, this is getting serious! #include -typedef std::set RefSet; // collection of addresses of all reference counted objects -RefSet* gpRefCountObj_Objects = 0; +typedef std::set RefSet; // collection of addresses of all reference counted objects +RefSet* gpRefCountObj_Objects = 0; // a way to see what hasn't been accounted for.... struct cRefCountObj_Debug @@ -57,10 +57,10 @@ struct cRefCountObj_Debug ~cRefCountObj_Debug() { RefSet::iterator i; - cDebug d("cRefCountObj_Debug"); - if(gpRefCountObj_Objects) + cDebug d("cRefCountObj_Debug"); + if (gpRefCountObj_Objects) { - for(i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++) + for (i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++) { d.TraceNever("Refrence Counted Object %p still exists\n", *i); } @@ -68,22 +68,22 @@ struct cRefCountObj_Debug } } gRefCountObj_Debug; -#endif // _DEBUG +#endif // DEBUG cRefCountObj::cRefCountObj() { mRefCount = 1; -//std::cout << "Allocated RefObj(" << std::hex << (int)this << ")\n"; + //std::cout << "Allocated RefObj(" << std::hex << (int)this << ")\n"; -#ifdef _DEBUG +#ifdef DEBUG ++objectCounter; ++referenceCounter; cDebug d("cRefCountObj::cRefCountObj"); d.TraceNever("Object Created[%p] %s\n", this, typeid(*this).name()); - if(! gpRefCountObj_Objects) + if (!gpRefCountObj_Objects) gpRefCountObj_Objects = new RefSet; gpRefCountObj_Objects->insert(this); #endif @@ -93,22 +93,22 @@ cRefCountObj::~cRefCountObj() { ASSERT(mRefCount == 0); -//std::cout << "Deleted RefObj(" << std::hex << (int)this << ")\n"; + //std::cout << "Deleted RefObj(" << std::hex << (int)this << ")\n"; -#ifdef _DEBUG +#ifdef DEBUG --objectCounter; cDebug d("cRefCountObj::~cRefCountObj"); d.TraceNever("Object Destroyed[%p] %s Objects Left = %d\n", this, typeid(*this).name(), objectCounter); - if(objectCounter == 0) + if (objectCounter == 0) { - d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n") ; + d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n"); } ASSERT(gpRefCountObj_Objects); RefSet::const_iterator i = gpRefCountObj_Objects->find(this); ASSERT(i != gpRefCountObj_Objects->end()); gpRefCountObj_Objects->erase(this); - if(gpRefCountObj_Objects->size() == 0) + if (gpRefCountObj_Objects->size() == 0) { delete gpRefCountObj_Objects; gpRefCountObj_Objects = 0; @@ -128,28 +128,24 @@ void cRefCountObj::AddRef() const ++mRefCount; - #ifdef _DEBUG +#ifdef DEBUG ++referenceCounter; - #endif +#endif } void cRefCountObj::Release() const { - if (this == 0) - return; - if (--mRefCount == 0) { Delete(); } - #ifdef _DEBUG +#ifdef DEBUG --referenceCounter; - #endif +#endif } void cRefCountObj::Delete() const { delete this; } - diff --git a/src/core/refcountobj.h b/src/core/refcountobj.h index 68f39f7..a484747 100644 --- a/src/core/refcountobj.h +++ b/src/core/refcountobj.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,7 +37,7 @@ #define __REFCOUNTOBJ_H /////////////////////////////////////////////////////////////////////////////// -// class cRefCountObj +// class cRefCountObj // // Base class for objects that are to be reference counted. Derive from this // class to create an object that will keep track of how many owners it has @@ -45,7 +45,7 @@ // // The convention for using this class it to call AddRef() when you pass // a pointer to the object to a new owner. When the new owner is done with -// the object it +// the object it // // Note: In the current implementation we do not support a reference counted // object being an owner of itself, either directly or indirectly. For instance @@ -53,7 +53,7 @@ // through some AddChild(cRefCountObj*) function) and then call AddRef() followed // by AddChild(), then call Release(), you will end up with an object of reference // count 1 but no owners outside itself. -// +// // This is not foreseen to be a problem with the tripwire usage of this class. // // See refcountobj_t.cpp for examples on use. @@ -67,28 +67,31 @@ class cRefCountObj virtual void AddRef() const; virtual void Release() const; - int GetRefCount() const { return mRefCount; } - // sometimes it is useful to know an object's refrence + int GetRefCount() const + { + return mRefCount; + } + // sometimes it is useful to know an object's refrence protected: virtual ~cRefCountObj(); virtual void Delete() const; - // override this if you don't want to be destroyed by "delete this"! + // override this if you don't want to be destroyed by "delete this"! private: mutable int mRefCount; -#ifdef _DEBUG +#ifdef DEBUG private: - static int objectCounter; - static int referenceCounter; + static int objectCounter; + static int referenceCounter; friend void TestRefCountObj(); + public: - static bool AllRefCountObjDestoryed() - { - return objectCounter == 0 && referenceCounter == 0; + static bool AllRefCountObjDestoryed() + { + return objectCounter == 0 && referenceCounter == 0; } #endif }; #endif - diff --git a/src/core/resources.h b/src/core/resources.h index 66333fe..2f3bf9f 100644 --- a/src/core/resources.h +++ b/src/core/resources.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,100 +42,90 @@ #define __RESOURCES_H -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#include // for: Resource Table Implementation -#include "debug.h" // for: ASSERT and Trace -#include "error.h" // for: eInternal +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +#include // for: Resource Table Implementation +#include "debug.h" // for: ASSERT and Trace +#include "error.h" // for: eInternal //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Classes Declared in this module //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -template< class KEY, class RSC > class cResources_; -template< class KEY, class CHR > class cMessages_; +template class cResources_; +template class cMessages_; //============================================================================= // cResources_ -- Keyed collection of resources //----------------------------------------------------------------------------- -// SYNOPSIS: +// SYNOPSIS: // Used to maintain a table of resources that are indexed by KEY // type values. The type can be any valid type that is // assignable. -// +// // CONSTRAINTS: // must be a valid key type for the std::map concept // must be a valid value type for the std::map concept. -// +// // INVARIANTS: -// // -template< class KeyT, class RscT > -class cResources_ +// +template class cResources_ { //--Type Definitions - private: - - typedef - std::map< KeyT, RscT > Table; // Storage Rep - - - public: - - // Type definitions - - typedef KeyT Key; // The resource id - typedef KeyT& KeyRef; - typedef const KeyT& ConstKeyRef; - - typedef RscT Value; // The managed resource - typedef Value& ValueRef; - typedef const Value& ConstValueRef; - - typedef typename Table::value_type Pair; - - +private: + typedef std::map Table; // Storage Rep + + +public: + // Type definitions + + typedef KeyT Key; // The resource id + typedef KeyT& KeyRef; + typedef const KeyT& ConstKeyRef; + + typedef RscT Value; // The managed resource + typedef Value& ValueRef; + typedef const Value& ConstValueRef; + + typedef typename Table::value_type Pair; + //--Interface. - public: - - // Observers - - ConstValueRef Get( ConstKeyRef ) const; +public: + // Observers + + ConstValueRef Get(ConstKeyRef) const; + + + // Modifiers + void Put(const Pair*, const Pair*); + void Put(ConstKeyRef, Value); - // Modifiers - void Put( const Pair*, const Pair* ); - void Put( ConstKeyRef, Value ); - - //--Implementation. - - protected: - - static ConstValueRef DefaultValueRef(); // NOTE: - - private: - - Table m_table; -}; +protected: + static ConstValueRef DefaultValueRef(); // NOTE: + +private: + Table m_table; +}; //============================================================================= // cMessages_ -- Specialization of Resources_ for message strings //----------------------------------------------------------------------------- -// SYNOPSIS: -// Specialization of cResources_ to store message strings -// instead of generalized resource objects. In the future this can +// SYNOPSIS: +// Specialization of cResources_ to store message strings +// instead of generalized resource objects. In the future this can // be refactored to use message objects so that they can come from // a dynamic source (i.e., not a string-literal) such as persistant // storage or some algorithm based on the concatenation of elements. @@ -145,110 +135,93 @@ class cResources_ // not allowing the client to expect a specific character sequence // representation, such as the near ubiquitous const char*. For // example: -// -// const char* psz = messages.GetAnsi( IDS_SOMESTRING ); -// +// +// const char* psz = messages.GetAnsi( IDS_SOMESTRING ); +// // The above call requires the caller to be responsible for memory -// resources in the case of a conversion. However, there is no -// clear way to know up front how many bytes will be required. +// resources in the case of a conversion. However, there is no +// clear way to know up front how many bytes will be required. // Another equally unsatisfactory solution is to allocate the // memory within cMessages and require the caller to release the // the resources when they are done with the message. If we instead // require calls in the following form: -// -// std::string str = messages.GetAnsi( IDS_SOMESTRING ); -// +// +// std::string str = messages.GetAnsi( IDS_SOMESTRING ); +// // We can allows assume proper resource use regardless of whether -// a simple character pointer is returned or newly allocated +// a simple character pointer is returned or newly allocated // resources used to convert the stored message. -// -// +// +// // CONSTRAINTS: // As with all classes which manipulate character sequences, CHAR // must be a valid character type as defined by the STDCPP standard. // // -template< class KeyT, class CharT > -class cMessages_ : public cResources_< KeyT, const CharT* > +template class cMessages_ : public cResources_ { //--Type definitions - protected: - - typedef - cResources_ - Resources; - - public: - - typedef std::basic_string String; - typedef const KeyT& ConstKeyRef; +protected: + typedef cResources_ Resources; +public: + typedef std::basic_string String; + typedef const KeyT& ConstKeyRef; - //--Interface. - public: + //--Interface. - String Get ( ConstKeyRef ) const; - std::string GetAnsi( ConstKeyRef ) const; +public: + String Get(ConstKeyRef) const; + std::string GetAnsi(ConstKeyRef) const; #if SUPPORTS_WCHART - std::wstring GetWide( ConstKeyRef ) const; -#endif//SUPPORTS_WCHART + std::wstring GetWide(ConstKeyRef) const; +#endif //SUPPORTS_WCHART }; - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // IMPLEMENTATION: cResources_ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // NOTE: Macros to ease any changes in template arguments -#define Resource_Template template< class KeyT, class RscT > -#define Resource_Class cResources_< KeyT, RscT > - - -Resource_Template -void Resource_Class::Put( const Pair* beg, const Pair* end ) +#define Resource_Template template +#define Resource_Class cResources_ + + +Resource_Template void Resource_Class::Put(const Pair* beg, const Pair* end) { - for ( const Pair* at = beg; at != end; ++at ) + for (const Pair* at = beg; at != end; ++at) { - if ( !m_table.insert( *at ).second ) + if (!m_table.insert(*at).second) { - ASSERTMSG( 0, "Resource key already exists!" ); + ASSERTMSG(0, "Resource key already exists!"); // throw eInternal( "Resource key already exists!" ); } } } // By value allows the user to Resource_table.Put( 6, "Literal" ); -Resource_Template -inline -void Resource_Class::Put( ConstKeyRef id, Value sResource ) +Resource_Template inline void Resource_Class::Put(ConstKeyRef id, Value sResource) { - if ( m_table.insert( Pair( id, sResource ) ).second == false ) + if (m_table.insert(Pair(id, sResource)).second == false) { - ASSERTMSG( 0, "Resource key already exists!" ); + ASSERTMSG(0, "Resource key already exists!"); // throw eInternal( "Resource key already exists!" ); } } -Resource_Template -typename Resource_Class::ConstValueRef -Resource_Class::Get( ConstKeyRef id ) const +Resource_Template typename Resource_Class::ConstValueRef Resource_Class::Get(ConstKeyRef id) const { - typename Table::const_iterator at = m_table.find( id ); - - if ( at == m_table.end() ) + typename Table::const_iterator at = m_table.find(id); + + if (at == m_table.end()) { - #if IS_UNIX - #ifdef _DEBUG +#ifdef DEBUG std::cerr << "*** Error Resource_Class::Get() [" __FILE__ ":" << __LINE__ << "]: Resource not found\n"; - #endif - #else - ASSERTMSG( 0, "Resource does not exist!" ); - #endif - // TSS_Raise( eInternal, "Resource does not exist!" ); +#endif return DefaultValueRef(); } @@ -258,40 +231,31 @@ Resource_Class::Get( ConstKeyRef id ) const } } -Resource_Template -typename Resource_Class::ConstValueRef -Resource_Class::DefaultValueRef() +Resource_Template typename Resource_Class::ConstValueRef Resource_Class::DefaultValueRef() { static Value _default; return _default; } - - -#undef Resource_Template //template< class KeyT, class RscT > -#undef Resource_Class //Resources_ - - + + +#undef Resource_Template //template< class KeyT, class RscT > +#undef Resource_Class //Resources_ + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // IMPLEMENTATION: cMessages_ //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // NOTE: Macros to ease any changes in template arguments -#define Message_Template template< class KeyT, class CharT > -#define Message_Class cMessages_< KeyT, CharT > - - -Message_Template -inline -typename Message_Class::String -Message_Class::Get( ConstKeyRef id ) const +#define Message_Template template +#define Message_Class cMessages_ + + +Message_Template inline typename Message_Class::String Message_Class::Get(ConstKeyRef id) const { - typename Message_Class::Value msg = Resources::Get( id ); - return - ( msg == this->DefaultValueRef() ) - ? String() - : String( msg ); + typename Message_Class::Value msg = Resources::Get(id); + return (msg == this->DefaultValueRef()) ? String() : String(msg); } @@ -299,86 +263,69 @@ Message_Class::Get( ConstKeyRef id ) const namespace tss { - namespace rsc - { - /* WARNING:RAD -- Cannot use StringUtil or CodeConvert since +namespace rsc +{ +/* WARNING:RAD -- Cannot use StringUtil or CodeConvert since these use ErrorMessages and String Resources! */ - inline - void - ToNTMBS( std::string& nbs, const std::string& src ) - { - nbs.assign( src ); - } +inline void ToNTMBS(std::string& nbs, const std::string& src) +{ + nbs.assign(src); +} - #if SUPPORTS_WCHART +#if SUPPORTS_WCHART - inline - void - ToNTMBS( std::string& nbs, const std::wstring& wcs ) - { - nbs.resize( MB_CUR_MAX * wcs.size() ); +inline void ToNTMBS(std::string& nbs, const std::wstring& wcs) +{ + nbs.resize(MB_CUR_MAX * wcs.size()); - size_t nWrote = - ::wcstombs( - const_cast< char * >( nbs.c_str() ), - wcs.c_str(), nbs.size() + 1 ); + size_t nWrote = ::wcstombs(const_cast(nbs.c_str()), wcs.c_str(), nbs.size() + 1); - if ( nWrote == (size_t)-1 ) - { - ASSERTMSG( false, "Conversion error in cMessages_!" ); - // throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - } + if (nWrote == (size_t)-1) + { + ASSERTMSG(false, "Conversion error in cMessages_!"); + // throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + } - nbs.resize( nWrote ); - } + nbs.resize(nWrote); +} - inline - void - ToNTWCS( std::wstring& dst, const std::wstring& src ) - { - dst.assign( src ); - } +inline void ToNTWCS(std::wstring& dst, const std::wstring& src) +{ + dst.assign(src); +} - inline - void - ToNTWCS( std::wstring& wcs, const std::string& nbs ) - { - wcs.resize( nbs.size() ); +inline void ToNTWCS(std::wstring& wcs, const std::string& nbs) +{ + wcs.resize(nbs.size()); - size_t nWrote = - ::mbstowcs( - const_cast< wchar_t * >( wcs.c_str() ), - nbs.c_str(), wcs.size() + 1 ); + size_t nWrote = ::mbstowcs(const_cast(wcs.c_str()), nbs.c_str(), wcs.size() + 1); - if ( nWrote == (size_t)-1 ) - { - ASSERTMSG( false, "Conversion error in cMessages_!" ); - // throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - } + if (nWrote == (size_t)-1) + { + ASSERTMSG(false, "Conversion error in cMessages_!"); + // throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + } - wcs.resize( nWrote ); - } - #endif//SUPPORTS_WCHART - }//rsc:: -}//tss:: + wcs.resize(nWrote); +} +#endif //SUPPORTS_WCHART +} // namespace rsc +} // namespace tss -Message_Template -inline -std::string -Message_Class::GetAnsi( ConstKeyRef id ) const +Message_Template inline std::string Message_Class::GetAnsi(ConstKeyRef id) const { - typename Message_Class::Value msg = Resources::Get( id ); - - if ( msg == this->DefaultValueRef() ) + typename Message_Class::Value msg = Resources::Get(id); + + if (msg == this->DefaultValueRef()) { return std::string(); } else { std::string nbs; - tss::rsc::ToNTMBS( nbs, String( msg ) ); + tss::rsc::ToNTMBS(nbs, String(msg)); return nbs; } } @@ -386,37 +333,33 @@ Message_Class::GetAnsi( ConstKeyRef id ) const #if SUPPORTS_WCHART -Message_Template -inline -std::wstring -Message_Class::GetWide( ConstKeyRef id ) const +Message_Template inline std::wstring Message_Class::GetWide(ConstKeyRef id) const { - Value msg = Resources::Get( id ); - - if ( msg == DefaultValueRef() ) + Value msg = Resources::Get(id); + + if (msg == DefaultValueRef()) { return std::string(); } else { std::wstring wcs; - tss::rsc::ToNTWCS( wcs, String( msg ) ); + tss::rsc::ToNTWCS(wcs, String(msg)); return wcs; } } -#endif//SUPPORTS_WCHART +#endif //SUPPORTS_WCHART #undef Message_Template #undef Message_Class -#endif//__RESOURCES_H - +#endif //__RESOURCES_H //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE +// OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE * OLD CODE //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #ifdef RAD_OLDCODE @@ -424,125 +367,107 @@ Message_Class::GetWide( ConstKeyRef id ) const //============================================================================= // cMessages_ -- Specializations //----------------------------------------------------------------------------- -// SYNOPSIS: +// SYNOPSIS: // MSVC does not yet support specializations. As a compromise, we fully // specialize on TCHR but assume a key type of "const int". // // for SUNPro enums are ints, not const ints #if IS_SUNPRO - #define ENUM_TYPE int +# define ENUM_TYPE int #else - #define ENUM_TYPE const int +# define ENUM_TYPE const int #endif -template<> -class cMessages_ : - public cResources_< ENUM_TYPE, const char* > +template<> class cMessages_ : public cResources_ { - protected: - - typedef - cResources_< ENUM_TYPE, const char* > - Resources; - - public: - - typedef std::string String; - typedef int ConstKeyRef; // Better than - - - String Get( ConstKeyRef id ) const - { - Value msg = Resources::Get( id ); - return ( msg != DefaultValueRef() ) - ? String( msg ) - : String(); - } - - String GetAnsi( ConstKeyRef id ) const +protected: + typedef cResources_ Resources; + +public: + typedef std::string String; + typedef int ConstKeyRef; // Better than + + + String Get(ConstKeyRef id) const + { + Value msg = Resources::Get(id); + return (msg != DefaultValueRef()) ? String(msg) : String(); + } + + String GetAnsi(ConstKeyRef id) const + { + return Get(id); + } + +#if SUPPORTS_WCHART + std::wstring GetWide(ConstKeyRef id) const + { + Value msg = Resources::Get(id); + + if (msg == DefaultValueRef()) { - return Get( id ); + return std::wstring(); } - -#if SUPPORTS_WCHART - std::wstring GetWide( ConstKeyRef id ) const + else { - Value msg = Resources::Get( id ); - - if ( msg == DefaultValueRef() ) - { - return std::wstring(); - } - else - { - String::size_type - N = String::traits_type::length( msg ); - - std::wstring dst( N, 0x00 ); - std::ctype< wchar_t >().widen( msg, msg + N, dst.begin() ); - - return dst; - } + String::size_type N = String::traits_type::length(msg); + + std::wstring dst(N, 0x00); + std::ctype().widen(msg, msg + N, dst.begin()); + + return dst; } -#endif//SUPPORTS_WCHART + } +#endif //SUPPORTS_WCHART }; #if SUPPORTS_WCHART - -template<> -class cMessages_ : - public cResources_< const int, const wchar_t* > + +template<> class cMessages_ : public cResources_ { - protected: - - typedef - cResources_ - Resources; - - public: - - typedef std::wstring String; - typedef int ConstKeyRef; // Better than - - - String Get( ConstKeyRef id ) const - { - Value msg = Resources::Get( id ); - if( msg != DefaultValueRef() ) - return String( msg ); - else - return String(); - } - - std::string GetAnsi( ConstKeyRef id ) const +protected: + typedef cResources_ Resources; + +public: + typedef std::wstring String; + typedef int ConstKeyRef; // Better than + + + String Get(ConstKeyRef id) const + { + Value msg = Resources::Get(id); + if (msg != DefaultValueRef()) + return String(msg); + else + return String(); + } + + std::string GetAnsi(ConstKeyRef id) const + { + Value msg = Resources::Get(id); + + if (msg == DefaultValueRef()) { - Value msg = Resources::Get( id ); - - if ( msg == DefaultValueRef() ) - { - return std::string(); - } - else - { - String::size_type - N = String::traits_type::length( msg ); - - std::string dst( N, 0x00 ); - std::ctype().narrow( msg, msg + N, '?', dst.begin() ); - - return dst; - } + return std::string(); } - - String GetWide( ConstKeyRef id ) const + else { - return Get( id ); - } -}; + String::size_type N = String::traits_type::length(msg); -#endif//SUPPORTS_WCHART + std::string dst(N, 0x00); + std::ctype().narrow(msg, msg + N, '?', dst.begin()); -#endif//RAD_OLDCODE + return dst; + } + } + + String GetWide(ConstKeyRef id) const + { + return Get(id); + } +}; +# endif //SUPPORTS_WCHART +#endif //RAD_OLDCODE diff --git a/src/core/serializable.cpp b/src/core/serializable.cpp index 7c559df..16e896b 100644 --- a/src/core/serializable.cpp +++ b/src/core/serializable.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,8 +36,13 @@ #include "serializable.h" #if IS_SUNPRO -iTypedSerializable::~iTypedSerializable() {} -iSerializable::~iSerializable() {} -iTyped::~iTyped() {} +iTypedSerializable::~iTypedSerializable() +{ +} +iSerializable::~iSerializable() +{ +} +iTyped::~iTyped() +{ +} #endif - diff --git a/src/core/serializable.h b/src/core/serializable.h index f5a5325..5e2defe 100644 --- a/src/core/serializable.h +++ b/src/core/serializable.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,7 +46,7 @@ class iSerializer; -// Some version documentation is in order here: +// Some version documentation is in order here: // // Objects that derive from iSerializable do not need to worry about versions, they // should just read and write themselves to and from the serializer. @@ -56,70 +56,82 @@ class iSerializer; // version number. Neither major or minor version number can be negative and at least one // must be greater than zero. // -// When an object is serialized using iSerializer::WriteObject() a header will be written that -// includes the current version number will be saved in the archive by. Therefore -// iSerializable::Write() implementations do not need to worry about versioning, They need only +// When an object is serialized using iSerializer::WriteObject() a header will be written that +// includes the current version number will be saved in the archive by. Therefore +// iSerializable::Write() implementations do not need to worry about versioning, They need only // write out the object in current format. // -// When an object is read back from an archive using iSerializer::ReadObject(), -// the version of the serialized object will be read from the header and is passed to -// iSerializable::Read(). Each implementation of Read() should this passed in version. +// When an object is read back from an archive using iSerializer::ReadObject(), +// the version of the serialized object will be read from the header and is passed to +// iSerializable::Read(). Each implementation of Read() should this passed in version. // If the version is greater than the current version Read() should throw a eSerializer -// exception. If the version is older than the current implementation, Read() should either -// read the older format or throw an eSerializer exception. +// exception. If the version is older than the current implementation, Read() should either +// read the older format or throw an eSerializer exception. // // IMPORTANT: If the version is 0 (the default parameter) then Read() it should read // in the current format of the object. This is important if Read() is called directly. // // In some cases it may be desirable to not incur the overhead of the serializer writing -// header information for each serialized object. In this case call iSerializable::Read() and -// iSerializable::Write() directly rather than using ReadObject() and WriteObject(). +// header information for each serialized object. In this case call iSerializable::Read() and +// iSerializable::Write() directly rather than using ReadObject() and WriteObject(). class iSerializable { public: - virtual void Read (iSerializer* pSerializer, int32 version = 0) = 0; // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const = 0; // throw (eSerializer, eArchive) - // objects implement these methods to read and write themselves to a serializer. + virtual void Read(iSerializer* pSerializer, int32 version = 0) = 0; // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const = 0; // throw (eSerializer, eArchive) + // objects implement these methods to read and write themselves to a serializer. - virtual ~iSerializable() {} + virtual ~iSerializable() + { + } }; class iTypedSerializable : public iTyped, public iSerializable { public: typedef iTypedSerializable* (*CreateFunc)(); - // Pointer to a function that creates an empty version of each typed serializable object + // Pointer to a function that creates an empty version of each typed serializable object virtual int32 Version() const = 0; - // Return the current version of that this serializable object writes. - // As a convention version number should be (major_version << 16) | minor_version. + // Return the current version of that this serializable object writes. + // As a convention version number should be (major_version << 16) | minor_version. - static int32 MkVersion(int16 major, int16 minor) { return (int32)(((uint32)major << 16) | (uint32)minor); } - static int16 MajorVersion(int32 version) { return (int16)((uint32)version >> 16); } - static int16 MinorVersion(int32 version) { return (int16)version; } + static int32 MkVersion(int16 major, int16 minor) + { + return (int32)(((uint32)major << 16) | (uint32)minor); + } + static int16 MajorVersion(int32 version) + { + return (int16)((uint32)version >> 16); + } + static int16 MinorVersion(int32 version) + { + return (int16)version; + } - virtual ~iTypedSerializable() {} + virtual ~iTypedSerializable() + { + } }; ////////////////////////////// // convenience macros -#define DECLARE_TYPEDSERIALIZABLE() \ - DECLARE_TYPED() \ -public: \ - static iTypedSerializable* Create(); \ - virtual int32 Version() const; +# define DECLARE_TYPEDSERIALIZABLE() \ + DECLARE_TYPED() \ + public: \ + static iTypedSerializable* Create(); \ + virtual int32 Version() const; -#define IMPLEMENT_TYPEDSERIALIZABLE(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ - IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ - iTypedSerializable* CLASS::Create() \ - { \ - return new CLASS; \ - } \ - int32 CLASS::Version() const \ - { \ - return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ - } +# define IMPLEMENT_TYPEDSERIALIZABLE(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ + IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ + iTypedSerializable* CLASS::Create() \ + { \ + return new CLASS; \ + } \ + int32 CLASS::Version() const \ + { \ + return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ + } #endif // __SERIALIZABLE_H - diff --git a/src/core/serializer.cpp b/src/core/serializer.cpp index f80ae8c..f32af5e 100644 --- a/src/core/serializer.cpp +++ b/src/core/serializer.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,47 +47,47 @@ { TSTRING ret; - if( !eSerializer::mDataSource.empty() ) + if (!eSerializer::mDataSource.empty()) { ret = mMsg; - switch( eSerializer::mSourceType ) + switch (eSerializer::mSourceType) { case TY_UNDEFINED: - ret.append( mDataSource ); + ret.append(mDataSource); break; case TY_FILE: - ret.append( _T("\nFile: ") ); - ret.append( mDataSource ); + ret.append(_T("\nFile: ")); + ret.append(mDataSource); break; case TY_TEMPFILE: - ret.append( _T("\nTemporary File: ") ); - ret.append( mDataSource ); + ret.append(_T("\nTemporary File: ")); + ret.append(mDataSource); break; case TY_MEMORY: - ret.append( _T("\nMemory Block: ") ); //uhhh...?? - ret.append( mDataSource ); + ret.append(_T("\nMemory Block: ")); //uhhh...?? + ret.append(mDataSource); break; case TY_PIPE: - ret.append( _T("\nNamed Pipe: ")); - ret.append( mDataSource ); + ret.append(_T("\nNamed Pipe: ")); + ret.append(mDataSource); break; case TY_SOCKET: - ret.append( _T("\nNetwork Socket: ")); - ret.append( mDataSource ); + ret.append(_T("\nNetwork Socket: ")); + ret.append(mDataSource); break; default: - ret.append( _T("\n")); - ret.append( mDataSource ); + ret.append(_T("\n")); + ret.append(mDataSource); break; } } - else + else { // Just use the base class method... ret = eError::GetMsg(); } - + return ret; } diff --git a/src/core/serializer.h b/src/core/serializer.h index 036a24e..3e45ef2 100644 --- a/src/core/serializer.h +++ b/src/core/serializer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,52 +46,51 @@ class iSerializable; //////////////////////////////////////////////////////////// // Serializer Base Exception //////////////////////////////////////////////////////////// -TSS_BEGIN_EXCEPTION_NO_CTOR( eSerializer, eError ) - // TODO: What else to add to this enumeration? Locked File? Temp file? - enum DataSourceType { - TY_UNDEFINED = 0, - TY_FILE, - TY_TEMPFILE, - TY_MEMORY, - TY_PIPE, - TY_SOCKET - }; +TSS_BEGIN_EXCEPTION_NO_CTOR(eSerializer, eError) +// TODO: What else to add to this enumeration? Locked File? Temp file? +enum DataSourceType +{ + TY_UNDEFINED = 0, + TY_FILE, + TY_TEMPFILE, + TY_MEMORY, + TY_PIPE, + TY_SOCKET +}; - eSerializer( const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED ) - : eError( msg ), - mDataSource( dataSource ), - mSourceType( paramType ) - {} - - virtual TSTRING GetMsg() const; +eSerializer(const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED) + : eError(msg), mDataSource(dataSource), mSourceType(paramType) +{ +} + +virtual TSTRING GetMsg() const; private: - TSTRING mDataSource; - // TSTRING indentifier of the datasource associated with a particular error - // (if one exists) EX: a filename. - DataSourceType mSourceType; +TSTRING mDataSource; +// TSTRING indentifier of the datasource associated with a particular error +// (if one exists) EX: a filename. +DataSourceType mSourceType; TSS_END_EXCEPTION(); //////////////////////////////////////////////////////////// // Helper Macro For Serializer Exceptions //////////////////////////////////////////////////////////// -#define TSS_SERIALIZER_EXCEPTION( except ) \ - TSS_BEGIN_EXCEPTION_NO_CTOR( except, eSerializer ) \ - except( const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED ) \ - : eSerializer( msg, dataSource, paramType ) \ - {}; \ +#define TSS_SERIALIZER_EXCEPTION(except) \ + TSS_BEGIN_EXCEPTION_NO_CTOR(except, eSerializer) \ + except(const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED) \ + : eSerializer(msg, dataSource, paramType){}; \ TSS_END_EXCEPTION() //////////////////////////////////////////////////////////// // Specific Exceptions //////////////////////////////////////////////////////////// -TSS_SERIALIZER_EXCEPTION( eSerializerUnknownType ); -TSS_SERIALIZER_EXCEPTION( eSerializerInputStreamFmt); -TSS_SERIALIZER_EXCEPTION( eSerializerOutputStreamFmt ); -TSS_SERIALIZER_EXCEPTION( eSerializerInputStremTypeArray ); -TSS_SERIALIZER_EXCEPTION( eSerializerArchive ); // not used -TSS_SERIALIZER_EXCEPTION( eSerializerVersionMismatch ); -TSS_SERIALIZER_EXCEPTION( eSerializerEncryption ); +TSS_SERIALIZER_EXCEPTION(eSerializerUnknownType); +TSS_SERIALIZER_EXCEPTION(eSerializerInputStreamFmt); +TSS_SERIALIZER_EXCEPTION(eSerializerOutputStreamFmt); +TSS_SERIALIZER_EXCEPTION(eSerializerInputStremTypeArray); +TSS_SERIALIZER_EXCEPTION(eSerializerArchive); // not used +TSS_SERIALIZER_EXCEPTION(eSerializerVersionMismatch); +TSS_SERIALIZER_EXCEPTION(eSerializerEncryption); /* E_UNKNOWN_TYPE = 700, @@ -107,59 +106,62 @@ class iSerializer { public: // Initializing and closing the archive - virtual void Init() = 0; // throw eSerializer + virtual void Init() = 0; // throw eSerializer // initializes the serializer; must be called before any reading or writing is done virtual void Finit() = 0; - // called after a session of serialization is done; called implicitely by the destructor - // if not called explicitely before destruction + // called after a session of serialization is done; called implicitely by the destructor + // if not called explicitely before destruction //Reading and writing objects Init() should have already been called or all these will fail. - virtual void WriteObjectDynCreate(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) - // writes an object such that it can be dynamically created when read back in with - // ReadObject. - virtual iTypedSerializable* ReadObjectDynCreate() = 0; // throw (eSerializer, eArchive); + virtual void WriteObjectDynCreate(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) + // writes an object such that it can be dynamically created when read back in with + // ReadObject. + virtual iTypedSerializable* ReadObjectDynCreate() = 0; // throw (eSerializer, eArchive); // reads an object from the archive, returning a pointer to it. The caller is responsible for // deleteing or Release()ing it when done. - virtual void WriteObject(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) + virtual void WriteObject(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) // writes an object to the archive that will not be dynamically created - virtual void ReadObject(iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) + virtual void ReadObject(iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) // reads an object that was written with WriteObject() // writing interface // all of these can throw eArchive - virtual void ReadInt16(int16& ret) = 0; - virtual void ReadInt32(int32& ret) = 0; - virtual void ReadInt64(int64& ret) = 0; - virtual void ReadString(TSTRING& ret) = 0; - virtual int ReadBlob(void* pBlob, int count) = 0; - virtual void WriteInt16(int16 i) = 0; - virtual void WriteInt32(int32 i) = 0; - virtual void WriteInt64(int64 i) = 0; - virtual void WriteString(const TSTRING& s) = 0; - virtual void WriteBlob(const void* pBlob, int count) = 0; - - virtual TSTRING GetFileName() const { return _T(""); } - // derived classes can implement this to return the file name associated with the serializer. - // it is only used in error reporting. + virtual void ReadInt16(int16& ret) = 0; + virtual void ReadInt32(int32& ret) = 0; + virtual void ReadInt64(int64& ret) = 0; + virtual void ReadString(TSTRING& ret) = 0; + virtual int ReadBlob(void* pBlob, int count) = 0; + virtual void WriteInt16(int16 i) = 0; + virtual void WriteInt32(int32 i) = 0; + virtual void WriteInt64(int64 i) = 0; + virtual void WriteString(const TSTRING& s) = 0; + virtual void WriteBlob(const void* pBlob, int count) = 0; + + virtual TSTRING GetFileName() const + { + return _T(""); + } + // derived classes can implement this to return the file name associated with the serializer. + // it is only used in error reporting. // the error enumeration: 700-799 enum ErrorNum { - E_UNKNOWN_TYPE = 700, - E_INPUT_STREAM_FORMAT = 701, - E_INPUT_STR_TYPEARRAY = 702, // bad index in to type array - E_ARCHIVE = 703, - E_VERSION_MISMATCH = 704, - E_ENCRYPTION_ERROR = 705, - E_OUTPUT_STREAM_FORMAT = 706, + E_UNKNOWN_TYPE = 700, + E_INPUT_STREAM_FORMAT = 701, + E_INPUT_STR_TYPEARRAY = 702, // bad index in to type array + E_ARCHIVE = 703, + E_VERSION_MISMATCH = 704, + E_ENCRYPTION_ERROR = 705, + E_OUTPUT_STREAM_FORMAT = 706, E_NUMITEMS }; - - virtual ~iSerializer() {} -}; + virtual ~iSerializer() + { + } +}; #endif - diff --git a/src/core/serializerimpl.cpp b/src/core/serializerimpl.cpp index dbad235..3fe8fe4 100644 --- a/src/core/serializerimpl.cpp +++ b/src/core/serializerimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,37 +34,19 @@ #include "serializerimpl.h" #include "debug.h" #include "archive.h" -#include "ntmbs.h" // for: eCharacterEncoding +#include "ntmbs.h" // for: eCharacterEncoding #include "crc32.h" // static members -cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap ; -cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap ; - - -// RAD:09/01/99 -- No longer needed! -/////////////////////////////////////////////////////////////////////////////// -// util_TstrToStr -- converts the passed in tstring into a narrow string. maxSize -// indicates the size of the narrow buffer -/////////////////////////////////////////////////////////////////////////////// -// static inline void util_TstrToStr(char* pStr, const TCHAR* pTstr, int maxSize) -// { -// #ifdef _UNICODE -// ASSERT( maxSize >= wcstombs( 0, pTstr -// wcstombs(pStr, pTstr, maxSize); -// #else -// strncpy( pStr, pTstr, maxSize ); -// #endif -// } -// - +cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap; +cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap; /////////////////////////////////////////////////////////////////////////////// // util_GetCrc -- calculates the crc for the narrow version of the type's AsString() /////////////////////////////////////////////////////////////////////////////// -static uint32 util_GetCRC( const cType& type ) +static uint32 util_GetCRC(const cType& type) { - // + // // convert this to narrow... // @@ -74,40 +56,22 @@ static uint32 util_GetCRC( const cType& type ) // - Increased performance by removing superflous conversion // when type.AsString() is already narrow. // -#ifdef _UNICODE - - char sz[256]; - const uint8* pszType = (const uint8*)(&sz[0]); - const wchar_t* wsz = type.AsString(); - - ASSERT( countof(sz) >= ::wcstombs( 0, wsz, size_t(-1) ) ); - - int nBytes = (int)::wcstombs( (char*)pszType, wsz, countof(sz) ); - if ( nBytes == -1 ) // Bad character conversion! - { - throw eCharacterEncoding( - TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - } - -#else//!_UNICODE // We only need to count the characters // RAD: Yeesh! This is already done for us in cType::mString!!! - const uint8* pszType = (const uint8*)( type.AsString() ); - int nBytes = ::strlen( (const char*)pszType ); + const uint8* pszType = (const uint8*)(type.AsString()); + int nBytes = ::strlen((const char*)pszType); -#endif//_UNICODE - - ASSERT( sizeof(uint8) == sizeof(byte) ); - ASSERT( pszType && *pszType ); + ASSERT(sizeof(uint8) == sizeof(byte)); + ASSERT(pszType && *pszType); // // calculate the crc... // CRC_INFO crc; - crcInit( crc ); - crcUpdate( crc, pszType, nBytes ); - crcFinit( crc ); + crcInit(crc); + crcUpdate(crc, pszType, nBytes); + crcFinit(crc); return crc.crc; } @@ -115,11 +79,8 @@ static uint32 util_GetCRC( const cType& type ) //############################################################################# // class cSerializerImpl //############################################################################# -cSerializerImpl::cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName) : - mpArchive(&archive), - mMode(action), - mbInit(false), - mFileName( fileName ) +cSerializerImpl::cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName) + : mpArchive(&archive), mMode(action), mbInit(false), mFileName(fileName) { } @@ -143,13 +104,13 @@ bool cSerializerImpl::IsWriting() const void cSerializerImpl::RegisterSerializable(const cType& type, iTypedSerializable::CreateFunc pFunc) { - uint32 crc = util_GetCRC( type ); + uint32 crc = util_GetCRC(type); - if( cSerializerImpl::mSerCreateMap.find( crc ) != cSerializerImpl::mSerCreateMap.end() ) + if (cSerializerImpl::mSerCreateMap.find(crc) != cSerializerImpl::mSerCreateMap.end()) { // duplicate entry! // - ASSERT( false ); + ASSERT(false); TOSTRINGSTREAM str; str << _T("Duplicate entry in type table: ") << type.AsString() << std::endl; throw eInternal(str.str()); @@ -159,13 +120,13 @@ void cSerializerImpl::RegisterSerializable(const cType& type, iTypedSerializable void cSerializerImpl::RegisterSerializableRefCt(const cType& type, iSerRefCountObj::CreateFunc pFunc) { - uint32 crc = util_GetCRC( type ); + uint32 crc = util_GetCRC(type); - if( cSerializerImpl::mSerRefCountCreateMap.find( crc ) != cSerializerImpl::mSerRefCountCreateMap.end() ) + if (cSerializerImpl::mSerRefCountCreateMap.find(crc) != cSerializerImpl::mSerRefCountCreateMap.end()) { // duplicate entry! // - ASSERT( false ); + ASSERT(false); TOSTRINGSTREAM str; str << _T("Duplicate entry in type table: ") << type.AsString() << std::ends; throw eInternal(str.str()); @@ -189,7 +150,7 @@ void cSerializerImpl::Init() } /////////////////////////////////////////////////////////////////////////////// -// Finit +// Finit /////////////////////////////////////////////////////////////////////////////// void cSerializerImpl::Finit() { @@ -220,23 +181,23 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj) // get the ident for this class type // - uint32 crc = util_GetCRC( pObj->GetType() ); + uint32 crc = util_GetCRC(pObj->GetType()); // // make sure this type is registered, and figure out if it is refrence counted // - SerRefCountMap::iterator i = mSerRefCountCreateMap.find( crc ); - bool bRefCount = true; - if( i == mSerRefCountCreateMap.end() ) + SerRefCountMap::iterator i = mSerRefCountCreateMap.find(crc); + bool bRefCount = true; + if (i == mSerRefCountCreateMap.end()) { // // maybe it is not refrence counted... // - SerMap::iterator si = mSerCreateMap.find( crc ); - if( si == mSerCreateMap.end() ) + SerMap::iterator si = mSerCreateMap.find(crc); + if (si == mSerCreateMap.end()) { d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString()); - ThrowAndAssert(eSerializerUnknownType( pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE )); + ThrowAndAssert(eSerializerUnknownType(pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE)); } bRefCount = false; } @@ -245,12 +206,12 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj) mpArchive->WriteInt32(pObj->Version()); // write a placeholder for the size; we will come back and fill in the right value later... mpArchive->WriteInt32(0xffffffff); - - if(bRefCount) + + if (bRefCount) { // see if the object has already been serialized... int idx; - if((idx = mRefCtObjTbl.Lookup(static_cast(pObj))) == 0) + if ((idx = mRefCtObjTbl.Lookup(static_cast(pObj))) == 0) { // it is not in the table yet; add it and serialize the object idx = mRefCtObjTbl.Add(static_cast(pObj)); @@ -271,7 +232,6 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj) mpArchive->WriteInt32(0); // ... then write the object. pObj->Write(this); - } } @@ -283,7 +243,7 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() cDebug d("cSerializerImpl::ReadObjectDynCreate"); //d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos()); - int32 size, objIdx; + int32 size, objIdx; uint32 crc; // first, get the type... mpArchive->ReadInt32(reinterpret_cast(crc)); @@ -299,21 +259,21 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() //int64 sizePos = mpArchive->CurrentPos(); mpArchive->ReadInt32(objIdx); - if(objIdx == 0) + if (objIdx == 0) { // the object is not reference counted; create and read in the object // first, we need to create the object. SerMap::iterator si; si = mSerCreateMap.find(crc); - if(si == mSerCreateMap.end()) + if (si == mSerCreateMap.end()) { // unable to find the creation function... d.TraceError("Unable to find creation function for non-ref counted object %d\n", crc); TOSTRINGSTREAM str; - #ifdef _DEBUG +#ifdef DEBUG // Let's only report the actual crc in debug mode str << (int32)crc << std::ends; - #endif +#endif ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE)); } iTypedSerializable* pObj = ((*si).second)(); @@ -322,7 +282,7 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() // seek past this object in case filepos is not correct! //mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING); - + return pObj; } else @@ -330,12 +290,12 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() // refrence counted... iSerRefCountObj* pObj; pObj = mRefCtObjTbl.Lookup(objIdx); - if(pObj == NULL) + if (pObj == NULL) { // not in table yet...first find the creation function SerRefCountMap::iterator rci; rci = mSerRefCountCreateMap.find(crc); - if(rci == mSerRefCountCreateMap.end()) + if (rci == mSerRefCountCreateMap.end()) { // unable to find the creation function... d.TraceError("Unable to find creation function for ref counted object %d\n", crc); @@ -347,7 +307,7 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() d.TraceDetail("Creating Ref-Coutnted object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj); pObj->Read(this); mRefCtObjTbl.Add(pObj, objIdx); - + // seek past this object in case filepos is not correct! //mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING); @@ -356,10 +316,13 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate() else { // already serialized; just return this object. - d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj); + d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n", + objIdx, + pObj->GetType().AsString(), + pObj); pObj->AddRef(); } - + // seek past this object in case filepos is not correct! //mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING); @@ -385,12 +348,12 @@ void cSerializerImpl::WriteObject(const iTypedSerializable* pObj) // data the object data ASSERT(mpArchive != 0); - + // 5Nov 98 mdb -- I am removing the read and write of type info for this method; it is never used, since // the object is already created when ReadObject() happens. The only good it might serve is in asserting that // the input stream is valid, but I can do that with the 0xffffffff size below (asserting that it is the same // when it is read back in) -/* int i = 0; + /* int i = 0; for(; i < mTypeArray.size(); i++) { if(pObj->GetType() == *mTypeArray[i]) @@ -409,13 +372,13 @@ void cSerializerImpl::WriteObject(const iTypedSerializable* pObj) mpArchive->WriteInt32(i); */ - mpArchive->WriteInt32(0); // place holder for type array index + mpArchive->WriteInt32(0); // place holder for type array index mpArchive->WriteInt32(pObj->Version()); // write a placeholder for the size; we will come back and fill in the right value later... //int64 sizePos = mpArchive->CurrentPos(); mpArchive->WriteInt32(0xffffffff); - - // write out the object! + + // write out the object! pObj->Write(this); // finally, we need to go back and patch up the size... @@ -431,7 +394,7 @@ void cSerializerImpl::ReadObject(iTypedSerializable* pObj) //d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos()); // NOTE -- type index stuff is gone; see the comment in WriteObject() - int32 /*typeIdx,*/ size; + int32 /*typeIdx,*/ size; // first, get the type... /* mpArchive->ReadInt32(typeIdx); @@ -446,14 +409,14 @@ void cSerializerImpl::ReadObject(iTypedSerializable* pObj) // read in the version int32 dummy, version; - mpArchive->ReadInt32(dummy); // old type array index + mpArchive->ReadInt32(dummy); // old type array index mpArchive->ReadInt32(version); // read in the size and the index... mpArchive->ReadInt32(size); // use the size to assert that the file format is correct - if(size != (int)0xffffffff) + if (size != (int)0xffffffff) { // unknown type index! d.TraceError("Encountered bad size: %d\n", size); @@ -529,6 +492,5 @@ void cSerializerImpl::WriteBlob(const void* pBlob, int count) /////////////////////////////////////////////////////////////////////////////// TSTRING cSerializerImpl::GetFileName() const { - return mFileName; + return mFileName; } - diff --git a/src/core/serializerimpl.h b/src/core/serializerimpl.h index 273672c..d622b3a 100644 --- a/src/core/serializerimpl.h +++ b/src/core/serializerimpl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,75 +60,76 @@ class cArchive; class cSerializerImpl : public iSerializer { public: - enum Mode { S_READ, S_WRITE }; - cSerializerImpl (cArchive& archive, Mode action, const TSTRING& fileName = _T("") ); - // fileName is only used for error reporting purposes + enum Mode + { + S_READ, + S_WRITE + }; + cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName = _T("")); + // fileName is only used for error reporting purposes virtual ~cSerializerImpl(); - bool IsWriting() const; + bool IsWriting() const; // Initializing and closing the archive - virtual void Init(); // throw eSerializer + virtual void Init(); // throw eSerializer // initializes the serializer; must be called before any reading or writing is done virtual void Finit(); - // called after a session of serialization is done; called implicitely by the destructor - // if not called explicitely before destruction + // called after a session of serialization is done; called implicitely by the destructor + // if not called explicitely before destruction //Reading and writing objects Init() should have already been called or all these will fail. - virtual void WriteObjectDynCreate(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) - // writes an object such that it can be dynamically created when read back in with - // ReadObject. - virtual iTypedSerializable* ReadObjectDynCreate(); // throw (eSerializer, eArchive); + virtual void WriteObjectDynCreate(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) + // writes an object such that it can be dynamically created when read back in with + // ReadObject. + virtual iTypedSerializable* ReadObjectDynCreate(); // throw (eSerializer, eArchive); // reads an object from the archive, returning a pointer to it. The caller is responsible for // deleteing or Release()ing it when done. - virtual void WriteObject(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) + virtual void WriteObject(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) // writes an object to the archive that will not be dynamically created - virtual void ReadObject(iTypedSerializable* pObj); // throw (eSerializer, eArchive) + virtual void ReadObject(iTypedSerializable* pObj); // throw (eSerializer, eArchive) // reads an object that was written with WriteObject() // members for registering classes to be serialized. One of these must be called exactly once // for each class that is to be serialized. - static void RegisterSerializable (const cType& type, iTypedSerializable::CreateFunc pFunc); - static void RegisterSerializableRefCt (const cType& type, iSerRefCountObj::CreateFunc pFunc); + static void RegisterSerializable(const cType& type, iTypedSerializable::CreateFunc pFunc); + static void RegisterSerializableRefCt(const cType& type, iSerRefCountObj::CreateFunc pFunc); -// writing interface - // TODO -- I am not sure if I want to keep these or just have the serializer expose the archive. Actually, + // writing interface + // TODO -- I am not sure if I want to keep these or just have the serializer expose the archive. Actually, // I think the best thing might be to have iSerializable only know about the archive // Standard data read/write // (All functions can throw eArchave exceptions). - virtual void ReadInt16(int16& ret); - virtual void ReadInt32(int32& ret); - virtual void ReadInt64(int64& ret); - virtual void ReadString(TSTRING& ret); - virtual int ReadBlob(void* pBlob, int count); - virtual void WriteInt16(int16 i); - virtual void WriteInt32(int32 i); - virtual void WriteInt64(int64 i); - virtual void WriteString(const TSTRING& s); - virtual void WriteBlob(const void* pBlob, int count); + virtual void ReadInt16(int16& ret); + virtual void ReadInt32(int32& ret); + virtual void ReadInt64(int64& ret); + virtual void ReadString(TSTRING& ret); + virtual int ReadBlob(void* pBlob, int count); + virtual void WriteInt16(int16 i); + virtual void WriteInt32(int32 i); + virtual void WriteInt64(int64 i); + virtual void WriteString(const TSTRING& s); + virtual void WriteBlob(const void* pBlob, int count); virtual TSTRING GetFileName() const; private: - cArchive* mpArchive; // the archive we are serializing to - Mode mMode; // are we writing or reading? - bool mbInit; // has init been called? - cSerRefCountTable mRefCtObjTbl; // keeps track of all ref counted objects that - // have been read or written during serialization - TSTRING mFileName; + cArchive* mpArchive; // the archive we are serializing to + Mode mMode; // are we writing or reading? + bool mbInit; // has init been called? + cSerRefCountTable mRefCtObjTbl; // keeps track of all ref counted objects that + // have been read or written during serialization + TSTRING mFileName; // creation function maps - typedef std::map SerMap; - typedef std::map SerRefCountMap; - static SerMap mSerCreateMap; - static SerRefCountMap mSerRefCountCreateMap; + typedef std::map SerMap; + typedef std::map SerRefCountMap; + static SerMap mSerCreateMap; + static SerRefCountMap mSerRefCountCreateMap; static void InitSerializableMaps(); static void FinitSerializableMaps(); }; - - #endif - diff --git a/src/core/serializerutil.cpp b/src/core/serializerutil.cpp index 3dd021d..d93e70b 100644 --- a/src/core/serializerutil.cpp +++ b/src/core/serializerutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,39 +35,41 @@ #include "archive.h" #include "serializer.h" -namespace { -template -int64 CopyImpl(TO* pTo, FROM* pFrom, int64 amt) +namespace { - enum { BUF_SIZE = 8192 }; - int8 buf[BUF_SIZE]; - int64 amtLeft = amt; +template int64 CopyImpl(TO* pTo, FROM* pFrom, int64 amt) +{ + enum + { + BUF_SIZE = 8192 + }; + int8 buf[BUF_SIZE]; + int64 amtLeft = amt; - while(amtLeft > 0) + while (amtLeft > 0) { // NOTE: We use int's here rather than int64 because iSerializer and cArchive // only take int's as their size parameter - dmb int amtToRead = amtLeft > BUF_SIZE ? BUF_SIZE : (int)amtLeft; - int amtRead = pFrom->ReadBlob(buf, amtToRead ); + int amtRead = pFrom->ReadBlob(buf, amtToRead); amtLeft -= amtRead; pTo->WriteBlob(buf, amtRead); - if(amtRead < amtToRead) + if (amtRead < amtToRead) break; } // return the amount copied ... return (amt - amtLeft); } -} +} // namespace -int64 cSerializerUtil::Copy( iSerializer* pDest, cArchive* pSrc, int64 amt ) +int64 cSerializerUtil::Copy(iSerializer* pDest, cArchive* pSrc, int64 amt) { - return CopyImpl( pDest, pSrc, amt ); + return CopyImpl(pDest, pSrc, amt); } -int64 cSerializerUtil::Copy( cArchive* pDest, iSerializer* pSrc, int64 amt ) +int64 cSerializerUtil::Copy(cArchive* pDest, iSerializer* pSrc, int64 amt) { - return CopyImpl( pDest, pSrc, amt ); + return CopyImpl(pDest, pSrc, amt); } - diff --git a/src/core/serializerutil.h b/src/core/serializerutil.h index 1aeb75c..dda1f3c 100644 --- a/src/core/serializerutil.h +++ b/src/core/serializerutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,11 +44,10 @@ class iSerializer; class cSerializerUtil { public: - static int64 Copy( iSerializer* pDest, cArchive* pSrc, int64 amt ); // throw( eArchvie, eSerilaizer ) - static int64 Copy( cArchive* pDest, iSerializer* pSrc, int64 amt ); // throw( eArchvie, eSerilaizer ) + static int64 Copy(iSerializer* pDest, cArchive* pSrc, int64 amt); // throw( eArchvie, eSerilaizer ) + static int64 Copy(cArchive* pDest, iSerializer* pSrc, int64 amt); // throw( eArchvie, eSerilaizer ) // these two methods copy data from archives to serializers and vice-versa. They // throw exceptions on error; the return value is the amount that was copied. }; #endif - diff --git a/src/core/serstring.cpp b/src/core/serstring.cpp index 84b8084..c570880 100644 --- a/src/core/serstring.cpp +++ b/src/core/serstring.cpp @@ -1,43 +1,43 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// serstring.cpp -- A serializable interface wrapper around a string +// serstring.cpp -- A serializable interface wrapper around a string // #include "stdcore.h" #include "serstring.h" IMPLEMENT_TYPEDSERIALIZABLE(cSerializableNString, _T("cSerializableNString"), 0, 1) -void cSerializableNString::Read (iSerializer* pSerializer, int32 version) +void cSerializableNString::Read(iSerializer* pSerializer, int32 version) { int32 len; pSerializer->ReadInt32(len); @@ -55,7 +55,7 @@ void cSerializableNString::Write(iSerializer* pSerializer) const IMPLEMENT_TYPEDSERIALIZABLE(cSerializableWString, _T("cSerializableWString"), 0, 1) -void cSerializableWString::Read (iSerializer* pSerializer, int32 version) +void cSerializableWString::Read(iSerializer* pSerializer, int32 version) { int32 len; pSerializer->ReadInt32(len); @@ -69,4 +69,3 @@ void cSerializableWString::Write(iSerializer* pSerializer) const pSerializer->WriteInt32(len); pSerializer->WriteBlob(mString.data(), len); } - diff --git a/src/core/serstring.h b/src/core/serstring.h index 06f4b0a..27e83f0 100644 --- a/src/core/serstring.h +++ b/src/core/serstring.h @@ -1,41 +1,41 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// serstring.h -- A serializable interface wrapper around a string +// serstring.h -- A serializable interface wrapper around a string /////////////////////////////////////////////////////////////////////////////// #ifndef __SERSTRING_H #define __SERSTRING_H - + #ifndef __SERIALIZABLE_H #include "serializable.h" #endif @@ -55,9 +55,9 @@ class cSerializableNString : public iTypedSerializable { public: std::string mString; - - virtual ~cSerializableNString() {}; - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + + virtual ~cSerializableNString(){}; + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) DECLARE_TYPEDSERIALIZABLE() @@ -70,19 +70,14 @@ class cSerializableWString : public iTypedSerializable { public: std::string mString; - - virtual ~cSerializableWString() {}; - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + + virtual ~cSerializableWString(){}; + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) DECLARE_TYPEDSERIALIZABLE() }; -#ifdef _UNICODE -typedef cSerializableWString cSerializableTSTRING; -#else -typedef cSerializableNString cSerializableTSTRING; -#endif - -#endif +typedef cSerializableNString cSerializableTSTRING; +#endif diff --git a/src/core/sha.cpp b/src/core/sha.cpp index bf3f104..3b3c414 100644 --- a/src/core/sha.cpp +++ b/src/core/sha.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -64,7 +64,10 @@ #include "stdcore.h" #include #include -#include + +#if HAVE_MEMORY_H +# include +#endif #include "sha.h" diff --git a/src/core/sha.h b/src/core/sha.h index ea1880f..502e170 100644 --- a/src/core/sha.h +++ b/src/core/sha.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/core/srefcountobj.cpp b/src/core/srefcountobj.cpp index da2a5c2..9ad77cc 100644 --- a/src/core/srefcountobj.cpp +++ b/src/core/srefcountobj.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,10 +36,9 @@ #include "srefcountobj.h" /////////////////////////////////////////////////////////////////////////////// -// class cSerializableRefCountObj +// class cSerializableRefCountObj // iSerRefCountObj::~iSerRefCountObj() { } - diff --git a/src/core/srefcountobj.h b/src/core/srefcountobj.h index 61080aa..d69087d 100644 --- a/src/core/srefcountobj.h +++ b/src/core/srefcountobj.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,7 +49,7 @@ #endif /////////////////////////////////////////////////////////////////////////////// -// class cSerializableRefCountObj +// class cSerializableRefCountObj // class iSerRefCountObj : public cRefCountObj, public iTypedSerializable { @@ -59,28 +59,26 @@ class iSerRefCountObj : public cRefCountObj, public iTypedSerializable protected: virtual ~iSerRefCountObj(); - }; ////////////////////////////// // convenience macros -#define DECLARE_SERREFCOUNT() \ - DECLARE_TYPED() \ -public: \ - static iSerRefCountObj* Create(); \ - virtual int32 Version() const; +# define DECLARE_SERREFCOUNT() \ + DECLARE_TYPED() \ + public: \ + static iSerRefCountObj* Create(); \ + virtual int32 Version() const; -#define IMPLEMENT_SERREFCOUNT(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ - IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ - iSerRefCountObj* CLASS::Create() \ - { \ - return new CLASS; \ - } \ - int32 CLASS::Version() const \ - { \ - return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ - } +# define IMPLEMENT_SERREFCOUNT(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ + IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ + iSerRefCountObj* CLASS::Create() \ + { \ + return new CLASS; \ + } \ + int32 CLASS::Version() const \ + { \ + return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ + } #endif - diff --git a/src/core/srefcounttbl.cpp b/src/core/srefcounttbl.cpp index 3e88c88..a3da794 100644 --- a/src/core/srefcounttbl.cpp +++ b/src/core/srefcounttbl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -79,8 +79,8 @@ iSerRefCountObj* cSerRefCountTable::Lookup(int id) return itr == mIDToObjTbl.end() ? NULL : itr->second; } -// Add an object to the table, optionally specifying an ID. Returns a -// unique ID for the object. ASSERTs and throws exception if object is +// Add an object to the table, optionally specifying an ID. Returns a +// unique ID for the object. ASSERTs and throws exception if object is // already in table or the ID is already taken. int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id) { @@ -100,8 +100,8 @@ int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id) ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table."))); } - mIDToObjTbl.insert( MapIDTObj::value_type(id, pObj)); - mObjToIdTbl.insert( MapObjIDT::value_type(pObj, id)); + mIDToObjTbl.insert(MapIDTObj::value_type(id, pObj)); + mObjToIdTbl.insert(MapObjIDT::value_type(pObj, id)); return id; } @@ -119,7 +119,7 @@ int cSerRefCountTable::Add(const iSerRefCountObj* pObj, int id) // creates a new cSerRefCountTable void cSerRefCountTableMap::AddSerializer(const cSerializer* pSerializer) { - #ifdef _DEBUG + #ifdef DEBUG // make sure we don't have this serialzier in here yet { std::map::iterator itr; @@ -154,4 +154,3 @@ cSerRefCountTableMap::~cSerRefCountTableMap() } } */ - diff --git a/src/core/srefcounttbl.h b/src/core/srefcounttbl.h index cab73db..b133ae1 100644 --- a/src/core/srefcounttbl.h +++ b/src/core/srefcounttbl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,16 +51,16 @@ class cSerRefCountTable // find object for specified id. returns NULL if not in table iSerRefCountObj* Lookup(int id); - // Add an object to the table, optionally specifying an ID. Returns a - // unique ID for the object. ASSERTs and throws exception if object is + // Add an object to the table, optionally specifying an ID. Returns a + // unique ID for the object. ASSERTs and throws exception if object is // already in table or the ID is already taken. - int Add( iSerRefCountObj* pObj, int id = 0); - int Add(const iSerRefCountObj* pObj, int id = 0); - // TODO -- Note that this class is not really const-correct in that the const version of - // Add() just casts away the constness. The right thing to do is to make the serializer - // use different versions of this class (const and non-const) depending on whether it is - // reading or writing and (maybe?) make this class a template class so that it can map - // to either const or non-const objects. + int Add(iSerRefCountObj* pObj, int id = 0); + int Add(const iSerRefCountObj* pObj, int id = 0); + // TODO -- Note that this class is not really const-correct in that the const version of + // Add() just casts away the constness. The right thing to do is to make the serializer + // use different versions of this class (const and non-const) depending on whether it is + // reading or writing and (maybe?) make this class a template class so that it can map + // to either const or non-const objects. // clears out the table @@ -89,4 +89,3 @@ class cSerRefCountTableMap }; */ #endif - diff --git a/src/core/stdcore.cpp b/src/core/stdcore.cpp index 1798c5b..9c32494 100644 --- a/src/core/stdcore.cpp +++ b/src/core/stdcore.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdcore.h" - -// eof: stdcore.cpp diff --git a/src/core/stdcore.h b/src/core/stdcore.h index fc5848b..acdc2c1 100644 --- a/src/core/stdcore.h +++ b/src/core/stdcore.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,43 +48,43 @@ //--Disable some level 4 warnings #if IS_MSVC - - #define NOMINMAX //--Disable min/max macros - - #include // ARGH!! This resumes certain warnings! - - #pragma warning( disable: 4786 ) // Token Name > 255 - #pragma warning( disable: 4127 ) // constant expression (e.g. ASSERT) - #pragma warning( disable: 4291 ) // Incorrectly called when new(nothrow)!!! - #pragma warning( disable: 4097 ) // Type synonyms are good! - #pragma warning( disable: 4511 ) // Can't create copy ctor! (e.g.Private CTOR) - #pragma warning( disable: 4512 ) // Can't create assignment!(e.g.Private CTOR) - #pragma warning( disable: 4100 ) // Formal argument not used - #pragma warning( disable: 4710 ) // Compiler did not inline function - -#ifndef _DEBUG // ASSERT's are disabled give a lot of these - #pragma warning( disable: 4702 ) // ---Unreachable Code -#endif - /* NOTE:RAD:05/09/1999 -- Plaguers STDCPP implementation is SOOO bad +# define NOMINMAX //--Disable min/max macros + +#include // ARGH!! This resumes certain warnings! + +# pragma warning(disable : 4786) // Token Name > 255 +# pragma warning(disable : 4127) // constant expression (e.g. ASSERT) +# pragma warning(disable : 4291) // Incorrectly called when new(nothrow)!!! +# pragma warning(disable : 4097) // Type synonyms are good! +# pragma warning(disable : 4511) // Can't create copy ctor! (e.g.Private CTOR) +# pragma warning(disable : 4512) // Can't create assignment!(e.g.Private CTOR) +# pragma warning(disable : 4100) // Formal argument not used +# pragma warning(disable : 4710) // Compiler did not inline function + +# ifndef DEBUG // ASSERT's are disabled give a lot of these +# pragma warning(disable : 4702) // ---Unreachable Code +# endif + +/* NOTE:RAD:05/09/1999 -- Plaguers STDCPP implementation is SOOO bad it creates all these errors when compiling at W4. By doing a push before disabling them, we can still generate them for ourselves without a lot of noise. The warnings before this push, we want to always disable. */ - #pragma warning( push ) +# pragma warning(push) - #pragma warning( disable: 4663 ) // Old template specialization syntax - #pragma warning( disable: 4018 ) // Signed unsigned mismatch - #pragma warning( disable: 4245 ) // Signed unsigned mismatch - #pragma warning( disable: 4663 ) // Use new template specialization syntax: template<> - #pragma warning( disable: 4701 ) // local variable 'X' may be used without having been initialized - #pragma warning( disable: 4510 ) // 'X' : default constructor could not be generated - #pragma warning( disable: 4610 ) // struct 'X' can never be instantiated - user defined constructor required - #pragma warning( disable: 4146 ) // unary minus operator applied to unsigned type, result still unsigned - #pragma warning( disable: 4244 ) // '=' : conversion from 'unsigned int' to 'char', possible loss of data - #pragma warning( disable: 4511 ) - #pragma warning( disable: 4503 ) +# pragma warning(disable : 4663) // Old template specialization syntax +# pragma warning(disable : 4018) // Signed unsigned mismatch +# pragma warning(disable : 4245) // Signed unsigned mismatch +# pragma warning(disable : 4663) // Use new template specialization syntax: template<> +# pragma warning(disable : 4701) // local variable 'X' may be used without having been initialized +# pragma warning(disable : 4510) // 'X' : default constructor could not be generated +# pragma warning(disable : 4610) // struct 'X' can never be instantiated - user defined constructor required +# pragma warning(disable : 4146) // unary minus operator applied to unsigned type, result still unsigned +# pragma warning(disable : 4244) // '=' : conversion from 'unsigned int' to 'char', possible loss of data +# pragma warning(disable : 4511) +# pragma warning(disable : 4503) #endif // #if IS_MSVC @@ -108,13 +108,12 @@ #include #if IS_MSVC - #pragma warning( pop ) // Resume W4 msgs for TSS code +# pragma warning(pop) // Resume W4 msgs for TSS code #endif //--Include Platform Specific Declarations - //--Include Common Core Declarations #include "./tchar.h" @@ -123,5 +122,4 @@ #include "./debug.h" -#endif//__STDCORE_H - +#endif //__STDCORE_H diff --git a/src/core/stringutil.cpp b/src/core/stringutil.cpp index f471613..edee741 100644 --- a/src/core/stringutil.cpp +++ b/src/core/stringutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -66,16 +66,15 @@ /// Requirements -#include "stdcore.h" // for: pch +#include "stdcore.h" // for: pch -#include "stringutil.h" // for: These Declarations -#include "debug.h" // for: Debugging Interface -#include "codeconvert.h" // for: iconv abstractions -#include "ntmbs.h" // for: eCharacterEncoding +#include "stringutil.h" // for: These Declarations +#include "debug.h" // for: Debugging Interface +#include "codeconvert.h" // for: iconv abstractions +#include "ntmbs.h" // for: eCharacterEncoding #include "hashtable.h" - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // String Cache //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -85,7 +84,7 @@ class tss_hash_key_convert { public: - const byte* operator()( const wc16_string& s, int* const pcbKeyLen ) + const byte* operator()(const wc16_string& s, int* const pcbKeyLen) { *pcbKeyLen = sizeof(WCHAR16) * s.length(); return (byte*)s.c_str(); @@ -95,82 +94,63 @@ class tss_hash_key_convert class tss_hash_key_compare { public: - bool operator()( const wc16_string& lhs, const wc16_string& rhs ) + bool operator()(const wc16_string& lhs, const wc16_string& rhs) { - return ( lhs.compare( rhs ) == 0 ); + return (lhs.compare(rhs) == 0); } }; namespace /* Module Local */ { - typedef - cHashTable< wc16_string, - TSTRING, - tss_hash_key_compare, - tss_hash_key_convert > - hashtable_t; - - hashtable_t& tss_GetHashTable() - { - static hashtable_t s_table; - return s_table; - } -}//Anon. - +typedef cHashTable hashtable_t; -inline void tss_insert_in_hash( const wc16_string& lhs, const TSTRING& rhs ) +hashtable_t& tss_GetHashTable() { - tss_GetHashTable().Insert( lhs, rhs ); -} - -inline bool tss_find_in_hash( const wc16_string& lhs, TSTRING& rhs ) -{ - return( tss_GetHashTable().Lookup( lhs, rhs ) ); + static hashtable_t s_table; + return s_table; } +} // namespace -#ifdef _UNICODE -inline bool tss_find_in_hash( const wc16_string& lhs, std::string& rhs ) +inline void tss_insert_in_hash(const wc16_string& lhs, const TSTRING& rhs) { - return false; // don't have a hash table for this! + tss_GetHashTable().Insert(lhs, rhs); } -inline void tss_insert_in_hash( const wc16_string& lhs, const std::string& rhs ) +inline bool tss_find_in_hash(const wc16_string& lhs, TSTRING& rhs) { - return; // don't have a hash table for this! + return (tss_GetHashTable().Lookup(lhs, rhs)); } -#endif //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Type Dispatched Conversions //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*static*/ -std::string::const_iterator -cStringUtil::Convert( std::string& nbs, const wc16_string& dbs ) +std::string::const_iterator cStringUtil::Convert(std::string& nbs, const wc16_string& dbs) { -#ifdef __AROS__ +#if IS_AROS nbs.resize(dbs.length()); - for (int x=0; xConvert( + (char*)nbs.c_str(), nbs.size(), dbs.c_str(), dbs.size()); // c_str() because must be null terminated - int nWrote = - iCodeConverter::GetInstance()->Convert( - (char*)nbs.c_str(), nbs.size(), - dbs.c_str(), dbs.size() ); // c_str() because must be null terminated + d.TraceDetail(_T("iCodeConverter returned %d\n"), nWrote); - d.TraceDetail( _T("iCodeConverter returned %d\n"), nWrote ); + if (nWrote == -1) + throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); - if ( nWrote == -1 ) - throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + nbs.resize(nWrote); - nbs.resize( nWrote ); - - tss_insert_in_hash( dbs, nbs ); + tss_insert_in_hash(dbs, nbs); } #endif @@ -202,37 +180,34 @@ cStringUtil::Convert( std::string& nbs, const wc16_string& dbs ) } /*static*/ -wc16_string::const_iterator -cStringUtil::Convert( wc16_string& dbs, const std::string& nbs ) +wc16_string::const_iterator cStringUtil::Convert(wc16_string& dbs, const std::string& nbs) { -#ifdef __AROS__ +#if IS_AROS dbs.resize(nbs.length()); - for (int x=0; x\n", nbs.c_str() ); - int nWrote = - iCodeConverter::GetInstance()->Convert( - (WCHAR16*)dbs.c_str(), dbs.length(), - nbs.c_str(), nbs.size() ); // c_str() because must be null terminated - - d.TraceDetail( _T("iCodeConverter returned %d\n"), nWrote ); - - if ( nWrote == -1 ) + int nWrote = iCodeConverter::GetInstance()->Convert( + (WCHAR16*)dbs.c_str(), dbs.length(), nbs.c_str(), nbs.size()); // c_str() because must be null terminated + + d.TraceDetail(_T("iCodeConverter returned %d\n"), nWrote); + + if (nWrote == -1) { - throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); + throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); } - dbs.resize( nWrote ); - + dbs.resize(nWrote); + /* d.TraceDebug( _T("converted to: \n") ); for( int i = 0; i < dbs.size(); i++ ) @@ -250,18 +225,17 @@ cStringUtil::Convert( wc16_string& dbs, const std::string& nbs ) #if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2 /*static*/ -std::wstring::const_iterator -cStringUtil::Convert( std::wstring& wcs, const wc16_string& dbs ) +std::wstring::const_iterator cStringUtil::Convert(std::wstring& wcs, const wc16_string& dbs) { if (dbs.size() != 0) { - if( tss_find_in_hash( dbs, wcs ) ) + if (tss_find_in_hash(dbs, wcs)) return wcs.begin(); - wcs.resize( dbs.size() ); - std::copy( dbs.begin(), dbs.end(), wcs.begin() ); - - tss_insert_in_hash( dbs, wcs ); + wcs.resize(dbs.size()); + std::copy(dbs.begin(), dbs.end(), wcs.begin()); + + tss_insert_in_hash(dbs, wcs); } else wcs.erase(); @@ -270,13 +244,12 @@ cStringUtil::Convert( std::wstring& wcs, const wc16_string& dbs ) } /*static*/ -wc16_string::const_iterator -cStringUtil::Convert( wc16_string& dbs, const std::wstring& wcs ) +wc16_string::const_iterator cStringUtil::Convert(wc16_string& dbs, const std::wstring& wcs) { if (wcs.size() != 0) { - dbs.resize( wcs.size() ); - std::copy( wcs.begin(), wcs.end(), dbs.begin() ); + dbs.resize(wcs.size()); + std::copy(wcs.begin(), wcs.end(), dbs.begin()); } else dbs.resize(0); @@ -285,18 +258,17 @@ cStringUtil::Convert( wc16_string& dbs, const std::wstring& wcs ) } /*static*/ -std::wstring::const_iterator -cStringUtil::Convert( std::wstring& wcs, const std::string& nbs ) +std::wstring::const_iterator cStringUtil::Convert(std::wstring& wcs, const std::string& nbs) { if (nbs.size() != 0) { - wcs.resize( nbs.size() ); - - size_t nWrote = ::mbstowcs( (wchar_t*)wcs.c_str(), nbs.c_str(), wcs.size() + 1 ); - if ( nWrote == (size_t)-1 ) - throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - - wcs.resize( nWrote ); + wcs.resize(nbs.size()); + + size_t nWrote = ::mbstowcs((wchar_t*)wcs.c_str(), nbs.c_str(), wcs.size() + 1); + if (nWrote == (size_t)-1) + throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); + + wcs.resize(nWrote); } else wcs.erase(); @@ -305,22 +277,21 @@ cStringUtil::Convert( std::wstring& wcs, const std::string& nbs ) } /*static*/ -std::string::const_iterator -cStringUtil::Convert( std::string& nbs, const std::wstring& wcs ) +std::string::const_iterator cStringUtil::Convert(std::string& nbs, const std::wstring& wcs) { if (wcs.size() != 0) { - if( tss_find_in_hash( wc16_string( wcs.c_str() ), nbs ) ) + if (tss_find_in_hash(wc16_string(wcs.c_str()), nbs)) return nbs.begin(); - nbs.resize( MB_CUR_MAX * wcs.size() ); - size_t nWrote = ::wcstombs( (char*)nbs.c_str(), wcs.c_str(), nbs.size() + 1 ); - if ( nWrote == (size_t)-1 ) - throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - - nbs.resize( nWrote ); - - tss_insert_in_hash( wc16_string( wcs.c_str() ), nbs ); + nbs.resize(MB_CUR_MAX * wcs.size()); + size_t nWrote = ::wcstombs((char*)nbs.c_str(), wcs.c_str(), nbs.size() + 1); + if (nWrote == (size_t)-1) + throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR)); + + nbs.resize(nWrote); + + tss_insert_in_hash(wc16_string(wcs.c_str()), nbs); } else nbs.erase(); @@ -337,188 +308,39 @@ cStringUtil::Convert( std::string& nbs, const std::wstring& wcs ) // TstrToStr /////////////////////////////////////////////////////////////////////////////// -std::string -cStringUtil::TstrToStr( const TSTRING& tstr ) +std::string cStringUtil::TstrToStr(const TSTRING& tstr) { std::string s; - cStringUtil::Convert( s, tstr ); + cStringUtil::Convert(s, tstr); return s; } /////////////////////////////////////////////////////////////////////////////// // StrToTstr /////////////////////////////////////////////////////////////////////////////// -TSTRING cStringUtil::StrToTstr( const std::string& rhs ) +TSTRING cStringUtil::StrToTstr(const std::string& rhs) { TSTRING lhs; - cStringUtil::Convert( lhs, rhs ); + cStringUtil::Convert(lhs, rhs); return lhs; } /////////////////////////////////////////////////////////////////////////////// // WstrToTstr /////////////////////////////////////////////////////////////////////////////// -TSTRING cStringUtil::WstrToTstr(const wc16_string& rhs ) -{ +TSTRING cStringUtil::WstrToTstr(const wc16_string& rhs) +{ TSTRING lhs; - cStringUtil::Convert( lhs, rhs ); - return lhs; -} - -/////////////////////////////////////////////////////////////////////////////// -// TstrToWstr -/////////////////////////////////////////////////////////////////////////////// -wc16_string cStringUtil::TstrToWstr( const TSTRING& rhs ) -{ - wc16_string lhs; - cStringUtil::Convert( lhs, rhs ); + cStringUtil::Convert(lhs, rhs); return lhs; } /////////////////////////////////////////////////////////////////////////////// -// StringIsInteger -- returns true if the string is a length of at least one -// and contains nothing other than [0-9]. -// Used to verify a string is acceptable to pass to atoi() +// TstrToWstr /////////////////////////////////////////////////////////////////////////////// -#ifdef OLDCODE -bool cStringUtil::StringIsInteger(TCHAR* pStr) +wc16_string cStringUtil::TstrToWstr(const TSTRING& rhs) { - int len = _tcslen(pStr); - - if (len <= 0) - return false; - - for (int i = 0; i < len; ++i) - { - if (pStr[i] < _T('0') || pStr[i] > _T('9')) - return false; - } - - return true; -} -#endif//OLDCODE - -// eof: stringutil.cpp - -/* - - -typedef wchar_t dbchar_t; -typedef char mbchar_t; - -class cMBUCS2Cache -{ -public: - cMBUCS2Cache(); - ~cMBUCS2Cache(); - - bool Convert(dbchar_t& ret, mbchar_t* pMBChar); - // returns false if conversion could not be done - void Add(mbchar_t* pMBchar, int mblen); - // add a mb char def to the chache - -protected: - struct Element - { - union - { - Element* mpNext; // points to another Element[256] - dbchar_t mUCS2; - }; - - enum ElementDefinition { UNDEFINED, UCS2, CONTINUES }; - short mElementDefinition; - - Element() { mElementDefinition = UNDEFINED; } - ~Element() { if (mElementDefinition == CONTINUES) delete mpNext; } - }; - - Element mTop[256]; -}; - - -cMBUCS2Cache::cMBUCS2Cache() -{ -} - -cMBUCS2Cache::~cMBUCS2Cache() -{ -} - -// returns false if conversion could not be done -bool cMBUCS2Cache::Convert(dbchar_t& ret, mbchar_t* pMBChar) -{ - Element* pNode = mTop; - while (pNode[*pMBChar].mElementDefinition == Element::CONTINUES) - { - pNode = pNode[*pMBChar].mpNext; - ++pMBChar; - } - - if (pNode[*pMBChar].mElementDefinition == Element::UCS2) - { - ret = pNode[*pMBChar].mUCS2; - return true; - } - - return false; -} - -// add a mb char def to the chache -void cMBUCS2Cache::Add(mbchar_t* pMBchar, int mblen, dbchar_t ucs2) -{ - ASSERT(mblen > 0); - - Element* pNode = mTop; - while (mblen > 1); - { - // this ASSERT fails if there is a UCS2 definition for a mbchar - // whose first few bytes are identical to this char - ASSERT(pNode[*pMBchar].mElementDefinition == Element::UNDEFINED || - pNode[*pMBchar].mElementDefinition == Element::CONTINUES) - - if (pNode[*pMBchar].mElementDefinition == Element::UNDEFINED) - { - pNode[*pMBchar].mElementDefinition = Element::CONINUES; - pNode = pNode[*pMBchar].mpNext = new Element[256]; - } - else - { - pNode = pNode[*pMBchar].mpNext; - } - - --mblen; - ++pMBChar; - } - - // this assert makes sure everything is sane - ASSERT(pNode[*pMBchar].mElementDefinition == Element::UNDEFINED || - (pNode[*pMBchar].mElementDefinition == Element::UCS2 && pNode[*pMBchar].mUCS2 == ucs2)); - - // this assert fails if we attempt to add the same mbchar twice - ASSERT(pNode[*pMBchar].mElementDefinition == Element::UNDEFINED) - - pNode[*pMBchar].mElementDefinition = Element::UCS2; - pNode[*pMBchar].mUCS2 = ucs2; -} -*/ -/* -static inline const byte* tss_hash_key_convert()( const TCHAR* psz, int* const pcbKeyLen ) -{ - *pcbKeyLen = sizeof(TCHAR) * _tcslen( psz ); - return (byte*)psz; -} - -static inline bool tss_hash_key_compare()( const TCHAR* lhs, const TCHAR* rhs ) -{ - return ( _tcscmp( lhs, rhs ) == 0 ); + wc16_string lhs; + cStringUtil::Convert(lhs, rhs); + return lhs; } - -cHashTable< dbchar_t*, - mbchar_t*, - tss_hash_key_convert, - tss_hash_key_compare > ha; - */ - - - diff --git a/src/core/stringutil.h b/src/core/stringutil.h index c4540ba..240e958 100644 --- a/src/core/stringutil.h +++ b/src/core/stringutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -55,98 +55,85 @@ //----------------------------------------------------------------------------- namespace cStringUtil { - //--Type Dispatched Conversion (Generalization away from TCHAR) +//--Type Dispatched Conversion (Generalization away from TCHAR) - /// Handle Like-Types (xstring to xstring) +/// Handle Like-Types (xstring to xstring) - inline - const char * - Convert( std::string& lhs, const std::string& rhs ) - { - lhs = rhs; - return lhs.c_str(); - } +inline const char* Convert(std::string& lhs, const std::string& rhs) +{ + lhs = rhs; + return lhs.c_str(); +} - /// Specialize Everything Else +/// Specialize Everything Else - std::string::const_iterator - Convert( std::string&, const wc16_string& ); +std::string::const_iterator Convert(std::string&, const wc16_string&); - wc16_string::const_iterator - Convert( wc16_string&, const std::string& ); +wc16_string::const_iterator Convert(wc16_string&, const std::string&); #if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2 - inline - std::wstring::const_iterator - Convert( std::wstring& lhs, const std::wstring& rhs ) - { - lhs = rhs; - return lhs.c_str(); - } +inline std::wstring::const_iterator Convert(std::wstring& lhs, const std::wstring& rhs) +{ + lhs = rhs; + return lhs.c_str(); +} - std::wstring::const_iterator - Convert( std::wstring&, const wc16_string& ); +std::wstring::const_iterator Convert(std::wstring&, const wc16_string&); - std::wstring::const_iterator - Convert( std::wstring&, const std::string& ); +std::wstring::const_iterator Convert(std::wstring&, const std::string&); - std::string::const_iterator - Convert( std::string&, const std::wstring& ); +std::string::const_iterator Convert(std::string&, const std::wstring&); - wc16_string::const_iterator - Convert( wc16_string&, const std::wstring& ); +wc16_string::const_iterator Convert(wc16_string&, const std::wstring&); -#endif//SUPPORTS_WCHART +#endif //SUPPORTS_WCHART - /// WARNING: These are deprecated, please use Convert()! +/// WARNING: These are deprecated, please use Convert()! - std::string TstrToStr( const TSTRING& tstr ); - // converts a tstring to a narrow string; useful for passphrase input, which must always be - // the same format, regardless of what TCHAR is defined to. +std::string TstrToStr(const TSTRING& tstr); +// converts a tstring to a narrow string; useful for passphrase input, which must always be +// the same format, regardless of what TCHAR is defined to. - TSTRING StrToTstr( const std::string& str ); - // converts a narrow string to a TSTRING +TSTRING StrToTstr(const std::string& str); +// converts a narrow string to a TSTRING - TSTRING WstrToTstr( const wc16_string& src ); - // convert wc16_string to a TSTRING - wc16_string TstrToWstr( const TSTRING& tstr ); - // convert a TSTRING to a wc16_string +TSTRING WstrToTstr(const wc16_string& src); +// convert wc16_string to a TSTRING +wc16_string TstrToWstr(const TSTRING& tstr); +// convert a TSTRING to a wc16_string - template - void splitstring(IterT& iter, - const TSTRING& str, - const TSTRING& delims) { - TSTRING::size_type where; - TSTRING tmpStr; - TSTRING workingString = str; +template void splitstring(IterT& iter, const TSTRING& str, const TSTRING& delims) +{ - while (workingString.length() > 0) { + TSTRING::size_type where; + TSTRING tmpStr; + TSTRING workingString = str; - where = workingString.find_first_of(delims, 0); + while (workingString.length() > 0) + { - // in the case of no delimeters, setp to - // grab the entire string. - // - if (where == TSTRING::npos) - where = workingString.length(); + where = workingString.find_first_of(delims, 0); - tmpStr = workingString.substr(0, where); - workingString.erase(0, where+1); + // in the case of no delimeters, setp to + // grab the entire string. + // + if (where == TSTRING::npos) + where = workingString.length(); - iter.push_back(tmpStr); + tmpStr = workingString.substr(0, where); + workingString.erase(0, where + 1); + iter.push_back(tmpStr); } - } - - - +} -}//cStringUtil:: +} // namespace cStringUtil +/* //----------------------------------------------------------------------------- // push_back_string // @@ -199,7 +186,6 @@ namespace std } }; } +*/ - -#endif//__STRINGUTIL_H - +#endif //__STRINGUTIL_H diff --git a/src/core/tasktimer.h b/src/core/tasktimer.h index c0d7f9b..60dfa50 100644 --- a/src/core/tasktimer.h +++ b/src/core/tasktimer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,7 +33,7 @@ // tasktimer.h // // cTaskTimer -- a class that can be used to time a given task -// TODO -- make this cross-platform -- maybe a template class with the time-reaping +// TODO -- make this cross-platform -- maybe a template class with the time-reaping // function as a parameter #ifndef __TASKTIMER_H #define __TASKTIMER_H @@ -46,106 +46,75 @@ #endif #include +#include + /////////////////////////////////////////////////////////////////////////////// -// cTaskTimer -- +// cTaskTimer -- /////////////////////////////////////////////////////////////////////////////// -template class cTaskTimer { -public: - cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0) {} - ~cTaskTimer(); - - void Start(); - void Stop(); - bool IsRunning() { return (mStartTime != 0); } - void Reset() { mNumStarts = mStartTime = mTotalTime = 0 } - int32 GetTotalTime() const; - int32 GetNumTimesStarted() const; // returns the number of times start() was called - const std::string& GetName() const; - -private: - TSTRING mName; - int32 mTotalTime; - TIME_TYPE mStartTime; - int32 mNumStarts; -}; -#if IS_UNIX -/////////////////////////////////////////////////////////////////////////////// -// cUnixTimeFn -- Unix version, inserts proper function call and overloads -// operator() -/////////////////////////////////////////////////////////////////////////////// -#include -class cUnixTimeFn -{ public: - typedef uint32 DataType; - - uint32 operator()() + cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0) { - return time( &dummy_var ); } -private: - time_t dummy_var; -}; - -/////////////////////////////////////////////////////////////////////////////// -// cUnixTaskTimer -- the Unix typedef... -/////////////////////////////////////////////////////////////////////////////// -typedef cTaskTimer cUnixTaskTimer; -typedef cUnixTaskTimer cGenericTaskTimer; - -#endif // IS_UNIX - -//----------------------------------------------------------------------------- -// inline implementation -//----------------------------------------------------------------------------- -template -inline void cTaskTimer::Start() -{ - ASSERT(! IsRunning()); - TIME_FN GetTime; - mStartTime = GetTime(); - mNumStarts++; -} + inline ~cTaskTimer() + { + // stop the timer if it is currently running + if (IsRunning()) + Stop(); -template -inline void cTaskTimer::Stop() -{ - ASSERT(IsRunning()); - TIME_FN GetTime; - mTotalTime += ( GetTime() - mStartTime ); - mStartTime = 0; -} + // trace out the time contents... + cDebug d("cTaskTimer"); + d.TraceDebug("----- Time to execute %s: %d (started %d times)\n", mName.c_str(), mTotalTime, mNumStarts); + } -template -inline int32 cTaskTimer::GetTotalTime() const -{ - return mTotalTime; -} + inline void Start() + { + ASSERT(!IsRunning()); + time_t dummy; + mStartTime = time(&dummy); + mNumStarts++; + } -template -inline const std::string& cTaskTimer::GetName() const -{ - return mName -} + void Stop() + { + ASSERT(IsRunning()); + time_t dummy; + mTotalTime += (time(&dummy) - mStartTime); + mStartTime = 0; + } -template -inline cTaskTimer::~cTaskTimer() -{ - // stop the timer if it is currently running - if(IsRunning()) - Stop(); + bool IsRunning() + { + return (mStartTime != 0); + } + void Reset() + { + mNumStarts = mStartTime = mTotalTime = 0; + } + uint32 GetTotalTime() const + { + return mTotalTime; + } + uint32 GetNumTimesStarted() const + { + return mNumStarts; + } + const std::string& GetName() const + { + return mName; + } - // trace out the time contents... - cDebug d("cTaskTimer"); - d.TraceDebug("----- Time to execute %s: %d (started %d times)\n", mName.c_str(), mTotalTime, mNumStarts); -} +private: + TSTRING mName; + uint32 mTotalTime; + uint32 mStartTime; + uint32 mNumStarts; +}; #endif - diff --git a/src/core/tchar.h b/src/core/tchar.h index d483883..3c35321 100644 --- a/src/core/tchar.h +++ b/src/core/tchar.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// tchar.h +// tchar.h // -// VCC version of TCHAR.H that is cross platform compatible between UNIX and +// VCC version of TCHAR.H that is cross platform compatible between UNIX and // Windows. /////////////////////////////////////////////////////////////////////////////// @@ -58,9 +58,7 @@ #define __TCHAR_H // A little macro that's useful for finding the number of characters in a TCHAR ARRAY -#define countof( x ) ( sizeof( x ) / sizeof( x[0] ) ) - -#if IS_UNIX +#define countof(x) (sizeof(x) / sizeof(x[0])) #include @@ -68,68 +66,63 @@ #include #include - - -#define TCHAR char +#define TCHAR char #define _tmain main -typedef std::string TSTRING; -typedef std::stringstream TSTRINGSTREAM; -typedef std::ostringstream TOSTRINGSTREAM; -typedef std::istringstream TISTRINGSTREAM; -typedef std::ostream TOSTREAM; -typedef std::istream TISTREAM; -typedef std::ofstream TOFSTREAM; -typedef std::ifstream TIFSTREAM; +typedef std::string TSTRING; +typedef std::stringstream TSTRINGSTREAM; +typedef std::ostringstream TOSTRINGSTREAM; +typedef std::istringstream TISTRINGSTREAM; +typedef std::ostream TOSTREAM; +typedef std::istream TISTREAM; +typedef std::ofstream TOFSTREAM; +typedef std::ifstream TIFSTREAM; // iostream abstractions -#define TCIN std::cin -#define TCOUT std::cout -#define TCERR std::cerr +# define TCIN std::cin +# define TCOUT std::cout +# define TCERR std::cerr // other functions -#define _ftprintf fprintf -#define _stprintf sprintf -#define _itot itoa -#define _ttoi atoi -#define _istdigit isdigit -#define _tcsftime strftime -#define _vtprintf vprintf -#define _vftprintf vfprintf -#define _topen open -#define _tfdopen fdopen -#define _tfopen fopen -#define _tmkdir mkdir -#define _tcscpy strcpy -#define _tgetenv getenv -#define _taccess access -#define _tcreat creat -#define _tunlink unlink -#define _tcscmp strcmp -#define _tcsicmp strcasecmp -#define _totlower tolower -#define _totupper toupper -#define _tcslen strlen -#define _tcscat strcat -#define _tcsncmp strncmp +# define _ftprintf fprintf +# define _stprintf sprintf +# define _itot itoa +# define _ttoi atoi +# define _istdigit isdigit +# define _tcsftime strftime +# define _vtprintf vprintf +# define _vftprintf vfprintf +# define _topen open +# define _tfdopen fdopen +# define _tfopen fopen +# define _tmkdir mkdir +# define _tcscpy strcpy +# define _tgetenv getenv +# define _taccess access +# define _tcreat creat +# define _tunlink unlink +# define _tcscmp strcmp +# define _tcsicmp strcasecmp +# define _totlower tolower +# define _totupper toupper +# define _tcslen strlen +# define _tcscat strcat +# define _tcsncmp strncmp // other abstractions -#define TUNLINK unlink +# define TUNLINK unlink // string representation -#if defined(_T) - // run it right over with a bulldozer, tripwire doesn't seem - // to use ctype.h's _T -PH -#undef _T -#endif -#define _T(x) x +# if defined(_T) + // run it right over with a bulldozer, tripwire doesn't seem + // to use ctype.h's _T -PH +# undef _T +# endif +# define _T(x) x // misc... -#ifndef __cdecl -#define __cdecl -#endif - -#endif // WIN32 +# ifndef __cdecl +# define __cdecl +# endif #endif // __TCHAR_H - diff --git a/src/core/timeconvert.cpp b/src/core/timeconvert.cpp index 2cece24..48c1846 100644 --- a/src/core/timeconvert.cpp +++ b/src/core/timeconvert.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,36 +52,34 @@ // METHOD CODE //========================================================================= -#define TIME_MAX 2147483647L // largest signed 32 bit number +#define TIME_MAX 2147483647L // largest signed 32 bit number -#ifdef __AROS__ - #define tzset() +#if IS_AROS +# define tzset() #endif -struct tm* cTimeUtil::TimeToDateGMT( const int64& seconds ) +struct tm* cTimeUtil::TimeToDateGMT(const int64& seconds) { - ASSERT( seconds < TIME_MAX );// this assumes time_t size is 32 bit. Yikes! + ASSERT(seconds < TIME_MAX); // this assumes time_t size is 32 bit. Yikes! time_t t = static_cast(seconds); - return gmtime( &t ); + return gmtime(&t); } -struct tm* cTimeUtil::TimeToDateLocal( const int64& seconds ) +struct tm* cTimeUtil::TimeToDateLocal(const int64& seconds) { - ASSERT( seconds < TIME_MAX );// this assumes time_t size is 32 bit. Yikes! + ASSERT(seconds < TIME_MAX); // this assumes time_t size is 32 bit. Yikes! time_t t = static_cast(seconds); tzset(); - return localtime( &t ); + return localtime(&t); } -int64 cTimeUtil::DateToTime( struct tm* ptm ) +int64 cTimeUtil::DateToTime(struct tm* ptm) { tzset(); - return mktime( ptm ); + return mktime(ptm); } int64 cTimeUtil::GetTime() -{ - return time( NULL ); +{ + return time(NULL); } - - diff --git a/src/core/timeconvert.h b/src/core/timeconvert.h index c8cb1a1..2e56f47 100644 --- a/src/core/timeconvert.h +++ b/src/core/timeconvert.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -62,15 +62,14 @@ class cTimeUtil { public: - static int64 DateToTime( struct tm* ptm ); - // simple conversion. ptm is considered to be in localtime. - static struct tm* TimeToDateGMT( const int64& seconds ); - // simple conversion - static struct tm* TimeToDateLocal( const int64& seconds ); - // conversion with timezone and daylight - static int64 GetTime(); - // returns current time in UTC + static int64 DateToTime(struct tm* ptm); + // simple conversion. ptm is considered to be in localtime. + static struct tm* TimeToDateGMT(const int64& seconds); + // simple conversion + static struct tm* TimeToDateLocal(const int64& seconds); + // conversion with timezone and daylight + static int64 GetTime(); + // returns current time in UTC }; -#endif//__TIMECONVERT_H - +#endif //__TIMECONVERT_H diff --git a/src/core/tw_signal.cpp b/src/core/tw_signal.cpp index 172d974..a2fbf6b 100644 --- a/src/core/tw_signal.cpp +++ b/src/core/tw_signal.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,11 +36,9 @@ #include #include -static void util_SignalHandler( int sig ); +static void util_SignalHandler(int sig); -#if IS_UNIX -static void tw_psignal( int sig, const TCHAR* s ); -#endif +static void tw_psignal(int sig, const TCHAR* s); tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc) { @@ -58,67 +56,64 @@ tw_sighandler_t tw_sigign(int sig) } ////////////////////////////////////////////////////////////////////// -// tw_HandleSignal -- Take a given signal and install a handler for +// tw_HandleSignal -- Take a given signal and install a handler for // it, which will then exit with the supplied exit value -tw_sighandler_t tw_HandleSignal( int sig ) +tw_sighandler_t tw_HandleSignal(int sig) { - return signal( sig, util_SignalHandler ); + return signal(sig, util_SignalHandler); } -void util_SignalHandler( int sig ) +void util_SignalHandler(int sig) { //If we're on unix, let's print out a nice error message telling //the user which signal we've recieved. -#if IS_UNIX - tw_psignal( sig, (TSS_GetString( cCore, core::STR_SIGNAL).c_str() ) ); -#endif - - exit( 8 ); + tw_psignal(sig, (TSS_GetString(cCore, core::STR_SIGNAL).c_str())); + exit(8); } -#if IS_UNIX - +/* For the morbidly curious, here's a thread where a POSIX standards committee + wrings its hands about how to define NSIG: http://austingroupbugs.net/view.php?id=741#c1834 */ #ifndef NSIG - #define NSIG 32 +# ifdef SIGMAX +# define NSIG (SIGMAX + 1) +# else +# define NSIG 32 +# endif #endif -void tw_psignal(int sig, const TCHAR *str) +void tw_psignal(int sig, const TCHAR* str) { - const TCHAR *siglist[NSIG] = { - _T("Unknown Signal"), - _T("Hangup"), - _T("Interrupt"), - _T("Quit"), - _T("Illegal Instruction"), - _T("Trace/Breakpoint Trap"), - _T("Abort"), - _T("Emulation Trap"), - _T("Arithmetic Exception"), - _T("Killed"), - _T("Bus Error"), - _T("Segmentation Fault"), - _T("Bad System Call"), - _T("Broken Pipe"), - _T("Alarm Clock"), - _T("Terminated"), - _T("User Signal 1"), - _T("User Signal 2"), - _T("Child Status Changed"), - _T("Power-Fail/Restart"), - _T("Virtual Timer Expired"), - _T("Profiling Timer Expired"), - _T("Pollable Event"), - _T("Window Size Change"), - _T("Stopped (signal)"), - _T("Stopped (user)"), - _T("Continued"), - _T("Stopped (tty input)"), - _T("Stopped (tty output)"), - _T("Urgent Socket Condition"), - _T("File Lock Lost") - }; + const TCHAR* siglist[NSIG] = {_T("Unknown Signal"), + _T("Hangup"), + _T("Interrupt"), + _T("Quit"), + _T("Illegal Instruction"), + _T("Trace/Breakpoint Trap"), + _T("Abort"), + _T("Emulation Trap"), + _T("Arithmetic Exception"), + _T("Killed"), + _T("Bus Error"), + _T("Segmentation Fault"), + _T("Bad System Call"), + _T("Broken Pipe"), + _T("Alarm Clock"), + _T("Terminated"), + _T("User Signal 1"), + _T("User Signal 2"), + _T("Child Status Changed"), + _T("Power-Fail/Restart"), + _T("Virtual Timer Expired"), + _T("Profiling Timer Expired"), + _T("Pollable Event"), + _T("Window Size Change"), + _T("Stopped (signal)"), + _T("Stopped (user)"), + _T("Continued"), + _T("Stopped (tty input)"), + _T("Stopped (tty output)"), + _T("Urgent Socket Condition"), + _T("File Lock Lost")}; _ftprintf(stderr, _T("%s %s\n"), str, sig < NSIG ? siglist[sig] : siglist[0]); } -#endif - diff --git a/src/core/tw_signal.h b/src/core/tw_signal.h index 573a256..ee4625e 100644 --- a/src/core/tw_signal.h +++ b/src/core/tw_signal.h @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// tw_signal.h -- a wrapper around signal(), needed because of linux +// tw_signal.h -- a wrapper around signal(), needed because of linux // build issues // #ifndef __TW_SIGNAL_H @@ -39,18 +39,19 @@ #include #ifdef HAVE_SIGNUM_H -#include // the signal number constants +#include // the signal number constants #endif #ifdef HAVE_BITS_SIGNUM_H #include #endif -extern "C" { -typedef void (*tw_sighandler_t)(int); +extern "C" +{ + typedef void (*tw_sighandler_t)(int); } tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc); -int tw_raise (int sig); +int tw_raise(int sig); /////////////////////////////////////////////////////////////////////////////// // tw_sigign -- wrapper around tw_signal(XXX, SIG_IGN) @@ -60,8 +61,7 @@ tw_sighandler_t tw_sigign(int sig); /////////////////////////////////////////////////////////////////////////////// // tw_HandleSignal --wrapper around signal( XXX, ) // -tw_sighandler_t tw_HandleSignal( int sig ); +tw_sighandler_t tw_HandleSignal(int sig); #endif //__TW_SIGNAL_H - diff --git a/src/core/twlimits.cpp b/src/core/twlimits.cpp index 9da1234..7de8772 100644 --- a/src/core/twlimits.cpp +++ b/src/core/twlimits.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,9 +44,9 @@ // METHOD CODE //========================================================================= -bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi ) +bool cInterpretInt::InterpretInt(const TSTRING& str, int* pi) { - ASSERT( pi != 0); + ASSERT(pi != 0); bool fFormatOK = true; @@ -55,21 +55,21 @@ bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi ) // TOSTRINGSTREAM sstr; sstr << cInterpretInt::LIMIT_MAX; - if( str.length() > sstr.str().length() ) + if (str.length() > sstr.str().length()) fFormatOK = false; // // make sure string is not too short // - if( fFormatOK && str.length() <= 0 ) + if (fFormatOK && str.length() <= 0) fFormatOK = false; // // make sure first character is a digit or the minus sign // - if( fFormatOK ) + if (fFormatOK) { - if( ! ( _T('-') == str[0] || std::isdigit( str[0], std::locale() ) ) ) + if (!(_T('-') == str[0] || std::isdigit(str[0], std::locale()))) fFormatOK = false; } @@ -77,23 +77,22 @@ bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi ) // make sure all other characters are digits // NOTE:BAM -- this assumes that all digits in all locales are SB characters. // TODO:BAM -- check this... - for( TSTRING::size_type j = 1; fFormatOK && j < str.length(); j++ ) + for (TSTRING::size_type j = 1; fFormatOK && j < str.length(); j++) { - if( ! std::isdigit( str[j], std::locale() ) ) + if (!std::isdigit(str[j], std::locale())) fFormatOK = false; } - + // // do _ttoi conversion and check that it is within allowable limits // - if( fFormatOK ) + if (fFormatOK) { - *pi = _ttoi( str.c_str() ); + *pi = _ttoi(str.c_str()); - if( *pi < GetMin() || *pi > GetMax() ) + if (*pi < GetMin() || *pi > GetMax()) fFormatOK = false; } - return fFormatOK; + return fFormatOK; } - diff --git a/src/core/twlimits.h b/src/core/twlimits.h index 5625b59..3f93b2d 100644 --- a/src/core/twlimits.h +++ b/src/core/twlimits.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,9 +33,9 @@ // twlimits.h // // this file contains classes that contain informations regarding -// "limits" that need to be shared between files. The classes should only +// "limits" that need to be shared between files. The classes should only // contain minimal functionality in support of these limits. -// +// // #ifndef __TWLIMITS_H @@ -68,15 +68,15 @@ class cInterpretInt // // basic functionality // - bool InterpretInt( const TSTRING& str, int* pi ); - // converts the string into an int value, returned in *pi. - // returns true if successfully converted value. - // *pi is undefined if function returns false. + bool InterpretInt(const TSTRING& str, int* pi); + // converts the string into an int value, returned in *pi. + // returns true if successfully converted value. + // *pi is undefined if function returns false. private: // // private enums - // + // enum Limits { LIMIT_MIN = INT_MIN, @@ -86,11 +86,19 @@ class cInterpretInt // // private functionality // - virtual int GetMax() { return LIMIT_MAX; }; - virtual int GetMin() { return LIMIT_MIN; }; + virtual int GetMax() + { + return LIMIT_MAX; + }; + virtual int GetMin() + { + return LIMIT_MIN; + }; public: - virtual ~cInterpretInt() {} + virtual ~cInterpretInt() + { + } }; /////////////////////////////////////////////// @@ -105,11 +113,19 @@ class cSeverityLimits : public cInterpretInt LIMIT_MAX = 1000000 }; - virtual int GetMax() { return LIMIT_MAX; }; - virtual int GetMin() { return LIMIT_MIN; }; + virtual int GetMax() + { + return LIMIT_MAX; + }; + virtual int GetMin() + { + return LIMIT_MIN; + }; public: - virtual ~cSeverityLimits() {} + virtual ~cSeverityLimits() + { + } }; /////////////////////////////////////////////// @@ -123,13 +139,20 @@ class cRecurseDepthLimits : public cInterpretInt LIMIT_MIN = -1, LIMIT_MAX = 1000000 }; - - virtual int GetMax() { return LIMIT_MAX; }; - virtual int GetMin() { return LIMIT_MIN; }; + + virtual int GetMax() + { + return LIMIT_MAX; + }; + virtual int GetMin() + { + return LIMIT_MIN; + }; public: - virtual ~cRecurseDepthLimits() {} + virtual ~cRecurseDepthLimits() + { + } }; #endif //__TWLIMITS_H - diff --git a/src/core/twlocale.cpp b/src/core/twlocale.cpp index ada1b25..b7d648d 100644 --- a/src/core/twlocale.cpp +++ b/src/core/twlocale.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -57,53 +57,53 @@ //========================================================================= // UTIL FUNCTION PROTOTYPES //========================================================================= -static TSTRING& util_FormatTimeC( struct tm* ptm, TSTRING& strBuf ); -static TSTRING& util_FormatTime( struct tm* ptm, TSTRING& strBuf ); +static TSTRING& util_FormatTimeC(struct tm* ptm, TSTRING& strBuf); +static TSTRING& util_FormatTime(struct tm* ptm, TSTRING& strBuf); #if !USES_CLIB_DATE_FUNCTION -static TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf ); +static TSTRING& util_FormatTimeCPlusPlus(struct tm* ptm, TSTRING& strBuf); #endif //========================================================================= // PUBLIC METHOD CODE //========================================================================= -#ifdef __AROS__ - #define tzset() +#if IS_AROS +# define tzset() #endif void cTWLocale::InitGlobalLocale() { cDebug d("cTWLocale::InitGlobalLocale"); - d.TraceDetail( "Attempting to set the program locale from the" - "default \"C\" locale to the system-default locale." ); + d.TraceDetail("Attempting to set the program locale from the" + "default \"C\" locale to the system-default locale."); #if USE_CLIB_LOCALE - char* pchLocale = setlocale( LC_ALL, "" ); - - d.TraceDetail( "C++ locale is incomplete or unavailable with this compiler, so" - "only changing the C-language locale. Some C++ locale-specific functionality" - "may not function properly." ); + char* pchLocale = setlocale(LC_ALL, ""); + + d.TraceDetail("C++ locale is incomplete or unavailable with this compiler, so" + "only changing the C-language locale. Some C++ locale-specific functionality" + "may not function properly."); - if( pchLocale ) + if (pchLocale) { - d.TraceDebug( "locale changed to the system-default locale (non-C++): <%s>\n", pchLocale ); + d.TraceDebug("locale changed to the system-default locale (non-C++): <%s>\n", pchLocale); } else { - d.TraceDebug( "Error: unable to change locale to the system-default.\n" - "It is possible that there is no other locale than\n" - "the \"C\" locale on this platform.\n" ); + d.TraceDebug("Error: unable to change locale to the system-default.\n" + "It is possible that there is no other locale than\n" + "the \"C\" locale on this platform.\n"); } #else std::locale l(""); - std::locale::global( l ); - d.TraceDebug( "locale changed to the system default std::locale (C++): <%s>\n", l.name().c_str() ); + std::locale::global(l); + d.TraceDebug("locale changed to the system default std::locale (C++): <%s>\n", l.name().c_str()); #endif - } +/* TSTRING cTWLocale::FormatNumberAsHex( int32 i ) { // @@ -125,71 +125,62 @@ TSTRING cTWLocale::FormatNumberAsHex( int32 i ) // return( sstr.str() ); } +*/ -template< class numT, class CharT > -class cFormatNumberUtil +template class cFormatNumberUtil { public: - // TODO:BAM -- these functions should really maybe take a stringstream that has been // already set up for formatting (basefield, locale, etc.) that way we can merge //. the FormatNumberAsHex function as well // //============================================================================= // template< class numT, class CharT > - // numT + // numT // cFormatNumberUtil::FormatNumber( const std::basic_string< CharT >& s, bool fCStyleFormatting = false ) //----------------------------------------------------------------------------- // EFFECTS: Does all actual formatting for FormatNumber methods - static - numT - Format( const std::basic_string< CharT >& s, bool fCStyleFormatting ) + static numT Format(const std::basic_string& s, bool fCStyleFormatting) { - static const std::num_get< CharT >* png; - std::basic_istringstream< CharT > ss( s ); - std::ios_base::iostate state; - numT n; + static const std::num_get* png; + std::basic_istringstream ss(s); + std::ios_base::iostate state; + numT n; - if( fCStyleFormatting ) - ss.imbue( std::locale::classic() ); + if (fCStyleFormatting) + ss.imbue(std::locale::classic()); - tss::GetFacet( ss.getloc(), png ).get( - ss, - std::istreambuf_iterator< CharT >(), - ss, - state, - n ); + tss::GetFacet(ss.getloc(), png).get(ss, std::istreambuf_iterator(), ss, state, n); - if( ( state & std::ios_base::failbit ) != 0 ) + if ((state & std::ios_base::failbit) != 0) throw eTWLocaleBadNumFormat(); - return( n ); + return (n); } //============================================================================= - // std::basic_string< CharT >& + // std::basic_string< CharT >& // Format( numT n, std::basic_string< CharT >& sBuf ) //----------------------------------------------------------------------------- // EFFECTS: Does all actual formatting for FormatNumber methods - // - static - std::basic_string< CharT >& - Format( numT n, std::basic_string< CharT >& sBuf, bool fCStyleFormatting = false ) + // + static std::basic_string& Format(numT n, std::basic_string& sBuf, bool fCStyleFormatting = false) { - static const std::num_put< CharT >* pnp; - std::basic_ostringstream< CharT > ss; + static const std::num_put* pnp; + std::basic_ostringstream ss; - if( fCStyleFormatting ) - ss.imbue( std::locale::classic() ); + if (fCStyleFormatting) + ss.imbue(std::locale::classic()); - tss::GetFacet( ss.getloc(), pnp ).put( ss, ss, ss.fill(), n ); + tss::GetFacet(ss.getloc(), pnp).put(ss, ss, ss.fill(), n); sBuf = ss.str(); - return( sBuf ); + return (sBuf); } }; +/* TSTRING cTWLocale::FormatNumberClassic( int32 i ) { TSTRING s; @@ -200,104 +191,104 @@ int32 cTWLocale::FormatNumberClassic( const TSTRING& s ) { return cFormatNumberUtil< long, TCHAR >::Format( s, true ); } +*/ - -TSTRING& cTWLocale::FormatNumber( uint64 ui, TSTRING& strBuf ) +TSTRING& cTWLocale::FormatNumber(uint64 ui, TSTRING& strBuf) { // try to use the int64 version - if( ui <= (uint64)TSS_INT64_MAX ) - return( FormatNumber( (int64)ui, strBuf ) ); + if (ui <= (uint64)TSS_INT64_MAX) + return (FormatNumber((int64)ui, strBuf)); else { - #if IS_MSVC - // MSVC can't convert from uint64 to a double for some reason - strBuf = TSS_GetString( cCore, core::STR_NUMBER_TOO_BIG ); - return( strBuf ); - #else - ASSERT( std::numeric_limits::max() >= TSS_UINT64_MAX ); - return( cFormatNumberUtil< double, TCHAR >::Format( (double)ui, strBuf ) ); - #endif +#if IS_MSVC + // MSVC can't convert from uint64 to a double for some reason + strBuf = TSS_GetString(cCore, core::STR_NUMBER_TOO_BIG); + return (strBuf); +#else + ASSERT(std::numeric_limits::max() >= TSS_UINT64_MAX); + return (cFormatNumberUtil::Format((double)ui, strBuf)); +#endif } } -TSTRING& cTWLocale::FormatNumber( int64 i, TSTRING& strBuf ) +TSTRING& cTWLocale::FormatNumber(int64 i, TSTRING& strBuf) { // try to use the int32 version - if( i <= (int64)TSS_INT32_MAX ) - return( FormatNumber( (int32)i, strBuf ) ); + if (i <= (int64)TSS_INT32_MAX) + return (FormatNumber((int32)i, strBuf)); else { - ASSERT( std::numeric_limits::max() >= TSS_INT64_MAX ); - return( cFormatNumberUtil< double, TCHAR >::Format( (double)i, strBuf ) ); + ASSERT(std::numeric_limits::max() >= TSS_INT64_MAX); + return (cFormatNumberUtil::Format((double)i, strBuf)); } } -TSTRING& cTWLocale::FormatNumber( uint32 ui, TSTRING& strBuf ) -{ - ASSERT( sizeof(unsigned long) >= sizeof(uint32) ); // must be able to cast to 'ulong' - return( cFormatNumberUtil< unsigned long, TCHAR >::Format( (unsigned long)ui, strBuf ) ); +TSTRING& cTWLocale::FormatNumber(uint32 ui, TSTRING& strBuf) +{ + ASSERT(sizeof(unsigned long) >= sizeof(uint32)); // must be able to cast to 'ulong' + return (cFormatNumberUtil::Format((unsigned long)ui, strBuf)); } -TSTRING& cTWLocale::FormatNumber( int32 i, TSTRING& strBuf ) -{ - ASSERT( sizeof(long) >= sizeof(int32) ); // must be able to cast to 'long' - return( cFormatNumberUtil< long, TCHAR >::Format( (long)i, strBuf ) ); +TSTRING& cTWLocale::FormatNumber(int32 i, TSTRING& strBuf) +{ + ASSERT(sizeof(long) >= sizeof(int32)); // must be able to cast to 'long' + return (cFormatNumberUtil::Format((long)i, strBuf)); } -TSTRING& cTWLocale::FormatTime( int64 t, TSTRING& strBuf ) +TSTRING& cTWLocale::FormatTime(int64 t, TSTRING& strBuf) { // clear return string strBuf.erase(); tzset(); - time_t tmpTime = t; - struct tm * ptm = localtime( &tmpTime ); - if( ptm ) + time_t tmpTime = t; + struct tm* ptm = localtime(&tmpTime); + if (ptm) { - util_FormatTime( ptm, strBuf ); + util_FormatTime(ptm, strBuf); } else { - strBuf = TSS_GetString( cCore, core::STR_UNKNOWN_TIME ); + strBuf = TSS_GetString(cCore, core::STR_UNKNOWN_TIME); } - return( strBuf ); + return (strBuf); } //========================================================================= // UTIL FUNCTION IMPLEMENTATION //========================================================================= -TSTRING& util_FormatTime( struct tm* ptm, TSTRING& strBuf ) +TSTRING& util_FormatTime(struct tm* ptm, TSTRING& strBuf) { - ASSERT( ptm ); - - #if USES_CLIB_DATE_FUNCTION + ASSERT(ptm); + +#if USES_CLIB_DATE_FUNCTION - return util_FormatTimeC( ptm, strBuf ); + return util_FormatTimeC(ptm, strBuf); - #else +#else - return util_FormatTimeCPlusPlus( ptm, strBuf ); + return util_FormatTimeCPlusPlus(ptm, strBuf); - #endif +#endif } #if !USES_CLIB_DATE_FUNCTION -TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf ) +TSTRING& util_FormatTimeCPlusPlus(struct tm* ptm, TSTRING& strBuf) { - ASSERT( ptm ); - TOSTRINGSTREAM sstr; + ASSERT(ptm); + TOSTRINGSTREAM sstr; static const std::time_put* ptp; - + // // format date // - #if IS_MSVC // MSVC uses old put() signature which didn't have the fill character, (and uses proprietary '#') - tss::GetFacet( sstr.getloc(), ptp ).put( sstr, sstr, ptm, 'c', '#' ); - #else - tss::GetFacet( sstr.getloc(), ptp ).put( sstr, sstr, sstr.fill(), ptm, 'c' ); - #endif +# if IS_MSVC // MSVC uses old put() signature which didn't have the fill character, (and uses proprietary '#') + tss::GetFacet(sstr.getloc(), ptp).put(sstr, sstr, ptm, 'c', '#'); +# else + tss::GetFacet(sstr.getloc(), ptp).put(sstr, sstr, sstr.fill(), ptm, 'c'); +# endif strBuf = sstr.str(); return strBuf; @@ -305,27 +296,27 @@ TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf ) #endif -TSTRING& util_FormatTimeC( struct tm* ptm, TSTRING& strBuf ) +TSTRING& util_FormatTimeC(struct tm* ptm, TSTRING& strBuf) { - ASSERT( ptm ); - + ASSERT(ptm); + TCHAR achTimeBuf[256]; /* XXX: This should check (#ifdef) for strftime - PH */ - size_t nbWritten = _tcsftime( achTimeBuf, countof( achTimeBuf ), - - #if IS_MSVC // MSVC uses proprietary '#' - _T("%#c"), - #else - _T("%c"), - #endif - ptm ); - - if( nbWritten ) + size_t nbWritten = _tcsftime(achTimeBuf, + countof(achTimeBuf), + +#if IS_MSVC // MSVC uses proprietary '#' + _T("%#c"), +#else + _T("%c"), +#endif + ptm); + + if (nbWritten) strBuf = achTimeBuf; else - strBuf = TSS_GetString( cCore, core::STR_UNKNOWN_TIME ); + strBuf = TSS_GetString(cCore, core::STR_UNKNOWN_TIME); return strBuf; } - diff --git a/src/core/twlocale.h b/src/core/twlocale.h index 18300a7..0929998 100644 --- a/src/core/twlocale.h +++ b/src/core/twlocale.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,8 +52,8 @@ // DECLARATION OF CLASSES //========================================================================= -TSS_EXCEPTION( eTWLocale, eError ); -TSS_EXCEPTION( eTWLocaleBadNumFormat, eError ); +TSS_EXCEPTION(eTWLocale, eError); +TSS_EXCEPTION(eTWLocaleBadNumFormat, eError); /////////////////////////////////////////////// // cTWLocale @@ -68,29 +68,30 @@ class cTWLocale { public: static void InitGlobalLocale(); - // initializes global locale to the default locale + // initializes global locale to the default locale // // basic functionality // - static TSTRING& FormatNumber( int32 i, TSTRING& strBuf ); - static TSTRING& FormatNumber( int64 i, TSTRING& strBuf ); - static TSTRING& FormatNumber( uint32 ui, TSTRING& strBuf ); - static TSTRING& FormatNumber( uint64 ui, TSTRING& strBuf ); - static TSTRING& FormatNumber( double d, TSTRING& strBuf ); - // returns the locale-specific representation of the given cardinal number - + static TSTRING& FormatNumber(int32 i, TSTRING& strBuf); + static TSTRING& FormatNumber(int64 i, TSTRING& strBuf); + static TSTRING& FormatNumber(uint32 ui, TSTRING& strBuf); + static TSTRING& FormatNumber(uint64 ui, TSTRING& strBuf); + static TSTRING& FormatNumber(double d, TSTRING& strBuf); + // returns the locale-specific representation of the given cardinal number + /* static TSTRING FormatNumberClassic( int32 i ); static int32 FormatNumberClassic( const TSTRING& s ); // returns the C-locale representation of the given cardinal number - - static TSTRING FormatNumberAsHex( int32 x ); - // locale-independant +*/ + // disabled this since nobody's using it + // static TSTRING FormatNumberAsHex( int32 x ); + // locale-independant - static TSTRING& FormatTime( int64 t, TSTRING& strBuf ); - // returns the local time and date formatted according to the current locale. - // t is the number of seconds elapsed since midnight (00:00:00), - // January 1, 1970, coordinated universal time + static TSTRING& FormatTime(int64 t, TSTRING& strBuf); + // returns the local time and date formatted according to the current locale. + // t is the number of seconds elapsed since midnight (00:00:00), + // January 1, 1970, coordinated universal time }; //========================================================================= @@ -99,22 +100,21 @@ class cTWLocale namespace tss { - //////////////////////////////////////////////// - // GetFacet - // - // Abstracts std::use_facet since Win32 and KAI - // each implement it in a non-standard way. - //////////////////////////////////////////////// - template< class FacetT > inline const FacetT& GetFacet( const std::locale& l, const FacetT* pf ) - { +//////////////////////////////////////////////// +// GetFacet +// +// Abstracts std::use_facet since Win32 and KAI +// each implement it in a non-standard way. +//////////////////////////////////////////////// +template inline const FacetT& GetFacet(const std::locale& l, const FacetT* pf) +{ #if USE_STD_CPP_LOCALE_WORKAROUND - return std::use_facet( l, pf ); + return std::use_facet(l, pf); #else - return std::use_facet< FacetT >( l ); (void)pf; // This is C++ standard + return std::use_facet(l); + (void)pf; // This is C++ standard #endif - } } +} // namespace tss #endif //__TWLOCALE_H - - diff --git a/src/core/twstringslang.h b/src/core/twstringslang.h index 9734312..daaefe1 100644 --- a/src/core/twstringslang.h +++ b/src/core/twstringslang.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,10 +36,9 @@ #ifndef __TWSTRINGSLANG_H #define __TWSTRINGSLANG_H -enum Languages +enum Languages { LANG_USENGLISH = 1 }; #endif - diff --git a/src/core/typed.h b/src/core/typed.h index dbef30f..bc42c23 100644 --- a/src/core/typed.h +++ b/src/core/typed.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,10 +45,11 @@ class cType { public: cType(const TCHAR* name); - + const TCHAR* AsString() const; - bool operator==(const cType& rhs) const; - bool operator!=(const cType& rhs) const; + bool operator==(const cType& rhs) const; + bool operator!=(const cType& rhs) const; + private: TSTRING mString; }; @@ -57,33 +58,35 @@ class iTyped { public: virtual const cType& GetType() const = 0; - // the type of an FCO; classes that implement this interface need to - // (a) declare a public static const cType member mType and - // (b) returning that object in their implementation of GetType() - // You can use the macros below to simplify the process + // the type of an FCO; classes that implement this interface need to + // (a) declare a public static const cType member mType and + // (b) returning that object in their implementation of GetType() + // You can use the macros below to simplify the process - virtual ~iTyped() {} + virtual ~iTyped() + { + } }; ////////////////////////////////////////////// // convenience macros for implementing iTyped ////////////////////////////////////////////// -#define DECLARE_TYPED()\ -public:\ -static const cType mType;\ -virtual const cType& GetType() const; - // put DECLARE_TYPED in the class definition - -#define IMPLEMENT_TYPED(CLASS, STRING)\ -const cType CLASS::mType(STRING);\ -const cType& CLASS::GetType() const\ -{\ - return mType;\ -} - // put IMPLEMENT_TYPED in the .cpp file where the class is implemented +#define DECLARE_TYPED() \ +public: \ + static const cType mType; \ + virtual const cType& GetType() const; +// put DECLARE_TYPED in the class definition + +#define IMPLEMENT_TYPED(CLASS, STRING) \ + const cType CLASS::mType(STRING); \ + const cType& CLASS::GetType() const \ + { \ + return mType; \ + } +// put IMPLEMENT_TYPED in the .cpp file where the class is implemented #define CLASS_TYPE(CLASS) CLASS::mType - // a convienent way to specify a class's type +// a convienent way to specify a class's type /////////////////////////////////////////////// // iTyped Example @@ -116,28 +119,26 @@ const cType& CLASS::GetType() const\ /////////////////////////////////////////////////////////////////////////////// // inline implementation /////////////////////////////////////////////////////////////////////////////// -inline cType::cType(const TCHAR* name) : - mString(name) +inline cType::cType(const TCHAR* name) : mString(name) { ASSERT(!mString.empty()); } -inline const TCHAR* cType::AsString() const -{ - return mString.c_str(); +inline const TCHAR* cType::AsString() const +{ + return mString.c_str(); } -inline bool cType::operator==(const cType& rhs) const -{ - return (this == &rhs); +inline bool cType::operator==(const cType& rhs) const +{ + return (this == &rhs); } -inline bool cType::operator!=(const cType& rhs) const -{ - return (this != &rhs); +inline bool cType::operator!=(const cType& rhs) const +{ + return (this != &rhs); } #endif //__TYPED_H - diff --git a/src/core/types.h b/src/core/types.h index 5744e02..4287bc2 100644 --- a/src/core/types.h +++ b/src/core/types.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,37 +36,50 @@ #include "platform.h" +#if HAVE_STDINT_H +#include +#endif + + //----------------------------------------------------------------------------- // standard TSS types //----------------------------------------------------------------------------- -typedef unsigned char byte ; // platform-independent +typedef unsigned char byte; // platform-independent -typedef signed char int8 ; -typedef short int16 ; -typedef float float32 ; -typedef double float64 ; -typedef unsigned char uint8 ; -typedef unsigned short uint16 ; +typedef signed char int8; +typedef short int16; +typedef float float32; +typedef double float64; +typedef unsigned char uint8; +typedef unsigned short uint16; + +#if HAVE_STDINT_H +typedef int32_t int32; +typedef uint32_t uint32; + +#elif SIZEOF_INT == 4 +typedef int int32; +typedef unsigned int uint32; -#if SIZEOF_INT == 4 -typedef int int32 ; -typedef unsigned int uint32 ; #elif SIZEOF_LONG == 4 -typedef long int32 ; -typedef unsigned long uint32 ; +typedef long int32; +typedef unsigned long uint32; #else -# error "I don't seem to have a 32-bit integer type on this system." +# error "I don't seem to have a 32-bit integer type on this system." #endif -#if SIZEOF_LONG == 8 -typedef long int64 ; -typedef unsigned long uint64 ; +#if HAVE_STDINT_H +typedef int64_t int64; +typedef uint64_t uint64; +#elif SIZEOF_LONG == 8 +typedef long int64; +typedef unsigned long uint64; #elif SIZEOF_LONG_LONG == 8 -typedef long long int64 ; -typedef unsigned long long uint64 ; +typedef long long int64; +typedef unsigned long long uint64; #else -# error "I don't seem to have a 64-bit integer type on this system." +# error "I don't seem to have a 64-bit integer type on this system." #endif // other Win32 definitions @@ -79,23 +92,23 @@ typedef unsigned long long uint64 ; #if (!(USES_2S_COMPLEMENT)) - #error limits.h depends on 2s complement integers. Check core/types.h +# error limits.h depends on 2s complement integers. Check core/types.h #endif #include // defines limits for built-in types -#define TSS_INT8_MIN (-127 - 1) -#define TSS_INT8_MAX 127 -#define TSS_UINT8_MAX 0xFFU -#define TSS_INT16_MIN (-32767 - 1) -#define TSS_INT16_MAX 32767 -#define TSS_UINT16_MAX 0xFFFFU -#define TSS_INT32_MIN (-2147483647 - 1) -#define TSS_INT32_MAX 2147483647 -#define TSS_UINT32_MAX 0xFFFFFFFFU -#define TSS_INT64_MIN (-9223372036854775807LL - 1) -#define TSS_INT64_MAX 9223372036854775807LL -#define TSS_UINT64_MAX 0xFFFFFFFFFFFFFFFFULL +#define TSS_INT8_MIN (-127 - 1) +#define TSS_INT8_MAX 127 +#define TSS_UINT8_MAX 0xFFU +#define TSS_INT16_MIN (-32767 - 1) +#define TSS_INT16_MAX 32767 +#define TSS_UINT16_MAX 0xFFFFU +#define TSS_INT32_MIN (-2147483647 - 1) +#define TSS_INT32_MAX 2147483647 +#define TSS_UINT32_MAX 0xFFFFFFFFU +#define TSS_INT64_MIN (-9223372036854775807LL - 1) +#define TSS_INT64_MAX 9223372036854775807LL +#define TSS_UINT64_MAX 0xFFFFFFFFFFFFFFFFULL /* //----------------------------------------------------------------------------- @@ -139,53 +152,53 @@ namespace std // Byte Swapping //----------------------------------------------------------------------------- -inline int16 SWAPBYTES16(int16 i) +inline int16 SWAPBYTES16(int16 i) { return ((uint16)i >> 8) | ((uint16)i << 8); - } -inline int32 SWAPBYTES32(int32 i) +inline int32 SWAPBYTES32(int32 i) { - return ((uint32)i >> 24) | - (((uint32)i & 0x00ff0000) >> 8) | - (((uint32)i & 0x0000ff00) << 8) | - ((uint32)i << 24); + return ((uint32)i >> 24) | (((uint32)i & 0x00ff0000) >> 8) | (((uint32)i & 0x0000ff00) << 8) | ((uint32)i << 24); } -inline int64 SWAPBYTES64(int64 i) +inline int64 SWAPBYTES64(int64 i) { - return ((uint64)i >> 56) | - (((uint64)i & 0x00ff000000000000ULL) >> 40) | - (((uint64)i & 0x0000ff0000000000ULL) >> 24) | - (((uint64)i & 0x000000ff00000000ULL) >> 8) | - (((uint64)i & 0x00000000ff000000ULL) << 8) | - (((uint64)i & 0x0000000000ff0000ULL) << 24) | - (((uint64)i & 0x000000000000ff00ULL) << 40) | - ((uint64)i << 56); + return ((uint64)i >> 56) | (((uint64)i & 0x00ff000000000000ULL) >> 40) | + (((uint64)i & 0x0000ff0000000000ULL) >> 24) | (((uint64)i & 0x000000ff00000000ULL) >> 8) | + (((uint64)i & 0x00000000ff000000ULL) << 8) | (((uint64)i & 0x0000000000ff0000ULL) << 24) | + (((uint64)i & 0x000000000000ff00ULL) << 40) | ((uint64)i << 56); } -#ifdef WORDS_BIGENDIAN +# ifdef WORDS_BIGENDIAN -#define tw_htonl(x) (x) -#define tw_ntohl(x) (x) -#define tw_htons(x) (x) -#define tw_ntohs(x) (x) -#define tw_htonll(x) (x) // int64 versions -#define tw_ntohll(x) (x) +# define tw_htonl(x) (x) +# define tw_ntohl(x) (x) +# define tw_htons(x) (x) +# define tw_ntohs(x) (x) +# define tw_htonll(x) (x) // int64 versions +# define tw_ntohll(x) (x) -#else //!WORDS_BIGENDIAN +# else //!WORDS_BIGENDIAN -#define tw_htonl(x) SWAPBYTES32((x)) -#define tw_ntohl(x) SWAPBYTES32((x)) -#define tw_htons(x) SWAPBYTES16((x)) -#define tw_ntohs(x) SWAPBYTES16((x)) -#define tw_htonll(x) SWAPBYTES64((x)) // int64 versions -#define tw_ntohll(x) SWAPBYTES64((x)) +# define tw_htonl(x) SWAPBYTES32((x)) +# define tw_ntohl(x) SWAPBYTES32((x)) +# define tw_htons(x) SWAPBYTES16((x)) +# define tw_ntohs(x) SWAPBYTES16((x)) +# define tw_htonll(x) SWAPBYTES64((x)) // int64 versions +# define tw_ntohll(x) SWAPBYTES64((x)) -#endif //WORDS_BIGENDIAN +# endif //WORDS_BIGENDIAN -#endif // __TYPES_H +//////////////////////////////////////////// +# if __cplusplus >= 201103L +# define TW_UNIQUE_PTR std::unique_ptr +# else +# define TW_UNIQUE_PTR std::auto_ptr +# endif + + +#endif // __TYPES_H diff --git a/src/core/unixexcept.cpp b/src/core/unixexcept.cpp index 5b89795..3bc9bee 100644 --- a/src/core/unixexcept.cpp +++ b/src/core/unixexcept.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,28 +38,26 @@ #include // TODO: JEB: make this look like eFileError -eUnix::eUnix( const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCallGetLastError) -: eError( _T("")) +eUnix::eUnix(const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCallGetLastError) : eError(_T("")) { -#if IS_UNIX - ASSERT( szFunctionName || szObjectName || fCallGetLastError ); + ASSERT(szFunctionName || szObjectName || fCallGetLastError); // // construct the error message: // // it will be of the form: FuncName() failed for Object: // - if( szFunctionName ) + if (szFunctionName) { mMsg = szFunctionName; mMsg += _T(" failed"); - if( szObjectName ) + if (szObjectName) { mMsg += _T(" for "); mMsg += szObjectName; } } - else if( szObjectName ) + else if (szObjectName) { mMsg = szObjectName; } @@ -68,17 +66,16 @@ eUnix::eUnix( const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCall mMsg = _T("Error"); } - if( fCallGetLastError ) + if (fCallGetLastError) { TSTRING strErr = strerror(errno); - if( ! strErr.empty() ) + if (!strErr.empty()) { mMsg += _T(": "); mMsg += strErr; } } -#endif // IS_UNIX } // eof - unixexcept.cpp diff --git a/src/core/unixexcept.h b/src/core/unixexcept.h index d9f9f50..7d748e8 100644 --- a/src/core/unixexcept.h +++ b/src/core/unixexcept.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,18 +41,16 @@ #include "error.h" #endif -TSS_BEGIN_EXCEPTION( eUnix, eError ) +TSS_BEGIN_EXCEPTION(eUnix, eError) - eUnix( const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true ); - // construct one of these to indicate a unix api failure. both functionName and - // objectName can be NULL. This method will construct a string to pass to eError - // that contains all of the above information plus whatever errno returns if the dusplayErrorNumber - // parameter is true. - +eUnix(const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true); +// construct one of these to indicate a unix api failure. both functionName and +// objectName can be NULL. This method will construct a string to pass to eError +// that contains all of the above information plus whatever errno returns if the dusplayErrorNumber +// parameter is true. -TSS_END_EXCEPTION() +TSS_END_EXCEPTION() #endif //__unixexcept_H - diff --git a/src/core/unixfsservices.cpp b/src/core/unixfsservices.cpp index dc2d72e..481bf1b 100644 --- a/src/core/unixfsservices.cpp +++ b/src/core/unixfsservices.cpp @@ -1,35 +1,35 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // -////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////// // unixfsservices.cpp // // Implements cUnixFSServices class in unixfsservices.h @@ -40,7 +40,7 @@ #include "core/file.h" #if !IS_UNIX //encase this all in an ifdef so it won't cause compile errors -#error Must be unix for unixfsservices +# error Must be unix for unixfsservices #endif //========================================================================= @@ -56,25 +56,37 @@ #include #include #ifdef HAVE_SYS_PARAM_H -# include +#include #endif #ifdef HAVE_SYS_MOUNT_H -# include +#include #endif #ifdef HAVE_SYS_USTAT_H -# include +#include #endif #ifdef HAVE_WCHAR_H -# include +#include #endif #ifdef HAVE_SYS_SYSMACROS_H -# include +#include #endif + +#if HAVE_SYS_UTSNAME_H #include +#endif + #include + +#if IS_REDOX +# define restrict __restrict__ +#endif + +#if HAVE_SYS_SOCKET_H #include #include #include +#endif + #include #include #include @@ -86,22 +98,21 @@ #include "unixfsservices.h" // commented out definition of _TWNBITSMAJOR because we should use the -// makedev macro in sys/sysmacros.h for portability. +// makedev macro in sys/sysmacros.h for portability. // except linux has the body of sysmacros.h commented out. why? // -jeb 7/26/99 // reduced to sys/statfs.h. Linux is OK and doesn't deserve // special treatment. 20010317-PH #ifdef HAVE_SYS_STATFS_H -# include +#include #endif //HAVE_SYS_STATFS_H - //========================================================================= // DEFINES AND MACROS //========================================================================= -#define TW_SLASH _T('/') +#define TW_SLASH _T('/') //========================================================================= // OTHER DIRECTIVES @@ -117,24 +128,26 @@ using namespace std; // UTIL FUNCTION PROTOTYES //========================================================================= -static bool util_FileIsExecutable( const TSTRING& ); -static bool util_PathFind( TSTRING& strFullPath, const TSTRING& strFilename ); -static void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem ); -static bool util_GetNextPathElement( const TSTRING& strPathC, TSTRING& strElem, int index ); -static void util_RemoveDuplicateSeps( TSTRING& strPath ); -static bool util_TrailingSep( TSTRING& str, bool fLeaveSep ); -static void util_RemoveTrailingSeps( TSTRING& str ); -template< typename T > static inline void util_ZeroMemory( T& obj ); +static bool util_FileIsExecutable(const TSTRING&); +static bool util_PathFind(TSTRING& strFullPath, const TSTRING& strFilename); +static void util_RemoveLastPathElement(TSTRING& strPath, TSTRING& strElem); +static bool util_GetNextPathElement(const TSTRING& strPathC, TSTRING& strElem, int index); +static void util_RemoveDuplicateSeps(TSTRING& strPath); +static bool util_TrailingSep(TSTRING& str, bool fLeaveSep); +static void util_RemoveTrailingSeps(TSTRING& str); +template static inline void util_ZeroMemory(T& obj); //========================================================================= // PUBLIC METHOD CODE //========================================================================= -cUnixFSServices::cUnixFSServices() -{} +cUnixFSServices::cUnixFSServices() : mResolveNames(true) +{ +} cUnixFSServices::~cUnixFSServices() -{} +{ +} //========================================================================= // *** VIRTUAL FUNCTION CODE *** @@ -146,14 +159,8 @@ cUnixFSServices::~cUnixFSServices() TSTRING cUnixFSServices::GetErrString() const { TSTRING ret; - char* pErrorStr = strerror(errno); -#ifdef _UNICODE - wchar_t pBuf[1024]; - mbstowcs(pBuf, pErrorStr, 1024); - ret = pBuf; -#else - ret = pErrorStr; -#endif + char* pErrorStr = strerror(errno); + ret = pErrorStr; return ret; } @@ -161,7 +168,7 @@ TSTRING cUnixFSServices::GetErrString() const /////////////////////////////////////////////////////////////////////////////// // GetHostID /////////////////////////////////////////////////////////////////////////////// -void cUnixFSServices::GetHostID( TSTRING& name ) const +void cUnixFSServices::GetHostID(TSTRING& name) const { TOSTRINGSTREAM ret; @@ -171,63 +178,70 @@ void cUnixFSServices::GetHostID( TSTRING& name ) const #else ret << 999999; #endif - } // returns "/" for unix and "\\" for win32 -TCHAR cUnixFSServices::GetPathSeparator() const +TCHAR cUnixFSServices::GetPathSeparator() const { return '/'; } -#ifndef __AROS__ -void cUnixFSServices::ReadDir(const TSTRING& strFilename, std::vector &v, bool bFullPaths) const throw(eFSServices) +#if !USES_DEVICE_PATH +void cUnixFSServices::ReadDir(const TSTRING& strFilename, std::vector& v, bool bFullPaths) const { #else -void cUnixFSServices::ReadDir(const TSTRING& strFilenameC, std::vector& v, bool bFullPaths) const throw(eFSServices) +void cUnixFSServices::ReadDir(const TSTRING& strFilenameC, std::vector& v, bool bFullPaths) const { - TSTRING strFilename = cArosPath::AsNative(strFilenameC); + TSTRING strFilename = cDevicePath::AsNative(strFilenameC); #endif //Get all the filenames - DIR* dp; - dp = opendir( strFilename.c_str() ); + DIR* dp = 0; - if (dp == NULL) +#if defined(O_DIRECTORY) && defined(O_NOATIME) + //dfd will be autoclosed by closedir(), should not be explicitly closed. + int dfd = open(strFilename.c_str(), O_RDONLY | O_DIRECTORY | O_NOATIME); + if (dfd > 0) + dp = fdopendir(dfd); +#else + dp = opendir(strFilename.c_str()); +#endif + + if (dp == NULL) { - throw eFSServicesGeneric( strFilename, iFSServices::GetInstance()->GetErrString() ); + throw eFSServicesGeneric(strFilename, iFSServices::GetInstance()->GetErrString()); return; } - + struct dirent* d; while ((d = readdir(dp)) != NULL) { if ((strcmp(d->d_name, _T(".")) != 0) && (strcmp(d->d_name, _T("..")) != 0)) { - if( bFullPaths ) + if (bFullPaths) { //Create the full pathname TSTRING strNewName = strFilename; // get full path of dir entry - util_TrailingSep( strNewName, true ); + util_TrailingSep(strNewName, true); strNewName += d->d_name; - + // save full path name - v.push_back( strNewName ); + v.push_back(strNewName); } else - v.push_back( d->d_name ); + v.push_back(d->d_name); } } //Close the directory - closedir( dp ); + closedir(dp); } /* needs to and with S_IFMT, check EQUALITY with S_*, and return more types -cFSStatArgs::FileType cUnixFSServices::GetFileType(const cFCOName &filename) throw(eFSServices) +cFSStatArgs::FileType cUnixFSServices::GetFileType(const cFCOName &filename) { cFSStatArgs stat; Stat(filename, stat); @@ -235,273 +249,276 @@ cFSStatArgs::FileType cUnixFSServices::GetFileType(const cFCOName &filename) thr } */ -void cUnixFSServices::GetCurrentDir( TSTRING& strCurDir ) const throw(eFSServices) +void cUnixFSServices::GetCurrentDir(TSTRING& strCurDir) const { TCHAR pathname[iFSServices::TW_MAX_PATH]; pathname[0] = '\0'; - TCHAR* ret = getcwd(pathname, sizeof(TCHAR)*iFSServices::TW_MAX_PATH); + TCHAR* ret = getcwd(pathname, sizeof(TCHAR) * iFSServices::TW_MAX_PATH); if (ret == NULL) - throw eFSServicesGeneric( strCurDir, iFSServices::GetInstance()->GetErrString() ); + throw eFSServicesGeneric(strCurDir, iFSServices::GetInstance()->GetErrString()); strCurDir = pathname; } -void cUnixFSServices::ChangeDir( const TSTRING& strDir ) const throw(eFSServices) -{ - if( chdir( strDir.c_str() ) < 0 ) - throw eFSServicesGeneric( strDir, iFSServices::GetInstance()->GetErrString() ); -} - -TSTRING& cUnixFSServices::MakeTempFilename( TSTRING& strName ) const throw(eFSServices) +TSTRING& cUnixFSServices::MakeTempFilename(TSTRING& strName) const { char* pchTempFileName; - char szTemplate[iFSServices::TW_MAX_PATH]; - int fd; + char szTemplate[iFSServices::TW_MAX_PATH]; + int fd; -#ifdef _UNICODE - // convert template from wide character to multi-byte string - char mbBuf[iFSServices::TW_MAX_PATH]; - wcstombs( mbBuf, strName.c_str(), strName.length() + 1 ); - strcpy( szTemplate, mbBuf ); -#else - strcpy( szTemplate, strName.c_str() ); -#endif + strncpy(szTemplate, strName.c_str(), iFSServices::TW_MAX_PATH); #ifdef HAVE_MKSTEMP - // create temp filename and check to see if mkstemp failed - if ((fd = mkstemp( szTemplate )) == -1) { - throw eFSServicesGeneric( strName ); - } else { - close(fd); - } + // create temp filename and check to see if mkstemp failed + if ((fd = mkstemp(szTemplate)) == -1) + { + throw eFSServicesGeneric(strName); + } + else + { + close(fd); + } pchTempFileName = szTemplate; #else fd = 0; // create temp filename - pchTempFileName = mktemp( szTemplate ); + pchTempFileName = mktemp(szTemplate); //check to see if mktemp failed - if ( pchTempFileName == NULL || strlen(pchTempFileName) == 0) { - throw eFSServicesGeneric( strName ); + if (pchTempFileName == NULL || strlen(pchTempFileName) == 0) + { + throw eFSServicesGeneric(strName); } #endif // change name so that it has the XXXXXX part filled in -#ifdef _UNICODE - // convert name from multi-byte to wide character string - wchar_t wcsbuf[1024]; - mbstowcs( wcsbuf, pchTempFileName, strlen( pchTempFileName ) + 1 )); - strName = wcsbuf; -#else strName = pchTempFileName; -#endif - // Linux creates the file!! Doh! // So I'll always attempt to delete it -bam - FileDelete( strName ); + FileDelete(strName.c_str()); - return( strName ); + return (strName); } -void cUnixFSServices::Mkdir( const TSTRING& strName ) const throw ( eFSServices ) -{ - if( 0 != _tmkdir( strName.c_str(), 0777 ) ) - { - // if mkdir failed because the dir existed, that's OK - if( errno != EEXIST ) - throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() ); - } -} - -bool cUnixFSServices::Rmdir( const TSTRING& strName ) const +void cUnixFSServices::GetTempDirName(TSTRING& strName) const { - if( 0 == rmdir( strName.c_str() ) ) - return true; - - return false; + strName = mTempPath; } -void cUnixFSServices::GetTempDirName( TSTRING& strName ) const throw(eFSServices) +void cUnixFSServices::SetTempDirName(TSTRING& tmpPath) { - strName = mTempPath; -} - -void cUnixFSServices::SetTempDirName(TSTRING& tmpPath) { - mTempPath = tmpPath; + mTempPath = tmpPath; } -#ifndef __AROS__ -void cUnixFSServices::Stat( const TSTRING& strName, cFSStatArgs &stat ) const throw(eFSServices) +#if !USES_DEVICE_PATH +void cUnixFSServices::Stat(const TSTRING& strName, cFSStatArgs& stat) const { #else -void cUnixFSServices::Stat( const TSTRING& strNameC, cFSStatArgs& stat) const throw(eFSServices) +void cUnixFSServices::Stat(const TSTRING& strNameC, cFSStatArgs& stat) const { - TSTRING strName = cArosPath::AsNative(strNameC); + TSTRING strName = cDevicePath::AsNative(strNameC); #endif //local variable for obtaining info on file. struct stat statbuf; int ret; - ret = lstat( strName.c_str(), &statbuf ); + ret = lstat(strName.c_str(), &statbuf); - cDebug d( "cUnixFSServices::Stat" ); - d.TraceDetail( "Executing on file %s (result=%d)\n", strName.c_str(), ret ); + cDebug d("cUnixFSServices::Stat"); + d.TraceDetail("Executing on file %s (result=%d)\n", strName.c_str(), ret); - if( ret < 0 ) - throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() ); + if (ret < 0) + throw eFSServicesGeneric(strName, iFSServices::GetInstance()->GetErrString()); +#if HAVE_STRUCT_STAT_ST_RDEV // new stuff 7/17/99 - BAM // if the file is not a device set rdev to zero by hand (most OSs will // do this for us, but some don't) - if( ! S_ISBLK( statbuf.st_mode ) && ! S_ISCHR( statbuf.st_mode ) ) + if (!S_ISBLK(statbuf.st_mode) && !S_ISCHR(statbuf.st_mode)) { - // must zero memory instead of '= 0' since we don't know the + // must zero memory instead of '= 0' since we don't know the // actual type of the object -- could be a struct (requiring '= {0}' ) - util_ZeroMemory( statbuf.st_rdev ); + util_ZeroMemory(statbuf.st_rdev); } +#endif //copy information returned by lstat call into the structure passed in - stat.gid = statbuf.st_gid; - stat.atime = statbuf.st_atime; - stat.ctime = statbuf.st_ctime; - stat.mtime = statbuf.st_mtime; - stat.dev = statbuf.st_dev; - stat.rdev = statbuf.st_rdev; - stat.ino = statbuf.st_ino; - stat.mode = statbuf.st_mode; - stat.nlink = statbuf.st_nlink; - stat.size = statbuf.st_size; - stat.uid = statbuf.st_uid; - stat.blksize = statbuf.st_blksize; - stat.blocks = statbuf.st_blocks; + stat.gid = statbuf.st_gid; + stat.atime = statbuf.st_atime; + stat.ctime = statbuf.st_ctime; + stat.mtime = statbuf.st_mtime; + stat.dev = statbuf.st_dev; + +#if HAVE_STRUCT_STAT_ST_RDEV + stat.rdev = statbuf.st_rdev; +#else + stat.rdev = 0; +#endif + + stat.ino = statbuf.st_ino; + stat.mode = statbuf.st_mode; + stat.nlink = statbuf.st_nlink; + stat.size = statbuf.st_size; + stat.uid = statbuf.st_uid; + stat.blksize = statbuf.st_blksize; + +#if HAVE_STRUCT_STAT_ST_BLOCKS + stat.blocks = statbuf.st_blocks; +#else + stat.blocks = 0; +#endif // set the file type - if(S_ISREG(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FILE; - else if(S_ISDIR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DIR; - else if(S_ISLNK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SYMLINK; - else if(S_ISBLK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_BLOCKDEV; - else if(S_ISCHR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_CHARDEV; - else if(S_ISFIFO(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FIFO; - else if(S_ISSOCK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SOCK; -#ifdef S_IFDOOR - else if(S_ISDOOR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DOOR; + if (S_ISREG(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_FILE; + else if (S_ISDIR(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_DIR; + else if (S_ISLNK(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_SYMLINK; + else if (S_ISBLK(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_BLOCKDEV; + else if (S_ISCHR(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_CHARDEV; + else if (S_ISFIFO(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_FIFO; +#ifdef S_ISSOCK + else if (S_ISSOCK(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_SOCK; #endif -#ifdef S_IFPORT - else if(S_ISPORT(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_PORT; + +#if HAVE_DOOR_CREATE + else if (S_ISDOOR(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_DOOR; #endif - - else stat.mFileType = cFSStatArgs::TY_INVALID; + +#if HAVE_PORT_CREATE + else if (S_ISPORT(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_PORT; +#endif + +#ifdef S_ISNAM + else if (S_ISNAM(statbuf.st_mode)) + stat.mFileType = cFSStatArgs::TY_NAMED; +#endif + + else + stat.mFileType = cFSStatArgs::TY_INVALID; } -void cUnixFSServices::GetMachineName( TSTRING& strName ) const throw( eFSServices ) +void cUnixFSServices::GetMachineName(TSTRING& strName) const { +#if HAVE_SYS_UTSNAME_H struct utsname namebuf; - if( uname( &namebuf ) == -1 ) - throw eFSServicesGeneric( strName ); + if (uname(&namebuf) == -1) + throw eFSServicesGeneric(strName); else strName = namebuf.nodename; +#else + strName = "localhost"; +#endif } -void cUnixFSServices::GetMachineNameFullyQualified( TSTRING& strName ) const +void cUnixFSServices::GetMachineNameFullyQualified(TSTRING& strName) const { +#if HAVE_SYS_UTSNAME_H char buf[256]; if (gethostname(buf, 256) != 0) { -#if defined(SOLARIS_NO_GETHOSTBYNAME) || defined(_SORTIX_SOURCE) +# if defined(SOLARIS_NO_GETHOSTBYNAME) || !SUPPORTS_NETWORKING strName = buf; return; -#else +# else struct hostent* ret; ret = gethostbyname(buf); - + if (ret != NULL) { strName = ret->h_name; return; } -#endif +# endif } - - try +#endif + try { cUnixFSServices::GetMachineName(strName); } - catch(eFSServices&) + catch (eFSServices&) { strName = TSS_GetString(cCore, core::STR_UNKNOWN); } } -bool cUnixFSServices::FileDelete( const TSTRING& strName ) const +bool cUnixFSServices::FileDelete(const TSTRING& strName) const { - return( 0 == remove( strName.c_str() ) ); + return (0 == remove(strName.c_str())); } -bool cUnixFSServices::GetCurrentUserName( TSTRING& strName ) const +bool cUnixFSServices::GetCurrentUserName(TSTRING& strName) const { bool fSuccess = false; - uid_t uid = getuid(); - struct passwd* pp = getpwuid( uid ); + uid_t uid = getuid(); + struct passwd* pp = getpwuid(uid); - if( pp ) + if (pp) { - strName = pp->pw_name; + strName = pp->pw_name; fSuccess = true; } else strName = _T(""); - return( fSuccess ); + return (fSuccess); } // returns IP address in network byte order -bool cUnixFSServices::GetIPAddress( uint32& uiIPAddress ) +bool cUnixFSServices::GetIPAddress(uint32& uiIPAddress) { - bool fGotAddress = false; - cDebug d( _T("cUnixFSServices::GetIPAddress") ); + bool fGotAddress = false; + cDebug d(_T("cUnixFSServices::GetIPAddress")); -#ifndef _SORTIX_SOURCE - struct utsname utsnameBuf; - if( EFAULT != uname( &utsnameBuf) ) +#if SUPPORTS_NETWORKING && HAVE_SYS_UTSNAME_H + struct utsname utsnameBuf; + if (EFAULT != uname(&utsnameBuf)) { - d.TraceDetail( "uname returned nodename: %s\n", utsnameBuf.nodename ); + d.TraceDetail("uname returned nodename: %s\n", utsnameBuf.nodename); - struct hostent* phostent = gethostbyname( utsnameBuf.nodename ); + struct hostent* phostent = gethostbyname(utsnameBuf.nodename); - if( phostent ) + if (phostent) { - ASSERT( AF_INET == phostent->h_addrtype ); - ASSERT( sizeof(int32) == phostent->h_length ); + ASSERT(AF_INET == phostent->h_addrtype); + ASSERT(sizeof(int32) == phostent->h_length); - if( phostent->h_length ) + if (phostent->h_length) { - if( phostent->h_addr_list[0] ) + if (phostent->h_addr_list[0]) { - int32* pAddress = reinterpret_cast( phostent->h_addr_list[0] ); - uiIPAddress = *pAddress; - fGotAddress = true; + int32* pAddress = reinterpret_cast(phostent->h_addr_list[0]); + uiIPAddress = *pAddress; + fGotAddress = true; } else - d.TraceError( _T("phostent->h_addr_list[0] was zero") ); + d.TraceError(_T("phostent->h_addr_list[0] was zero")); } else - d.TraceError( _T("phostent->h_length was zero") ); + d.TraceError(_T("phostent->h_length was zero")); } else - d.TraceError( _T("gethostbyname failed") ); + d.TraceError(_T("gethostbyname failed")); } else - d.TraceError( _T("uname failed") ); + d.TraceError(_T("uname failed")); #endif - return( fGotAddress ); + return (fGotAddress); } bool cUnixFSServices::IsCaseSensitive() const @@ -510,114 +527,128 @@ bool cUnixFSServices::IsCaseSensitive() const } -bool cUnixFSServices::GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tstrUser ) const +void cUnixFSServices::SetResolveNames(bool resolve) { - bool fSuccess = true; - struct stat statbuf; + mResolveNames = resolve; +} - int ret = lstat(tstrFilename.c_str(), &statbuf); - if(ret < 0) - { - fSuccess = false; - } - if( fSuccess ) +bool cUnixFSServices::GetUserName(uid_t user_id, TSTRING& tstrUser) const +{ + bool fSuccess = true; + + if (mResolveNames) { - struct passwd* pp = getpwuid( statbuf.st_uid ); - //ASSERT( pp ); - // We shouldn't assert this, because it might be the case that a file - // is associated with some old user that no longer exists... we should - // not fail this case. Instead, the method will just return false per - // the test below. - if( pp == NULL ) + struct passwd* pp = getpwuid(user_id); + if (pp == NULL) { fSuccess = false; + tstrUser = TSS_GetString(cCore, core::STR_UNKNOWN); } else tstrUser = pp->pw_name; } + else + { + std::stringstream sstr; + sstr << user_id; + tstrUser = sstr.str(); + } - return( fSuccess ); - + return (fSuccess); } -bool cUnixFSServices::GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tstrGroup ) const -{ +bool cUnixFSServices::GetGroupName(gid_t group_id, TSTRING& tstrGroup) const +{ bool fSuccess = true; - struct stat statbuf; - int ret = lstat(tstrFilename.c_str(), &statbuf); - if(ret < 0) +#if !IS_REDOX + if (mResolveNames) { - fSuccess = false; - } - - if( fSuccess ) - { - struct group* pg = getgrgid( statbuf.st_gid ); - //ASSERT( pg ); this assert stops everything in debug mode if we can't lookup a groupid - - if( pg == NULL ) + struct group* pg = getgrgid(group_id); + if (pg == NULL) { - fSuccess = false; + fSuccess = false; tstrGroup = TSS_GetString(cCore, core::STR_UNKNOWN); } else tstrGroup = pg->gr_name; - } + } + else + { +#endif + std::stringstream sstr; + sstr << group_id; + tstrGroup = sstr.str(); +#if !IS_REDOX + } +#endif - return( fSuccess ); + return (fSuccess); } + +#ifndef S_ISVTX // DOS/DJGPP doesn't have this +# define S_ISVTX 0 +#endif + //////////////////////////////////////////////////////////////////////// // Function name : cUnixFSServices::ConvertModeToString // Description : takes a TSTRING and fills it with an "ls -l" representation -// of the object's permission bits ( e.g. "drwxr-x--x" ). +// of the object's permission bits ( e.g. "drwxr-x--x" ). // // Returns : void -- no errors are reported // // Argument : uint64 perm -- st_mode from "stat" // Argument : TSTRING& tstrPerm -- converted permissions, ls -l style // -void cUnixFSServices::ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const -{ - TCHAR szPerm[11]; //10 permission bits plus the NULL - _tcscpy( szPerm, _T("----------") ); +void cUnixFSServices::ConvertModeToString(uint64 perm, TSTRING& tstrPerm) const +{ + TCHAR szPerm[12]; //10 permission bits plus the NULL + strncpy(szPerm, _T("----------"), 11); - ASSERT( sizeof(unsigned short) <= sizeof(uint32) ); + ASSERT(sizeof(unsigned short) <= sizeof(uint32)); // We do this in case an "unsigned short" is ever larger than the // value we are switching on, since the size of the mode parameter // will be unsigned short (whatever that means, for the given platform...) // check file type - switch ((uint32)perm & S_IFMT) //some versions of Unix don't like to switch on - //64 bit values. + switch ((uint32)perm & S_IFMT) //some versions of Unix don't like to switch on + //64 bit values. { - case S_IFDIR: - szPerm[0] = _T('d'); - break; - case S_IFCHR: - szPerm[0] = _T('c'); - break; - case S_IFBLK: - szPerm[0] = _T('b'); - break; - case S_IFIFO: - szPerm[0] = _T('p'); - break; - case S_IFLNK: - szPerm[0] = _T('l'); - break; -#ifdef S_IFDOOR - case S_IFDOOR: - szPerm[0] = _T('D'); - break; + case S_IFDIR: + szPerm[0] = _T('d'); + break; + case S_IFCHR: + szPerm[0] = _T('c'); + break; + case S_IFBLK: + szPerm[0] = _T('b'); + break; + case S_IFIFO: + szPerm[0] = _T('p'); + break; + case S_IFLNK: + szPerm[0] = _T('l'); + break; + +#if HAVE_DOOR_CREATE // Solaris doors + case S_IFDOOR: + szPerm[0] = _T('D'); + break; #endif -#ifdef S_IFPORT - case S_IFPORT: - szPerm[0] = _T('P'); - break; + +#if HAVE_PORT_CREATE // Solaris event ports + case S_IFPORT: + szPerm[0] = _T('P'); + break; +#endif + +#ifdef S_IFNAM + case S_IFNAM: + szPerm[0] = _T('n'); + break; #endif break; } @@ -677,15 +708,15 @@ void cUnixFSServices::ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) cons bool cUnixFSServices::Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool overwrite) const { #ifdef _UNICODE -#error UNICODE Rename not implemented +# error UNICODE Rename not implemented #endif // delete new file if overwriting - if ( overwrite ) - if ( access( strNewName.c_str(), F_OK ) == 0 && remove( strNewName.c_str() ) != 0 ) + if (overwrite) + if (access(strNewName.c_str(), F_OK) == 0 && remove(strNewName.c_str()) != 0) return false; - - if ( rename( strOldName.c_str(), strNewName.c_str() ) == 0 ) + + if (rename(strOldName.c_str(), strNewName.c_str()) == 0) return true; // Note: errno will be set @@ -693,45 +724,45 @@ bool cUnixFSServices::Rename(const TSTRING& strOldName, const TSTRING& strNewNam } -bool cUnixFSServices::GetExecutableFilename( TSTRING& strFullPath, const TSTRING& strFilename ) const +bool cUnixFSServices::GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const { bool fGotName = false; - if( strFilename.empty() ) + if (strFilename.empty()) return false; // if there is a slash in the filename, it's absolute or relative to cwd - if( TSTRING::npos != strFilename.find( _T('/') ) ) + if (TSTRING::npos != strFilename.find(_T('/'))) { // if absolute path - if( strFilename[0] == _T('/') ) + if (strFilename[0] == _T('/')) { strFullPath = strFilename; - fGotName = true; + fGotName = true; } else // is relative path; find path from cwd { - fGotName = FullPath( strFullPath, strFilename ); + fGotName = FullPath(strFullPath, strFilename); } } else // it's just a filename: should be found in path { - fGotName = util_PathFind( strFullPath, strFilename ); + fGotName = util_PathFind(strFullPath, strFilename); TSTRING strFP; - if( fGotName && FullPath( strFP, strFullPath ) ) + if (fGotName && FullPath(strFP, strFullPath)) strFullPath = strFP; } - return( fGotName ); + return (fGotName); } /////////////////////////////////////////////////////////////////////////////// // Function name : cUnixFSServices::FullPath -// Description : +// Description : // -// Return type : bool +// Return type : bool // Argument : TSTRING& strFullPath // Argument : const TSTRING& strRelPathC // Argument : const TSTRING& pathRelFromC @@ -739,14 +770,20 @@ bool cUnixFSServices::GetExecutableFilename( TSTRING& strFullPath, const TSTRING // TODO -- is throwing an exception the more appropriate alternative to returning // a bool? I think it is ... mdb /////////////////////////////////////////////////////////////////////////////// -bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC, const TSTRING& pathRelFromC ) const -{ +bool cUnixFSServices::FullPath(TSTRING& strFullPath, const TSTRING& strRelPathC, const TSTRING& pathRelFromC) const +{ + cDebug d("cUnixFSServices::FullPath"); + d.TraceDebug("strRelPathC = %s, pathRelFromC = %s\n", strRelPathC.c_str(), pathRelFromC.c_str()); + // don't do anything with an empty path - if( strRelPathC.empty() ) + if (strRelPathC.empty()) return false; +#if USES_DEVICE_PATH + TSTRING strRelPath = cDevicePath::AsPosix(strRelPathC); // make non-const temp var +#else TSTRING strRelPath = strRelPathC; // make non-const temp var - +#endif // // get base name (where strRelPath will be relative to), which will either be; // 1. the root directory if strRelPath is an absolute path @@ -754,11 +791,12 @@ bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC // 3. otherwise ( not abs path AND no rel path ) the current working directory // - if( strRelPath[0] == TW_SLASH ) // if is absolute path + if (strRelPath[0] == TW_SLASH) // if is absolute path { - if( IsRoot( strRelPath ) ) // if it's root, don't monkey with it, just return it. + if (IsRoot(strRelPath)) // if it's root, don't monkey with it, just return it. { strFullPath = strRelPath; + d.TraceDebug("Is root; returning %s\n", strFullPath.c_str()); return true; } else @@ -769,60 +807,80 @@ bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC } else // is a relative path, so check pathRelFromC { - if( pathRelFromC.empty() ) // if we're relative to CWD... + if (pathRelFromC.empty()) // if we're relative to CWD... { // // get the current working directory // try { - GetCurrentDir( strFullPath ); - util_TrailingSep( strFullPath, false ); + GetCurrentDir(strFullPath); +#if USES_DEVICE_PATH + strFullPath = cDevicePath::AsPosix(strFullPath); +#endif + util_TrailingSep(strFullPath, false); } - catch( eFSServices& ) + catch (eFSServices&) { return false; } + + d.TraceDebug("Creating prefix relative to CWD: %s\n", strFullPath.c_str()); } else // we're relative to a given dir { + +#if USES_DEVICE_PATH + strFullPath = cDevicePath::AsPosix(pathRelFromC); +#else strFullPath = pathRelFromC; - util_RemoveDuplicateSeps( strFullPath ); - util_TrailingSep( strFullPath, false ); +#endif + util_RemoveDuplicateSeps(strFullPath); + util_TrailingSep(strFullPath, false); + + d.TraceDebug("Creating prefix from supplied path: %s\n", strFullPath.c_str()); } } // - // start adding path elements from strRelPath to the base name + // start adding path elements from strRelPath to the base name // ( which already has an absolute starting point. see above. ) // TSTRING strElem; - int index = 0; - while( util_GetNextPathElement( strRelPath, strElem, index++ ) ) + int index = 0; + while (util_GetNextPathElement(strRelPath, strElem, index++)) { - if( 0 == strElem.compare( _T(".") ) ) + d.TraceDebug("Path element = %s\n", strElem.c_str()); + if (0 == strElem.compare(_T("."))) { // ignore it } - else if( 0 == strElem.compare( _T("..") ) ) + else if (0 == strElem.compare(_T(".."))) { // go up a dir ( the function takes care of root dir case ) TSTRING strDummy; - util_RemoveLastPathElement( strFullPath, strDummy ); + util_RemoveLastPathElement(strFullPath, strDummy); } else // just a regular old path element { strFullPath += TW_SLASH; strFullPath += strElem; } + + d.TraceDebug("FullPath is now %s\n", strFullPath.c_str()); } +#if IS_AROS || IS_REDOX + strFullPath = cDevicePath::AsNative(strFullPath); +#endif + + d.TraceDebug("Done, returning %s\n", strFullPath.c_str()); return true; } /////////////////////////////////////////////////////////////////////////////// -// GetStandardBackupExtension() +// GetStandardBackupExtension() // // Returns normal string to append to backup files for this os. // (e.g. "~" for unix and ".bak" for winos) @@ -833,42 +891,9 @@ const TCHAR* cUnixFSServices::GetStandardBackupExtension() const } - // TODO: remove this function - // Matt theorized that this is no longer used - dmb Aug 23 1999 -/* -int cUnixFSServices::CreateLockedTemporaryFile( const TCHAR* szFilename, int perm ) const -{ - // make sure perm is AT LEAST one of: O_RDWR, O_WRONLY - ASSERT( 0 != ( perm & ( O_RDWR | O_WRONLY ) ) ); - // make sure perm is ONLY composed of: O_RDWR, O_WRONLY - ASSERT( 0 == ( perm & ~( O_RDWR | O_WRONLY ) ) ); - // get rid of any unsupported bits caller may have supplied - perm &= ( O_RDWR | O_WRONLY ); - - // set flags - int oflags = perm | - O_CREAT | O_EXCL; // only create a new file -- error if it exists already - - // create file - int fh = _topen( szFilename, oflags, 0666 ); - if( fh >= 0 ) - { - // file was created. Now unlink it - if( 0 != unlink( szFilename ) ) - { - // we weren't able to unlink file, so close handle and fail - close( fh ); - fh = -1; - } - } - - return( fh ); -} -*/ - -void cUnixFSServices::Sleep( int nSeconds ) const +void cUnixFSServices::Sleep(int nSeconds) const { - sleep( nSeconds ); + sleep(nSeconds); } @@ -876,20 +901,20 @@ void cUnixFSServices::Sleep( int nSeconds ) const // Function name : IsRoot // Description : A root path is all '/'s // -// Return type : bool +// Return type : bool // Argument : const TSTRING& strPath /////////////////////////////////////////////////////////////////////////////// -bool cUnixFSServices::IsRoot( const TSTRING& strPath ) const +bool cUnixFSServices::IsRoot(const TSTRING& strPath) const { // and empty path is NOT the root path - if( strPath.empty() ) + if (strPath.empty()) return false; // check to see if all characters are a slash - for( TSTRING::const_iterator iter = strPath.begin(); iter != strPath.end(); iter++ ) + for (TSTRING::const_iterator iter = strPath.begin(); iter != strPath.end(); iter++) { // if we've found a char that's not '/', then it's not the root path - if( *iter != TW_SLASH ) + if (*iter != TW_SLASH) return false; } @@ -905,39 +930,39 @@ bool cUnixFSServices::IsRoot( const TSTRING& strPath ) const /////////////////////////////////////////////////////////////////////////////// // Function name : util_PathFind -// Description : +// Description : // takes single-element executible filename and looks in path env var for it // assumes path is colon-delimited string of directories. // -// Return type : bool +// Return type : bool // Argument : TSTRING& strFullPath // Argument : const TSTRING& strFilename /////////////////////////////////////////////////////////////////////////////// -bool util_PathFind( TSTRING& strFullPath, const TSTRING& strFilename ) +bool util_PathFind(TSTRING& strFullPath, const TSTRING& strFilename) { bool fFoundFile = false; - - if( strFilename.empty() ) + + if (strFilename.empty()) return false; // // get the path environment variable // - TCHAR* pszPathVar = _tgetenv("PATH"); - if( pszPathVar != NULL ) + TCHAR* pszPathVar = getenv("PATH"); + if (pszPathVar != NULL) { // // cycle over characters in path looking for the ':' - // + // TSTRING strCurPath; - TCHAR* pchTemp = pszPathVar; - bool fMorePaths = true; + TCHAR* pchTemp = pszPathVar; + bool fMorePaths = true; do // while still more paths and haven't found file { // // are we at the ':'? - // - if( *pchTemp && *pchTemp != _T(':') ) // if we're not at the end of the path + // + if (*pchTemp && *pchTemp != _T(':')) // if we're not at the end of the path { strCurPath += *pchTemp; } @@ -948,25 +973,25 @@ bool util_PathFind( TSTRING& strFullPath, const TSTRING& strFilename ) // if it's empty, use current directory // TSTRING strFP; - if( strCurPath.empty() ) + if (strCurPath.empty()) strCurPath = _T("."); - if( iFSServices::GetInstance()->FullPath( strFP, strCurPath ) ) + if (iFSServices::GetInstance()->FullPath(strFP, strCurPath)) strCurPath = strFP; // // put the file together with the path dir // TSTRING strFullName = strCurPath; - util_TrailingSep( strFullName, true ); + util_TrailingSep(strFullName, true); strFullName += strFilename; // // the file must exist and be executable // - if( util_FileIsExecutable( strFullName ) ) + if (util_FileIsExecutable(strFullName)) { strFullPath = strFullName; - fFoundFile = true; + fFoundFile = true; } else strCurPath.erase(); // start over @@ -976,63 +1001,62 @@ bool util_PathFind( TSTRING& strFullPath, const TSTRING& strFilename ) // keep searching if we're not at the end of the path string // - if( *pchTemp ) + if (*pchTemp) pchTemp++; else fMorePaths = false; - } - while( !fFoundFile && fMorePaths ); + } while (!fFoundFile && fMorePaths); } - return( fFoundFile ); + return (fFoundFile); } /////////////////////////////////////////////////////////////////////////////// // Function name : util_FileIsExecutable -// Description : file ( or file a link points to ) must be a regular +// Description : file ( or file a link points to ) must be a regular // file and executable by someone // -// Return type : bool +// Return type : bool // Argument : const TSTRING& strFile /////////////////////////////////////////////////////////////////////////////// -bool util_FileIsExecutable( const TSTRING& strFile ) +bool util_FileIsExecutable(const TSTRING& strFile) { - if( strFile.empty() ) + if (strFile.empty()) return false; - + struct stat s; - if( stat( strFile.c_str(), &s ) < 0 ) // this call handles links + if (stat(strFile.c_str(), &s) < 0) // this call handles links return false; - return( S_ISREG( s.st_mode ) && ( s.st_mode & ( S_IXUSR | S_IXGRP | S_IXOTH ) ) ); // can someone execute it? + return (S_ISREG(s.st_mode) && (s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))); // can someone execute it? } //////////////////////////////////////////////////////////////////////////////// // Function name : util_RemoveDuplicateSeps -// Description : +// Description : // takes all adjacent slashes and replaces them with a single slash // ///root//foo -> /root/foo // rel//foo/// -> rel/foo/ // -// Return type : void +// Return type : void // Argument : TSTRING& strPath /////////////////////////////////////////////////////////////////////////////// -void util_RemoveDuplicateSeps( TSTRING& strPath ) +void util_RemoveDuplicateSeps(TSTRING& strPath) { - bool fLastCharWasSep = false; - TSTRING::iterator iter = strPath.begin(); - while( iter != strPath.end() ) + bool fLastCharWasSep = false; + TSTRING::iterator iter = strPath.begin(); + while (iter != strPath.end()) { bool fErasedChar = false; // if we've found a char that's not '/', then it's not the root - if( *iter == TW_SLASH ) + if (*iter == TW_SLASH) { // if this char is a duplicate sep, erase it - if( fLastCharWasSep ) + if (fLastCharWasSep) { - iter = strPath.erase( iter ); + iter = strPath.erase(iter); fErasedChar = true; } @@ -1044,7 +1068,7 @@ void util_RemoveDuplicateSeps( TSTRING& strPath ) } // don't go past end of string (could happen with erase) - if( ! fErasedChar ) + if (!fErasedChar) iter++; } } @@ -1052,31 +1076,31 @@ void util_RemoveDuplicateSeps( TSTRING& strPath ) ////////////////////////////////////////////////////////////////////////////////// // Function name : util_RemoveLastPathElement -// Description : +// Description : // effectively pops off a path element from the end, except for the root dir, where it does nothing // it removes any slashes before and after the element // ///root//foo/ -> leaves "///root" ("foo" is strElem) // ///root -> leaves "" ("root" is strElem) // // -> leaves "" ("" is strElem) // -// Return type : void +// Return type : void // Argument : TSTRING& strPath // Argument : TSTRING& strElem ///////////////////////////////////////////////////////////////////////////////// -void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem ) +void util_RemoveLastPathElement(TSTRING& strPath, TSTRING& strElem) { - + // remove all trailing separators - util_RemoveTrailingSeps( strPath ); + util_RemoveTrailingSeps(strPath); // find the last separator - TSTRING::size_type lastSep = strPath.rfind( TW_SLASH ); + TSTRING::size_type lastSep = strPath.rfind(TW_SLASH); // if separator was found, take all chars after it - if( lastSep != TSTRING::npos ) + if (lastSep != TSTRING::npos) { - strElem = strPath.substr( lastSep + 1 ); - strPath.resize( lastSep + 1 ); + strElem = strPath.substr(lastSep + 1); + strPath.resize(lastSep + 1); } else // no seps in name, take whole string { @@ -1084,15 +1108,15 @@ void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem ) strElem = strPath; strPath.erase(); } - + // remove all trailing separators - util_RemoveTrailingSeps( strPath ); + util_RemoveTrailingSeps(strPath); } //////////////////////////////////////////////////////////////////////////////////// // Function name : util_GetNextPathElement -// Description : +// Description : // starting from the left side of the path string, returns the index'th path element // returns true if the element exists, false if there aren't many elements // @@ -1106,43 +1130,42 @@ void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem ) // Argument : TSTRING& strElem // Argument : int index ///////////////////////////////////////////////////////////////////////////////// -bool util_GetNextPathElement( const TSTRING& strPathC, TSTRING& strElem, int index ) +bool util_GetNextPathElement(const TSTRING& strPathC, TSTRING& strElem, int index) { // don't do anything if root or empty - if( strPathC.empty() || iFSServices::GetInstance()->IsRoot( strPathC ) ) + if (strPathC.empty() || iFSServices::GetInstance()->IsRoot(strPathC)) return false; TSTRING strPath = strPathC; // writable local version - - bool fMoreSeps = true; - TSTRING::size_type firstSep, nextSep, nextNonSep; - firstSep = nextSep = nextNonSep = (TSTRING::size_type)-1; - for( int i = 0; i <= index && fMoreSeps; i++ ) - { + + bool fMoreSeps = true; + TSTRING::size_type nextSep, nextNonSep; + nextSep = nextNonSep = (TSTRING::size_type)-1; + for (int i = 0; i <= index && fMoreSeps; i++) + { // go past leading separators - nextNonSep = strPath.find_first_not_of( TW_SLASH, nextSep + 1 ); + nextNonSep = strPath.find_first_not_of(TW_SLASH, nextSep + 1); - if( nextNonSep != TSTRING::npos ) + if (nextNonSep != TSTRING::npos) { // find index'th slash (start of index'th element) - nextSep = strPath.find( TW_SLASH, nextNonSep ); + nextSep = strPath.find(TW_SLASH, nextNonSep); // if we're at the end and we haven't found the index'th element // left, then tell the caller that there aren't that many elemnts - if( nextSep == TSTRING::npos && i < index ) + if (nextSep == TSTRING::npos && i < index) fMoreSeps = false; - } else fMoreSeps = false; } // get the element and remove it from the path - if( fMoreSeps ) - strElem = strPath.substr( nextNonSep, nextSep - nextNonSep ); + if (fMoreSeps) + strElem = strPath.substr(nextNonSep, nextSep - nextNonSep); - return( fMoreSeps ); + return (fMoreSeps); } ///////////////////////////////////////////////////////////////////////// @@ -1153,46 +1176,42 @@ bool util_GetNextPathElement( const TSTRING& strPathC, TSTRING& strElem, int ind // Argument : TSTRING& str // Argument : bool fLeaveSep ///////////////////////////////////////////////////////////////////////////////// -bool util_TrailingSep( TSTRING& str, bool fLeaveSep ) +bool util_TrailingSep(TSTRING& str, bool fLeaveSep) { bool fWasSep = false; // if there's a trailing sep - if( - ! str.empty() - && - str[ str.size() - 1 ] == TW_SLASH - ) + if (!str.empty() && str[str.size() - 1] == TW_SLASH) { - if( ! fLeaveSep ) - str.resize( str.size() - 1 ); + if (!fLeaveSep) + str.resize(str.size() - 1); fWasSep = true; } else // else no trailing sep { - if( fLeaveSep ) + if (fLeaveSep) str += TW_SLASH; fWasSep = false; } - return( fWasSep ); + return (fWasSep); } ///////////////////////////////////////////////////////////////////////// // Function name : util_RemoveTrailingSeps // Description : removes all trailing separators // -// Return type : void +// Return type : void // Argument : TSTRING& str ///////////////////////////////////////////////////////////////////////////////// -void util_RemoveTrailingSeps( TSTRING& str ) +void util_RemoveTrailingSeps(TSTRING& str) { - while( util_TrailingSep( str, false ) ) - {} + while (util_TrailingSep(str, false)) + { + } } -template< typename T > static inline void util_ZeroMemory( T& obj ) +template static inline void util_ZeroMemory(T& obj) { - memset( &obj, 0, sizeof( obj ) ); + memset(&obj, 0, sizeof(obj)); } - diff --git a/src/core/unixfsservices.h b/src/core/unixfsservices.h index 8a3d3b7..dae69bd 100644 --- a/src/core/unixfsservices.h +++ b/src/core/unixfsservices.h @@ -1,45 +1,45 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // //////////////////////////////////////////////////////////////////////// // unixfsservices.h // -// cUnixFSServices implements iFSServices, which abstacts out all +// cUnixFSServices implements iFSServices, which abstacts out all // system dependent filesystem calls. #ifndef __UNIXFSSERVICES_H #define __UNIXFSSERVICES_H #if !IS_UNIX -#error unixfsservices.h should only be included for instantiating cUnixFSServices objects. If you just want to use iFSServices methods, include fsservices.h. Same goes for cWin32FSServices. +#error unixfsservices.h should only be included for instantiating cUnixFSServices objects. If you just want to use iFSServices methods, include fsservices.h. #endif //========================================================================= @@ -54,153 +54,113 @@ // DECLARATION OF CLASSES //========================================================================= -//Set up in constructor. Stores pertinent information about the filesystem -//serviced by each instantiation. - -struct UnixSysInfo +class cUnixFSServices : public iFSServices { - uint32 maxcomplen; - //max name length of a file on filesystem - uint32 fsflags; - //bitmask of flags - TSTRING fsname; - //The filesystem basename - uint32 fsid; - //unique indentifier for the filesystem -}; - -class cUnixFSServices : public iFSServices -{ - /////////////////////////////////////////////////////////////// - // ENUMS - /////////////////////////////////////////////////////////////// - - //////////////////////////////////////// - // file system types - //////////////////////////////////////// - enum FSType - { - FS_UFS = 0, - FS_NFS, - FS_HSFS, - FS_PCFS - }; - - /////////////////////////////////////////////////////////////// - // MEMBER FUNCTIONS - /////////////////////////////////////////////////////////////// - public: - cUnixFSServices(); - virtual ~cUnixFSServices(); - - - //////////////////////////////////////// - // platform specific functions - //////////////////////////////////////// - virtual bool IsCaseSensitive() const; - // returns true if the file system is case sensitive - virtual const TCHAR* GetStandardBackupExtension() const; - // returns normal string to append to backup files for this os. - // (e.g. "~" for unix and ".bak" for winos) - virtual TCHAR GetPathSeparator() const; - - //////////////////////////////////////// - // process functions - //////////////////////////////////////// - virtual void Sleep( int nSeconds ) const; - // makes the current process sleep for the specified number of seconds - - //////////////////////////////////////// - // major filesystem functions - //////////////////////////////////////// - virtual void Stat( const TSTRING& strFileName, cFSStatArgs& pStat ) const throw( eFSServices ); - // fills out the cFSStatArgs structure with the stat info for the named file - - virtual void GetTempDirName( TSTRING& strName ) const throw( eFSServices ); - // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) - - virtual void SetTempDirName(TSTRING& tmpName); - // set the default dir name which GetTempDirName will use... - - virtual TSTRING& MakeTempFilename( TSTRING& strName ) const throw( eFSServices ); - // create temporary file - // strName must have the form ("baseXXXXXX"), where the X's are replaced with - // characters to make it a unique file. There must be at least 6 Xs. - - // TODO: remove this function - // Matt theorized that this is no longer used - dmb Aug 23 1999 - //virtual int CreateLockedTemporaryFile( const TCHAR* szFilename, int perm ) const; - - - //////////////////////////////////////// - // minor filesystem functions - //////////////////////////////////////// - virtual void GetHostID( TSTRING& name ) const; - - virtual void GetMachineName( TSTRING& name) const throw(eFSServices); - - virtual void GetMachineNameFullyQualified( TSTRING& name ) const; - - virtual bool GetCurrentUserName( TSTRING& tstrName ) const; - - virtual bool GetIPAddress( uint32& uiIPAddress ); - - - //////////////////////////////////////// - // directory specific functions - //////////////////////////////////////// - virtual void ReadDir( const TSTRING& strName, std::vector &vDirContents, bool bFullPaths = true ) const throw( eFSServices ); - // puts the contents of the specified directory, except for . and .., into the supplied vector. - virtual void GetCurrentDir( TSTRING& strCurDir ) const throw( eFSServices ); - // returns the current working directory - virtual void ChangeDir( const TSTRING& strName ) const throw( eFSServices ); - // sets the current working directory - virtual void Mkdir( const TSTRING& strName ) const throw( eFSServices ); - - virtual bool Rmdir( const TSTRING& strName ) const; - - - //////////////////////////////////////// - // file specific functions - //////////////////////////////////////// - virtual bool FileDelete( const TSTRING& name ) const; - - - //////////////////////////////////////// - // directory and file functions - //////////////////////////////////////// - virtual bool Rename( const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true ) const; - // rename a file - virtual bool GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tstrUser ) const; - - virtual bool GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tstrGroup ) const; - - - //////////////////////////////////////// - // miscellaneous utility functions - //////////////////////////////////////// - virtual void ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const; - // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) - virtual bool FullPath( TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("") ) const; - // converts relPath into a fully qualified path, storing it in FullPath. If this - // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. - virtual bool GetExecutableFilename( TSTRING& strFullPath, const TSTRING& strFilename ) const; - // get the path to the current executable file - virtual bool IsRoot( const TSTRING& strPath ) const; - // returns true if strPath is all '/'s - - //////////////////////////////////////// - // error functions - //////////////////////////////////////// - virtual TSTRING GetErrString() const; - - private: - UnixSysInfo info; - //struct stores pertinent system info. to be used by member functions - - TSTRING mTempPath; - + /////////////////////////////////////////////////////////////// + // MEMBER FUNCTIONS + /////////////////////////////////////////////////////////////// +public: + cUnixFSServices(); + virtual ~cUnixFSServices(); + + + //////////////////////////////////////// + // platform specific functions + //////////////////////////////////////// + virtual bool IsCaseSensitive() const; + // returns true if the file system is case sensitive + virtual const TCHAR* GetStandardBackupExtension() const; + // returns normal string to append to backup files for this os. + // (e.g. "~" for unix and ".bak" for winos) + virtual TCHAR GetPathSeparator() const; + + //////////////////////////////////////// + // process functions + //////////////////////////////////////// + virtual void Sleep(int nSeconds) const; + // makes the current process sleep for the specified number of seconds + + //////////////////////////////////////// + // major filesystem functions + //////////////////////////////////////// + virtual void Stat(const TSTRING& strFileName, cFSStatArgs& pStat) const; + // fills out the cFSStatArgs structure with the stat info for the named file + + virtual void GetTempDirName(TSTRING& strName) const; + // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) + + virtual void SetTempDirName(TSTRING& tmpName); + // set the default dir name which GetTempDirName will use... + + virtual TSTRING& MakeTempFilename(TSTRING& strName) const; + // create temporary file + // strName must have the form ("baseXXXXXX"), where the X's are replaced with + // characters to make it a unique file. There must be at least 6 Xs. + + + //////////////////////////////////////// + // minor filesystem functions + //////////////////////////////////////// + virtual void GetHostID(TSTRING& name) const; + + virtual void GetMachineName(TSTRING& name) const; + + virtual void GetMachineNameFullyQualified(TSTRING& name) const; + + virtual bool GetCurrentUserName(TSTRING& tstrName) const; + + virtual bool GetIPAddress(uint32& uiIPAddress); + + + //////////////////////////////////////// + // directory specific functions + //////////////////////////////////////// + virtual void ReadDir(const TSTRING& strName, std::vector& vDirContents, bool bFullPaths = true) const; + // puts the contents of the specified directory, except for . and .., into the supplied vector. + virtual void GetCurrentDir(TSTRING& strCurDir) const; + // returns the current working directory + + + //////////////////////////////////////// + // file specific functions + //////////////////////////////////////// + virtual bool FileDelete(const TSTRING& name) const; + + //////////////////////////////////////// + // directory and file functions + //////////////////////////////////////// + virtual bool Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true) const; + // rename a file + + virtual bool GetUserName(uid_t user_id, TSTRING& tstrUser) const; + virtual bool GetGroupName(gid_t group_id, TSTRING& tstrGroup) const; + + //Set whether we try to resolve uid/gid to a name, since Linux static binaries can + //have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup. + //This defaults to true if not specified. + virtual void SetResolveNames(bool resolve); + + //////////////////////////////////////// + // miscellaneous utility functions + //////////////////////////////////////// + virtual void ConvertModeToString(uint64 perm, TSTRING& tstrPerm) const; + // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) + virtual bool FullPath(TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("")) const; + // converts relPath into a fully qualified path, storing it in FullPath. If this + // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. + virtual bool GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const; + // get the path to the current executable file + virtual bool IsRoot(const TSTRING& strPath) const; + // returns true if strPath is all '/'s + + //////////////////////////////////////// + // error functions + //////////////////////////////////////// + virtual TSTRING GetErrString() const; + +private: + TSTRING mTempPath; + bool mResolveNames; }; #endif //__UNIXFSSERVICES_H - diff --git a/src/core/upperbound.h b/src/core/upperbound.h index 6fecc17..78d0fd9 100644 --- a/src/core/upperbound.h +++ b/src/core/upperbound.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,15 +37,15 @@ #define __UPPERBOUND_H ///////////////////////////////////////////////////////////////////////////////////////////// -// Function name: template< class FwdIterT, class CmpObjT, class CmpFuncT > +// Function name: template< class FwdIterT, class CmpObjT, class CmpFuncT > // UpperBound // -// Description : same as std::upper_bound except it allows 'less' to take +// Description : same as std::upper_bound except it allows 'less' to take // parameters of dissimilar types. Therefore, *FwdIter need not be // the same type as CmpObjT. Uses a binary search algorithm. // -// Return type : FwdIterT : First element in the sequence [first, last) -// that is equal to or greater than 'obj' or +// Return type : FwdIterT : First element in the sequence [first, last) +// that is equal to or greater than 'obj' or // 'last' if there is no such element. // // Argument : FwdIterT first : First element in sequence. @@ -54,25 +54,26 @@ // Argument : CmpFuncT less : Comparison function. Must return as 'std::less'. // Will be called as: 'bool less( *FwdIterT, CmpObjT )'. ///////////////////////////////////////////////////////////////////////////////////////////// -template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( FwdIterT first, FwdIterT last, const CmpObjT& obj, CmpFuncT less ) -{ +template +FwdIterT UpperBound(FwdIterT first, FwdIterT last, const CmpObjT& obj, CmpFuncT less) +{ // count elements in set - int nElemsInSet = 0; - FwdIterT iCur = first; - for (; iCur != last; ++iCur ) + int nElemsInSet = 0; + FwdIterT iCur = first; + for (; iCur != last; ++iCur) ++nElemsInSet; iCur = first; - while( 0 < nElemsInSet ) + while (0 < nElemsInSet) { // go to halfway point - int iHalfWay = nElemsInSet/2; - FwdIterT iTemp = iCur; - for( int j = 0; j < iHalfWay; j++ ) + int iHalfWay = nElemsInSet / 2; + FwdIterT iTemp = iCur; + for (int j = 0; j < iHalfWay; j++) iTemp++; - if( less( *iTemp, obj ) ) + if (less(*iTemp, obj)) { // start next search set at next elem with half of the last search set's elements iCur = ++iTemp; @@ -89,4 +90,3 @@ template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( F } #endif // __UPPERBOUND_H - diff --git a/src/core/usernotify.cpp b/src/core/usernotify.cpp index ba45a0c..9508929 100644 --- a/src/core/usernotify.cpp +++ b/src/core/usernotify.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,20 +36,17 @@ // There was a problem with varargs on some combo of old OpenBSD & old compiler. // Not needed with current, but it's here if you need it. #ifdef TW_OLD_OPENBSD_VARARGS -# undef va_start -# ifdef __GNUC__ -# define va_start(ap, last) \ - ((ap) = (va_list)__builtin_next_arg(last)) -# else -# define va_start(ap, last) \ - ((ap) = (va_list)&(last) + __va_size(last)) -# endif +# undef va_start +# ifdef __GNUC__ +# define va_start(ap, last) ((ap) = (va_list)__builtin_next_arg(last)) +# else +# define va_start(ap, last) ((ap) = (va_list) & (last) + __va_size(last)) +# endif #endif // TW_OLD_OPENBSD_VARARGS iUserNotify* iUserNotify::mpInstance = 0; -iUserNotify::iUserNotify(int verboseLevel) : - mVerboseLevel(verboseLevel) +iUserNotify::iUserNotify(int verboseLevel) : mVerboseLevel(verboseLevel) { } @@ -70,33 +67,33 @@ int iUserNotify::GetVerboseLevel() const /////////////////////////////////////////////////////////////////////////////// // NotifySilent /////////////////////////////////////////////////////////////////////////////// -void iUserNotify::NotifySilent( const TCHAR* format, ... ) +void iUserNotify::NotifySilent(const TCHAR* format, ...) { va_list args; va_start(args, format); - HandleNotify( V_SILENT, format, args ); + HandleNotify(V_SILENT, format, args); va_end(args); } /////////////////////////////////////////////////////////////////////////////// // NotifyNormal /////////////////////////////////////////////////////////////////////////////// -void iUserNotify::NotifyNormal( const TCHAR* format, ... ) +void iUserNotify::NotifyNormal(const TCHAR* format, ...) { va_list args; va_start(args, format); - HandleNotify( V_NORMAL, format, args ); + HandleNotify(V_NORMAL, format, args); va_end(args); } /////////////////////////////////////////////////////////////////////////////// // NotifyVerbose /////////////////////////////////////////////////////////////////////////////// -void iUserNotify::NotifyVerbose( const TCHAR* format, ... ) +void iUserNotify::NotifyVerbose(const TCHAR* format, ...) { va_list args; va_start(args, format); - HandleNotify( V_VERBOSE, format, args ); + HandleNotify(V_VERBOSE, format, args); va_end(args); } @@ -107,8 +104,6 @@ void iUserNotify::Notify(int verboseLevel, const TCHAR* format, ...) { va_list args; va_start(args, format); - HandleNotify( verboseLevel, format, args ); + HandleNotify(verboseLevel, format, args); va_end(args); } - - diff --git a/src/core/usernotify.h b/src/core/usernotify.h index 4796491..ffdcb5b 100644 --- a/src/core/usernotify.h +++ b/src/core/usernotify.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,19 +49,19 @@ class iUserNotify // singleton interface; caller is responsible for deleting pointer; static iUserNotify* GetInstance(); static void SetInstance(iUserNotify* pInst); - - virtual void Notify(int verboseLevel, const TCHAR* format, ...) ; - // notify the user that an event has occured. The outcome of this operation is - // dependant on the type of object that is implementing this interface (for example, - // a console application would want an iUserNotify that prints things to stdout) - // If the current verbosity level is less than verboseLevel, nothing will happen. - // All output should be sent through the cDisplayEncoder beforehand - // TODO:BAM -- enforce this somehow? - - virtual void SetVerboseLevel(int level); - virtual int GetVerboseLevel() const; - // get/set the current verbosity level. Notify()s that occur whose verbosity level - // is greater than the current level will not be processed. + + virtual void Notify(int verboseLevel, const TCHAR* format, ...); + // notify the user that an event has occured. The outcome of this operation is + // dependant on the type of object that is implementing this interface (for example, + // a console application would want an iUserNotify that prints things to stdout) + // If the current verbosity level is less than verboseLevel, nothing will happen. + // All output should be sent through the cDisplayEncoder beforehand + // TODO:BAM -- enforce this somehow? + + virtual void SetVerboseLevel(int level); + virtual int GetVerboseLevel() const; + // get/set the current verbosity level. Notify()s that occur whose verbosity level + // is greater than the current level will not be processed. // a convenience enumeration; no one is bound by law to use these enum VerboseLevel @@ -73,45 +73,47 @@ class iUserNotify // // convenience methods for notifying at these three levels... // - void NotifySilent ( const TCHAR* format, ... ); - void NotifyNormal ( const TCHAR* format, ... ); - void NotifyVerbose ( const TCHAR* format, ... ); + void NotifySilent(const TCHAR* format, ...); + void NotifyNormal(const TCHAR* format, ...); + void NotifyVerbose(const TCHAR* format, ...); iUserNotify(int verboseLevel = 0); virtual ~iUserNotify(); + protected: - virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) = 0; - // this is implemented in derived classes to implement the specific type of - // notification desired - + virtual void HandleNotify(int level, const TCHAR* format, va_list& args) = 0; + // this is implemented in derived classes to implement the specific type of + // notification desired + int mVerboseLevel; + private: static iUserNotify* mpInstance; }; //----------------------------------------------------------------------------- -// notify macros +// notify macros // -// use these as an alternative to iUserNotify::GetInstance()->Notify( XXX ) +// use these as an alternative to iUserNotify::GetInstance()->Notify( XXX ) // becuase the call will not be made if it is not the appropriate verbosity // level. This is useful when you don't want the "..." part of Notify() to be // evaluated (for example, if it is an expensive operation like cFCOName::AsString() // //----------------------------------------------------------------------------- -#define TW_NOTIFY_SILENT\ - if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT )\ - iUserNotify::GetInstance()->NotifySilent +#define TW_NOTIFY_SILENT \ + if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT) \ + iUserNotify::GetInstance()->NotifySilent -#define TW_NOTIFY_NORMAL\ - if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL )\ - iUserNotify::GetInstance()->NotifyNormal +#define TW_NOTIFY_NORMAL \ + if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL) \ + iUserNotify::GetInstance()->NotifyNormal -#define TW_NOTIFY_VERBOSE\ - if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE )\ - iUserNotify::GetInstance()->NotifyVerbose +#define TW_NOTIFY_VERBOSE \ + if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE) \ + iUserNotify::GetInstance()->NotifyVerbose //############################################################################# // inline implementation @@ -129,4 +131,3 @@ inline void iUserNotify::SetInstance(iUserNotify* pInst) #endif //__USERNOTIFY_H - diff --git a/src/core/usernotifystdout.cpp b/src/core/usernotifystdout.cpp index d41b0f9..7418c76 100644 --- a/src/core/usernotifystdout.cpp +++ b/src/core/usernotifystdout.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,21 +36,20 @@ /////////////////////////////////////////////////////////////////////////////// // HandleNotify /////////////////////////////////////////////////////////////////////////////// -void cUserNotifyStdout::HandleNotify( int level, const TCHAR* format, va_list& args ) +void cUserNotifyStdout::HandleNotify(int level, const TCHAR* format, va_list& args) { - if(GetVerboseLevel() < level) + if (GetVerboseLevel() < level) return; // all verbose output now goes to stderr - if(level < iUserNotify::V_VERBOSE) + if (level < iUserNotify::V_VERBOSE) { _vtprintf(format, args); - fflush( stdout ); + fflush(stdout); } else { _vftprintf(stderr, format, args); - fflush( stderr ); + fflush(stderr); } } - diff --git a/src/core/usernotifystdout.h b/src/core/usernotifystdout.h index e48af7b..eb8cde8 100644 --- a/src/core/usernotifystdout.h +++ b/src/core/usernotifystdout.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,11 +43,10 @@ class cUserNotifyStdout : public iUserNotify { public: - virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) ; - // formats the string and sends it to stdout - // NOTE -- a little tripwire specific hack has been applied that makes all output - // at or above iUserNotify::V_VERBOSE go to stderr instead of stdout + virtual void HandleNotify(int level, const TCHAR* format, va_list& args); + // formats the string and sends it to stdout + // NOTE -- a little tripwire specific hack has been applied that makes all output + // at or above iUserNotify::V_VERBOSE go to stderr instead of stdout }; #endif /* __USERNOTIFYSTDOUT_H */ - diff --git a/src/core/userstring.h b/src/core/userstring.h deleted file mode 100644 index 301f8de..0000000 --- a/src/core/userstring.h +++ /dev/null @@ -1,134 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// UserString.h -- A single point of access for all strings that will be -// displayed to the end user. This implementation is intended to ease -// any future localization efforts. -/////////////////////////////////////////////////////////////////////////////// - -#ifndef __USERSTRING_H -#define __USERSTRING_H - -#ifndef __DEBUG_H -#include "core/debug.h" -#endif - -#ifndef _MAP_ -#include -#endif - -/////////////////////////////////////////////////////////////////////////////// -// class iUserString -- Abstract interface for retrieving User Strings -/////////////////////////////////////////////////////////////////////////////// - -class iUserString -{ -public: - virtual ~iUserString() {} - - struct tStringPair - { - int id; - TCHAR* string; - }; - - // Select between the different localized string sets - // for this product. Returns false if string not defined. - virtual bool SelectStringSet(int setID) = 0; - - // Get the string from the localized string set - virtual const TCHAR* GetString(int stringID) const = 0; - - // Clear all strings in specified string set - virtual void ClearStringSet(int id) = 0; - - // Add an array of string pairs to a string set. The pair array passed in - // should terminate with an id of -1. If this string set contains string IDs - // that already exist in the string set, they will "overwrite" the - // the previous strings. - // Note: We store only pointers to the string pairs so they must remain - // around for as long as this class uses them. A static array defined at - // compile time is perfect for this. - virtual void AddStringSet(int setID, const tStringPair* pPairArray) = 0; - - // Add a single string. The above rules apply. - virtual void AddString(int setID, int stringID, TCHAR* string) = 0; - - // singleton manipulation - static iUserString* GetInstance(); - static void SetInstance(iUserString* pInst); -private: - static iUserString* mpInstance; -}; - -/////////////////////////////////////////////////////////////////////////////// -// Macros useful for building UserString tables. -/////////////////////////////////////////////////////////////////////////////// - -/* -Example Use: - - static struct iUserString::tStringPair englishStrings[] = - { - USERSTRING(STR_HELLO_WORLD, "Hello World\n") - USERSTRING(STR_OUT_OF_MEM, "Fatal Error: Out of memory.\n") - USERSTRING_END() - }; - - pUSMB->AddStringSet(LANG_USENGLISH, englishStrings); -*/ - -#define USERSTRING(id, str) { (id), _T(str) }, - -#define USERSTRING_END() { -1, _T("") } - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// inline implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// -inline iUserString* iUserString::GetInstance() -{ - ASSERT(mpInstance); - - return mpInstance; -} - -inline void iUserString::SetInstance(iUserString* pInst) -{ - mpInstance = pInst; -} - - -#ifdef _MSC_VER -//#pragma warning(default:4786) -#endif /* _MSC_VER */ - -#endif // __USERSTRING_H diff --git a/src/core/userstringmem.cpp b/src/core/userstringmem.cpp index ffa84e4..bf94af9 100644 --- a/src/core/userstringmem.cpp +++ b/src/core/userstringmem.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -72,7 +72,7 @@ const TCHAR* cUserStringMemBased::GetString(int stringID) const if (setItr == mStringSets.end()) { // mCurrentStringSet is invallid - ASSERT(false); + ASSERT(false); return _T(""); } @@ -106,10 +106,10 @@ void cUserStringMemBased::ClearStringSet(int id) } // Add an array of string pairs to a string set. The pair array passed in -// should terminate with an id of -1. If this string set contains string IDs +// should terminate with an id of -1. If this string set contains string IDs // that already exist in the string set, they will "overwrite" the -// the previous strings. -// Note: We store only pointers to the string pairs so they must remain +// the previous strings. +// Note: We store only pointers to the string pairs so they must remain // around for as long as this class uses them. A static array defined at // compile time is perfect for this. void cUserStringMemBased::AddStringSet(int setID, const iUserString::tStringPair* pPairArray) @@ -167,4 +167,3 @@ void cUserStringMemBased::AddString(int setID, int stringID, TCHAR* string) setItr->second->insert(std::pair(stringID, string)); } - diff --git a/src/core/userstringmem.h b/src/core/userstringmem.h index 84fcf2a..8c7a179 100644 --- a/src/core/userstringmem.h +++ b/src/core/userstringmem.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,16 +40,16 @@ #endif #ifndef __USERSTRINGMEM_H -#define __USERSTRINGMEM_H +# define __USERSTRINGMEM_H -#ifdef _MSC_VER -#pragma warning(disable:4786) /* disable unwanted C++ /W4 warning */ -/* #pragma warning(default:4786) */ /* use this to reenable, if necessary */ -#endif /* _MSC_VER */ +# ifdef _MSC_VER +# pragma warning(disable : 4786) /* disable unwanted C++ /W4 warning */ +/* #pragma warning(default:4786) */ /* use this to reenable, if necessary */ +# endif /* _MSC_VER */ -#ifndef __USERSTRING_H -#include "userstring.h" -#endif +# ifndef __USERSTRING_H +# include "userstring.h" +# endif /////////////////////////////////////////////////////////////////////////////// // class cUserStringMemBased -- A implementation where the various string @@ -69,23 +69,22 @@ class cUserStringMemBased : public iUserString ~cUserStringMemBased(); // the abstract interface - virtual bool SelectStringSet (int setID); - virtual const TCHAR* GetString (int stringID) const; - virtual void ClearStringSet (int id); - virtual void AddStringSet (int setID, const iUserString::tStringPair* pPairArray); - virtual void AddString (int setID, int stringID, TCHAR* string); + virtual bool SelectStringSet(int setID); + virtual const TCHAR* GetString(int stringID) const; + virtual void ClearStringSet(int id); + virtual void AddStringSet(int setID, const iUserString::tStringPair* pPairArray); + virtual void AddString(int setID, int stringID, TCHAR* string); private: typedef std::map StringSet; - int mCurrentStringSet; - std::map mStringSets; + int mCurrentStringSet; + std::map mStringSets; }; -#ifdef _MSC_VER +# ifdef _MSC_VER //#pragma warning(default:4786) -#endif /* _MSC_VER */ +# endif /* _MSC_VER */ #endif // __USERSTRINGMEM_H - diff --git a/src/core/utf8.cpp b/src/core/utf8.cpp deleted file mode 100644 index 1070882..0000000 --- a/src/core/utf8.cpp +++ /dev/null @@ -1,152 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// utf8.h -// -#include "stdcore.h" -#include "utf8.h" // Required Deps -#include "tchar.h" -//#include "integ/tss.integ.strings.h" -//#include "integ/tss.integ.strings.inl" - -#ifdef _UNICODE - - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// CLASS UTF8: Member Definitions -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// NOTES: utf8 uses "lazy evaluation" so that members are only allocated -// if they are used. However, once they are evaluated, the evaluation results -// will be saved so that values may henceforth simply be returned. This -// scheme gives the best time vs. space performance possible as the complexity -// of each operation is at most, linear. - - -const char* cUTF8::str() const THROW(std::bad_alloc) // UTF8: Get as Narrow UTF8 -{ - if ( mUTF8Str == 0 ) // If mUTF8Str is NULL mUnicodeStr can't be - mUTF8Str = cUTF8::allocate( mUnicodeStr ); - - return mUTF8Str; -} - -const wchar_t* cUTF8::ustr() const THROW(std::bad_alloc) // UTF8: Get as UNICODE NTWCS -{ - if ( mUnicodeStr == 0 ) - mUnicodeStr = cUTF8::allocate( mUTF8Str ); // If mUnicodeStr is NULL mUTF8WideStr can't be - - return mUnicodeStr; -} - -const wchar_t* cUTF8::wstr() const THROW(std::bad_alloc) // UTF8: Get as Wide UTF8 -{ - if ( mUTF8WideStr == 0 ) - { - size_t N = ::strlen( str() ); // WARNING: Get strlen NOT mbcslen!!! - mUTF8WideStr = new wchar_t[ N + 1 ]; // This may throw bad_alloc to client - - for ( size_t n = 0; n < N; n++ ) // index ordinal, not pointer - mUTF8WideStr[n] = wchar_t( BYTE(mUTF8Str[n]) ); // WARNING: First convert to "unsigned char" - - mUTF8WideStr[N] = 0; // add a final NULL - } - - return mUTF8WideStr; -} - - -/// UTF8: UTF8-Unicode Round-trip Conversions - -wchar_t* cUTF8::allocate( const char* in ) THROW( std::bad_alloc ) -{ - ASSERT( in /* && TSS_IsValidString( in )*/ ); // Verify Input - - size_t N = ::MultiByteToWideChar( CP_UTF8, 0, in, -1, 0, 0 ); - wchar_t* out = new wchar_t[ N + 1 ]; // Allocate required size - - - //--Convert - - out[0] = 0x00; // NOTE: Just in case we fail - #ifdef _DEBUG - //size_t nWritten = - #endif - ::MultiByteToWideChar( CP_UTF8, 0, in, -1, out, N ); - out[N] = 0; - -#ifdef _INTEG2 // Verify Output - if ( nWritten == 0 ) - { - cDebug d( "cUTF8::allocate" ); - d.TraceError( "MultiByteToWideChar failed with %x\n", ::GetLastError() ); - } - - ASSERT( out && TSS_IsValidString( out, nWritten ) ); -#endif - - return out; -} - -char* cUTF8::allocate( const wchar_t* in ) THROW( std::bad_alloc ) -{ - ASSERT( in /*&& TSS_IsValidString( in ) */); // Verify Input - - // Allocate required size - size_t N = ::WideCharToMultiByte( CP_UTF8, 0, in, -1,0,0,0,0 ); - char* out = new char[ N + 1 ]; - - - //--Convert - - out[0] = 0x00; // NOTE: Just in case we fail - #ifdef _DEBUG - //size_t nWritten = - #endif - ::WideCharToMultiByte( CP_UTF8, 0, in, -1, out, N, 0, 0 ); - out[N] = 0; - -#ifdef _INTEG2 // Verify Output - if ( nWritten == 0 ) - { - cDebug d( "cUTF8::allocate" ); - d.TraceError( "WideCharToMultiByte failed with %x\n", ::GetLastError() ); - } - - ASSERT( out /*&& TSS_IsValidString( out, nWritten ) */); -#endif - - return out; -} - -#endif //_UNICODE - diff --git a/src/core/utf8.h b/src/core/utf8.h deleted file mode 100644 index da772d7..0000000 --- a/src/core/utf8.h +++ /dev/null @@ -1,187 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// utf8.h -// - -// UTF8 is used to map UNICODE characters to NTBS targets -// that would normally not be able to dealt with. UTF8 -// ensures symetrical round-trip conversions. In other -// words an unmapable UNICODE character converted to UTF8 -// will always convert back to the same UNICODE value. -// -// For more information, go to: -// mk:@MSITStore:\\SQUID\MSDN%20January%201999\MSDN\kbwindev.chm::/Source/win32sdk/q175392.htm - -#ifndef __UTF8_H -#define __UTF8_H - -#include // operator<< - -//#ifndef __TSS_INTEG_STRINGS_H -//#include "integ/tss.integ.strings.h" // IsValidAddress and IsValidString -//#endif -#ifndef __DEBUG_H -#include "debug.h" -#endif - -//----------------------------------------------------------------------------- -// convenience macros -// -// use these when printing a string ( TCHAR* ) to stdout, stderr, of printf-style -// function to safely convert the string to something printable -//----------------------------------------------------------------------------- -#ifdef _UNICODE -# define TSS_UTF8( x ) cUTF8( x ).wstr() -#else -# define TSS_UTF8( x ) x -#endif - -#ifdef _UNICODE // this class is only needed in unicode builds... - -//----------------------------------------------------------------------------- -// Entities Declared in this Module -//----------------------------------------------------------------------------- - -class cUTF8; - -std::ostream& operator<<( std::ostream&, const cUTF8& ); -std::wostream& operator<<( std::wostream&, const cUTF8& ); - - -/// Class Declaration - -#ifdef _THROW_SUPPORTED -#define THROW( x ) throw( x ) -#define THROW_0 throw() -#else -#define THROW( x ) -#define THROW_0 -#endif - -//============================================================================= -// class cUTF8: Encapsulate UTF8 Encoding -// -// SYNOPSIS: -// Allows unmappable UNICODE characters to be embedded into Narrow strings -// and displayable by narrow display streams. -// -// CONSTRAINTS: -// Cannot default or copy construct or assign UTF8 instances. Each UTF8 -// instance is an exclusive owner of its resources for its life-time. -// This cuts down on the amount of redundant allocation and copying that -// is required by the class. -//============================================================================= - -class cUTF8 -{ - /// Interface. - - public: - - cUTF8( const char* ) THROW( std::bad_alloc ); - cUTF8( const wchar_t* ) THROW( std::bad_alloc ); - ~cUTF8(); - - const char* str() const THROW( std::bad_alloc ); // Narrow UTF8 - const wchar_t* wstr() const THROW( std::bad_alloc ); // Wide UTF8 - const wchar_t* ustr() const THROW( std::bad_alloc ); // Unicode - - - /// Implementation. - - protected: - - static char* allocate( const wchar_t* ) THROW( std::bad_alloc ); - static wchar_t* allocate( const char* ) THROW( std::bad_alloc ); - - protected: - - cUTF8( const cUTF8& ); // Disallow - cUTF8& operator=( const cUTF8& ); // Disallow - - private: - - mutable wchar_t* mUnicodeStr; // UNICODE String - mutable char* mUTF8Str; // UTF8 Bytes String - mutable wchar_t* mUTF8WideStr; // UTF8 Wide Character String -}; - -//----------------------------------------------------------------------------- -// UTF8 Inlines: Members and Global Binary Non-Member Operators -//----------------------------------------------------------------------------- - -// Create from NTBS UTF8 -inline cUTF8::cUTF8( const char* psz ) THROW( std::bad_alloc ) -: mUnicodeStr( cUTF8::allocate( psz ) ), - mUTF8Str( 0 ), - mUTF8WideStr( 0 ) -{ - ASSERT( mUnicodeStr || mUTF8Str ); -} - -// Create from NTWCS UNICODE -inline cUTF8::cUTF8( const wchar_t* wsz ) THROW( std::bad_alloc ) -: mUnicodeStr( 0 ), - mUTF8Str( cUTF8::allocate( wsz ) ), - mUTF8WideStr( 0 ) -{ - ASSERT( mUnicodeStr || mUTF8Str ); -} - -inline cUTF8::~cUTF8() -{ - delete [] mUnicodeStr; // Delete UNICODE (if exists) - delete [] mUTF8Str; // Delete UTF8 (NTBS) - delete [] mUTF8WideStr; // Delete UTF8 (NTWCS) -} - - -/// Operators - -inline std::ostream& operator<<( std::ostream& out, const cUTF8& str ) -{ - out << str.str(); - return out; -} - -inline std::wostream& operator<<( std::wostream& wout, const cUTF8& str ) -{ - wout << str.wstr(); // CAUTION: Don't send UNICODE string, it won't display! - return wout; -} - - -#endif //_UNICODE - -#endif/*_TSS_UTF8_H*/ - diff --git a/src/core/wchar16.cpp b/src/core/wchar16.cpp index f7e465d..efc9647 100644 --- a/src/core/wchar16.cpp +++ b/src/core/wchar16.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,7 +40,7 @@ #include "debug.h" #include // for stl::out_of_range #ifdef HAVE_MEMORY_H -# include +#include #endif int wchar16len(const WCHAR16* s) @@ -55,8 +55,8 @@ int wchar16len(const WCHAR16* s) //============================================================================= // class wc16_string // -// This clas implements enough of the std::basic_string interface so we -// can use it like an STL string. +// This clas implements enough of the std::basic_string interface so we +// can use it like an STL string. // // In an ideal world we this would be a std::basic_string instantiation, but // UNIX doesn't seem to dealing 16 bit wide chars, it uses 32 bit chars. @@ -76,17 +76,19 @@ class wc16_string_impl void Release(); void Resize(int newlen); void CopyString(const wc16_string_impl& rhs); - // note: does not alter this->referenceCount, and ASSERTs that refcount == 1 + // note: does not alter this->referenceCount, and ASSERTs that refcount == 1 - ~wc16_string_impl(); // call Release() to delete + ~wc16_string_impl(); // call Release() to delete private: - void operator = (const wc16_string_impl& rhs) { return; } // don't call + void operator=(const wc16_string_impl& rhs) + { + return; + } // don't call }; static WCHAR16 NULL_WCHAR16 = 0; -wc16_string::wc16_string() -: mpData(0) +wc16_string::wc16_string() : mpData(0) { } @@ -112,42 +114,39 @@ wc16_string::~wc16_string() mpData->Release(); } -void wc16_string::operator = (const wc16_string& rhs) +void wc16_string::operator=(const wc16_string& rhs) { if (mpData) mpData->Release(); mpData = rhs.mpData; - if( mpData ) + if (mpData) mpData->AddRef(); } int wc16_string::compare(const wc16_string& rhs) const { - if( length() > rhs.length() ) + if (length() > rhs.length()) return 1; - else if ( length() < rhs.length() ) + else if (length() < rhs.length()) return -1; else - return memcmp( c_str(), rhs.c_str(), length()*sizeof( WCHAR16 ) ); + return memcmp(c_str(), rhs.c_str(), length() * sizeof(WCHAR16)); } -wc16_string::size_type -wc16_string::length() const +wc16_string::size_type wc16_string::length() const { return mpData ? mpData->length : 0; } -wc16_string::size_type -wc16_string::size() const +wc16_string::size_type wc16_string::size() const { return mpData ? mpData->length : 0; } -wc16_string::const_iterator -wc16_string::c_str() const +wc16_string::const_iterator wc16_string::c_str() const { if (mpData == 0) return &NULL_WCHAR16; @@ -157,35 +156,24 @@ wc16_string::c_str() const return mpData->pString; } -wc16_string::const_iterator -wc16_string::begin() const +wc16_string::const_iterator wc16_string::begin() const { return (const_cast(this))->begin(); } -wc16_string::iterator -wc16_string::begin() +wc16_string::iterator wc16_string::begin() { return mpData ? mpData->pString : &NULL_WCHAR16; } -wc16_string::const_iterator -wc16_string::end() const +wc16_string::const_iterator wc16_string::end() const { - return - const_cast< iterator >( - mpData - ? mpData->pString + mpData->length - : &NULL_WCHAR16 ); + return const_cast(mpData ? mpData->pString + mpData->length : &NULL_WCHAR16); } -wc16_string::iterator -wc16_string::end() +wc16_string::iterator wc16_string::end() { - return - mpData - ? mpData->pString + mpData->length - : &NULL_WCHAR16; + return mpData ? mpData->pString + mpData->length : &NULL_WCHAR16; } wc16_string::const_iterator wc16_string::data() const @@ -193,7 +181,7 @@ wc16_string::const_iterator wc16_string::data() const return begin(); } -const wc16_string::value_type& wc16_string::operator [] (int i) const +const wc16_string::value_type& wc16_string::operator[](int i) const { ASSERT(i >= 0); @@ -206,7 +194,7 @@ const wc16_string::value_type& wc16_string::operator [] (int i) const return mpData->pString[i]; } -wc16_string::value_type& wc16_string::operator [] (int i) +wc16_string::value_type& wc16_string::operator[](int i) { ASSERT(i >= 0); @@ -222,24 +210,24 @@ wc16_string::value_type& wc16_string::operator [] (int i) mpData->Release(); mpData = newImpl; } - + return mpData->pString[i]; } -void wc16_string::resize( size_type nCount ) +void wc16_string::resize(size_type nCount) { - if ( mpData == 0 ) + if (mpData == 0) { mpData = new wc16_string_impl; } - else if ( mpData->refCount > 1 ) + else if (mpData->refCount > 1) { - wc16_string_impl* newImpl = new wc16_string_impl( *mpData ); + wc16_string_impl* newImpl = new wc16_string_impl(*mpData); mpData->Release(); mpData = newImpl; } - mpData->Resize( nCount ); + mpData->Resize(nCount); } // useful to convert to network byte order @@ -264,17 +252,17 @@ void wc16_string::swapbytes() wc16_string_impl::wc16_string_impl() { - length = 0; - pString = new WCHAR16[1]; + length = 0; + pString = new WCHAR16[1]; refCount = 1; } wc16_string_impl::wc16_string_impl(const wc16_string_impl& rhs) { int newlen = rhs.length; - pString = new WCHAR16[newlen + 1]; - length = newlen; - refCount = 1; + pString = new WCHAR16[newlen + 1]; + length = newlen; + refCount = 1; memcpy(pString, rhs.pString, newlen * sizeof(WCHAR16)); } @@ -306,13 +294,13 @@ void wc16_string_impl::Resize(int newlen) return; WCHAR16* newString = new WCHAR16[newlen + 1]; - + if (newlen < length) { memcpy(newString, pString, newlen * sizeof(WCHAR16)); delete [] pString; pString = newString; - length = newlen; + length = newlen; } else { @@ -320,7 +308,7 @@ void wc16_string_impl::Resize(int newlen) memset(newString + length, 0, (newlen - length) * sizeof(WCHAR16)); delete [] pString; pString = newString; - length = newlen; + length = newlen; } } @@ -333,10 +321,9 @@ void wc16_string_impl::CopyString(const wc16_string_impl& rhs) if (rhs.length != this->length) { delete [] pString; - pString = new WCHAR16[newlen + 1]; + pString = new WCHAR16[newlen + 1]; this->length = newlen; } memcpy(this->pString, rhs.pString, newlen * sizeof(WCHAR16)); } - diff --git a/src/core/wchar16.h b/src/core/wchar16.h index 74abe7f..10bed6f 100644 --- a/src/core/wchar16.h +++ b/src/core/wchar16.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,16 +44,16 @@ #endif #if WCHAR_IS_16_BITS -typedef unsigned short WCHAR16; +typedef unsigned short WCHAR16; #else -typedef uint16 WCHAR16; // unix has 4 byte wchar_t, but we want to standardize on 16 bit wide chars +typedef uint16 WCHAR16; // unix has 4 byte wchar_t, but we want to standardize on 16 bit wide chars #endif //============================================================================= // class wc16_string // -// This clas implements enough of the std::basic_string interface so we -// can use it like an STL string. +// This clas implements enough of the std::basic_string interface so we +// can use it like an STL string. // // In an ideal world we this would be a std::basic_string instantiation, but // UNIX doesn't seem to dealing 16 bit wide chars, it uses 32 bit chars. @@ -70,49 +70,46 @@ class wc16_string_impl; class wc16_string { public: - - typedef WCHAR16 value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - typedef size_t size_type; + typedef WCHAR16 value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + typedef size_t size_type; wc16_string(); - wc16_string( const wc16_string& rhs); - wc16_string( const_iterator pStr); + wc16_string(const wc16_string& rhs); + wc16_string(const_iterator pStr); ~wc16_string(); - void operator=( const wc16_string& rhs ); - int compare( const wc16_string& rhs ) const; + void operator=(const wc16_string& rhs); + int compare(const wc16_string& rhs) const; + + size_type length() const; + size_type size() const; + + const_iterator begin() const; + iterator begin(); - size_type length() const; - size_type size() const; - - const_iterator begin() const; - iterator begin(); + const_iterator end() const; + iterator end(); - const_iterator end() const; - iterator end(); + const_iterator c_str() const; + const_iterator data() const; - const_iterator c_str() const; - const_iterator data() const; - bool empty() const - { + { return length() == 0; } - const value_type& operator[]( int i ) const; // throw std::out_of_range - value_type& operator[]( int i ); // throw std::out_of_range + const value_type& operator[](int i) const; // throw std::out_of_range + value_type& operator[](int i); // throw std::out_of_range - void resize( size_type ); - void swapbytes(); // useful to convert to network byte order + void resize(size_type); + void swapbytes(); // useful to convert to network byte order private: - wc16_string_impl* mpData; }; #endif - diff --git a/src/cryptlib/Makefile.am b/src/cryptlib/Makefile.am index 90ea8a1..156082d 100644 --- a/src/cryptlib/Makefile.am +++ b/src/cryptlib/Makefile.am @@ -1,18 +1,26 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. -I../.. +AM_CPPFLAGS = -I.. -I../.. LN=@LN@ DEFAULT_INCLUDES = $(D_INCLUDES) +EXTRA_DIST=license.txt readme.txt rmcr.pl noinst_LIBRARIES = libcryptlib.a +libcryptlib_adir=. libcryptlib_a_SOURCES = \ algebra.cpp asn.cpp cryptlib.cpp des.cpp dessp.cpp elgamal.cpp \ eprecomp.cpp filters.cpp forkjoin.cpp integer.cpp iterhash.cpp misc.cpp \ nbtheory.cpp pch.cpp queue.cpp rng.cpp sha.cpp zbits.cpp zdeflate.cpp \ zinflate.cpp ztrees.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../lib/libcryptlib.a +libcryptlib_a_HEADERS = \ + algebra.h asn.h config.h cryptlib.h des.h elgamal.h eprecomp.h filters.h \ + forkjoin.h integer.h iterhash.h misc.h modarith.h nbtheory.h pch.h \ + queue.h rng.h sha.h smartptr.h words.h zbits.h zdeflate.h zinflate.h \ + ztrees.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = ../../lib/libcryptlib.a *.gcno *.gcda all: $(noinst_LIBRARIES) $(LN) -f $(noinst_LIBRARIES) ../../lib/libcryptlib.a diff --git a/src/cryptlib/Makefile.in b/src/cryptlib/Makefile.in index b111e5f..4f6d772 100644 --- a/src/cryptlib/Makefile.in +++ b/src/cryptlib/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libcryptlib_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/cryptlib -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libcryptlib_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libcryptlib_a_AR = $(AR) $(ARFLAGS) libcryptlib_a_LIBADD = am_libcryptlib_a_OBJECTS = algebra.$(OBJEXT) asn.$(OBJEXT) \ @@ -60,22 +118,94 @@ am_libcryptlib_a_OBJECTS = algebra.$(OBJEXT) asn.$(OBJEXT) \ queue.$(OBJEXT) rng.$(OBJEXT) sha.$(OBJEXT) zbits.$(OBJEXT) \ zdeflate.$(OBJEXT) zinflate.$(OBJEXT) ztrees.$(OBJEXT) libcryptlib_a_OBJECTS = $(am_libcryptlib_a_OBJECTS) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libcryptlib_a_SOURCES) DIST_SOURCES = $(libcryptlib_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libcryptlib_adir)" +HEADERS = $(libcryptlib_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -91,7 +221,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -99,6 +229,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -110,6 +241,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -126,21 +258,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -170,23 +305,35 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. -I../.. +AM_CPPFLAGS = -I.. -I../.. DEFAULT_INCLUDES = $(D_INCLUDES) +EXTRA_DIST = license.txt readme.txt rmcr.pl noinst_LIBRARIES = libcryptlib.a +libcryptlib_adir = . libcryptlib_a_SOURCES = \ algebra.cpp asn.cpp cryptlib.cpp des.cpp dessp.cpp elgamal.cpp \ eprecomp.cpp filters.cpp forkjoin.cpp integer.cpp iterhash.cpp misc.cpp \ nbtheory.cpp pch.cpp queue.cpp rng.cpp sha.cpp zbits.cpp zdeflate.cpp \ zinflate.cpp ztrees.cpp -CLEANFILES = ../../lib/libcryptlib.a +libcryptlib_a_HEADERS = \ + algebra.h asn.h config.h cryptlib.h des.h elgamal.h eprecomp.h filters.h \ + forkjoin.h integer.h iterhash.h misc.h modarith.h nbtheory.h pch.h \ + queue.h rng.h sha.h smartptr.h words.h zbits.h zdeflate.h zinflate.h \ + ztrees.h + +CLEANFILES = ../../lib/libcryptlib.a *.gcno *.gcda all: all-am .SUFFIXES: @@ -195,15 +342,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cryptlib/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/cryptlib/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cryptlib/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/cryptlib/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -220,13 +366,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libcryptlib.a: $(libcryptlib_a_OBJECTS) $(libcryptlib_a_DEPENDENCIES) - -rm -f libcryptlib.a - $(libcryptlib_a_AR) libcryptlib.a $(libcryptlib_a_OBJECTS) $(libcryptlib_a_LIBADD) - $(RANLIB) libcryptlib.a + +libcryptlib.a: $(libcryptlib_a_OBJECTS) $(libcryptlib_a_DEPENDENCIES) $(EXTRA_libcryptlib_a_DEPENDENCIES) + $(AM_V_at)-rm -f libcryptlib.a + $(AM_V_AR)$(libcryptlib_a_AR) libcryptlib.a $(libcryptlib_a_OBJECTS) $(libcryptlib_a_LIBADD) + $(AM_V_at)$(RANLIB) libcryptlib.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -235,91 +383,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libcryptlib_aHEADERS: $(libcryptlib_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libcryptlib_a_HEADERS)'; test -n "$(libcryptlib_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libcryptlib_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libcryptlib_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libcryptlib_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libcryptlib_adir)" || exit $$?; \ + done + +uninstall-libcryptlib_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libcryptlib_a_HEADERS)'; test -n "$(libcryptlib_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libcryptlib_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libcryptlib_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -330,17 +508,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -360,18 +544,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libcryptlib_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -390,22 +594,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libcryptlib_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libcryptlib_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libcryptlib_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(LN) -f $(noinst_LIBRARIES) ../../lib/libcryptlib.a + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/cryptlib/asn.cpp b/src/cryptlib/asn.cpp index 88b015e..d5265e6 100644 --- a/src/cryptlib/asn.cpp +++ b/src/cryptlib/asn.cpp @@ -3,6 +3,8 @@ #include "pch.h" #include "asn.h" #include "misc.h" +#include +#include unsigned int DERLengthEncode(unsigned int length, byte *output) { @@ -87,7 +89,11 @@ BERSequenceDecoder::~BERSequenceDecoder() { // remove end-of-content octects word16 i; if (!inQueue.GetShort(i) || (i!=0)) - BERDecodeError(); + { + fputs("### Internal Error.\n### Invalid or corrupt key.\n### Exiting...\n\ +", stderr); + exit(1); + } } } diff --git a/src/cryptlib/filters.cpp b/src/cryptlib/filters.cpp index b3dbfee..ef47f2a 100644 --- a/src/cryptlib/filters.cpp +++ b/src/cryptlib/filters.cpp @@ -5,6 +5,12 @@ #include "queue.h" #include +#if __cplusplus >= 201103L +# define TW_UNIQUE_PTR std::unique_ptr +#else +# define TW_UNIQUE_PTR std::auto_ptr +#endif + Filter::Filter(BufferedTransformation *outQ) : outQueue(outQ ? outQ : new ByteQueue) { @@ -17,7 +23,7 @@ Filter::Filter(const Filter &source) void Filter::Detach(BufferedTransformation *newOut) { - std::auto_ptr out(newOut ? newOut : new ByteQueue); + TW_UNIQUE_PTR out(newOut ? newOut : new ByteQueue); outQueue->Close(); outQueue->TransferTo(*out); outQueue.reset(out.release()); diff --git a/src/cryptlib/forkjoin.cpp b/src/cryptlib/forkjoin.cpp index 054cc47..899ec85 100644 --- a/src/cryptlib/forkjoin.cpp +++ b/src/cryptlib/forkjoin.cpp @@ -5,6 +5,12 @@ #include "queue.h" #include +#if __cplusplus >= 201103L +# define TW_UNIQUE_PTR std::unique_ptr +#else +# define TW_UNIQUE_PTR std::auto_ptr +#endif + Fork::Fork(int n, BufferedTransformation *const *givenOutPorts) : numberOfPorts(n), outPorts(n) { @@ -21,7 +27,7 @@ void Fork::SelectOutPort(int portNumber) void Fork::Detach(BufferedTransformation *newOut) { - std::auto_ptr out(newOut ? newOut : new ByteQueue); + TW_UNIQUE_PTR out(newOut ? newOut : new ByteQueue); outPorts[currentPort]->Close(); outPorts[currentPort]->TransferTo(*out); outPorts[currentPort].reset(out.release()); diff --git a/src/cryptlib/misc.h b/src/cryptlib/misc.h index 467a7a7..d390fa2 100644 --- a/src/cryptlib/misc.h +++ b/src/cryptlib/misc.h @@ -9,7 +9,8 @@ #include #endif -#ifdef __MINT__ // has memory.h, but memset defined in string.h anyway. +#if defined(__MINT__) || defined(__DJGPP__) + // OS has memory.h, but memset defined in string.h anyway. #include #endif diff --git a/src/cryptlib/zdeflate.cpp b/src/cryptlib/zdeflate.cpp index 8a4302a..60d74e3 100644 --- a/src/cryptlib/zdeflate.cpp +++ b/src/cryptlib/zdeflate.cpp @@ -236,7 +236,7 @@ int Deflator::longest_match(IPos cur_match) if (prev_length >= good_match) { chain_length >>= 2; } - assert(strstart <= (unsigned)WINDOW_SIZE-MIN_LOOKAHEAD); + //assert(strstart <= (unsigned)WINDOW_SIZE-MIN_LOOKAHEAD); do { assert(cur_match < strstart); diff --git a/src/db/Makefile.am b/src/db/Makefile.am index 4a436e3..68a57ed 100644 --- a/src/db/Makefile.am +++ b/src/db/Makefile.am @@ -1,13 +1,19 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libdb.a +libdb_adir=. libdb_a_SOURCES = \ blockfile.cpp blockrecordarray.cpp blockrecordfile.cpp \ - db.cpp hierdatabase.cpp hierdbpath.cpp stddb.cpp + db.cpp dberrors.cpp hierdatabase.cpp hierdbpath.cpp stddb.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +libdb_a_HEADERS = \ + block.h blockfile.h blockrecordarray.h blockrecordfile.h \ + db.h dberrors.h hierdatabase.h hierdbnode.h hierdbpath.h stddb.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libdb_a_OBJECTS) diff --git a/src/db/Makefile.in b/src/db/Makefile.in index 42685bc..c875d47 100644 --- a/src/db/Makefile.in +++ b/src/db/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libdb_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,43 +87,122 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/db -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libdb_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libdb_a_AR = $(AR) $(ARFLAGS) libdb_a_LIBADD = am_libdb_a_OBJECTS = blockfile.$(OBJEXT) blockrecordarray.$(OBJEXT) \ - blockrecordfile.$(OBJEXT) db.$(OBJEXT) hierdatabase.$(OBJEXT) \ - hierdbpath.$(OBJEXT) stddb.$(OBJEXT) + blockrecordfile.$(OBJEXT) db.$(OBJEXT) dberrors.$(OBJEXT) \ + hierdatabase.$(OBJEXT) hierdbpath.$(OBJEXT) stddb.$(OBJEXT) libdb_a_OBJECTS = $(am_libdb_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libdb_a_SOURCES) DIST_SOURCES = $(libdb_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdb_adir)" +HEADERS = $(libdb_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -88,7 +218,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -96,6 +226,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -107,6 +238,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -123,21 +255,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -167,19 +302,29 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libdb.a +libdb_adir = . libdb_a_SOURCES = \ blockfile.cpp blockrecordarray.cpp blockrecordfile.cpp \ - db.cpp hierdatabase.cpp hierdbpath.cpp stddb.cpp + db.cpp dberrors.cpp hierdatabase.cpp hierdbpath.cpp stddb.cpp + +libdb_a_HEADERS = \ + block.h blockfile.h blockrecordarray.h blockrecordfile.h \ + db.h dberrors.h hierdatabase.h hierdbnode.h hierdbpath.h stddb.h +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -188,15 +333,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/db/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/db/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/db/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/db/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -213,13 +357,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libdb.a: $(libdb_a_OBJECTS) $(libdb_a_DEPENDENCIES) - -rm -f libdb.a - $(libdb_a_AR) libdb.a $(libdb_a_OBJECTS) $(libdb_a_LIBADD) - $(RANLIB) libdb.a + +libdb.a: $(libdb_a_OBJECTS) $(libdb_a_DEPENDENCIES) $(EXTRA_libdb_a_DEPENDENCIES) + $(AM_V_at)-rm -f libdb.a + $(AM_V_AR)$(libdb_a_AR) libdb.a $(libdb_a_OBJECTS) $(libdb_a_LIBADD) + $(AM_V_at)$(RANLIB) libdb.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -228,91 +374,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libdb_aHEADERS: $(libdb_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libdb_a_HEADERS)'; test -n "$(libdb_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libdb_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libdb_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libdb_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libdb_adir)" || exit $$?; \ + done + +uninstall-libdb_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libdb_a_HEADERS)'; test -n "$(libdb_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libdb_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libdb_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -323,16 +499,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -352,18 +535,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libdb_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -382,22 +585,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libdb_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libdb_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libdb_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libdb_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/db/block.h b/src/db/block.h index fca863f..1a97825 100644 --- a/src/db/block.h +++ b/src/db/block.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,78 +45,87 @@ //----------------------------------------------------------------------------- // cBlock //----------------------------------------------------------------------------- -template -class cBlock +template class cBlock { public: - enum { INVALID_NUM = -1 }; + enum + { + INVALID_NUM = -1 + }; cBlock(); - void SetDirty () { mbDirty = true; } - bool IsDirty () const { return mbDirty; } - int GetBlockNum () const { return mBlockNum; } - int8* GetData() { return mpData; } - - bool AssertValid() const; - // this asserts and returns false if the guard bytes have been corrupted - bool IsValidAddr(int8* pAddr) const; - // returns true if pAddr falls within mpData + void SetDirty() + { + mbDirty = true; + } + bool IsDirty() const + { + return mbDirty; + } + int GetBlockNum() const + { + return mBlockNum; + } + int8* GetData() + { + return mpData; + } + + bool AssertValid() const; + // this asserts and returns false if the guard bytes have been corrupted + bool IsValidAddr(int8* pAddr) const; + // returns true if pAddr falls within mpData protected: - enum { NUM_GUARD_BLOCKS = 8, // associated with BYTE_ALIGN: see ctor for info - GUARD_BLOCK_VAL = 0xAB }; // odd, non-zero value for debugging + enum + { + NUM_GUARD_BLOCKS = 8, // associated with BYTE_ALIGN: see ctor for info + GUARD_BLOCK_VAL = 0xAB + }; // odd, non-zero value for debugging // guardMin and guardMax are used to detect bad writes - uint8 mGuardMin[NUM_GUARD_BLOCKS]; - int8 mpData[SIZE]; - uint8 mGuardMax[NUM_GUARD_BLOCKS]; - bool mbDirty; - int mBlockNum; + uint8 mGuardMin[NUM_GUARD_BLOCKS]; + int8 mpData[SIZE]; + uint8 mGuardMax[NUM_GUARD_BLOCKS]; + bool mbDirty; + int mBlockNum; }; /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -template -inline cBlock::cBlock() -: mbDirty (false), - mBlockNum (cBlock::INVALID_NUM) +template inline cBlock::cBlock() : mbDirty(false), mBlockNum(cBlock::INVALID_NUM) { - // To prevent misaligned memory access, the size of the data and the - // number of guard blocks must be a multiple of the byte alignment + // To prevent misaligned memory access, the size of the data and the + // number of guard blocks must be a multiple of the byte alignment // and they both must be at least as large as the byte alignment - ASSERT( 0 == ( SIZE % BYTE_ALIGN ) ); - ASSERT( 0 == ( NUM_GUARD_BLOCKS % BYTE_ALIGN ) ); - ASSERT( SIZE >= BYTE_ALIGN ); - ASSERT( NUM_GUARD_BLOCKS >= BYTE_ALIGN ); - + ASSERT(0 == (SIZE % BYTE_ALIGN)); + ASSERT(0 == (NUM_GUARD_BLOCKS % BYTE_ALIGN)); + ASSERT(SIZE >= BYTE_ALIGN); + ASSERT(NUM_GUARD_BLOCKS >= BYTE_ALIGN); + // init guard blocks to dummy value - for( int i = 0; i < NUM_GUARD_BLOCKS; i++ ) + for (int i = 0; i < NUM_GUARD_BLOCKS; i++) { mGuardMin[i] = (uint8)GUARD_BLOCK_VAL; mGuardMax[i] = (uint8)GUARD_BLOCK_VAL; } // zero out memory - memset( mpData, 0, SIZE ); + memset(mpData, 0, SIZE); } /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -template -inline bool cBlock::AssertValid() const +template inline bool cBlock::AssertValid() const { // determine if guard bites have been accidentally overwritten - for( int i = 0; i < NUM_GUARD_BLOCKS; i++ ) + for (int i = 0; i < NUM_GUARD_BLOCKS; i++) { - if( - ( mGuardMin[i] != (uint8) GUARD_BLOCK_VAL ) - || - ( mGuardMax[i] != (uint8) GUARD_BLOCK_VAL ) - ) + if ((mGuardMin[i] != (uint8)GUARD_BLOCK_VAL) || (mGuardMax[i] != (uint8)GUARD_BLOCK_VAL)) { - ASSERT( false ); + ASSERT(false); return false; } } @@ -124,56 +133,62 @@ inline bool cBlock::AssertValid() const return true; } -template -inline bool cBlock::IsValidAddr(int8* pAddr) const +template inline bool cBlock::IsValidAddr(int8* pAddr) const { - return ( (pAddr >= &mpData[0]) && (pAddr <= &mpData[SIZE-1]) ); + return ((pAddr >= &mpData[0]) && (pAddr <= &mpData[SIZE - 1])); } //----------------------------------------------------------------------------- // cBlockImpl //----------------------------------------------------------------------------- -template -class cBlockImpl : public cBlock +template class cBlockImpl : public cBlock { public: - enum { INVALID_NUM = -1 }; + enum + { + INVALID_NUM = -1 + }; cBlockImpl(); - void SetBlockNum ( int blockNum ) { cBlock::mBlockNum = blockNum; } - void SetTimestamp( uint32 timestamp ) { mTimestamp = timestamp; } - uint32 GetTimestamp() const { return mTimestamp; } + void SetBlockNum(int blockNum) + { + cBlock::mBlockNum = blockNum; + } + void SetTimestamp(uint32 timestamp) + { + mTimestamp = timestamp; + } + uint32 GetTimestamp() const + { + return mTimestamp; + } - void Write ( cBidirArchive& arch ); //throw( eArchive ) - void Read ( cBidirArchive& arch, int blockNum = INVALID_NUM ); //throw( eArchive ) + void Write(cBidirArchive& arch); //throw( eArchive ) + void Read(cBidirArchive& arch, int blockNum = INVALID_NUM); //throw( eArchive ) // if blockNum is INVALID_NUM, then it reads in the current block number protected: - uint32 mTimestamp; + uint32 mTimestamp; }; /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -template -inline cBlockImpl::cBlockImpl() -: cBlock ( ), - mTimestamp (0) +template inline cBlockImpl::cBlockImpl() : cBlock(), mTimestamp(0) { } /////////////////////////////////////////////////////////////////////////////// // Write /////////////////////////////////////////////////////////////////////////////// -template -inline void cBlockImpl::Write( cBidirArchive& arch ) //throw( eArchive ) +template inline void cBlockImpl::Write(cBidirArchive& arch) //throw( eArchive ) { - ASSERT( mbDirty ); - ASSERT( (mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()) ); + ASSERT(mbDirty); + ASSERT((mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length())); - arch.Seek ( (cBlock::mBlockNum * SIZE), cBidirArchive::BEGINNING ); - arch.WriteBlob ( cBlock::mpData, SIZE ); + arch.Seek((cBlock::mBlockNum * SIZE), cBidirArchive::BEGINNING); + arch.WriteBlob(cBlock::mpData, SIZE); cBlock::mbDirty = false; } @@ -181,21 +196,19 @@ inline void cBlockImpl::Write( cBidirArchive& arch ) //throw( eArchive ) /////////////////////////////////////////////////////////////////////////////// // Read /////////////////////////////////////////////////////////////////////////////// -template -inline void cBlockImpl::Read( cBidirArchive& arch, int blockNum ) //throw( eArchive ) +template inline void cBlockImpl::Read(cBidirArchive& arch, int blockNum) //throw( eArchive ) { - if( blockNum != INVALID_NUM ) + if (blockNum != INVALID_NUM) cBlock::mBlockNum = blockNum; - ASSERT( (mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()) ); + ASSERT((mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length())); -// std::cout << "cBlockImpl::Read() mBlockNum = " << mBlockNum << " arch.Length() = " << arch.Length() << std::endl; + // std::cout << "cBlockImpl::Read() mBlockNum = " << mBlockNum << " arch.Length() = " << arch.Length() << std::endl; - arch.Seek ( (cBlock::mBlockNum * SIZE), cBidirArchive::BEGINNING ); - arch.ReadBlob ( cBlock::mpData, SIZE ); + arch.Seek((cBlock::mBlockNum * SIZE), cBidirArchive::BEGINNING); + arch.ReadBlob(cBlock::mpData, SIZE); cBlock::mbDirty = false; } #endif - diff --git a/src/db/blockfile.cpp b/src/db/blockfile.cpp index b936bb4..1fb588c 100644 --- a/src/db/blockfile.cpp +++ b/src/db/blockfile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,7 +35,7 @@ #include "stddb.h" #ifndef __TCHAR_H -#error +# error #endif #include "blockfile.h" @@ -52,18 +52,14 @@ /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cBlockFile::cBlockFile() -: mNumPages (-1), - mNumBlocks (-1), - mTimer (0), - mpArchive (0) +cBlockFile::cBlockFile() : mNumPages(-1), mNumBlocks(-1), mTimer(0), mpArchive(0) { #ifdef _BLOCKFILE_DEBUG - mNumBlockWrite = 0; - mNumBlockRead = 0; - mNumPageFault = 0; - mNumPageRequests = 0; + mNumBlockWrite = 0; + mNumBlockRead = 0; + mNumPageFault = 0; + mNumPageRequests = 0; #endif //_BLOCKFILE_DEBUG } @@ -79,44 +75,44 @@ cBlockFile::~cBlockFile() /////////////////////////////////////////////////////////////////////////////// // Open /////////////////////////////////////////////////////////////////////////////// -void cBlockFile::Open( const TSTRING& fileName, int numPages, bool bTruncate) //throw (eArchive) +void cBlockFile::Open(const TSTRING& fileName, int numPages, bool bTruncate) //throw (eArchive) { - ASSERT( numPages > 0 ); - ASSERT( ! mpArchive ); - + ASSERT(numPages > 0); + ASSERT(!mpArchive); + cFileArchive* pArch = new cFileArchive; - pArch->OpenReadWrite( fileName.c_str(), ( bTruncate ? cFileArchive::FA_OPEN_TRUNCATE : 0 ) ); - - Open( pArch, numPages ); + pArch->OpenReadWrite(fileName.c_str(), (bTruncate ? cFileArchive::FA_OPEN_TRUNCATE : 0)); + + Open(pArch, numPages); } -void cBlockFile::Open( cBidirArchive* pArch, int numPages ) //throw (eArchive) +void cBlockFile::Open(cBidirArchive* pArch, int numPages) //throw (eArchive) { - ASSERT( numPages > 0 ); - ASSERT( ! mpArchive ); + ASSERT(numPages > 0); + ASSERT(!mpArchive); // // keep my sanity... // - pArch->Seek( 0, cBidirArchive::BEGINNING ); + pArch->Seek(0, cBidirArchive::BEGINNING); // // initialize the paged blocks list... // - mpArchive = pArch; - mNumPages = numPages; - mvPagedBlocks.resize( mNumPages ); - ASSERT( mvPagedBlocks.capacity() == mNumPages ); // make sure that we didn't alloc too many! + mpArchive = pArch; + mNumPages = numPages; + mvPagedBlocks.resize(mNumPages); + ASSERT(mvPagedBlocks.capacity() == mNumPages); // make sure that we didn't alloc too many! // // if the file is newly created, set its size to that of a single block // - if( mpArchive->Length() == 0 ) + if (mpArchive->Length() == 0) { - mpArchive->WriteBlob( mvPagedBlocks[0].GetData(), GetBlockSize() ); + mpArchive->WriteBlob(mvPagedBlocks[0].GetData(), GetBlockSize()); } // // make sure that the file is an appropriate length // TODO -- what is the correct thing to do if this fails? right now, I assert, but // perhaps I should throw an exception or increase the file size to the next block interval - ASSERT( mpArchive->Length() % GetBlockSize() == 0 ); + ASSERT(mpArchive->Length() % GetBlockSize() == 0); mNumBlocks = mpArchive->Length() / GetBlockSize(); } @@ -126,7 +122,7 @@ void cBlockFile::Open( cBidirArchive* pArch, int numPages ) //throw (eArchive) /////////////////////////////////////////////////////////////////////////////// void cBlockFile::Close() { - if( mpArchive ) + if (mpArchive) { Flush(); delete mpArchive; @@ -139,17 +135,17 @@ void cBlockFile::Close() /////////////////////////////////////////////////////////////////////////////// void cBlockFile::Flush() { - ASSERT( mpArchive ); - for( BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++ ) + ASSERT(mpArchive); + for (BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); ++i) { - FlushBlock( &(*i) ); + FlushBlock(&(*i)); } } /////////////////////////////////////////////////////////////////////////////// // GetBlock /////////////////////////////////////////////////////////////////////////////// -cBlockFile::Block* cBlockFile::GetBlock( int blockNum ) //throw (eArchive) +cBlockFile::Block* cBlockFile::GetBlock(int blockNum) //throw (eArchive) { #ifdef _BLOCKFILE_DEBUG mNumPageRequests++; @@ -158,71 +154,71 @@ cBlockFile::Block* cBlockFile::GetBlock( int blockNum ) //throw (eArchive) // // debug stuff // - cDebug d( "cBlockFile::GetBlock" ); - d.TraceNever( "Request for block %d\n", blockNum ); - + cDebug d("cBlockFile::GetBlock"); + d.TraceNever("Request for block %d\n", blockNum); + //TODO -- I should really throw an exception here... - ASSERT( (blockNum >= 0) && (blockNum < GetNumBlocks()) ); - ASSERT( mpArchive ); + ASSERT((blockNum >= 0) && (blockNum < GetNumBlocks())); + ASSERT(mpArchive); // // first, increment the timer; if it flips, reset everybody's access times to 0. // mTimer++; - if( mTimer == 0 ) + if (mTimer == 0) { - for( BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++ ) + for (BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); ++i) { - i->SetTimestamp( 0 ); + i->SetTimestamp(0); } } // // now, see if the desired block is in memory... // - for( BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++ ) + for (BlockVector::iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); ++i) { - if( i->GetBlockNum() == blockNum ) + if (i->GetBlockNum() == blockNum) { // this is easy; just return the block. - i->SetTimestamp( mTimer ); - d.TraceNever( "\tBlock %d was in memory.\n", blockNum ); + i->SetTimestamp(mTimer); + d.TraceNever("\tBlock %d was in memory.\n", blockNum); return &(*i); } } // - // ok, we are going to have to page it into memory; look for the page with the earliest timestamp to + // ok, we are going to have to page it into memory; look for the page with the earliest timestamp to // remove... // #ifdef _BLOCKFILE_DEBUG mNumPageFault++; #endif - d.TraceNever( "\tBlock %d was not in memory; paging it in\n", blockNum ); - - uint32 earliestTime = mvPagedBlocks[0].GetTimestamp(); - BlockVector::iterator it = mvPagedBlocks.begin(); - BlockVector::iterator earliestIter = it; - it++; // since we don't want to check the first one + d.TraceNever("\tBlock %d was not in memory; paging it in\n", blockNum); + + uint32 earliestTime = mvPagedBlocks[0].GetTimestamp(); + BlockVector::iterator it = mvPagedBlocks.begin(); + BlockVector::iterator earliestIter = it; + ++it; // since we don't want to check the first one ASSERT(it != mvPagedBlocks.end()); - for( ; it != mvPagedBlocks.end(); it++ ) + for (; it != mvPagedBlocks.end(); ++it) { - if( it->GetTimestamp() < earliestTime ) + if (it->GetTimestamp() < earliestTime) { earliestIter = it; earliestTime = it->GetTimestamp(); } } - ASSERT( (earliestIter >= mvPagedBlocks.begin()) && (earliestIter < mvPagedBlocks.end()) ); + ASSERT((earliestIter >= mvPagedBlocks.begin()) && (earliestIter < mvPagedBlocks.end())); // // flush the page data to disk if it is dirty... // - FlushBlock( &(*earliestIter) ); - d.TraceNever( "\tPaging out block %d\n", earliestIter->GetBlockNum() ); + FlushBlock(&(*earliestIter)); + d.TraceNever("\tPaging out block %d\n", earliestIter->GetBlockNum()); // // ok, now we can read in the new page... // - earliestIter->SetBlockNum ( blockNum ); - earliestIter->Read ( *mpArchive ); - earliestIter->SetTimestamp ( mTimer ); + earliestIter->SetBlockNum(blockNum); + earliestIter->Read(*mpArchive); + earliestIter->SetTimestamp(mTimer); // // this variable keeps track of how many block reads we do. #ifdef _BLOCKFILE_DEBUG @@ -230,7 +226,6 @@ cBlockFile::Block* cBlockFile::GetBlock( int blockNum ) //throw (eArchive) AssertValid(); #endif return &(*earliestIter); - } /////////////////////////////////////////////////////////////////////////////// @@ -240,34 +235,34 @@ cBlockFile::Block* cBlockFile::CreateBlock() { // debug stuff // - ASSERT( mpArchive ); - cDebug d( "cBlockFile::CreateBlock()" ); - d.TraceDetail( "Creating new block (number %d)\n", GetNumBlocks() ); - + ASSERT(mpArchive); + cDebug d("cBlockFile::CreateBlock()"); + d.TraceDetail("Creating new block (number %d)\n", GetNumBlocks()); + char emptyBlock[BLOCK_SIZE]; - memset( emptyBlock, 0, BLOCK_SIZE ); + memset(emptyBlock, 0, BLOCK_SIZE); // // write empty data in the new block's location // //ASSERT(GetNumBlocks() * GetBlockSize() <= mpArchive->Length()); d.TraceDetail("Seeking to %d * %d = %d\n", GetNumBlocks(), GetBlockSize(), GetNumBlocks() * GetBlockSize()); - mpArchive->Seek ( GetNumBlocks() * GetBlockSize(), cBidirArchive::BEGINNING ); - mpArchive->WriteBlob ( emptyBlock, BLOCK_SIZE ); + mpArchive->Seek(GetNumBlocks() * GetBlockSize(), cBidirArchive::BEGINNING); + mpArchive->WriteBlob(emptyBlock, BLOCK_SIZE); // // now, page it in... // mNumBlocks++; - return GetBlock( GetNumBlocks() - 1 ); + return GetBlock(GetNumBlocks() - 1); } /////////////////////////////////////////////////////////////////////////////// // DestroyLastBlock /////////////////////////////////////////////////////////////////////////////// -void cBlockFile::DestroyLastBlock( ) +void cBlockFile::DestroyLastBlock() { //TODO -- implement this!!! - ASSERT( false ); -/* + ASSERT(false); + /* mNumBlocks--; mpArchive->Seek( mNumBlocks * BLOCK_SIZE, cBidirArchive::BEGINNING ); mpArchive->Truncate(); @@ -287,33 +282,37 @@ void cBlockFile::DestroyLastBlock( ) /////////////////////////////////////////////////////////////////////////////// void cBlockFile::TraceContents(int dl) const { - cDebug d( "cBlockFile::TraceContents" ); - if( dl == -1 ) + cDebug d("cBlockFile::TraceContents"); + if (dl == -1) dl = cDebug::D_DEBUG; - d.Trace( dl, "Block size: %d\n", GetBlockSize() ); - d.Trace( dl, "Number of blocks: %d\n", mNumBlocks ); - d.Trace( dl, "Current timer: %d\n", mTimer ); + d.Trace(dl, "Block size: %d\n", GetBlockSize()); + d.Trace(dl, "Number of blocks: %d\n", mNumBlocks); + d.Trace(dl, "Current timer: %d\n", mTimer); // // trace out the profiling info... // - d.Trace( dl, "Number of page writes: %d\n", mNumBlockWrite ); - d.Trace( dl, "Number of page reads: %d\n", mNumBlockRead ); - d.Trace( dl, "Number of page faults: %d\n", mNumPageFault ); - d.Trace( dl, "Number of page requests:%d\n", mNumPageRequests ); - - d.Trace( dl, "Number of pages: %d\n", mNumPages ); - d.Trace( dl, "-------------------------\n"); + d.Trace(dl, "Number of page writes: %d\n", mNumBlockWrite); + d.Trace(dl, "Number of page reads: %d\n", mNumBlockRead); + d.Trace(dl, "Number of page faults: %d\n", mNumPageFault); + d.Trace(dl, "Number of page requests:%d\n", mNumPageRequests); + + d.Trace(dl, "Number of pages: %d\n", mNumPages); + d.Trace(dl, "-------------------------\n"); // // trace out all the block information... // int cnt = 0; - for( BlockVector::const_iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++, cnt++ ) + for (BlockVector::const_iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++, cnt++) { - d.Trace( dl, "Page[%d] Block Num=%d Timestamp=%d Dirty=%s\n", cnt, i->GetBlockNum(), i->GetTimestamp(), i->IsDirty() ? "true" : "false"); + d.Trace(dl, + "Page[%d] Block Num=%d Timestamp=%d Dirty=%s\n", + cnt, + i->GetBlockNum(), + i->GetTimestamp(), + i->IsDirty() ? "true" : "false"); } - d.Trace( dl, "-------------------------\n"); - + d.Trace(dl, "-------------------------\n"); } /////////////////////////////////////////////////////////////////////////////// @@ -321,37 +320,40 @@ void cBlockFile::TraceContents(int dl) const /////////////////////////////////////////////////////////////////////////////// void cBlockFile::AssertValid() const { - if( ! mpArchive ) + if (!mpArchive) return; - // - // make sure the archive length and block count match up - // - #ifdef _DEBUG + // + // make sure the archive length and block count match up + // +# ifdef DEBUG if (mpArchive->Length() != (GetBlockSize() * GetNumBlocks())) { cDebug d("cBlockFile::AssertValid"); d.Trace(cDebug::D_DEBUG, "FATAL ERROR!!!\n"); - d.Trace(cDebug::D_DEBUG, "mpArchive->Length() = %d \n\t!= blocksize * numblocks = %d * %d\n", int(mpArchive->Length()), int(GetBlockSize()), int(GetNumBlocks())); + d.Trace(cDebug::D_DEBUG, + "mpArchive->Length() = %d \n\t!= blocksize * numblocks = %d * %d\n", + int(mpArchive->Length()), + int(GetBlockSize()), + int(GetNumBlocks())); d.Trace(cDebug::D_DEBUG, "now tracing the contents...\n"); TraceContents(cDebug::D_DEBUG); } - #endif - ASSERT( mpArchive->Length() == (GetBlockSize() * GetNumBlocks()) ); +# endif + ASSERT(mpArchive->Length() == (GetBlockSize() * GetNumBlocks())); // // iterate through the pages... // - for( BlockVector::const_iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++) + for (BlockVector::const_iterator i = mvPagedBlocks.begin(); i != mvPagedBlocks.end(); i++) { // make sure the block number is valid // int blockNum = i->GetBlockNum(); - ASSERT( (blockNum == cBlock::INVALID_NUM) || - ( (blockNum >= 0) && (blockNum < GetNumBlocks()) ) ); + ASSERT((blockNum == cBlock::INVALID_NUM) || ((blockNum >= 0) && (blockNum < GetNumBlocks()))); // // make sure the time stamp is less than or equal to the timer time... - // - ASSERT( i->GetTimestamp() <= mTimer ); + // + ASSERT(i->GetTimestamp() <= mTimer); // // assert that the guard bytes haven't been modified i->AssertValid(); @@ -359,4 +361,3 @@ void cBlockFile::AssertValid() const } #endif //_BLOCKFILE_DEBUG - diff --git a/src/db/blockfile.h b/src/db/blockfile.h index 884bb8f..187f962 100644 --- a/src/db/blockfile.h +++ b/src/db/blockfile.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // blockfile.h // -// cBlockFile -- +// cBlockFile -- #ifndef __BLOCKFILE_H #define __BLOCKFILE_H @@ -46,9 +46,9 @@ #include "block.h" #endif -#ifdef _DEBUG -#undef _BLOCKFILE_DEBUG // If we dont do this, test does not compile on unix -#define _BLOCKFILE_DEBUG // If we dont do this, test does not compile on unix +#ifdef DEBUG +# undef _BLOCKFILE_DEBUG // If we dont do this, test does not compile on unix +# define _BLOCKFILE_DEBUG // If we dont do this, test does not compile on unix #endif class cBlockFile_i; @@ -60,53 +60,65 @@ class cBidirArchive; class cBlockFile { public: - enum { BLOCK_SIZE = 4096 }; - typedef cBlock Block; + enum + { + BLOCK_SIZE = 4096 + }; + typedef cBlock Block; cBlockFile(); ~cBlockFile(); - void Open( const TSTRING& fileName, int numPages, bool bTruncate = false ); //throw (eArchive) - // opens the given file name as a block file, and uses numPages to signify the + void Open(const TSTRING& fileName, int numPages, bool bTruncate = false); //throw (eArchive) + // opens the given file name as a block file, and uses numPages to signify the // number of pages to cache blocks in as they are accessed from disk. // if bTruncate is true, then the file is created with zero length. - void Open( cBidirArchive* pArch, int numPages ); //throw (eArchive) + void Open(cBidirArchive* pArch, int numPages); //throw (eArchive) // the same as the previous Open(), except the passed in archive is used. This class will destroy // the archive when it is done (when Close() is called). If the archive length is zero, then // we create a new database. Otherwise, we assume we are opening an existing file. - void Close(); //throw (eArchive) + void Close(); //throw (eArchive) // writes all unsaved data to disk and disassociates the block file from its archive - void Flush(); //throw (eArchive) + void Flush(); //throw (eArchive) // flushes all dirty data to disk - Block* GetBlock( int blockNum ); //throw (eArchive) + Block* GetBlock(int blockNum); //throw (eArchive) // returns the specified block. This asserts that the block number is below GetNumBlocks() // this method takes care of paging the block into memory and returns a pointer to the block. Block* CreateBlock(); //throw (eArchive) - // this creates a new block, sets its number to GetNumBlocks(), pages it into memory, and + // this creates a new block, sets its number to GetNumBlocks(), pages it into memory, and // returns a pointer to it - void DestroyLastBlock( ); - // this method removes the last block from the file + void DestroyLastBlock(); + // this method removes the last block from the file - int GetNumBlocks() const { return mNumBlocks; } - int GetBlockSize() const { return BLOCK_SIZE; } + int GetNumBlocks() const + { + return mNumBlocks; + } + int GetBlockSize() const + { + return BLOCK_SIZE; + } - cBidirArchive* GetArchive() { return mpArchive; } - // NOTE -- be _very_ careful with this archive. It should probably not be written to + cBidirArchive* GetArchive() + { + return mpArchive; + } + // NOTE -- be _very_ careful with this archive. It should probably not be written to private: - typedef cBlockImpl BlockImpl; - typedef std::vector< BlockImpl > BlockVector; - - int mNumPages; - int mNumBlocks; // the total number of blocks in the archive. - uint32 mTimer; // keeps track of the current "time" - cBidirArchive* mpArchive; // note: I always own the deletion of the archive - BlockVector mvPagedBlocks; - - void FlushBlock( BlockImpl* pBlock ); //throw (eArchive) - // helper function that writes a block to disk if it is dirty + typedef cBlockImpl BlockImpl; + typedef std::vector BlockVector; + + int mNumPages; + int mNumBlocks; // the total number of blocks in the archive. + uint32 mTimer; // keeps track of the current "time" + cBidirArchive* mpArchive; // note: I always own the deletion of the archive + BlockVector mvPagedBlocks; + + void FlushBlock(BlockImpl* pBlock); //throw (eArchive) + // helper function that writes a block to disk if it is dirty /////////////////////////////////////////////////////////////////////////// // Profiling / Debugging interface @@ -114,31 +126,30 @@ class cBlockFile #ifdef _BLOCKFILE_DEBUG public: void TraceContents(int dl = -1) const; - // traces out all the info we can on the current state of this class - // dl is the debug level to trace it at; -1 means to use D_DEBUG + // traces out all the info we can on the current state of this class + // dl is the debug level to trace it at; -1 means to use D_DEBUG void AssertValid() const; - // ASSERTs as much as we can about the consistancy of our internal state. + // ASSERTs as much as we can about the consistancy of our internal state. int mNumBlockWrite; - // counts how many writes we have done + // counts how many writes we have done int mNumBlockRead; - // counts how many reads we have done + // counts how many reads we have done int mNumPageFault; - // number of times a page fault occured + // number of times a page fault occured int mNumPageRequests; - // number of page requests (useful to compare with mNumPageFault) + // number of page requests (useful to compare with mNumPageFault) #endif //_BLOCKFILE_DEBUG - }; //############################################################################# // inline implementation //############################################################################# -inline void cBlockFile::FlushBlock( cBlockFile::BlockImpl* pBlock ) //throw (eArchive) +inline void cBlockFile::FlushBlock(cBlockFile::BlockImpl* pBlock) //throw (eArchive) { - if( (pBlock->GetBlockNum() != Block::INVALID_NUM) && pBlock->IsDirty() ) + if ((pBlock->GetBlockNum() != Block::INVALID_NUM) && pBlock->IsDirty()) { // mNumBlockWrite keeps track of how many block writes we do // @@ -146,10 +157,9 @@ inline void cBlockFile::FlushBlock( cBlockFile::BlockImpl* pBlock ) //throw (eAr mNumBlockWrite++; #endif - pBlock->Write( *mpArchive ); + pBlock->Write(*mpArchive); } } #endif //__BLOCKFILE_H - diff --git a/src/db/blockfile_t.cpp b/src/db/blockfile_t.cpp deleted file mode 100644 index 340f555..0000000 --- a/src/db/blockfile_t.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -// blockfile_t -#include "stddb.h" -#include "blockfile.h" -#include "block.h" -#include "core/archive.h" -#include "test/test.h" -#include "core/debug.h" - -void TestBlockFile() -{ - cDebug d( "TestBlockFile" ); - - try - { - static const TCHAR fileName[] = _T("c:/tmp/test.bf"); - // truncate the file I am going to use... - // - cFileArchive a; - a.OpenReadWrite( fileName ); - a.Close(); - // - // open up the block file... - // - cBlockFile bf; - bf.Open( fileName, 2 ); // opened up with two pages - #ifdef _BLOCKFILE_DEBUG - bf.TraceContents(); - #endif - - // get a block and write something to it... - // - cBlockFile::Block* pB = bf.GetBlock( 0 ); - TEST( pB ); - static const TCHAR str1[] = _T("Block 1"); - memcpy( pB->GetData(), str1, sizeof(str1) ); - pB->SetDirty(); - #ifdef _BLOCKFILE_DEBUG - bf.TraceContents(); - #endif - - // get another block... - // - pB = bf.CreateBlock(); - TEST( pB ); - static const TCHAR str2[] = _T("Block 2"); - memcpy( pB->GetData(), str2, sizeof(str2) ); - pB->SetDirty(); - #ifdef _BLOCKFILE_DEBUG - bf.TraceContents(); - #endif - - // get the first block we wrote... - // - pB = bf.GetBlock( 0 ); - TEST( pB ); - *pB->GetData() = _T('F'); - #ifdef _BLOCKFILE_DEBUG - bf.TraceContents(); - #endif - - // - // create a third block -- someone will have to be paged out in order for this to happen - // - pB = bf.CreateBlock(); - TEST( pB ); - static const TCHAR str3[] = _T("Block 3"); - memcpy( pB->GetData(), str3, sizeof(str3) ); - pB->SetDirty(); - #ifdef _BLOCKFILE_DEBUG - bf.TraceContents(); - #endif - - // - // test the guard bytes... - /* - memcpy( pB->GetData() + (cBlockFile::BLOCK_SIZE - 4), str3, sizeof(str3) ); - memcpy( pB->GetData() - 1, str3, sizeof(str3) ); - pB->AssertValid(); - */ - - bf.Close(); - } - catch( eError& e ) - { - d.TraceError( _T("Exception caught: %d %s\n"), e.GetID(), e.GetMsg().c_str() ); - TEST( false ); - } -} diff --git a/src/db/blockrecordarray.cpp b/src/db/blockrecordarray.cpp index 51b6642..247012d 100644 --- a/src/db/blockrecordarray.cpp +++ b/src/db/blockrecordarray.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,7 +44,7 @@ /////////////////////////////////////////////////////////////////////////////// inline cBlockRecordArray::tIndexArray& util_GetIndexArray(cBlockFile::Block* pBlock) { - return (* reinterpret_cast( pBlock->GetData() ) ); + return (*reinterpret_cast(pBlock->GetData())); } /////////////////////////////////////////////////////////////////////////////// @@ -54,35 +54,25 @@ inline cBlockRecordArray::tIndexArray& util_GetIndexArray(cBlockFile::Block* pBl /////////////////////////////////////////////////////////////////////////////// inline int8* util_OffsetToAddr(cBlockFile::Block* pBlock, int offset) { - return ( pBlock->GetData() + (cBlockFile::BLOCK_SIZE - offset) ); + return (pBlock->GetData() + (cBlockFile::BLOCK_SIZE - offset)); } - /////////////////////////////////////////////////////////////////////////////// -// ctor +// ctor /////////////////////////////////////////////////////////////////////////////// cBlockRecordArray::cBlockRecordArray(cBlockFile* pBlockFile, int blockNum) -: mpBlockFile ( pBlockFile ), - mBlockNum ( blockNum ), - mSpaceAvailable ( -1 ), - mNumItems ( 0 ), - mbInit ( false ) + : mpBlockFile(pBlockFile), mBlockNum(blockNum), mSpaceAvailable(-1), mNumItems(0), mbInit(false) { } -cBlockRecordArray::cBlockRecordArray() -: mpBlockFile ( 0 ), - mBlockNum ( -1 ), - mSpaceAvailable ( -1 ), - mNumItems ( 0 ), - mbInit ( false ) +cBlockRecordArray::cBlockRecordArray() : mpBlockFile(0), mBlockNum(-1), mSpaceAvailable(-1), mNumItems(0), mbInit(false) { } void cBlockRecordArray::Init(cBlockFile* pBlockFile, int blockNum) { - ASSERT(! pBlockFile ); + ASSERT(!pBlockFile); mpBlockFile = pBlockFile; mBlockNum = blockNum; @@ -93,11 +83,10 @@ void cBlockRecordArray::Init(cBlockFile* pBlockFile, int blockNum) /////////////////////////////////////////////////////////////////////////////// -// dtor +// dtor /////////////////////////////////////////////////////////////////////////////// cBlockRecordArray::~cBlockRecordArray() { - } /////////////////////////////////////////////////////////////////////////////// @@ -105,24 +94,24 @@ cBlockRecordArray::~cBlockRecordArray() /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::InitNewBlock() //throw (eArchive) { - ASSERT( mpBlockFile != 0); - ASSERT( (mBlockNum >= 0) && (mBlockNum < mpBlockFile->GetNumBlocks()) ); + ASSERT(mpBlockFile != 0); + ASSERT((mBlockNum >= 0) && (mBlockNum < mpBlockFile->GetNumBlocks())); #ifdef _BLOCKFILE_DEBUG mpBlockFile->AssertValid(); -#endif +#endif - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& array = util_GetIndexArray( pBlock ); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& array = util_GetIndexArray(pBlock); // // set everything to zero.. // - memset( pBlock->GetData(), 0, cBlockFile::BLOCK_SIZE ); + memset(pBlock->GetData(), 0, cBlockFile::BLOCK_SIZE); pBlock->SetDirty(); // // set up the guard byte for the index array... // - array.maRecordIndex[0].SetOffset ( -1 ); - array.maRecordIndex[0].SetMainIndex ( INVALID_INDEX ); + array.maRecordIndex[0].SetOffset(-1); + array.maRecordIndex[0].SetMainIndex(INVALID_INDEX); // // remember that we have been initialized // @@ -131,9 +120,8 @@ void cBlockRecordArray::InitNewBlock() //throw (eArchive) // update the free space and max index variables... // mNumItems = 0; - UpdateFreeSpace( pBlock ); - WriteHeaderInfo( pBlock ); - + UpdateFreeSpace(pBlock); + WriteHeaderInfo(pBlock); } /////////////////////////////////////////////////////////////////////////////// @@ -141,13 +129,13 @@ void cBlockRecordArray::InitNewBlock() //throw (eArchive) /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::InitForExistingBlock() //throw (eArchive) { - ASSERT( mpBlockFile != 0); - ASSERT( (mBlockNum >= 0) && (mBlockNum < mpBlockFile->GetNumBlocks()) ); - ASSERT( ! mbInit ); + ASSERT(mpBlockFile != 0); + ASSERT((mBlockNum >= 0) && (mBlockNum < mpBlockFile->GetNumBlocks())); + ASSERT(!mbInit); // // read in our header info... // - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); ReadHeaderInfo(pBlock); // // remember that we have been initialized @@ -166,21 +154,21 @@ void cBlockRecordArray::InitForExistingBlock() //throw (eArchive) /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::WriteHeaderInfo(cBlockFile::Block* pBlock) { - ASSERT( mpBlockFile != 0); - ASSERT( Initialized() ); - - util_GetIndexArray(pBlock).mHeader.SetNumItems ( mNumItems ); - util_GetIndexArray(pBlock).mHeader.SetSpaceAvail( mSpaceAvailable ); + ASSERT(mpBlockFile != 0); + ASSERT(Initialized()); + + util_GetIndexArray(pBlock).mHeader.SetNumItems(mNumItems); + util_GetIndexArray(pBlock).mHeader.SetSpaceAvail(mSpaceAvailable); pBlock->SetDirty(); } /////////////////////////////////////////////////////////////////////////////// -// ReadHeaderInfo +// ReadHeaderInfo /////////////////////////////////////////////////////////////////////////////// -void cBlockRecordArray::ReadHeaderInfo (cBlockFile::Block* pBlock) +void cBlockRecordArray::ReadHeaderInfo(cBlockFile::Block* pBlock) { - ASSERT( mpBlockFile != 0); + ASSERT(mpBlockFile != 0); mNumItems = util_GetIndexArray(pBlock).mHeader.GetNumItems(); mSpaceAvailable = util_GetIndexArray(pBlock).mHeader.GetSpaceAvail(); @@ -192,33 +180,33 @@ void cBlockRecordArray::ReadHeaderInfo (cBlockFile::Block* pBlock) /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::UpdateFreeSpace(cBlockFile::Block* pBlock) { - ASSERT( Initialized() ); - ASSERT( mpBlockFile != 0); + ASSERT(Initialized()); + ASSERT(mpBlockFile != 0); // first, take into account the size of all of the index structures. Note that // we add one to the current number because we want to account for the new one - // that might be added if another item were added to the array + // that might be added if another item were added to the array // - int availSpace = cBlockFile::BLOCK_SIZE - sizeof(tHeader) - ( (GetNumItems() + 1) * sizeof(tRecordIndex) ); + int availSpace = cBlockFile::BLOCK_SIZE - sizeof(tHeader) - ((GetNumItems() + 1) * sizeof(tRecordIndex)); // // always take the MARGIN away, to give ourselves some breathing room between the indexes and // the data - // + // availSpace -= MARGIN; // // subtract from availSpace the amount of room that the actual data is taking up... // note that it is always true that the top index points to a valid value // - if( GetNumItems() > 0 ) + if (GetNumItems() > 0) { - int topOffset = util_GetIndexArray(pBlock).maRecordIndex[ GetNumItems()-1 ].GetOffset(); + int topOffset = util_GetIndexArray(pBlock).maRecordIndex[GetNumItems() - 1].GetOffset(); availSpace -= topOffset; - } + } - mSpaceAvailable = availSpace < 0 ? 0 : availSpace ; + mSpaceAvailable = availSpace < 0 ? 0 : availSpace; #ifdef _BLOCKFILE_DEBUG AssertValid(); -#endif +#endif } /////////////////////////////////////////////////////////////////////////////// @@ -226,14 +214,14 @@ void cBlockRecordArray::UpdateFreeSpace(cBlockFile::Block* pBlock) /////////////////////////////////////////////////////////////////////////////// bool cBlockRecordArray::IsItemValid(int index) const //throw (eArchive) { - ASSERT( Initialized() ); + ASSERT(Initialized()); - if ( (index < 0) || (index >= GetNumItems()) ) + if ((index < 0) || (index >= GetNumItems())) return false; - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); - return (util_GetIndexArray(pBlock).maRecordIndex[ index ].GetMainIndex() != INVALID_INDEX ); + return (util_GetIndexArray(pBlock).maRecordIndex[index].GetMainIndex() != INVALID_INDEX); } @@ -244,101 +232,100 @@ int cBlockRecordArray::AddItem(int8* pData, int dataSize, int mainIndex) //throw { // make ourselves initialized, if we are not right now... // - if( ! Initialized() ) + if (!Initialized()) { InitForExistingBlock(); } - - ASSERT( dataSize <= GetAvailableSpace() ); - ASSERT( GetNumItems() <= MAX_RECORDS ); - ASSERT( dataSize > 0 ); // I am not sure if this is the right thing to do ! - ASSERT( mpBlockFile != 0); - ASSERT( mainIndex != INVALID_INDEX ); - ASSERT( Initialized() ); + + ASSERT(dataSize <= GetAvailableSpace()); + ASSERT(GetNumItems() <= MAX_RECORDS); + ASSERT(dataSize > 0); // I am not sure if this is the right thing to do ! + ASSERT(mpBlockFile != 0); + ASSERT(mainIndex != INVALID_INDEX); + ASSERT(Initialized()); #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); -#endif +#endif cDebug d("cBlockRecordArray::AddItem"); - d.TraceDetail( "Entering... adding item of size %d to block %d\n", dataSize, mBlockNum ); + d.TraceDetail("Entering... adding item of size %d to block %d\n", dataSize, mBlockNum); // // get the block we need and a reference into the index array.... // - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& indexArray = util_GetIndexArray(pBlock); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& indexArray = util_GetIndexArray(pBlock); // // find an unused entry to put the item into... // - tRecordIndex* pIndex = indexArray.maRecordIndex; - int newIndex = 0; - for( ; newIndex < mNumItems; newIndex++, pIndex++ ) + tRecordIndex* pIndex = indexArray.maRecordIndex; + int newIndex = 0; + for (; newIndex < mNumItems; newIndex++, pIndex++) { - if( pIndex->GetMainIndex() == INVALID_INDEX ) + if (pIndex->GetMainIndex() == INVALID_INDEX) break; } - d.TraceDetail( "Adding new item to index %d (max index + 1 = %d)\n", newIndex, mNumItems ); + d.TraceDetail("Adding new item to index %d (max index + 1 = %d)\n", newIndex, mNumItems); // write the data we know for sure at this point... // - pIndex->SetMainIndex( mainIndex ); + pIndex->SetMainIndex(mainIndex); pBlock->SetDirty(); // // calculate the offset for the new data // - int prevOffset = ( newIndex == 0 ? 0 : indexArray.maRecordIndex[ newIndex-1 ].GetOffset() ); - pIndex->SetOffset( prevOffset + dataSize ); - - if( newIndex == mNumItems ) + int prevOffset = (newIndex == 0 ? 0 : indexArray.maRecordIndex[newIndex - 1].GetOffset()); + pIndex->SetOffset(prevOffset + dataSize); + + if (newIndex == mNumItems) { // // increment the max number of indexes... // mNumItems++; - indexArray.maRecordIndex[ mNumItems ].SetOffset ( -1 ); - indexArray.maRecordIndex[ mNumItems ].SetMainIndex ( INVALID_INDEX ); + indexArray.maRecordIndex[mNumItems].SetOffset(-1); + indexArray.maRecordIndex[mNumItems].SetMainIndex(INVALID_INDEX); } else { // we are going to have to shift up the data that is above us... // - int topOffset = indexArray.maRecordIndex[GetNumItems()-1].GetOffset(); - int8* pTop = util_OffsetToAddr( pBlock, topOffset ); - int amtToMove = topOffset - prevOffset; - ASSERT( amtToMove >= 0 ); + int topOffset = indexArray.maRecordIndex[GetNumItems() - 1].GetOffset(); + int8* pTop = util_OffsetToAddr(pBlock, topOffset); + int amtToMove = topOffset - prevOffset; + ASSERT(amtToMove >= 0); - memmove( pTop - dataSize, pTop, amtToMove ); + memmove(pTop - dataSize, pTop, amtToMove); // // now, we need to iterate over all of the existing entries, updating their offsets... // - tRecordIndex* pMovedIndex = pIndex + 1; - for( int i = newIndex + 1; i < mNumItems; i++, pMovedIndex++ ) + tRecordIndex* pMovedIndex = pIndex + 1; + for (int i = newIndex + 1; i < mNumItems; i++, pMovedIndex++) { - pMovedIndex->SetOffset( pMovedIndex->GetOffset() + dataSize ); + pMovedIndex->SetOffset(pMovedIndex->GetOffset() + dataSize); } - } // // write the data... // - memcpy( util_OffsetToAddr( pBlock, pIndex->GetOffset() ), pData, dataSize ); + memcpy(util_OffsetToAddr(pBlock, pIndex->GetOffset()), pData, dataSize); // // update the free space... // - indexArray.maRecordIndex[ mNumItems ].SetOffset ( -1 ); - indexArray.maRecordIndex[ mNumItems ].SetMainIndex ( INVALID_INDEX ); - UpdateFreeSpace( pBlock ); - WriteHeaderInfo( pBlock ); + indexArray.maRecordIndex[mNumItems].SetOffset(-1); + indexArray.maRecordIndex[mNumItems].SetMainIndex(INVALID_INDEX); + UpdateFreeSpace(pBlock); + WriteHeaderInfo(pBlock); #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); - d.TraceDetail( "*** Add Complete; here are the new contents ***\n"); - TraceContents( cDebug::D_NEVER ); -#endif + d.TraceDetail("*** Add Complete; here are the new contents ***\n"); + TraceContents(cDebug::D_NEVER); +#endif return newIndex; } - + /////////////////////////////////////////////////////////////////////////////// // DeleteItem /////////////////////////////////////////////////////////////////////////////// @@ -346,228 +333,233 @@ void cBlockRecordArray::DeleteItem(int index) //throw (eArchive) { // make ourselves initialized, if we are not right now... // - if( ! Initialized() ) + if (!Initialized()) { InitForExistingBlock(); } - - ASSERT( mpBlockFile != 0); - ASSERT( IsItemValid(index) ); - ASSERT( Initialized() ); + + ASSERT(mpBlockFile != 0); + ASSERT(IsItemValid(index)); + ASSERT(Initialized()); #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); -#endif +#endif cDebug d("cBlockRecordArray::DeleteItem"); - d.TraceDetail( "Entering... Removing item index %d from block %d\n", index, mBlockNum); + d.TraceDetail("Entering... Removing item index %d from block %d\n", index, mBlockNum); // // get the block we need and a reference into the index array.... // - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& indexArray = util_GetIndexArray(pBlock); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& indexArray = util_GetIndexArray(pBlock); pBlock->SetDirty(); // // if this is the last entry, then our job is easy... // - if( (index + 1) == mNumItems ) + if ((index + 1) == mNumItems) { mNumItems--; // we need to clean out all the entries that are empty at the end of the index list... // - while( (mNumItems > 0) && (indexArray.maRecordIndex[ mNumItems-1 ].GetMainIndex() == INVALID_INDEX) ) + while ((mNumItems > 0) && (indexArray.maRecordIndex[mNumItems - 1].GetMainIndex() == INVALID_INDEX)) { mNumItems--; } // // set the guard bytes... // - indexArray.maRecordIndex[ mNumItems ].SetOffset ( -1 ); - indexArray.maRecordIndex[ mNumItems ].SetMainIndex ( INVALID_INDEX ); + indexArray.maRecordIndex[mNumItems].SetOffset(-1); + indexArray.maRecordIndex[mNumItems].SetMainIndex(INVALID_INDEX); } else - { + { // we are going to shift all entries above the deleted entry down; // first, figure out how far we are shifting and the source address... // - int sizeToShift = indexArray.maRecordIndex[GetNumItems()-1].GetOffset() - indexArray.maRecordIndex[index].GetOffset(); + int sizeToShift = + indexArray.maRecordIndex[GetNumItems() - 1].GetOffset() - indexArray.maRecordIndex[index].GetOffset(); int distToShift = indexArray.maRecordIndex[index].GetOffset(); - if( index > 0 ) + if (index > 0) { distToShift -= indexArray.maRecordIndex[index - 1].GetOffset(); } - int8* pSrc = util_OffsetToAddr( pBlock, indexArray.maRecordIndex[GetNumItems()-1].GetOffset() ); + int8* pSrc = util_OffsetToAddr(pBlock, indexArray.maRecordIndex[GetNumItems() - 1].GetOffset()); // // copy the data.. // - ASSERT ( pBlock->IsValidAddr(pSrc) && pBlock->IsValidAddr(pSrc + distToShift + sizeToShift - 1) ); - ASSERT ( sizeToShift >= 0 ); - ASSERT ( distToShift >= 0 ); - memmove ( pSrc + distToShift, pSrc, sizeToShift ); + ASSERT(pBlock->IsValidAddr(pSrc) && pBlock->IsValidAddr(pSrc + distToShift + sizeToShift - 1)); + ASSERT(sizeToShift >= 0); + ASSERT(distToShift >= 0); + memmove(pSrc + distToShift, pSrc, sizeToShift); // // mark this entry as unused... // note that the offset is set to be the same as the item before it. // - tRecordIndex* pIndex = &indexArray.maRecordIndex[ index ]; - pIndex->SetMainIndex ( INVALID_INDEX ); - pIndex->SetOffset ( (index == 0 ? 0 : indexArray.maRecordIndex[ index-1 ].GetOffset()) ); + tRecordIndex* pIndex = &indexArray.maRecordIndex[index]; + pIndex->SetMainIndex(INVALID_INDEX); + pIndex->SetOffset((index == 0 ? 0 : indexArray.maRecordIndex[index - 1].GetOffset())); // // now, iterate over the items, moving their offsets down... - // + // pIndex++; - for( int i = index+1; i < GetNumItems(); i++, pIndex++ ) + for (int i = index + 1; i < GetNumItems(); i++, pIndex++) { - pIndex->SetOffset( pIndex->GetOffset() - distToShift ); + pIndex->SetOffset(pIndex->GetOffset() - distToShift); } } - UpdateFreeSpace( pBlock ); - WriteHeaderInfo( pBlock ); + UpdateFreeSpace(pBlock); + WriteHeaderInfo(pBlock); #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); - d.TraceDetail( "*** Removal Complete; here are the new contents ***\n"); - TraceContents( cDebug::D_NEVER ); -#endif - + d.TraceDetail("*** Removal Complete; here are the new contents ***\n"); + TraceContents(cDebug::D_NEVER); +#endif } /////////////////////////////////////////////////////////////////////////////// // GetDataForReading /////////////////////////////////////////////////////////////////////////////// -int8* cBlockRecordArray::GetDataForReading( int index, int32& dataSize ) //throw (eArchive) +int8* cBlockRecordArray::GetDataForReading(int index, int32& dataSize) //throw (eArchive) { // make ourselves initialized, if we are not right now... // - if( ! Initialized() ) + if (!Initialized()) { InitForExistingBlock(); } - ASSERT( IsItemValid(index) ); - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& indexArray = util_GetIndexArray(pBlock); + ASSERT(IsItemValid(index)); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& indexArray = util_GetIndexArray(pBlock); // // figure out the size of the block // dataSize = indexArray.maRecordIndex[index].GetOffset(); - if( index != 0 ) + if (index != 0) { - dataSize -= indexArray.maRecordIndex[index-1].GetOffset(); + dataSize -= indexArray.maRecordIndex[index - 1].GetOffset(); } #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); -#endif +#endif - return( util_OffsetToAddr(pBlock, indexArray.maRecordIndex[index].GetOffset()) ); + return (util_OffsetToAddr(pBlock, indexArray.maRecordIndex[index].GetOffset())); } /////////////////////////////////////////////////////////////////////////////// // GetDataForWriting /////////////////////////////////////////////////////////////////////////////// -int8* cBlockRecordArray::GetDataForWriting( int index, int32& dataSize ) //throw (eArchive) +int8* cBlockRecordArray::GetDataForWriting(int index, int32& dataSize) //throw (eArchive) { // make ourselves initialized, if we are not right now... // - if( ! Initialized() ) + if (!Initialized()) { InitForExistingBlock(); } - ASSERT( IsItemValid(index) ); - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& indexArray = util_GetIndexArray(pBlock); + ASSERT(IsItemValid(index)); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& indexArray = util_GetIndexArray(pBlock); pBlock->SetDirty(); // // figure out the size of the block // dataSize = indexArray.maRecordIndex[index].GetOffset(); - if( index != 0 ) + if (index != 0) { - dataSize -= indexArray.maRecordIndex[index-1].GetOffset(); + dataSize -= indexArray.maRecordIndex[index - 1].GetOffset(); } #ifdef _BLOCKFILE_DEBUG AssertValid(); mpBlockFile->AssertValid(); -#endif +#endif - return( util_OffsetToAddr(pBlock, indexArray.maRecordIndex[index].GetOffset()) ); + return (util_OffsetToAddr(pBlock, indexArray.maRecordIndex[index].GetOffset())); } /////////////////////////////////////////////////////////////////////////////// // IsClassValid /////////////////////////////////////////////////////////////////////////////// -#define BRA_ASSERT(x) if(x) ; else { ASSERT(false); return false; } +#define BRA_ASSERT(x) \ + if (x) \ + ; \ + else \ + { \ + ASSERT(false); \ + return false; \ + } bool cBlockRecordArray::IsClassValid() const { - ASSERT( mpBlockFile != 0); - cDebug d( "cBlockRecordArray::AssertValid" ); - if( ! mbInit ) + ASSERT(mpBlockFile != 0); + cDebug d("cBlockRecordArray::AssertValid"); + if (!mbInit) { // if we haven't been initialized yet, then I assume that we are valid... // return true; } - + // // get the block we need and a reference into the index array.... // try { - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& array = util_GetIndexArray(pBlock); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& array = util_GetIndexArray(pBlock); // // make sure that the num items and available space make sense... // - BRA_ASSERT( (mNumItems >= 0) && (mNumItems <= MAX_RECORDS) ); - BRA_ASSERT( (mSpaceAvailable >= 0) && (mSpaceAvailable <= MAX_DATA_SIZE) ); + BRA_ASSERT((mNumItems >= 0) && (mNumItems <= MAX_RECORDS)); + BRA_ASSERT((mSpaceAvailable >= 0) && (mSpaceAvailable <= MAX_DATA_SIZE)); // // assert that the top index points to a valid value... // - if(mNumItems != 0) + if (mNumItems != 0) { - BRA_ASSERT( array.maRecordIndex[mNumItems-1].GetMainIndex() != INVALID_INDEX ); - BRA_ASSERT( array.maRecordIndex[mNumItems-1].GetOffset() != -1 ); + BRA_ASSERT(array.maRecordIndex[mNumItems - 1].GetMainIndex() != INVALID_INDEX); + BRA_ASSERT(array.maRecordIndex[mNumItems - 1].GetOffset() != -1); } - + int prevOff = 0; int i; - for( i = 0; i < mNumItems; i++ ) + for (i = 0; i < mNumItems; i++) { - BRA_ASSERT( array.maRecordIndex[i].GetOffset() >= prevOff ); - prevOff = array.maRecordIndex[i].GetOffset(); + BRA_ASSERT(array.maRecordIndex[i].GetOffset() >= prevOff); + prevOff = array.maRecordIndex[i].GetOffset(); } // make sure the guard byte is there... // - BRA_ASSERT( array.maRecordIndex[i].GetOffset() == -1 ); - // + BRA_ASSERT(array.maRecordIndex[i].GetOffset() == -1); + // // make sure the final offset is less than the highest record index offset. // - BRA_ASSERT( (int8*)&array.maRecordIndex[i] < util_OffsetToAddr( pBlock, prevOff ) ); + BRA_ASSERT((int8*)&array.maRecordIndex[i] < util_OffsetToAddr(pBlock, prevOff)); // // TODO -- is there anything else that is worth checking? - } - catch( eArchive& e ) + catch (eArchive& e) { - d.TraceError( "*** cBlockFile::GetBlock threw an eArchive: %d %s\n", e.GetID(), e.GetMsg().c_str() ); - BRA_ASSERT( false ); + d.TraceError("*** cBlockFile::GetBlock threw an eArchive: %d %s\n", e.GetID(), e.GetMsg().c_str()); + BRA_ASSERT(false); } // if we got here, then everything worked ok. - // + // return true; } - #ifdef _BLOCKFILE_DEBUG /////////////////////////////////////////////////////////////////////////////// @@ -575,27 +567,30 @@ bool cBlockRecordArray::IsClassValid() const /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::TraceContents(int dl) const { - if( dl == -1 ) + if (dl == -1) dl = cDebug::D_DEBUG; - cDebug d( "cBlockRecordArray::TraceContents" ); + cDebug d("cBlockRecordArray::TraceContents"); + + d.Trace(dl, "---------- Block Record Array ----------\n"); + d.Trace(dl, "----------------------------------------\n"); + d.Trace(dl, "Block Number %d\n", mBlockNum); + d.Trace(dl, "Space Available %d\n", mSpaceAvailable); + d.Trace(dl, "Num Entries %d\n", mNumItems); - d.Trace( dl, "---------- Block Record Array ----------\n" ); - d.Trace( dl, "----------------------------------------\n" ); - d.Trace( dl, "Block Number %d\n", mBlockNum ); - d.Trace( dl, "Space Available %d\n", mSpaceAvailable ); - d.Trace( dl, "Num Entries %d\n", mNumItems); - - cBlockFile::Block* pBlock = mpBlockFile->GetBlock( mBlockNum ); - tIndexArray& indexArray = util_GetIndexArray(pBlock); + cBlockFile::Block* pBlock = mpBlockFile->GetBlock(mBlockNum); + tIndexArray& indexArray = util_GetIndexArray(pBlock); - for( int i=0; i < mNumItems; i++ ) + for (int i = 0; i < mNumItems; i++) { - d.Trace( dl, "(%d)\tOffset %d\tMain Idx %d\n", i, indexArray.maRecordIndex[i].GetOffset(), indexArray.maRecordIndex[i].GetMainIndex() ); + d.Trace(dl, + "(%d)\tOffset %d\tMain Idx %d\n", + i, + indexArray.maRecordIndex[i].GetOffset(), + indexArray.maRecordIndex[i].GetMainIndex()); } - d.Trace( dl, "----------------------------------------\n" ); - + d.Trace(dl, "----------------------------------------\n"); } /////////////////////////////////////////////////////////////////////////////// @@ -603,8 +598,7 @@ void cBlockRecordArray::TraceContents(int dl) const /////////////////////////////////////////////////////////////////////////////// void cBlockRecordArray::AssertValid() const { - ASSERT( IsClassValid() ); + ASSERT(IsClassValid()); } #endif - diff --git a/src/db/blockrecordarray.h b/src/db/blockrecordarray.h index d973f69..df77b93 100644 --- a/src/db/blockrecordarray.h +++ b/src/db/blockrecordarray.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,7 +45,7 @@ #endif // -// TODO -- I need to guarantee that all of the structures in this class do not have any pad bytes. +// TODO -- I need to guarantee that all of the structures in this class do not have any pad bytes. // This is true under win32, but I am not sure if it will always be true. -- 10 feb 99 mdb // @@ -58,53 +58,64 @@ class cBlockRecordArray // Construction //------------------------------------------------------------------------------------- cBlockRecordArray(cBlockFile* pBlockFile, int blockNum); - // this object is associated with a single block in a cBlockFile. It is _not_ - // asserted that the blockNum is valid for the associated file at this point, - // since it is possible that the file has not been loaded yet + // this object is associated with a single block in a cBlockFile. It is _not_ + // asserted that the blockNum is valid for the associated file at this point, + // since it is possible that the file has not been loaded yet cBlockRecordArray(); - // if this version of the ctor is called, then Init() must be called before it can be used. - void Init(cBlockFile* pBlockFile, int blockNum); + // if this version of the ctor is called, then Init() must be called before it can be used. + void Init(cBlockFile* pBlockFile, int blockNum); virtual ~cBlockRecordArray(); //------------------------------------------------------------------------------------- // Initialization ... exactly one of these methods must be called before this class can be used //------------------------------------------------------------------------------------- - void InitNewBlock() ; //throw (eArchive) - // this method should be called when a new block has been created, and before this + void InitNewBlock(); //throw (eArchive) + // this method should be called when a new block has been created, and before this // class operates on it. - void InitForExistingBlock() ; //throw (eArchive) - // this method should be called to initialize this class for use with a block that has + void InitForExistingBlock(); //throw (eArchive) + // this method should be called to initialize this class for use with a block that has // previously been created and initialized with InitNewBlock(). //------------------------------------------------------------------------------------- // Data Manipulation //------------------------------------------------------------------------------------- - int AddItem(int8* pData, int dataSize, int mainIndex) ; //throw (eArchive) + int AddItem(int8* pData, int dataSize, int mainIndex); //throw (eArchive) // inserts the given item into the array; returns the index that it was inserted into. // this asserts that there is room for the new element, and updates the avail. space and // max index as necessary. - void DeleteItem(int index ) ; //throw (eArchive) + void DeleteItem(int index); //throw (eArchive) // deletes the specified item; this asserts that the index is valid, and updates the avail. - // space and max index as necessary. - int8* GetDataForReading( int index, int32& dataSize ) ; //throw (eArchive) + // space and max index as necessary. + int8* GetDataForReading(int index, int32& dataSize); //throw (eArchive) // returns a pointer to the named data. This method will assert that the address is // valid. The data pointer returned is guarenteed to be valid only until the next // method call into this class. - int8* GetDataForWriting( int index, int32& dataSize ) ; //throw (eArchive) + int8* GetDataForWriting(int index, int32& dataSize); //throw (eArchive) // this is the same as the previous function, except the dirty bit for the page is also set - bool IsItemValid(int index) const ; //throw (eArchive) + bool IsItemValid(int index) const; //throw (eArchive) // returns true if the given index has a valid value. - bool IsClassValid() const; - // returns true if the class has an internally consistant state. If an archive exception - // occurs, false is returned. This method is good for determining if a newly opened block - // file is actually a block file + bool IsClassValid() const; + // returns true if the class has an internally consistant state. If an archive exception + // occurs, false is returned. This method is good for determining if a newly opened block + // file is actually a block file - bool Initialized() const { return mbInit; } - int GetAvailableSpace() const { ASSERT( Initialized() ); return mSpaceAvailable; } - int GetNumItems() const { ASSERT( Initialized() ); return mNumItems; } - // returns the number of items currently being stored in the array + bool Initialized() const + { + return mbInit; + } + int GetAvailableSpace() const + { + ASSERT(Initialized()); + return mSpaceAvailable; + } + int GetNumItems() const + { + ASSERT(Initialized()); + return mNumItems; + } + // returns the number of items currently being stored in the array /////////////////////////////////////////////////////////////////// // tRecordIndex -- this is what each record in the array is @@ -114,15 +125,27 @@ class cBlockRecordArray struct tRecordIndex { private: - int32 mOffset; // offset from the end of the block that my data is at; offset 1 is the last byte in the block - int32 mMainIndex; // my main array index + int32 mOffset; // offset from the end of the block that my data is at; offset 1 is the last byte in the block + int32 mMainIndex; // my main array index public: // byte order safe access methods... // - void SetOffset ( int32 off ) { mOffset = tw_htonl( off ); } - int32 GetOffset ( ) { return tw_ntohl( mOffset ); } - void SetMainIndex ( int32 idx ) { mMainIndex= tw_htonl( idx ); } - int32 GetMainIndex ( ) { return tw_ntohl( mMainIndex ); } + void SetOffset(int32 off) + { + mOffset = tw_htonl(off); + } + int32 GetOffset() + { + return tw_ntohl(mOffset); + } + void SetMainIndex(int32 idx) + { + mMainIndex = tw_htonl(idx); + } + int32 GetMainIndex() + { + return tw_ntohl(mMainIndex); + } }; /////////////////////////////////////////////////////////////////// // tHeader -- the info that appears at the beginning of the block @@ -130,58 +153,73 @@ class cBlockRecordArray struct tHeader { private: - int32 mSpaceAvailable; - int32 mNumItems; + int32 mSpaceAvailable; + int32 mNumItems; + public: // byte order safe access methods... // - void SetSpaceAvail ( int32 sa ) { mSpaceAvailable = tw_htonl( sa ); } - int32 GetSpaceAvail ( ) { return tw_ntohl( mSpaceAvailable ); } - void SetNumItems ( int32 ni ) { mNumItems = tw_htonl( ni ); } - int32 GetNumItems ( ) { return tw_ntohl( mNumItems ); } + void SetSpaceAvail(int32 sa) + { + mSpaceAvailable = tw_htonl(sa); + } + int32 GetSpaceAvail() + { + return tw_ntohl(mSpaceAvailable); + } + void SetNumItems(int32 ni) + { + mNumItems = tw_htonl(ni); + } + int32 GetNumItems() + { + return tw_ntohl(mNumItems); + } }; - enum { MAX_RECORDS = cBlockFile::BLOCK_SIZE / ( sizeof(tRecordIndex) + sizeof(uint32) ), - // MAX_RECORDS signifies the maximum number of records that can be stored in a single block. - // It is rationalized like this: each used record needs a tRecordIndex plus an extra uint32 - // as a minimum storage requirement (even though it is ok to have a record that is filled in - // with zero bytes) - MARGIN = 10 , - // MARGIN is the min. amount of room that should exist between the indexes and the data. This - // is used when calculating the available space, and also in assertions. - MAX_DATA_SIZE = cBlockFile::BLOCK_SIZE - sizeof(tRecordIndex) - sizeof(tHeader) - MARGIN, - // this is the largest single piece of data that could theoreticaly be stored (if it were the - // only thing stored in the block). We assume that the single record index will take up space, - // the header will take up space, and the margin will take up space. - INVALID_INDEX = -1 - // when tRecordIndex::mMainIndex is set to this, it indicates that the index is not being used. - }; + enum + { + MAX_RECORDS = cBlockFile::BLOCK_SIZE / (sizeof(tRecordIndex) + sizeof(uint32)), + // MAX_RECORDS signifies the maximum number of records that can be stored in a single block. + // It is rationalized like this: each used record needs a tRecordIndex plus an extra uint32 + // as a minimum storage requirement (even though it is ok to have a record that is filled in + // with zero bytes) + MARGIN = 10, + // MARGIN is the min. amount of room that should exist between the indexes and the data. This + // is used when calculating the available space, and also in assertions. + MAX_DATA_SIZE = cBlockFile::BLOCK_SIZE - sizeof(tRecordIndex) - sizeof(tHeader) - MARGIN, + // this is the largest single piece of data that could theoreticaly be stored (if it were the + // only thing stored in the block). We assume that the single record index will take up space, + // the header will take up space, and the margin will take up space. + INVALID_INDEX = -1 + // when tRecordIndex::mMainIndex is set to this, it indicates that the index is not being used. + }; /////////////////////////////////////////////////////////////////// - // tIndexArray -- the beginning of a block is treated + // tIndexArray -- the beginning of a block is treated // as one of these /////////////////////////////////////////////////////////////////// struct tIndexArray { - tHeader mHeader; - tRecordIndex maRecordIndex[MAX_RECORDS]; + tHeader mHeader; + tRecordIndex maRecordIndex[MAX_RECORDS]; }; private: - cBlockFile* mpBlockFile; - int mBlockNum; // the block that I am operating on - int mSpaceAvailable; // amount of storage I have left - int mNumItems; // number of items currently being stored in this array - bool mbInit; // has InitXXX() been called? + cBlockFile* mpBlockFile; + int mBlockNum; // the block that I am operating on + int mSpaceAvailable; // amount of storage I have left + int mNumItems; // number of items currently being stored in this array + bool mbInit; // has InitXXX() been called? void UpdateFreeSpace(cBlockFile::Block* pBlock); - // calculates the total free space available in this array and assigns - // it to mSpaceAvailable. Note that the value of mSpaceAvailable signifies - // the size of the largest single item that could be added to the array. + // calculates the total free space available in this array and assigns + // it to mSpaceAvailable. Note that the value of mSpaceAvailable signifies + // the size of the largest single item that could be added to the array. void WriteHeaderInfo(cBlockFile::Block* pBlock); - // gets the header information at the top of our block in sync with our member vars - void ReadHeaderInfo (cBlockFile::Block* pBlock); - // reads the header info from the block and sets our member vars to what was read + // gets the header information at the top of our block in sync with our member vars + void ReadHeaderInfo(cBlockFile::Block* pBlock); + // reads the header info from the block and sets our member vars to what was read /////////////////////////////////////////////////////////////////////////// // Profiling / Debugging interface @@ -189,14 +227,12 @@ class cBlockRecordArray #ifdef _BLOCKFILE_DEBUG public: void TraceContents(int dl = -1) const; - // traces out all the info we can on the current state of this class - // dl is the debug level to trace it at; -1 means to use D_DEBUG + // traces out all the info we can on the current state of this class + // dl is the debug level to trace it at; -1 means to use D_DEBUG void AssertValid() const; - // ASSERTs as much as we can about the consistency of our internal state. + // ASSERTs as much as we can about the consistency of our internal state. #endif }; - #endif //__BLOCKRECORDARRAY_H - diff --git a/src/db/blockrecordarray_t.cpp b/src/db/blockrecordarray_t.cpp deleted file mode 100644 index 181b7a2..0000000 --- a/src/db/blockrecordarray_t.cpp +++ /dev/null @@ -1,134 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -// blockrecordarray_t.cpp - -#include "stddb.h" -#include "db/blockrecordarray.h" -#include "test/test.h" -#include "core/debug.h" -#include "core/error.h" - -void TestBlockRecordArray() -{ - cDebug d( "TestBlockRecordArray" ); - try - { - static const TCHAR fileName[] = _T("c:/tmp/test.bf"); - - cBlockFile bf; - bf.Open( fileName, 2, true ); // opened up with two pages - - // make sure the file is large enough... - // - while( bf.GetNumBlocks() < 2 ) - { - bf.CreateBlock(); - } - - // create the record arrays and associate them with the two blocks... - // - cBlockRecordArray ra1( &bf, 0 ); ra1.InitNewBlock(); - cBlockRecordArray ra2( &bf, 1 ); ra2.InitNewBlock(); - // - // now, start adding and removing things from the arrays... - // - static const char data1[] = "This is data 1"; - static const char data2[] = "And here we have data 2"; - static const char data3[] = "Here is d a t a 3!"; - static const char data4[] = "Three cheers for data 4!"; - ra1.AddItem( (int8*)data1, sizeof(data1), 1 ); - ra1.AddItem( (int8*)data2, sizeof(data2), 2 ); - ra1.AddItem( (int8*)data3, sizeof(data3), 3 ); - ra1.AddItem( (int8*)data4, sizeof(data4), 4 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // TODO -- try deleting the second to last and then the last thing from the array to - // see if we clean up properly. - - // delete item 2... - ra1.DeleteItem( 1 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // add a new item... - static const char data5[] = "fffiiivvveee!"; - ra1.AddItem( (int8*)data5, sizeof(data5), 5 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // delete the second to last and last items to see if we clean up properly... - // note that there are four things here at this point. - ra1.DeleteItem( 2 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - ra1.DeleteItem( 3 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // delete the first item to see if that works ok.... - ra1.DeleteItem( 0 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // add a couple more just for kicks :-) - static const char data6[] = "We're looking for six"; - static const char data7[] = "All 7s go to heaven"; - ra1.AddItem( (int8*)data6, sizeof(data6), 6 ); - ra1.AddItem( (int8*)data7, sizeof(data7), 7 ); - #ifdef _BLOCKFILE_DEBUG - ra1.TraceContents(); - #endif - - // Now, we will close the file, reopen it and see if we can read it ok. - // - bf.Close(); - bf.Open( fileName, 2, false ); - cBlockRecordArray ra3( &bf, 0 ); ra3.InitForExistingBlock(); - d.TraceDebug( "\n------ Tracing out the contents of the first block after being read back in from disk...\n\n"); - #ifdef _BLOCKFILE_DEBUG - ra3.TraceContents(); - #endif - } - catch( eError& e ) - { - d.TraceError( "Exception caught: %d %s\n", e.GetID(), e.GetMsg().c_str() ); - TEST( false ); - } -} - diff --git a/src/db/blockrecordfile.cpp b/src/db/blockrecordfile.cpp index e049181..9cc9961 100644 --- a/src/db/blockrecordfile.cpp +++ b/src/db/blockrecordfile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,9 +40,9 @@ /////////////////////////////////////////////////////////////////////////////// // util_InitBlockArray /////////////////////////////////////////////////////////////////////////////// -static inline void util_InitBlockArray( cBlockRecordArray& block ) +static inline void util_InitBlockArray(cBlockRecordArray& block) { - if( ! block.Initialized() ) + if (!block.Initialized()) { block.InitForExistingBlock(); } @@ -51,9 +51,7 @@ static inline void util_InitBlockArray( cBlockRecordArray& block ) /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cBlockRecordFile::cBlockRecordFile() -: mLastAddedTo( -1 ), - mbOpen ( false ) +cBlockRecordFile::cBlockRecordFile() : mLastAddedTo(-1), mbOpen(false) { } @@ -68,43 +66,43 @@ cBlockRecordFile::~cBlockRecordFile() /////////////////////////////////////////////////////////////////////////////// // Open /////////////////////////////////////////////////////////////////////////////// -void cBlockRecordFile::Open ( const TSTRING& fileName, int numPages, bool bTruncate) //throw (eArchive) +void cBlockRecordFile::Open(const TSTRING& fileName, int numPages, bool bTruncate) //throw (eArchive) { - ASSERT( ! mbOpen ); + ASSERT(!mbOpen); // first, open the file.. // - mBlockFile.Open( fileName, numPages, bTruncate ); + mBlockFile.Open(fileName, numPages, bTruncate); } -void cBlockRecordFile::Open( cBidirArchive* pArch, int numPages ) //throw (eArchive) +void cBlockRecordFile::Open(cBidirArchive* pArch, int numPages) //throw (eArchive) { - ASSERT( ! mbOpen ); - bool bTruncate = ( pArch->Length() == 0 ); + ASSERT(!mbOpen); + bool bTruncate = (pArch->Length() == 0); - mBlockFile.Open( pArch, numPages ); + mBlockFile.Open(pArch, numPages); - OpenImpl( bTruncate ); + OpenImpl(bTruncate); } /////////////////////////////////////////////////////////////////////////////// // OpenImpl /////////////////////////////////////////////////////////////////////////////// -void cBlockRecordFile::OpenImpl( bool bTruncate ) //throw (eArchive) +void cBlockRecordFile::OpenImpl(bool bTruncate) //throw (eArchive) { - ASSERT( ! mbOpen ); + ASSERT(!mbOpen); // // create the vector of block record arrays...avoid initializing them all // right now so that we don't page the whole file into memory // mvBlocks.clear(); - for( int i=0; i < mBlockFile.GetNumBlocks(); i++ ) + for (int i = 0; i < mBlockFile.GetNumBlocks(); i++) { - mvBlocks.push_back( cBlockRecordArray( &mBlockFile, i ) ); + mvBlocks.push_back(cBlockRecordArray(&mBlockFile, i)); // // if we are creating a new file, initialize the block for first usage... // - if( bTruncate ) + if (bTruncate) { mvBlocks.back().InitNewBlock(); } @@ -112,15 +110,15 @@ void cBlockRecordFile::OpenImpl( bool bTruncate ) //throw (eArchive) // // use the integrity of the first block as a q&d check for file integrity... // - ASSERT( mvBlocks.size() > 0 ); - if(! mvBlocks.begin()->Initialized() ) + ASSERT(mvBlocks.size() > 0); + if (!mvBlocks.begin()->Initialized()) { mvBlocks.begin()->InitForExistingBlock(); } - if( ! mvBlocks.begin()->IsClassValid() ) + if (!mvBlocks.begin()->IsClassValid()) { TSTRING str = _T("Bad file format for the Block Record File"); - throw eArchiveFormat( str ); + throw eArchiveFormat(str); } // set the last item added to to zero (TODO -- is this the right thing to do or // should I store it in the archive? @@ -152,9 +150,9 @@ void cBlockRecordFile::Flush() //throw (eArchive) /////////////////////////////////////////////////////////////////////////////// // AddItem /////////////////////////////////////////////////////////////////////////////// -cBlockRecordFile::tAddr cBlockRecordFile::AddItem( int8* pData, int dataSize ) //throw (eArchive) +cBlockRecordFile::tAddr cBlockRecordFile::AddItem(int8* pData, int dataSize) //throw (eArchive) { - ASSERT( mbOpen ); + ASSERT(mbOpen); #ifdef _BLOCKFILE_DEBUG AssertValid(); #endif @@ -162,11 +160,11 @@ cBlockRecordFile::tAddr cBlockRecordFile::AddItem( int8* pData, int dataSize ) / // // first, let's find room for this data item... // - rtn.mBlockNum = FindRoomForData( dataSize ); + rtn.mBlockNum = FindRoomForData(dataSize); // // now, insert the data... // - rtn.mIndex = mvBlocks[rtn.mBlockNum].AddItem( pData, dataSize, 1 ); + rtn.mIndex = mvBlocks[rtn.mBlockNum].AddItem(pData, dataSize, 1); // // update the last added to pointer and return the location... // @@ -177,15 +175,15 @@ cBlockRecordFile::tAddr cBlockRecordFile::AddItem( int8* pData, int dataSize ) / /////////////////////////////////////////////////////////////////////////////// // RemoveItem /////////////////////////////////////////////////////////////////////////////// -void cBlockRecordFile::RemoveItem( cBlockRecordFile::tAddr dataAddr ) //throw (eArchive) +void cBlockRecordFile::RemoveItem(cBlockRecordFile::tAddr dataAddr) //throw (eArchive) { - ASSERT( mbOpen ); - ASSERT( IsValidAddr( dataAddr ) ); + ASSERT(mbOpen); + ASSERT(IsValidAddr(dataAddr)); #ifdef _BLOCKFILE_DEBUG AssertValid(); #endif - - mvBlocks[ dataAddr.mBlockNum ].DeleteItem( dataAddr.mIndex ); + + mvBlocks[dataAddr.mBlockNum].DeleteItem(dataAddr.mIndex); // // remove unneeded blocks at the end... // @@ -211,53 +209,53 @@ void cBlockRecordFile::RemoveItem( cBlockRecordFile::tAddr dataAddr ) //throw (e /////////////////////////////////////////////////////////////////////////////// // IsValidAddr /////////////////////////////////////////////////////////////////////////////// -bool cBlockRecordFile::IsValidAddr( cBlockRecordFile::tAddr addr ) //throw (eArchive) +bool cBlockRecordFile::IsValidAddr(cBlockRecordFile::tAddr addr) //throw (eArchive) { - ASSERT( mbOpen ); + ASSERT(mbOpen); - if( (addr.mBlockNum < 0) || (addr.mBlockNum >= mBlockFile.GetNumBlocks()) ) + if ((addr.mBlockNum < 0) || (addr.mBlockNum >= mBlockFile.GetNumBlocks())) return false; - - util_InitBlockArray( mvBlocks[ addr.mBlockNum ] ); - return ( mvBlocks[ addr.mBlockNum ].IsItemValid( addr.mIndex ) ); + util_InitBlockArray(mvBlocks[addr.mBlockNum]); + + return (mvBlocks[addr.mBlockNum].IsItemValid(addr.mIndex)); } /////////////////////////////////////////////////////////////////////////////// // GetDataForReading /////////////////////////////////////////////////////////////////////////////// -int8* cBlockRecordFile::GetDataForReading( cBlockRecordFile::tAddr dataAddr, int32& dataSize ) //throw (eArchive) +int8* cBlockRecordFile::GetDataForReading(cBlockRecordFile::tAddr dataAddr, int32& dataSize) //throw (eArchive) { - ASSERT( mbOpen ); - ASSERT( IsValidAddr( dataAddr ) ); + ASSERT(mbOpen); + ASSERT(IsValidAddr(dataAddr)); #ifdef _BLOCKFILE_DEBUG AssertValid(); #endif - return ( mvBlocks[ dataAddr.mBlockNum ].GetDataForReading( dataAddr.mIndex, dataSize ) ); + return (mvBlocks[dataAddr.mBlockNum].GetDataForReading(dataAddr.mIndex, dataSize)); } /////////////////////////////////////////////////////////////////////////////// // GetDataForWriting /////////////////////////////////////////////////////////////////////////////// -int8* cBlockRecordFile::GetDataForWriting( cBlockRecordFile::tAddr dataAddr, int32& dataSize ) //throw (eArchive) +int8* cBlockRecordFile::GetDataForWriting(cBlockRecordFile::tAddr dataAddr, int32& dataSize) //throw (eArchive) { - ASSERT( mbOpen ); - ASSERT( IsValidAddr( dataAddr ) ); + ASSERT(mbOpen); + ASSERT(IsValidAddr(dataAddr)); #ifdef _BLOCKFILE_DEBUG AssertValid(); #endif - return ( mvBlocks[ dataAddr.mBlockNum ].GetDataForWriting( dataAddr.mIndex, dataSize ) ); + return (mvBlocks[dataAddr.mBlockNum].GetDataForWriting(dataAddr.mIndex, dataSize)); } /////////////////////////////////////////////////////////////////////////////// // FindRoomForData /////////////////////////////////////////////////////////////////////////////// -int cBlockRecordFile::FindRoomForData( int32 dataSize ) //throw (eArchive) +int cBlockRecordFile::FindRoomForData(int32 dataSize) //throw (eArchive) { - ASSERT( (dataSize > 0) && (dataSize <= cBlockRecordArray::MAX_DATA_SIZE) ); - ASSERT( mbOpen ); + ASSERT((dataSize > 0) && (dataSize <= cBlockRecordArray::MAX_DATA_SIZE)); + ASSERT(mbOpen); #ifdef _BLOCKFILE_DEBUG AssertValid(); #endif @@ -265,37 +263,40 @@ int cBlockRecordFile::FindRoomForData( int32 dataSize ) //throw (eArchive) // first, try the last added to block... // - d.TraceDetail( "Looking for room for %d bytes; first trying mLastAddedTo (%d)\n", dataSize, mLastAddedTo ); - util_InitBlockArray( mvBlocks[mLastAddedTo] ); - if( mvBlocks[mLastAddedTo].GetAvailableSpace() >= dataSize ) + d.TraceDetail("Looking for room for %d bytes; first trying mLastAddedTo (%d)\n", dataSize, mLastAddedTo); + if (mLastAddedTo >= 0) { - d.TraceDetail( "---Found room in block %d\n", mLastAddedTo ); - return mLastAddedTo; + util_InitBlockArray(mvBlocks[mLastAddedTo]); + if (mvBlocks[mLastAddedTo].GetAvailableSpace() >= dataSize) + { + d.TraceDetail("---Found room in block %d\n", mLastAddedTo); + return mLastAddedTo; + } } // // ok, I guess we will have to iterate through all the blocks... // BlockArray::iterator it; - int cnt = 0; - for( it = mvBlocks.begin(); it != mvBlocks.end(); it++, cnt++ ) + int cnt = 0; + for (it = mvBlocks.begin(); it != mvBlocks.end(); ++it, ++cnt) { - util_InitBlockArray( *it ); - if( it->GetAvailableSpace() >= dataSize ) + util_InitBlockArray(*it); + if (it->GetAvailableSpace() >= dataSize) { - d.TraceDetail( "---Found room in block %d\n", cnt ); + d.TraceDetail("---Found room in block %d\n", cnt); return cnt; } } // // if we got here, then we need to add a new block // - d.TraceDetail( "---We need to add new block(%d)\n", cnt); + d.TraceDetail("---We need to add new block(%d)\n", cnt); mBlockFile.CreateBlock(); - ASSERT( (mBlockFile.GetNumBlocks() == (mvBlocks.size()+1)) && (mvBlocks.size() == cnt) ); - mvBlocks.push_back( cBlockRecordArray( &mBlockFile, cnt ) ); + ASSERT((mBlockFile.GetNumBlocks() == (mvBlocks.size() + 1)) && (mvBlocks.size() == cnt)); + mvBlocks.push_back(cBlockRecordArray(&mBlockFile, cnt)); mvBlocks.back().InitNewBlock(); - ASSERT( mvBlocks.back().GetAvailableSpace() >= dataSize ); + ASSERT(mvBlocks.back().GetAvailableSpace() >= dataSize); return cnt; } @@ -310,9 +311,9 @@ void cBlockRecordFile::TraceContents(int dl) const { // TODO -- this is probably not what I want to do, but it helps me right now... // - for( BlockArray::const_iterator i = mvBlocks.begin(); i != mvBlocks.end(); i++ ) + for (BlockArray::const_iterator i = mvBlocks.begin(); i != mvBlocks.end(); ++i) { - i->TraceContents( dl ); + i->TraceContents(dl); } } @@ -321,16 +322,16 @@ void cBlockRecordFile::TraceContents(int dl) const /////////////////////////////////////////////////////////////////////////////// void cBlockRecordFile::AssertValid() const { - ASSERT( (mLastAddedTo >= 0) && (mLastAddedTo < mvBlocks.size()) ); - ASSERT( mvBlocks.size() == mBlockFile.GetNumBlocks() ); + ASSERT((mLastAddedTo >= 0) && (mLastAddedTo < mvBlocks.size())); + ASSERT(mvBlocks.size() == mBlockFile.GetNumBlocks()); } /////////////////////////////////////////////////////////////////////////////// // AssertAllBlocksValid /////////////////////////////////////////////////////////////////////////////// -void cBlockRecordFile::AssertAllBlocksValid() +void cBlockRecordFile::AssertAllBlocksValid() { - for( BlockArray::iterator i = mvBlocks.begin(); i != mvBlocks.end(); i++ ) + for (BlockArray::iterator i = mvBlocks.begin(); i != mvBlocks.end(); ++i) { i->AssertValid(); } @@ -338,4 +339,3 @@ void cBlockRecordFile::AssertAllBlocksValid() #endif - diff --git a/src/db/blockrecordfile.h b/src/db/blockrecordfile.h index 5a664af..c12897b 100644 --- a/src/db/blockrecordfile.h +++ b/src/db/blockrecordfile.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -62,11 +62,11 @@ class cBlockRecordFile //------------------------------------------------------------------------- // Opening and Closing Files //------------------------------------------------------------------------- - virtual void Open ( const TSTRING& fileName, int numPages, bool bTruncate = false ) ; //throw (eArchive) - virtual void Open ( cBidirArchive* pArch, int numPages ) ; //throw (eArchive) + virtual void Open(const TSTRING& fileName, int numPages, bool bTruncate = false); //throw (eArchive) + virtual void Open(cBidirArchive* pArch, int numPages); //throw (eArchive) // for the second Open(), this class owns the destruction of the archive - virtual void Close () ; //throw (eArchive) - virtual void Flush () ; //throw (eArchive) + virtual void Close(); //throw (eArchive) + virtual void Flush(); //throw (eArchive) //------------------------------------------------------------------------- // tAddr -- struct that is used to identify the location of a data item in @@ -74,66 +74,76 @@ class cBlockRecordFile //------------------------------------------------------------------------- struct tAddr { - int32 mBlockNum; - int32 mIndex; + int32 mBlockNum; + int32 mIndex; - tAddr(int32 block = -1, int32 addr = -1) : mBlockNum(block), mIndex(addr) {} + tAddr(int32 block = -1, int32 addr = -1) : mBlockNum(block), mIndex(addr) + { + } }; //------------------------------------------------------------------------- // Adding and Removing Data //------------------------------------------------------------------------- - tAddr AddItem( int8* pData, int dataSize ) ; //throw (eArchive) + tAddr AddItem(int8* pData, int dataSize); //throw (eArchive) // adds the given data to the file, growing it as necessary. Return value // can be used in the future to retrieve the data - void RemoveItem( tAddr dataAddr ) ; //throw (eArchive) - // removes the named data from the file. This will assert that the given - // address is valid, and will shrink the end of the file if there are + void RemoveItem(tAddr dataAddr); //throw (eArchive) + // removes the named data from the file. This will assert that the given + // address is valid, and will shrink the end of the file if there are // empty blocks at the end after the removal TODO -- it doesn't actually // do the latter. //------------------------------------------------------------------------- // Accessing Data //------------------------------------------------------------------------- - bool IsValidAddr( tAddr addr ) ; //throw (eArchive) + bool IsValidAddr(tAddr addr); //throw (eArchive) // returns true if the given address points to valid data - int8* GetDataForReading( tAddr dataAddr, int32& dataSize ) ; //throw (eArchive) + int8* GetDataForReading(tAddr dataAddr, int32& dataSize); //throw (eArchive) // returns a pointer to the named data. This method will assert that the address is // valid. The data pointer returned is guarenteed to be valid only until the next // method call into this class. - int8* GetDataForWriting( tAddr dataAddr, int32& dataSize ) ; //throw (eArchive) + int8* GetDataForWriting(tAddr dataAddr, int32& dataSize); //throw (eArchive) // this is the same as the previous function, except the dirty bit for the page is also set - cBidirArchive* GetArchive() { return mBlockFile.GetArchive(); } - // NOTE -- be very careful with this; only read from it and do not write to it. + cBidirArchive* GetArchive() + { + return mBlockFile.GetArchive(); + } + // NOTE -- be very careful with this; only read from it and do not write to it. //------------------------------------------------------------------------- // Private Implementation //------------------------------------------------------------------------- protected: - typedef std::vector BlockArray; + typedef std::vector BlockArray; // // NOTE -- use all of these methods with much care! // - cBlockFile* GetBlockFile () { return &mBlockFile; } - BlockArray* GetBlockArray () { return &mvBlocks; } + cBlockFile* GetBlockFile() + { + return &mBlockFile; + } + BlockArray* GetBlockArray() + { + return &mvBlocks; + } private: + int32 mLastAddedTo; // optimization that keeps track of last block added to + bool mbOpen; // are we currently associated with a file? + cBlockFile mBlockFile; + BlockArray mvBlocks; - int32 mLastAddedTo; // optimization that keeps track of last block added to - bool mbOpen; // are we currently associated with a file? - cBlockFile mBlockFile; - BlockArray mvBlocks; - - cBlockRecordFile ( const cBlockRecordFile& rhs ); //not impl - void operator= ( const cBlockRecordFile& rhs ); //not impl + cBlockRecordFile(const cBlockRecordFile& rhs); //not impl + void operator=(const cBlockRecordFile& rhs); //not impl - int FindRoomForData( int32 dataSize ); //throw (eArchive) - // searches through all the blocks, starting with mLastAddedTo, looking + int FindRoomForData(int32 dataSize); //throw (eArchive) + // searches through all the blocks, starting with mLastAddedTo, looking // for one with dataSize free space. This asserts that the size is valid // for storage in a block - void OpenImpl( bool bTruncate ); //throw (eArchive) - // implementation of the Open() methods above; both end up calling this. + void OpenImpl(bool bTruncate); //throw (eArchive) + // implementation of the Open() methods above; both end up calling this. //------------------------------------------------------------------------- // Profiling / Debugging Interface @@ -141,16 +151,14 @@ class cBlockRecordFile #ifdef _BLOCKFILE_DEBUG public: void TraceContents(int dl = -1) const; - // traces out all the info we can on the current state of this class - // dl is the debug level to trace it at; -1 means to use D_DEBUG + // traces out all the info we can on the current state of this class + // dl is the debug level to trace it at; -1 means to use D_DEBUG void AssertValid() const; - // ASSERTs as much as we can about the consistancy of our internal state. - void AssertAllBlocksValid() ; - // time consuming function that calls AssertValid() on all of the blocks + // ASSERTs as much as we can about the consistancy of our internal state. + void AssertAllBlocksValid(); + // time consuming function that calls AssertValid() on all of the blocks #endif - }; #endif //__BLOCKRECORDFILE_H - diff --git a/src/db/db.cpp b/src/db/db.cpp index 6493d78..2a3d4b9 100644 --- a/src/db/db.cpp +++ b/src/db/db.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,15 +37,11 @@ // #include "stddb.h" #include "db.h" -#include "core/core.h" // for: TSS_Package( cCore ) +#include "core/core.h" // for: TSS_Package( cCore ) -TSS_ImplementPackage( cDb ) +TSS_ImplementPackage(cDb) cDb::cDb() { - TSS_Dependency( cCore ); + TSS_Dependency(cCore); } - - -// eof: db.cpp - diff --git a/src/db/db.h b/src/db/db.h index 2102ca9..b688ace 100644 --- a/src/db/db.h +++ b/src/db/db.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,18 +41,17 @@ //--Include Core Platform Declarations -#include "core/package.h" // for: Packaging Abstraction +#include "core/package.h" // for: Packaging Abstraction //--Classes -TSS_BeginPackage( cDb ) +TSS_BeginPackage(cDb) - public: + public : - cDb(); + cDb(); -TSS_EndPackage( cDb ) +TSS_EndPackage(cDb) #endif //__DB_H - diff --git a/src/db/dberrors.cpp b/src/db/dberrors.cpp index 822159e..5257937 100644 --- a/src/db/dberrors.cpp +++ b/src/db/dberrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,18 +36,17 @@ // #include "stddb.h" -#include "core/errortable.h" - +#include "dberrors.h" #include "hierdatabase.h" -TSS_BEGIN_ERROR_REGISTRATION( db ) +TSS_BEGIN_ERROR_REGISTRATION(db) // // HierDatabase // -TSS_REGISTER_ERROR( eHierDatabase(), _T("Database Error.") ) -TSS_REGISTER_ERROR( eHierDbInternal(), _T("Internal database error.") ) -TSS_REGISTER_ERROR( eHierDbDupeName(), _T("Attempt to add duplicate name to database.") ) +TSS_REGISTER_ERROR(eHierDatabase(), _T("Database Error.")) +TSS_REGISTER_ERROR(eHierDbInternal(), _T("Internal database error.")) +TSS_REGISTER_ERROR(eHierDbDupeName(), _T("Attempt to add duplicate name to database.")) TSS_END_ERROR_REGISTRATION() diff --git a/src/core/userstring.cpp b/src/db/dberrors.h similarity index 81% rename from src/core/userstring.cpp rename to src/db/dberrors.h index f94d8af..d9a7fbe 100644 --- a/src/core/userstring.cpp +++ b/src/db/dberrors.h @@ -1,37 +1,47 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // -// userstring.cpp -#include "stdcore.h" -#include "userstring.h" +// +// Name....: dberrors.h +// Date....: 5/17/99 +// Creator.: Matthew Brinkley (brinkley) +// +// + +#ifndef __DBERRORS_H +#define __DBERRORS_H + +#include "core/errortable.h" + +TSS_DECLARE_ERROR_REGISTRATION(db) -iUserString* iUserString::mpInstance; +#endif //__DBERRORS_H diff --git a/src/db/hierdatabase.cpp b/src/db/hierdatabase.cpp index 8c98ea3..227439b 100644 --- a/src/db/hierdatabase.cpp +++ b/src/db/hierdatabase.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,53 +39,54 @@ #include "core/archive.h" #include "core/upperbound.h" #include "core/errorbucket.h" +#include "core/errorbucketimpl.h" -// TODO -- all of these util_ functions should throw an eArchive if an attempt is made to +// TODO -- all of these util_ functions should throw an eArchive if an attempt is made to // write to a null address -static inline void util_ThrowIfNull( const cHierAddr& addr, const TSTRING& context ) +static inline void util_ThrowIfNull(const cHierAddr& addr, const TSTRING& context) { - ASSERT( ! addr.IsNull() ); - if( addr.IsNull() ) + ASSERT(!addr.IsNull()); + if (addr.IsNull()) { TSTRING msg(_T("Attempt to access null address")); - if( ! context.empty() ) + if (!context.empty()) { msg += _T(" in ") + context; } - throw eHierDatabase( msg ); - } + throw eHierDatabase(msg); + } } /////////////////////////////////////////////////////////////////////////////// // util_ReadObject -- this will read the given object from the database from the // given address. eArchive is thrown on exception. /////////////////////////////////////////////////////////////////////////////// -static void util_ReadObject( cHierDatabase* pDb, cHierNode* pNode, const cHierAddr& addr ) +static void util_ReadObject(cHierDatabase* pDb, cHierNode* pNode, const cHierAddr& addr) { - int32 dataSize; - int8* pData = pDb->GetDataForReading( cBlockRecordFile::tAddr(addr.mBlockNum, addr.mIndex), dataSize ); + int32 dataSize; + int8* pData = pDb->GetDataForReading(cBlockRecordFile::tAddr(addr.mBlockNum, addr.mIndex), dataSize); // // make sure we aren't trying to read a null object // - util_ThrowIfNull( addr, _T("util_ReadObject") ); + util_ThrowIfNull(addr, _T("util_ReadObject")); - cFixedMemArchive arch( pData, dataSize ); - pNode->Read( arch ); + cFixedMemArchive arch(pData, dataSize); + pNode->Read(arch); } /////////////////////////////////////////////////////////////////////////////// // util_WriteObject -- this will write the given object to the database, returning // the address that it was written to, and throwing eArchive on error. /////////////////////////////////////////////////////////////////////////////// -static cHierAddr util_WriteObject( cHierDatabase* pDb, cHierNode* pNode ) +static cHierAddr util_WriteObject(cHierDatabase* pDb, cHierNode* pNode) { static cMemoryArchive arch; - arch.Seek( 0, cBidirArchive::BEGINNING ); - pNode->Write( arch ); + arch.Seek(0, cBidirArchive::BEGINNING); + pNode->Write(arch); - cBlockRecordFile::tAddr addr = pDb->AddItem( arch.GetMemory(), arch.CurrentPos() ); - return cHierAddr( addr.mBlockNum, addr.mIndex ); + cBlockRecordFile::tAddr addr = pDb->AddItem(arch.GetMemory(), arch.CurrentPos()); + return cHierAddr(addr.mBlockNum, addr.mIndex); } /////////////////////////////////////////////////////////////////////////////// @@ -93,27 +94,24 @@ static cHierAddr util_WriteObject( cHierDatabase* pDb, cHierNode* pNode ) // its size has not; this will update the database without changing the // object's address. /////////////////////////////////////////////////////////////////////////////// -static void util_RewriteObject( cHierDatabase* pDb, cHierNode* pNode, const cHierAddr& addr ) +static void util_RewriteObject(cHierDatabase* pDb, cHierNode* pNode, const cHierAddr& addr) { - int32 dataSize; - int8* pData = pDb->GetDataForWriting( cBlockRecordFile::tAddr(addr.mBlockNum, addr.mIndex), dataSize ); + int32 dataSize; + int8* pData = pDb->GetDataForWriting(cBlockRecordFile::tAddr(addr.mBlockNum, addr.mIndex), dataSize); - util_ThrowIfNull( addr, _T("util_RewriteObject") ); + util_ThrowIfNull(addr, _T("util_RewriteObject")); - cFixedMemArchive arch( pData, dataSize ); - pNode->Write( arch ); + cFixedMemArchive arch(pData, dataSize); + pNode->Write(arch); } /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cHierDatabase::cHierDatabase( bool bCaseSensitive, TCHAR delChar ) -: mRootArrayAddr (), - mbCaseSensitive ( bCaseSensitive ), - mDelimitingChar ( delChar ) +cHierDatabase::cHierDatabase(bool bCaseSensitive, TCHAR delChar) + : mRootArrayAddr(), mbCaseSensitive(bCaseSensitive), mDelimitingChar(delChar) { - } /////////////////////////////////////////////////////////////////////////////// @@ -121,22 +119,21 @@ cHierDatabase::cHierDatabase( bool bCaseSensitive, TCHAR delChar ) /////////////////////////////////////////////////////////////////////////////// cHierDatabase::~cHierDatabase() { - } /////////////////////////////////////////////////////////////////////////////// // Open /////////////////////////////////////////////////////////////////////////////// -void cHierDatabase::Open ( cBidirArchive* pArch, int numPages ) //throw (eArchive, eHierDatabase) +void cHierDatabase::Open(cBidirArchive* pArch, int numPages) //throw (eArchive, eHierDatabase) { - bool bTruncate = ( pArch->Length() == 0 ); - inherited::Open( pArch, numPages ); + bool bTruncate = (pArch->Length() == 0); + inherited::Open(pArch, numPages); - OpenImpl( bTruncate ); + OpenImpl(bTruncate); } -void cHierDatabase::Open ( const TSTRING& fileName, int numPages, bool bTruncate ) //throw (eArchive, eHierDatabase) +void cHierDatabase::Open(const TSTRING& fileName, int numPages, bool bTruncate) //throw (eArchive, eHierDatabase) { inherited::Open(fileName, numPages, bTruncate); @@ -144,49 +141,49 @@ void cHierDatabase::Open ( const TSTRING& fileName, int numPages, bool bTruncate AssertValid(); #endif - OpenImpl( bTruncate ); + OpenImpl(bTruncate); } /////////////////////////////////////////////////////////////////////////////// // OpenImpl /////////////////////////////////////////////////////////////////////////////// -void cHierDatabase::OpenImpl ( bool bTruncate ) //throw (eArchive, eHierDatabase) +void cHierDatabase::OpenImpl(bool bTruncate) //throw (eArchive, eHierDatabase) { // now, we should write the root node at (0,0) if we are creating, and assert that the root node // is there if we are opening an existing one... // - if( bTruncate ) + if (bTruncate) { // // make the root node that we are creating... // cHierRoot rootNode; - rootNode.mChild = cHierAddr( 0, 1 ); // the first array will be placed at (0,1) - rootNode.mbCaseSensitive = mbCaseSensitive; - rootNode.mDelimitingChar = mDelimitingChar; - cHierAddr addr = util_WriteObject( this, &rootNode ); + rootNode.mChild = cHierAddr(0, 1); // the first array will be placed at (0,1) + rootNode.mbCaseSensitive = mbCaseSensitive; + rootNode.mDelimitingChar = mDelimitingChar; + cHierAddr addr = util_WriteObject(this, &rootNode); // // assert that it was written to (0, 0) // - ASSERT( (addr.mBlockNum == 0) && (addr.mIndex == 0) ); + ASSERT((addr.mBlockNum == 0) && (addr.mIndex == 0)); // // make an empty array to serve as the root array. // - cHierArrayInfo arrayInfo; - arrayInfo.mParent = cHierAddr(); - arrayInfo.mArray = cHierAddr(); + cHierArrayInfo arrayInfo; + arrayInfo.mParent = cHierAddr(); + arrayInfo.mArray = cHierAddr(); // // actually write the objects and assert that they were written to the right places. // - addr = util_WriteObject( this, &arrayInfo ); - ASSERT( (addr.mBlockNum == 0) && (addr.mIndex == 1) ); + addr = util_WriteObject(this, &arrayInfo); + ASSERT((addr.mBlockNum == 0) && (addr.mIndex == 1)); - mRootArrayAddr = cHierAddr( 0, 1 ); + mRootArrayAddr = cHierAddr(0, 1); } else { cHierRoot rootNode; - util_ReadObject( this, &rootNode, cHierAddr( 0, 0 ) ); + util_ReadObject(this, &rootNode, cHierAddr(0, 0)); // // set the location of the top-level array and the other root parameters... // @@ -197,16 +194,15 @@ void cHierDatabase::OpenImpl ( bool bTruncate ) //throw (eArchive, eHierDatabase } //----------------------------------------------------------------------------- -// cHierDatabaseIter +// cHierDatabaseIter //----------------------------------------------------------------------------- -cHierDatabaseIter::cHierDatabaseIter( cHierDatabase* pDb ) //throw(eArchive) -: mpDb ( pDb ), - mCurPath( ) +cHierDatabaseIter::cHierDatabaseIter(cHierDatabase* pDb) //throw(eArchive) + : mpDb(pDb), mCurPath() { - ASSERT( pDb != 0); - mCurPath.SetCaseSensitive ( mpDb->IsCaseSensitive() ); - mCurPath.SetDelimiter ( mpDb->GetDelimitingChar() ); + ASSERT(pDb != 0); + mCurPath.SetCaseSensitive(mpDb->IsCaseSensitive()); + mCurPath.SetDelimiter(mpDb->GetDelimitingChar()); // // load in the root array... // @@ -222,16 +218,16 @@ cHierDatabaseIter::~cHierDatabaseIter() /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::SeekToRoot() //throw (eArchive) { - ASSERT( mpDb != 0); - ASSERT( ! mpDb->mRootArrayAddr.IsNull() ); + ASSERT(mpDb != 0); + ASSERT(!mpDb->mRootArrayAddr.IsNull()); mCurPath.Clear(); - LoadArrayAt( mpDb->mRootArrayAddr ); + LoadArrayAt(mpDb->mRootArrayAddr); } /////////////////////////////////////////////////////////////////////////////// // copy ctor /////////////////////////////////////////////////////////////////////////////// -cHierDatabaseIter::cHierDatabaseIter( const cHierDatabaseIter& rhs ) +cHierDatabaseIter::cHierDatabaseIter(const cHierDatabaseIter& rhs) { *this = rhs; } @@ -239,26 +235,26 @@ cHierDatabaseIter::cHierDatabaseIter( const cHierDatabaseIter& rhs ) /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -cHierDatabaseIter& cHierDatabaseIter::operator=( const cHierDatabaseIter& rhs ) +cHierDatabaseIter& cHierDatabaseIter::operator=(const cHierDatabaseIter& rhs) { - mpDb = rhs.mpDb; - mEntries = rhs.mEntries; - mInfo = rhs.mInfo; - mInfoAddr = rhs.mInfoAddr; - mCurPath = rhs.mCurPath; + mpDb = rhs.mpDb; + mEntries = rhs.mEntries; + mInfo = rhs.mInfo; + mInfoAddr = rhs.mInfoAddr; + mCurPath = rhs.mCurPath; // // the iterator is a little trickier // - if( rhs.Done() ) + if (rhs.Done()) { mIter = mEntries.end(); } else { EntryArray::const_iterator p1, p2; - p1 = rhs.mIter; - p2 = rhs.mEntries.begin(); - mIter = mEntries.begin() + (p1 - p2); + p1 = rhs.mIter; + p2 = rhs.mEntries.begin(); + mIter = mEntries.begin() + (p1 - p2); } return (*this); @@ -270,7 +266,7 @@ cHierDatabaseIter& cHierDatabaseIter::operator=( const cHierDatabaseIter& rhs ) /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::LoadArrayAt(const cHierAddr& addr) //throw (eArchive, eHierDatabase) { - ASSERT( mpDb != 0); + ASSERT(mpDb != 0); // // make sure the address is non-null // @@ -278,20 +274,32 @@ void cHierDatabaseIter::LoadArrayAt(const cHierAddr& addr) //throw (eArchive, eH // // load the info and the array // - mInfoAddr = addr; - util_ReadObject( mpDb, &mInfo, mInfoAddr ); + mInfoAddr = addr; + util_ReadObject(mpDb, &mInfo, mInfoAddr); cHierAddr curAddr = mInfo.mArray; // // load in all the array entries... // mEntries.clear(); - while( ! curAddr.IsNull() ) + while (!curAddr.IsNull()) { - mEntries.push_back( cHierEntry() ); - util_ReadObject( mpDb, &mEntries.back(), curAddr ); + mEntries.push_back(cHierEntry()); + //Catch db errors, in case only part of db is broken + try + { + util_ReadObject(mpDb, &mEntries.back(), curAddr); + } + catch (eError& e) + { + e.SetFatality(false); + cErrorReporter::PrintErrorMsg(e); + mEntries.pop_back(); + break; + } + curAddr = mEntries.back().mNext; } - + // // seek to the beginning of the array // @@ -304,42 +312,42 @@ void cHierDatabaseIter::LoadArrayAt(const cHierAddr& addr) //throw (eArchive, eH /////////////////////////////////////////////////////////////////////////////// bool cHierDatabaseIter::AtRoot() const //throw (eHierDatabase) { - bool bResult = ( mInfoAddr == mpDb->mRootArrayAddr ); + bool bResult = (mInfoAddr == mpDb->mRootArrayAddr); // TODO -- maybe I want to put this in a #ifdef? // - if( bResult ) + if (bResult) { // we are at the root; assert that we have no parent... // - ASSERT( mInfo.mParent.IsNull() ); - if( ! mInfo.mParent.IsNull() ) + ASSERT(mInfo.mParent.IsNull()); + if (!mInfo.mParent.IsNull()) { - throw eHierDatabase( _T("Root node of db has a non-null parent") ); + throw eHierDatabase(_T("Root node of db has a non-null parent")); } } else { // if we are not at the root, assert that we have a parent... - ASSERT( ! mInfo.mParent.IsNull() ); - if( mInfo.mParent.IsNull() ) + ASSERT(!mInfo.mParent.IsNull()); + if (mInfo.mParent.IsNull()) { - throw eHierDatabase( _T("Non-root node of db has a null parent!") ); + throw eHierDatabase(_T("Non-root node of db has a null parent!")); } } return bResult; -} +} /////////////////////////////////////////////////////////////////////////////// // CanDescend /////////////////////////////////////////////////////////////////////////////// bool cHierDatabaseIter::CanDescend() const { - if( Done() ) + if (Done()) return false; - return (! mIter->mChild.IsNull() ); + return (!mIter->mChild.IsNull()); } /////////////////////////////////////////////////////////////////////////////// @@ -347,13 +355,13 @@ bool cHierDatabaseIter::CanDescend() const /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::Descend() { - ASSERT( CanDescend() ); - // + ASSERT(CanDescend()); + // // alter the cwd... // - mCurPath.Push( mIter->mName ); + mCurPath.Push(mIter->mName); - LoadArrayAt ( mIter->mChild ); + LoadArrayAt(mIter->mChild); } /////////////////////////////////////////////////////////////////////////////// @@ -361,14 +369,14 @@ void cHierDatabaseIter::Descend() /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::Ascend() { - ASSERT( ! AtRoot() ); - ASSERT( mCurPath.GetSize() > 0 ); + ASSERT(!AtRoot()); + ASSERT(mCurPath.GetSize() > 0); // // alter the cwd... // mCurPath.Pop(); - - LoadArrayAt ( mInfo.mParent ); + + LoadArrayAt(mInfo.mParent); } /////////////////////////////////////////////////////////////////////////////// @@ -377,14 +385,14 @@ void cHierDatabaseIter::Ascend() void cHierDatabaseIter::SeekBegin() { mIter = mEntries.begin(); -} +} /////////////////////////////////////////////////////////////////////////////// // Done /////////////////////////////////////////////////////////////////////////////// -bool cHierDatabaseIter::Done() const +bool cHierDatabaseIter::Done() const { - return ( mIter == mEntries.end() ); + return (mIter == mEntries.end()); } /////////////////////////////////////////////////////////////////////////////// @@ -392,7 +400,7 @@ bool cHierDatabaseIter::Done() const /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::Next() { - mIter++; + ++mIter; } /////////////////////////////////////////////////////////////////////////////// @@ -400,10 +408,10 @@ void cHierDatabaseIter::Next() /////////////////////////////////////////////////////////////////////////////// bool cHierDatabaseIter::SeekTo(const TCHAR* pName) { - EntryArray::iterator i = UpperBound( pName ); - if( i != mEntries.end() ) + EntryArray::iterator i = UpperBound(pName); + if (i != mEntries.end()) { - if( 0 == Compare( pName, (*i).mName.c_str() ) ) + if (0 == Compare(pName, (*i).mName.c_str())) { mIter = i; return true; @@ -419,10 +427,10 @@ bool cHierDatabaseIter::SeekTo(const TCHAR* pName) /////////////////////////////////////////////////////////////////////////////// const TCHAR* cHierDatabaseIter::GetName() const { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) { - throw eHierDatabase( _T("Attempt to call iter::GetName() when done is true")); + throw eHierDatabase(_T("Attempt to call iter::GetName() when done is true")); } return mIter->mName.c_str(); @@ -431,7 +439,7 @@ const TCHAR* cHierDatabaseIter::GetName() const /////////////////////////////////////////////////////////////////////////////// // GetCwd /////////////////////////////////////////////////////////////////////////////// -const TSTRING cHierDatabaseIter::GetCwd() const +const TSTRING cHierDatabaseIter::GetCwd() const { return mCurPath.AsString(); } @@ -441,18 +449,18 @@ const TSTRING cHierDatabaseIter::GetCwd() const /////////////////////////////////////////////////////////////////////////////// cHierAddr cHierDatabaseIter::GetCurrentAddr() const { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) { return cHierAddr(); } - if( mIter == mEntries.begin() ) + if (mIter == mEntries.begin()) { return mInfo.mArray; } - return (mIter-1)->mNext; + return (mIter - 1)->mNext; } /////////////////////////////////////////////////////////////////////////////// @@ -460,35 +468,35 @@ cHierAddr cHierDatabaseIter::GetCurrentAddr() const /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::CreateChildArray() //throw (eArchive, eHierDatabase) { - ASSERT( ! Done() ); - ASSERT( ! CanDescend() ); - if( Done() ) + ASSERT(!Done()); + ASSERT(!CanDescend()); + if (Done()) { - throw eHierDatabase( _T("Attempt to call iter::CreateChildArray() when done is true")); + throw eHierDatabase(_T("Attempt to call iter::CreateChildArray() when done is true")); } - if( CanDescend() ) + if (CanDescend()) { - throw eHierDatabase( _T("Attempt to call iter::CreateChildArray() when child already exists")); + throw eHierDatabase(_T("Attempt to call iter::CreateChildArray() when child already exists")); } - - cHierArrayInfo newInfo; - cHierAddr infoAddr; + + cHierArrayInfo newInfo; + cHierAddr infoAddr; // write the new info newInfo.mParent = mInfoAddr; - infoAddr = util_WriteObject( mpDb, &newInfo ); + infoAddr = util_WriteObject(mpDb, &newInfo); mIter->mChild = infoAddr; // // rewrite the current object, since its child info just changed // - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); } /////////////////////////////////////////////////////////////////////////////// // CreateEntry // /////////////////////////////////////////////////////////////////////////////// -void cHierDatabaseIter::CreateEntry( const TSTRING& name ) //throw (eArchive, eHierDatabase) +void cHierDatabaseIter::CreateEntry(const TSTRING& name) //throw (eArchive, eHierDatabase) { cHierEntry newEntry; newEntry.mName = name; @@ -496,53 +504,53 @@ void cHierDatabaseIter::CreateEntry( const TSTRING& name ) //throw (eArchive, eH // // insert this in order in the set... // - mIter = UpperBound( newEntry.mName.c_str() ); - + mIter = UpperBound(newEntry.mName.c_str()); + // // make sure that no duplicate names are added to the database... // - if( mIter != mEntries.end() ) + if (mIter != mEntries.end()) { - if( 0 == Compare( mIter->mName.c_str(), newEntry.mName.c_str() ) ) + if (0 == Compare(mIter->mName.c_str(), newEntry.mName.c_str())) { - return; - //throw eHierDbDupeName( name ); + return; + //throw eHierDbDupeName( name ); } } // Note -- insert() inserts directly _before_ the iterator - // we need to get the current address so we can set the new object's + // we need to get the current address so we can set the new object's // next pointer appropriately // cHierAddr nextAddr; - if( ! Done() ) + if (!Done()) { nextAddr = GetCurrentAddr(); } - mIter = mEntries.insert( mIter, newEntry ); + mIter = mEntries.insert(mIter, newEntry); // // first, we should write the new object to the database // - mIter->mNext = nextAddr; - cHierAddr newAddr = util_WriteObject( mpDb, &(*mIter) ); + mIter->mNext = nextAddr; + cHierAddr newAddr = util_WriteObject(mpDb, &(*mIter)); // // set the previous object's next pointer, and rewrite that object to disk... // - if( mIter == mEntries.begin() ) + if (mIter == mEntries.begin()) { // we need to rewrite the array info... // mInfo.mArray = newAddr; - util_RewriteObject( mpDb, &mInfo, mInfoAddr ); + util_RewriteObject(mpDb, &mInfo, mInfoAddr); } else { // altering the previous node... // - mIter--; + --mIter; mIter->mNext = newAddr; - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); - mIter++; + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); + ++mIter; } } @@ -551,30 +559,29 @@ void cHierDatabaseIter::CreateEntry( const TSTRING& name ) //throw (eArchive, eH /////////////////////////////////////////////////////////////////////////////// int8* cHierDatabaseIter::GetData(int32& length) const //throw (eArchive, eHierDatabase) { - ASSERT( HasData() ); - if( ! HasData() ) + ASSERT(HasData()); + if (!HasData()) { - throw eHierDatabase( _T("Attempt to get data from a node when HasData() is false")); + throw eHierDatabase(_T("Attempt to get data from a node when HasData() is false")); } // // note that we can only get data for reading; perhaps in the future I will add // support for retrieving data for writing as well. // - return mpDb->GetDataForReading( cBlockRecordFile::tAddr(mIter->mData.mBlockNum, mIter->mData.mIndex), length ); - + return mpDb->GetDataForReading(cBlockRecordFile::tAddr(mIter->mData.mBlockNum, mIter->mData.mIndex), length); } /////////////////////////////////////////////////////////////////////////////// // HasData /////////////////////////////////////////////////////////////////////////////// -bool cHierDatabaseIter::HasData() const +bool cHierDatabaseIter::HasData() const { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) return false; - return ( ! mIter->mData.IsNull() ); + return (!mIter->mData.IsNull()); } /////////////////////////////////////////////////////////////////////////////// @@ -582,25 +589,24 @@ bool cHierDatabaseIter::HasData() const /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::SetData(int8* pData, int32 length) //throw (eArchive, eHierDatabase) { - ASSERT( ! Done() ); - ASSERT( ! HasData() ); - + ASSERT(!Done()); + ASSERT(!HasData()); + // remove the item's data, if there is any... // - if( HasData() ) + if (HasData()) { RemoveData(); } // // add the data and set the entry's data pointer appropriately // - cBlockRecordFile::tAddr addr = mpDb->AddItem( pData, length ); - mIter->mData = cHierAddr( addr.mBlockNum, addr.mIndex ); + cBlockRecordFile::tAddr addr = mpDb->AddItem(pData, length); + mIter->mData = cHierAddr(addr.mBlockNum, addr.mIndex); // // update the entry on disk... // - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); - + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); } /////////////////////////////////////////////////////////////////////////////// @@ -608,68 +614,66 @@ void cHierDatabaseIter::SetData(int8* pData, int32 length) //throw (eArchive, eH /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::RemoveData() //throw (eArchive, eHierDatabase) { - ASSERT( ! Done() ); - if( ! HasData() ) + ASSERT(!Done()); + if (!HasData()) { - ASSERT( false ); + ASSERT(false); return; } - mpDb->RemoveItem( cBlockRecordFile::tAddr( mIter->mData.mBlockNum, mIter->mData.mIndex ) ); + mpDb->RemoveItem(cBlockRecordFile::tAddr(mIter->mData.mBlockNum, mIter->mData.mIndex)); // // now, we need to update the node's data pointer and save the node to disk // mIter->mData = cHierAddr(); - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); } - /////////////////////////////////////////////////////////////////////////////// // DeleteEntry /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::DeleteEntry() //throw (eArchive, eHierDatabase) { - ASSERT( ! Done() ); - ASSERT( ! CanDescend() ); // this node can't have any children. + ASSERT(!Done()); + ASSERT(!CanDescend()); // this node can't have any children. cDebug d("cHierDatabaseIter::DeleteEntry"); - if( Done() ) + if (Done()) { d.TraceDetail("Attempt to DeleteEntry() when Done() == true; returning\n"); return; } - if( CanDescend() ) + if (CanDescend()) { - throw eHierDatabase( _T("Attempt to delete an entry that still has children.\n")); + throw eHierDatabase(_T("Attempt to delete an entry that still has children.\n")); } - + // // first, we should set the previous node's next pointer... // cHierAddr curAddr = GetCurrentAddr(); - if( mIter == mEntries.begin() ) + if (mIter == mEntries.begin()) { // we are changing the info's mArray pointer // mInfo.mArray = mIter->mNext; - util_RewriteObject( mpDb, &mInfo, mInfoAddr ); + util_RewriteObject(mpDb, &mInfo, mInfoAddr); } else { // altering the previous node... // - mIter--; - mIter->mNext = (mIter+1)->mNext; - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); - mIter++; + --mIter; + mIter->mNext = (mIter + 1)->mNext; + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); + ++mIter; } // // now, delete the node from the file and from our array... // - mpDb->RemoveItem( cBlockRecordFile::tAddr( curAddr.mBlockNum, curAddr.mIndex ) ); + mpDb->RemoveItem(cBlockRecordFile::tAddr(curAddr.mBlockNum, curAddr.mIndex)); mIter = mEntries.erase(mIter); - } /////////////////////////////////////////////////////////////////////////////// @@ -677,12 +681,12 @@ void cHierDatabaseIter::DeleteEntry() //throw (eArchive, eHierDatabase) /////////////////////////////////////////////////////////////////////////////// bool cHierDatabaseIter::ChildArrayEmpty() { - ASSERT( ! Done() ); - ASSERT( CanDescend() ); + ASSERT(!Done()); + ASSERT(CanDescend()); - cHierArrayInfo info; - util_ReadObject ( mpDb, &info, mIter->mChild ); - return ( info.mArray.IsNull() ); + cHierArrayInfo info; + util_ReadObject(mpDb, &info, mIter->mChild); + return (info.mArray.IsNull()); } /////////////////////////////////////////////////////////////////////////////// @@ -690,16 +694,16 @@ bool cHierDatabaseIter::ChildArrayEmpty() /////////////////////////////////////////////////////////////////////////////// void cHierDatabaseIter::DeleteChildArray() //throw (eArchive, eHierDatabase) { - ASSERT( ! Done() ); - ASSERT( CanDescend() ); + ASSERT(!Done()); + ASSERT(CanDescend()); cDebug d("cHierDatabaseIter::DeleteChildArray"); - if( Done() ) + if (Done()) { d.TraceDetail("Attempt to DeleteChildArray() when Done() == true; returning\n"); return; } - if( ! CanDescend() ) + if (!CanDescend()) { d.TraceDetail("Attempt to DeleteChildArray() when none exists; returning\n"); return; @@ -707,17 +711,17 @@ void cHierDatabaseIter::DeleteChildArray() //throw (eArchive, eHierDatabase) // // make sure that the child index is empty... // - if( ! ChildArrayEmpty() ) + if (!ChildArrayEmpty()) { - ASSERT( false ); - throw eHierDatabase( _T("Attempt to delete a child array that still has entries") ); + ASSERT(false); + throw eHierDatabase(_T("Attempt to delete a child array that still has entries")); } // // ok, no we can remove it... // - mpDb->RemoveItem( cBlockRecordFile::tAddr( mIter->mChild.mBlockNum, mIter->mChild.mIndex ) ); + mpDb->RemoveItem(cBlockRecordFile::tAddr(mIter->mChild.mBlockNum, mIter->mChild.mIndex)); mIter->mChild = cHierAddr(); - util_RewriteObject( mpDb, &(*mIter), GetCurrentAddr() ); + util_RewriteObject(mpDb, &(*mIter), GetCurrentAddr()); } @@ -725,25 +729,24 @@ void cHierDatabaseIter::DeleteChildArray() //throw (eArchive, eHierDatabase) // CompareForUpperBound /////////////////////////////////////////////////////////////////////////////// -bool cHierDatabaseIter::CompareForUpperBound( const cHierEntry& he, const TCHAR* pchName ) const +bool cHierDatabaseIter::CompareForUpperBound(const cHierEntry& he, const TCHAR* pchName) const { - return( 0 > Compare( he.mName.c_str(), pchName ) ); + return (0 > Compare(he.mName.c_str(), pchName)); } /////////////////////////////////////////////////////////////////////////////// // cHierDatabaseIterCallCompare -// -- used to sneak a pointer-to-member-function where a +// -- used to sneak a pointer-to-member-function where a // pointer-to-non-member-function is expected /////////////////////////////////////////////////////////////////////////////// class cHierDatabaseIterCallCompare { public: - cHierDatabaseIterCallCompare( const cHierDatabaseIter* pcls ) - : pc( pcls ) {}; - - bool operator()( const cHierEntry& a1, const TCHAR* a2 ) + explicit cHierDatabaseIterCallCompare(const cHierDatabaseIter* pcls) : pc(pcls){}; + + bool operator()(const cHierEntry& a1, const TCHAR* a2) { - return pc->CompareForUpperBound( a1, a2 ); + return pc->CompareForUpperBound(a1, a2); } private: @@ -754,10 +757,8 @@ class cHierDatabaseIterCallCompare // UpperBound /////////////////////////////////////////////////////////////////////////////// -cHierDatabaseIter::EntryArray::iterator cHierDatabaseIter::UpperBound( const TCHAR* pchName ) +cHierDatabaseIter::EntryArray::iterator cHierDatabaseIter::UpperBound(const TCHAR* pchName) { - cHierDatabaseIterCallCompare comp( this ); - return ::UpperBound( mEntries.begin(), mEntries.end(), pchName, comp ); + cHierDatabaseIterCallCompare comp(this); + return ::UpperBound(mEntries.begin(), mEntries.end(), pchName, comp); } - - diff --git a/src/db/hierdatabase.h b/src/db/hierdatabase.h index a2f8413..52d1649 100644 --- a/src/db/hierdatabase.h +++ b/src/db/hierdatabase.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,16 +49,21 @@ #include "hierdbpath.h" #endif +#if HAVE_STRINGS_H // RTEMS needs this for strcasecmp +#include +#endif + + class cHierDatabaseIter; class cErrorBucket; -TSS_EXCEPTION( eHierDatabase, eError ); -TSS_EXCEPTION( eHierDbInternal, eHierDatabase ); // not used -TSS_EXCEPTION( eHierDbDupeName, eHierDatabase ); +TSS_EXCEPTION(eHierDatabase, eError); +TSS_EXCEPTION(eHierDbInternal, eHierDatabase); // not used +TSS_EXCEPTION(eHierDbDupeName, eHierDatabase); // -// TODO -- store some header info with the root node -- at least whether the db is case-sensitive or not +// TODO -- store some header info with the root node -- at least whether the db is case-sensitive or not // and what the delimiting character is // @@ -68,35 +73,46 @@ TSS_EXCEPTION( eHierDbDupeName, eHierDatabase ); class cHierDatabase : public cBlockRecordFile { public: - cHierDatabase( bool bCaseSensitive = true, TCHAR delChar = _T('/') ); - // NOTE -- these two parameters are only used if the database is being created; otherwise, they - // are overwritten when Open() is called. + cHierDatabase(bool bCaseSensitive = true, TCHAR delChar = _T('/')); + // NOTE -- these two parameters are only used if the database is being created; otherwise, they + // are overwritten when Open() is called. virtual ~cHierDatabase(); // // overrides from base class // - virtual void Open ( const TSTRING& fileName, int numPages = 5, bool bTruncate = false ); //throw (eArchive, eHierDatabase) - virtual void Open ( cBidirArchive* pArch, int numPages = 5 ); //throw (eArchive, eHierDatabase) + virtual void + Open(const TSTRING& fileName, int numPages = 5, bool bTruncate = false); //throw (eArchive, eHierDatabase) + virtual void Open(cBidirArchive* pArch, int numPages = 5); //throw (eArchive, eHierDatabase) // for the second Open(), this class owns the destruction of the archive //TODO -- make numPages the last parameter - bool IsCaseSensitive() const { return mbCaseSensitive; } - TCHAR GetDelimitingChar() const { return mDelimitingChar; } + bool IsCaseSensitive() const + { + return mbCaseSensitive; + } + TCHAR GetDelimitingChar() const + { + return mDelimitingChar; + } - enum { INVALID_INDEX = -1 }; + enum + { + INVALID_INDEX = -1 + }; + + typedef cHierDatabaseIter iterator; + typedef cBlockRecordFile inherited; - typedef cHierDatabaseIter iterator; - typedef cBlockRecordFile inherited; private: - cHierAddr mRootArrayAddr; // this is the address of the top-level array - bool mbCaseSensitive; - TCHAR mDelimitingChar; - - cHierDatabase ( const cHierDatabase& rhs ); //not impl - void operator= ( const cHierDatabase& rhs ); //not impl - - void OpenImpl ( bool bTruncate ); //throw (eArchive, eHierDatabase) + cHierAddr mRootArrayAddr; // this is the address of the top-level array + bool mbCaseSensitive; + TCHAR mDelimitingChar; + + cHierDatabase(const cHierDatabase& rhs); //not impl + void operator=(const cHierDatabase& rhs); //not impl + + void OpenImpl(bool bTruncate); //throw (eArchive, eHierDatabase) // both Open() methods call this to initialize the class after calling // inherited::Open() @@ -109,98 +125,97 @@ class cHierDatabase : public cBlockRecordFile class cHierDatabaseIter { public: - cHierDatabaseIter( cHierDatabase* pDb ); //throw (eArchive) + explicit cHierDatabaseIter(cHierDatabase* pDb); //throw (eArchive) ~cHierDatabaseIter(); // // copying // - cHierDatabaseIter ( const cHierDatabaseIter& rhs ); - cHierDatabaseIter& operator=( const cHierDatabaseIter& rhs ); + cHierDatabaseIter(const cHierDatabaseIter& rhs); + cHierDatabaseIter& operator=(const cHierDatabaseIter& rhs); // // name characteristics -- these are alternatives to specifying in the ctor // - void SetCaseSensitive ( bool bCaseSensitive ); - bool IsCaseSensitive ( void ) const; - void SetDelimitingChar ( TCHAR c ); - TCHAR GetDelimitingChar ( void ) const; + void SetCaseSensitive(bool bCaseSensitive); + bool IsCaseSensitive(void) const; + void SetDelimitingChar(TCHAR c); + TCHAR GetDelimitingChar(void) const; // // traverse up and down the hierarchy // - bool AtRoot() const; //throw (eHierDatabase) - bool CanDescend() const; - void Descend() ; - void Ascend() ; + bool AtRoot() const; //throw (eHierDatabase) + bool CanDescend() const; + void Descend(); + void Ascend(); // // traverse my peers (objects in the same directory as me) // - void SeekBegin(); - bool Done() const; - void Next(); - bool SeekTo(const TCHAR* pName); - // seeks to the named peer; returns false and is positioned in an undefined - // place if it can't find the peer. - // it is either case sensitive or insensitive, depending on what was passed to the - // ctor. - void SeekToRoot(); //throw (eArchive) + void SeekBegin(); + bool Done() const; + void Next(); + bool SeekTo(const TCHAR* pName); + // seeks to the named peer; returns false and is positioned in an undefined + // place if it can't find the peer. + // it is either case sensitive or insensitive, depending on what was passed to the + // ctor. + void SeekToRoot(); //throw (eArchive) // positions the iterator at the root node - void Refresh(); //throw (eArchive, eHierDatabase) + void Refresh(); //throw (eArchive, eHierDatabase) // refresh the iterator's contents in case the db has changed since we first entered // this directory. // note that this will move the iterator back to the beginning of the array - + // // getting at the entry's data... // - const TCHAR* GetName() const; - const TSTRING GetCwd() const; + const TCHAR* GetName() const; + const TSTRING GetCwd() const; // // creating arrays and entries (ie directories and files) // - void CreateChildArray(); //throw (eArchive, eHierDatabase) - void CreateEntry ( const TSTRING& name );//throw (eArchive, eHierDatabase) + void CreateChildArray(); //throw (eArchive, eHierDatabase) + void CreateEntry(const TSTRING& name); //throw (eArchive, eHierDatabase) // after the entry is added, this iterator points at it. // if the entry already exists in the database, an error is added to pError. // // getting and setting the data associated with a given entry // - int8* GetData(int32& length) const; //throw (eArchive, eHierDatabase) + int8* GetData(int32& length) const; //throw (eArchive, eHierDatabase) // returns the data associated with the current entry; this asserts that the iterator is // not done and the current entry has data associated with it - bool HasData() const ; - // returns true if the current entry has data - void SetData(int8* pData, int32 length); //throw (eArchive, eHierDatabase) - void RemoveData(); //throw (eArchive, eHierDatabase) + bool HasData() const; + // returns true if the current entry has data + void SetData(int8* pData, int32 length); //throw (eArchive, eHierDatabase) + void RemoveData(); //throw (eArchive, eHierDatabase) // removes the data associated with the current entry; this asserts that the current - // entry actually _has_ data + // entry actually _has_ data // // deleting arrays and entries // - void DeleteEntry(); //throw (eArchive, eHierDatabase) - // deletes the currently pointed-at entry; this assumes that Done() is not true, and + void DeleteEntry(); //throw (eArchive, eHierDatabase) + // deletes the currently pointed-at entry; this assumes that Done() is not true, and // advances to the next node. - bool ChildArrayEmpty(); //throw (eArchive, eHierDatabase) + bool ChildArrayEmpty(); //throw (eArchive, eHierDatabase) // returns true if the node's child array is empty - void DeleteChildArray(); //throw (eArchive, eHierDatabase) + void DeleteChildArray(); //throw (eArchive, eHierDatabase) // this method deletes the child array of the current object. This method asserts that - // Done() is not true, that the current node has a child, and that the child array is + // Done() is not true, that the current node has a child, and that the child array is // empty (TODO -- perhaps in the future we will want to make the equivalant of "rm -rf" // // util function for sorting/searching // - bool CompareForUpperBound( const cHierEntry& he, const TCHAR* pchName ) const; - // compares shortname of FCO to pchName. returns < == or > 0 as strcmp does. + bool CompareForUpperBound(const cHierEntry& he, const TCHAR* pchName) const; + // compares shortname of FCO to pchName. returns < == or > 0 as strcmp does. protected: - cHierAddr GetCurrentAddr() const; - // returns the address of the current cHierEntry by examining either the previous pNext pointer or the + // returns the address of the current cHierEntry by examining either the previous pNext pointer or the // array info pointer if the first entry is current. This asserts (! Done()) //------------------------------------------------------------------------- @@ -211,24 +226,24 @@ class cHierDatabaseIter typedef std::vector EntryArray; - cHierDatabase* mpDb; // the database - EntryArray mEntries; // vector of entries for the current level - cHierArrayInfo mInfo; - cHierAddr mInfoAddr; - EntryArray::iterator mIter; // my current position in the array - cHierDbPath mCurPath; // The current working directory. + cHierDatabase* mpDb; // the database + EntryArray mEntries; // vector of entries for the current level + cHierArrayInfo mInfo; + cHierAddr mInfoAddr; + EntryArray::iterator mIter; // my current position in the array + cHierDbPath mCurPath; // The current working directory. //------------------------------------------------------------------------- // helper methods //------------------------------------------------------------------------- void LoadArrayAt(const cHierAddr& addr); //throw (eArchive, eHierDatabase) // initializes the iterator so that it is pointing at the array named by addr. - int Compare( const TCHAR* pc1, const TCHAR* pc2 ) const; - // this acts just like strcmp, but takes into account whether the database is case-sensitive or not. + int Compare(const TCHAR* pc1, const TCHAR* pc2) const; + // this acts just like strcmp, but takes into account whether the database is case-sensitive or not. - EntryArray::iterator UpperBound( const TCHAR* pchName ); - // same as std::upper_bound except it calls CompareForUpperBound() to - // do its comparison. + EntryArray::iterator UpperBound(const TCHAR* pchName); + // same as std::upper_bound except it calls CompareForUpperBound() to + // do its comparison. }; //############################################################################# @@ -237,25 +252,25 @@ class cHierDatabaseIter inline void cHierDatabaseIter::Refresh() { cHierAddr infoAddr = mInfoAddr; - LoadArrayAt( infoAddr ); + LoadArrayAt(infoAddr); } -inline void cHierDatabaseIter::SetCaseSensitive ( bool bCaseSensitive ) +inline void cHierDatabaseIter::SetCaseSensitive(bool bCaseSensitive) { - mCurPath.SetCaseSensitive( bCaseSensitive ); + mCurPath.SetCaseSensitive(bCaseSensitive); } -inline bool cHierDatabaseIter::IsCaseSensitive( void ) const +inline bool cHierDatabaseIter::IsCaseSensitive(void) const { return mCurPath.IsCaseSensitive(); } -inline void cHierDatabaseIter::SetDelimitingChar( TCHAR c ) +inline void cHierDatabaseIter::SetDelimitingChar(TCHAR c) { - mCurPath.SetDelimiter( c ); + mCurPath.SetDelimiter(c); } -inline TCHAR cHierDatabaseIter::GetDelimitingChar( void ) const +inline TCHAR cHierDatabaseIter::GetDelimitingChar(void) const { return mCurPath.GetDelimiter(); } @@ -263,18 +278,17 @@ inline TCHAR cHierDatabaseIter::GetDelimitingChar( void ) const /////////////////////////////////////////////////////////////////////////////// // Compare /////////////////////////////////////////////////////////////////////////////// -inline int cHierDatabaseIter::Compare( const TCHAR* pc1, const TCHAR* pc2 ) const +inline int cHierDatabaseIter::Compare(const TCHAR* pc1, const TCHAR* pc2) const { - if( mCurPath.IsCaseSensitive() ) + if (mCurPath.IsCaseSensitive()) { - return ( _tcscmp( pc1, pc2 ) ); + return (_tcscmp(pc1, pc2)); } else { - return ( _tcsicmp( pc1, pc2 ) ); + return (_tcsicmp(pc1, pc2)); } } #endif //__HIERDATABASE_H - diff --git a/src/db/hierdatabase_t.cpp b/src/db/hierdatabase_t.cpp deleted file mode 100644 index 064fc53..0000000 --- a/src/db/hierdatabase_t.cpp +++ /dev/null @@ -1,350 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -// hierdatabase_t -#include "stddb.h" -#include "hierdatabase.h" -#include "test/test.h" -#include "core/error.h" - -static void PrintDb( cHierDatabase::iterator iter, cDebug d, bool bFirst = true ) -{ - if( ! bFirst ) - { - iter.Descend(); - } - d.TraceDebug( "-- Processing directory %s\n", iter.GetCwd().c_str() ); - - for( iter.SeekBegin(); ! iter.Done(); iter.Next() ) - { - d.TraceDebug( "Processing entry %s\n", iter.GetName() ); - if( iter.CanDescend() ) - { - d.TraceDebug( ">>Descending...\n" ); - PrintDb(iter, d, false); - } - } - - d.TraceDebug( "-- Done Processing directory %s\n", iter.GetCwd().c_str() ); -} - -static void GetNoun( TSTRING& noun ) -{ - static TSTRING prevNoun; - TCIN >> noun; - if( noun.compare( _T("!$") ) == 0 ) - { - noun = prevNoun; - } - prevNoun = noun; -} - -/////////////////////////////////////////////////////////////////////////////// -// TestHierDatabaseInteractive -- this provides an interactive interface to -// the database -/////////////////////////////////////////////////////////////////////////////// -void TestHierDatabaseInteractive() -{ - cDebug d( "TestHierDatabaseInteractive" ); - try - { - cHierDatabase db; - //db.Open( _T("c:/tmp/tw.hdb"), 5, true); - db.Open( _T("c:/tmp/tw.db"), 5, false); - cHierDatabase::iterator iter(&db); - - while( true ) - { - TSTRING verb, noun; - TCOUT << _T(">>"); - TCIN >> verb; - // - // ok, now we switch on the command... - // - //----------------------------------------------------------------- - // quit - //----------------------------------------------------------------- - if( verb.compare( _T("quit") ) == 0 ) - { - // the quit command... - break; - } - //----------------------------------------------------------------- - // print - //----------------------------------------------------------------- - if( verb.compare( _T("print") ) == 0 ) - { - // the print command... - ASSERT( false ); - // TODO -- Implement this! - } - //----------------------------------------------------------------- - // mkdir - //----------------------------------------------------------------- - else if( verb.compare( _T("mkdir") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Making a child of " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - iter.CreateChildArray(); - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // mk - //----------------------------------------------------------------- - else if( verb.compare( _T("mk") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Making object " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - TCOUT << "Error: object already exists!" << std::endl; - } - else - { - iter.CreateEntry( noun ); - } - } - //----------------------------------------------------------------- - // rmdir - //----------------------------------------------------------------- - else if( verb.compare( _T("rmdir") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Removing the child of " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - //TODO -- check that it has an empty child - iter.DeleteChildArray(); - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // rm - //----------------------------------------------------------------- - else if( verb.compare( _T("rm") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Removing object " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << "Can't delete object; it still has children." << std::endl; - } - else - { - iter.DeleteEntry(); - } - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // pwd - //----------------------------------------------------------------- - else if( verb.compare( _T("pwd") ) == 0 ) - { - TCOUT << iter.GetCwd() << std::endl; - } - //----------------------------------------------------------------- - // ls - //----------------------------------------------------------------- - else if( verb.compare( _T("ls") ) == 0 ) - { - int cnt = 0; - for( iter.SeekBegin(); ! iter.Done(); iter.Next(), cnt++ ) - { - TCOUT << "[" << cnt ; - if( iter.CanDescend() ) - { - TCOUT << "]*\t" ; - } - else - { - TCOUT << "]\t" ; - } - TCOUT << iter.GetName() << std::endl; - } - } - //----------------------------------------------------------------- - // cd - //----------------------------------------------------------------- - else if( verb.compare( _T("cd") ) == 0 ) - { - GetNoun(noun); - if( noun.compare( _T("..") ) == 0 ) - { - if( iter.AtRoot() ) - { - TCOUT << "Can't ascend above root." << std::endl; - } - else - { - TCOUT << "Ascending..." << std::endl; - iter.Ascend(); - } - } - else - { - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << "Descending into " << noun << std::endl; - iter.Descend(); - } - else - { - TCOUT << noun << " has no children; can't descend." << std::endl; - } - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - } - //----------------------------------------------------------------- - // rmdir - //----------------------------------------------------------------- - else if( verb.compare( _T("rmdir") ) == 0 ) - { - GetNoun(noun); - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << "Deleting child of " << iter.GetName() << std::endl; - iter.DeleteChildArray(); - } - else - { - TCOUT << noun << " has no child; can't delete." << std::endl; - } - } - - } - //----------------------------------------------------------------- - // rm - //----------------------------------------------------------------- - else if( verb.compare( _T("rm") ) == 0 ) - { - GetNoun(noun); - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << noun << " doesn't exist; can't delete." << std::endl; - } - else - { - TCOUT << "Deleting " << iter.GetName() << std::endl; - iter.DeleteEntry(); - } - } - - } - //----------------------------------------------------------------- - // set - //----------------------------------------------------------------- - else if( verb.compare( _T("set") ) == 0 ) - { - GetNoun(noun); - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.HasData() ) - { - iter.RemoveData(); - } - TSTRING data; - TCIN >> data; - iter.SetData( (int8*)data.c_str(), data.length() + 1 ); - TCOUT << "Setting " << noun << "'s data to " << data << std::endl; - } - else - { - TCOUT << "Can't find object " << noun << std::endl; - } - - } - //----------------------------------------------------------------- - // get - //----------------------------------------------------------------- - else if( verb.compare( _T("get") ) == 0 ) - { - GetNoun(noun); - if( iter.SeekTo( noun.c_str() ) ) - { - if( ! iter.HasData() ) - { - TCOUT << "Object has no data!" << std::endl; - } - else - { - int32 dummyLength; - TCOUT << noun << "'s data is: " << (TCHAR*)iter.GetData(dummyLength) << std::endl; - } - } - else - { - TCOUT << "Can't find object " << noun << std::endl; - } - - } - - // make sure the file is still valid... - // -#ifdef _BLOCKFILE_DEBUG - db.AssertAllBlocksValid() ; -#endif - } - - TCOUT << "Exiting..." << std::endl; - - } - catch( eError& e ) - { - d.TraceError( "Exception caught: %d %s\n", e.GetID(), e.GetMsg().c_str() ); - TEST( false ); - } - -} diff --git a/src/db/hierdbnode.h b/src/db/hierdbnode.h index 560344e..a92bd89 100644 --- a/src/db/hierdbnode.h +++ b/src/db/hierdbnode.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -50,7 +50,7 @@ /////////////////////////// //----------------------------------------------------------------------------- -// cHierNode -- the base class for all other nodes; this class contains type +// cHierNode -- the base class for all other nodes; this class contains type // information //----------------------------------------------------------------------------- class cHierNode @@ -58,45 +58,53 @@ class cHierNode public: enum Type { - TYPE_INVALID = -1, - TYPE_MIN = 0, - TYPE_ROOT = 1, + TYPE_INVALID = -1, + TYPE_MIN = 0, + TYPE_ROOT = 1, TYPE_ENTRY, TYPE_ARRAY, TYPE_ARRAY_INFO, TYPE_MAX }; - - cHierNode( Type type = TYPE_INVALID ) : mType( type ) {} - virtual ~cHierNode() {} - int32 mType; + explicit cHierNode(Type type = TYPE_INVALID) : mType(type) + { + } + virtual ~cHierNode() + { + } + + int32 mType; ///////////////////////////////////////// // methods to override ///////////////////////////////////////// - virtual int32 CalcArchiveSize() const { return ( sizeof(mType) ); } - // this method should return the amount of space that this class will take up in an archive - // derived classes should override this if they have any data members that will be stored - // with Read() or Write() - virtual void Write ( cArchive& arch ) const //throw(eArchive) - { arch.WriteInt32( mType ); } - virtual void Read ( cArchive& arch ) //throw(eArchive) - { - arch.ReadInt32( mType ); + virtual int32 CalcArchiveSize() const + { + return (sizeof(mType)); + } + // this method should return the amount of space that this class will take up in an archive + // derived classes should override this if they have any data members that will be stored + // with Read() or Write() + virtual void Write(cArchive& arch) const //throw(eArchive) + { + arch.WriteInt32(mType); + } + virtual void Read(cArchive& arch) //throw(eArchive) + { + arch.ReadInt32(mType); // // do a rudimentary integrity check... // - if( (mType <= TYPE_MIN) || (mType >= TYPE_MAX) ) + if ((mType <= TYPE_MIN) || (mType >= TYPE_MAX)) { - ASSERT( false ); - throw eArchiveFormat( _T("Invalid type encountered in cHierNode::Read") ); + ASSERT(false); + throw eArchiveFormat(_T("Invalid type encountered in cHierNode::Read")); } - } - // these methods read and write the class to an archive. We had better be sure that - // we don't write more than we said we would in CalcArchiveSize() ! + // these methods read and write the class to an archive. We had better be sure that + // we don't write more than we said we would in CalcArchiveSize() ! }; //----------------------------------------------------------------------------- @@ -105,34 +113,41 @@ class cHierNode class cHierAddr { public: - int32 mBlockNum; - int32 mIndex; + int32 mBlockNum; + int32 mIndex; - cHierAddr( int32 block = -1, int32 index = -1 ) : mBlockNum( block ), mIndex( index ) {} + cHierAddr(int32 block = -1, int32 index = -1) : mBlockNum(block), mIndex(index) + { + } - bool IsNull() const { return (mBlockNum == -1); } - // returns true if the address points to "null" (ie -- no valid address) - bool operator==( const cHierAddr& rhs ) const { return( (mBlockNum == rhs.mBlockNum) && (mIndex == rhs.mIndex) ); } + bool IsNull() const + { + return (mBlockNum == -1); + } + // returns true if the address points to "null" (ie -- no valid address) + bool operator==(const cHierAddr& rhs) const + { + return ((mBlockNum == rhs.mBlockNum) && (mIndex == rhs.mIndex)); + } ///////////////////////////////////////////////// // serialization methods ///////////////////////////////////////////////// - int32 CalcArchiveSize () const - { - return ( sizeof(mBlockNum) + sizeof(mIndex) ); + int32 CalcArchiveSize() const + { + return (sizeof(mBlockNum) + sizeof(mIndex)); } - void Write( cArchive& arch ) const //throw(eArchive) - { - arch.WriteInt32( mBlockNum ); - arch.WriteInt32( mIndex ); + void Write(cArchive& arch) const //throw(eArchive) + { + arch.WriteInt32(mBlockNum); + arch.WriteInt32(mIndex); } - void Read( cArchive& arch ) //throw(eArchive) - { - arch.ReadInt32 ( mBlockNum ); - arch.ReadInt32 ( mIndex ); + void Read(cArchive& arch) //throw(eArchive) + { + arch.ReadInt32(mBlockNum); + arch.ReadInt32(mIndex); } - }; @@ -143,49 +158,51 @@ class cHierAddr class cHierRoot : public cHierNode { public: - cHierRoot() : cHierNode( TYPE_ROOT ), mbCaseSensitive(true), mDelimitingChar('/') {} + cHierRoot() : cHierNode(TYPE_ROOT), mbCaseSensitive(true), mDelimitingChar('/') + { + } - cHierAddr mChild; // points to a cHierArray or an invalid address - bool mbCaseSensitive; // determines the case-sensitiveness of lookups, ordering, etc. - TCHAR mDelimitingChar; // the delimiting character; this is used when displaying a path to the user + cHierAddr mChild; // points to a cHierArray or an invalid address + bool mbCaseSensitive; // determines the case-sensitiveness of lookups, ordering, etc. + TCHAR mDelimitingChar; // the delimiting character; this is used when displaying a path to the user ///////////////////////////////////////////////// // serialization methods ///////////////////////////////////////////////// - virtual int32 CalcArchiveSize() const - { - return ( cHierNode::CalcArchiveSize() + mChild.CalcArchiveSize() ); + virtual int32 CalcArchiveSize() const + { + return (cHierNode::CalcArchiveSize() + mChild.CalcArchiveSize()); } - virtual void Write ( cArchive& arch ) const //throw(eArchive) - { - cHierNode::Write ( arch ); - mChild.Write ( arch ); - arch.WriteInt32 ( mbCaseSensitive ? 1 : 0 ); - TSTRING dc ( &mDelimitingChar, 1 ); - arch.WriteString ( dc ); + virtual void Write(cArchive& arch) const //throw(eArchive) + { + cHierNode::Write(arch); + mChild.Write(arch); + arch.WriteInt32(mbCaseSensitive ? 1 : 0); + TSTRING dc(&mDelimitingChar, 1); + arch.WriteString(dc); } - virtual void Read ( cArchive& arch ) //throw(eArchive) - { - cHierNode::Read ( arch ); + virtual void Read(cArchive& arch) //throw(eArchive) + { + cHierNode::Read(arch); // // make sure the type is correct // - if( mType != TYPE_ROOT ) + if (mType != TYPE_ROOT) { - ASSERT( false ); - throw eArchiveFormat( _T("Invalid type encountered; expected ROOT node") ); + ASSERT(false); + throw eArchiveFormat(_T("Invalid type encountered; expected ROOT node")); } - mChild.Read ( arch ); + mChild.Read(arch); int32 cs; arch.ReadInt32(cs); mbCaseSensitive = cs ? true : false; TSTRING dc; arch.ReadString(dc); - if( dc.length() != 1 ) + if (dc.length() != 1) { - ASSERT( false ); - throw eArchiveFormat( _T("Read of the root node failed; invalid delimiting character.") ); + ASSERT(false); + throw eArchiveFormat(_T("Read of the root node failed; invalid delimiting character.")); } mDelimitingChar = dc[0]; } @@ -197,48 +214,48 @@ class cHierRoot : public cHierNode class cHierEntry : public cHierNode { public: - cHierEntry() : cHierNode( TYPE_ENTRY ) {} + cHierEntry() : cHierNode(TYPE_ENTRY) + { + } - TSTRING mName; // TODO -- change this to a wchar_t string - cHierAddr mData; - cHierAddr mChild; // points to a cHierArray or an invalid address - cHierAddr mNext; // the next peer entry in the linked list, or Null() if done + TSTRING mName; // TODO -- change this to a wchar_t string + cHierAddr mData; + cHierAddr mChild; // points to a cHierArray or an invalid address + cHierAddr mNext; // the next peer entry in the linked list, or Null() if done ///////////////////////////////////////////////// // serialization methods ///////////////////////////////////////////////// - virtual int32 CalcArchiveSize() const - { - return ( cHierNode::CalcArchiveSize() + mChild.CalcArchiveSize() + - mData.CalcArchiveSize() + cArchive::GetStorageSize( mName ) + - mNext.CalcArchiveSize() ); + virtual int32 CalcArchiveSize() const + { + return (cHierNode::CalcArchiveSize() + mChild.CalcArchiveSize() + mData.CalcArchiveSize() + + cArchive::GetStorageSize(mName) + mNext.CalcArchiveSize()); } - virtual void Write ( cArchive& arch ) const //throw(eArchive) - { - cHierNode::Write( arch ); - arch.WriteString( mName ); - mChild.Write ( arch ); - mData.Write ( arch ); - mNext.Write ( arch ); + virtual void Write(cArchive& arch) const //throw(eArchive) + { + cHierNode::Write(arch); + arch.WriteString(mName); + mChild.Write(arch); + mData.Write(arch); + mNext.Write(arch); } - virtual void Read ( cArchive& arch ) //throw(eArchive) - { - cHierNode::Read ( arch ); + virtual void Read(cArchive& arch) //throw(eArchive) + { + cHierNode::Read(arch); // // make sure the type is correct // - if( mType != TYPE_ENTRY ) + if (mType != TYPE_ENTRY) { - ASSERT( false ); - throw eArchiveFormat( _T("Invalid type encountered; expected ENTRY node") ); + ASSERT(false); + throw eArchiveFormat(_T("Invalid type encountered; expected ENTRY node")); } - arch.ReadString ( mName ); - mChild.Read ( arch ); - mData.Read ( arch ); - mNext.Read ( arch ); + arch.ReadString(mName); + mChild.Read(arch); + mData.Read(arch); + mNext.Read(arch); } - }; //----------------------------------------------------------------------------- @@ -247,43 +264,42 @@ class cHierEntry : public cHierNode class cHierArrayInfo : public cHierNode { public: - cHierArrayInfo() : cHierNode( TYPE_ARRAY_INFO ) {} + cHierArrayInfo() : cHierNode(TYPE_ARRAY_INFO) + { + } - cHierAddr mParent; // points to a cHierArrayInfo or cHierRoot - cHierAddr mArray; // points to cHierEntryArray + cHierAddr mParent; // points to a cHierArrayInfo or cHierRoot + cHierAddr mArray; // points to cHierEntryArray ///////////////////////////////////////////////// // serialization methods ///////////////////////////////////////////////// - virtual int32 CalcArchiveSize() const - { - return (cHierNode::CalcArchiveSize() + mParent.CalcArchiveSize() + mArray.CalcArchiveSize()); + virtual int32 CalcArchiveSize() const + { + return (cHierNode::CalcArchiveSize() + mParent.CalcArchiveSize() + mArray.CalcArchiveSize()); } - virtual void Write ( cArchive& arch ) const //throw(eArchive) - { - cHierNode::Write( arch ); - mParent.Write ( arch ); - mArray.Write ( arch ); + virtual void Write(cArchive& arch) const //throw(eArchive) + { + cHierNode::Write(arch); + mParent.Write(arch); + mArray.Write(arch); } - virtual void Read ( cArchive& arch ) //throw(eArchive) - { - cHierNode::Read ( arch ); + virtual void Read(cArchive& arch) //throw(eArchive) + { + cHierNode::Read(arch); // // make sure the type is correct // - if( mType != TYPE_ARRAY_INFO ) + if (mType != TYPE_ARRAY_INFO) { - ASSERT( false ); - throw eArchiveFormat( _T("Invalid type encountered; expected TYPE_ARRAY_INFO node") ); + ASSERT(false); + throw eArchiveFormat(_T("Invalid type encountered; expected TYPE_ARRAY_INFO node")); } - mParent.Read ( arch ); - mArray.Read ( arch ); + mParent.Read(arch); + mArray.Read(arch); } - }; - #endif //__HIERDBNODE_H - diff --git a/src/db/hierdbpath.cpp b/src/db/hierdbpath.cpp index 42c99c4..bb165d8 100644 --- a/src/db/hierdbpath.cpp +++ b/src/db/hierdbpath.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,71 +39,70 @@ #include "core/debug.h" //Ctor: -cHierDbPath::cHierDbPath( void ) : - mbCaseSensitive(false), mDelimitingChar( _T('/') ) +cHierDbPath::cHierDbPath(void) : mbCaseSensitive(false), mDelimitingChar(_T('/')) { - ASSERT( mCurrPath.empty() ); + ASSERT(mCurrPath.empty()); } -cHierDbPath::cHierDbPath( TCHAR cDelChar, bool bCaseSensitive ) : - mbCaseSensitive( bCaseSensitive ), mDelimitingChar( cDelChar ) +cHierDbPath::cHierDbPath(TCHAR cDelChar, bool bCaseSensitive) + : mbCaseSensitive(bCaseSensitive), mDelimitingChar(cDelChar) { - ASSERT( mCurrPath.empty() ); + ASSERT(mCurrPath.empty()); } //Copy Ctor: -cHierDbPath::cHierDbPath( const cHierDbPath& rhs ) +cHierDbPath::cHierDbPath(const cHierDbPath& rhs) { mbCaseSensitive = rhs.mbCaseSensitive; mDelimitingChar = rhs.mDelimitingChar; - if( !rhs.mCurrPath.empty() ) + if (!rhs.mCurrPath.empty()) { DbPath::const_iterator it = rhs.mCurrPath.begin(); - for( ; it != rhs.mCurrPath.end(); ++it ) - mCurrPath.push_back( *it ); + for (; it != rhs.mCurrPath.end(); ++it) + mCurrPath.push_back(*it); } } /////////////////////////////////////////////////////////////////////////////// // operator= -cHierDbPath& cHierDbPath::operator=( const cHierDbPath& rhs ) +cHierDbPath& cHierDbPath::operator=(const cHierDbPath& rhs) { if (this != &rhs) { mbCaseSensitive = rhs.mbCaseSensitive; mDelimitingChar = rhs.mDelimitingChar; - if( !rhs.mCurrPath.empty() ) + if (!rhs.mCurrPath.empty()) { DbPath::const_iterator it = rhs.mCurrPath.begin(); - for( ; it != (rhs.mCurrPath.end()); ++it ) - mCurrPath.push_back( *it ); + for (; it != (rhs.mCurrPath.end()); ++it) + mCurrPath.push_back(*it); } } return *this; } //Dtor: -cHierDbPath::~cHierDbPath( void ) +cHierDbPath::~cHierDbPath(void) { } /////////////////////////////////////////////////////////////////////////////// // Push: Adds a substring to the end of the sequence(path) -void cHierDbPath::Push( const TSTRING &str ) +void cHierDbPath::Push(const TSTRING& str) { - mCurrPath.push_back( str ); + mCurrPath.push_back(str); } /////////////////////////////////////////////////////////////////////////////// -// Pop: Removes a substring from the end of the path and returns it as a +// Pop: Removes a substring from the end of the path and returns it as a // TSTRING. -TSTRING cHierDbPath::Pop( void ) +TSTRING cHierDbPath::Pop(void) { TSTRING ret; - if ( mCurrPath.empty() ) + if (mCurrPath.empty()) return _T(""); ret = mCurrPath.back(); @@ -113,40 +112,40 @@ TSTRING cHierDbPath::Pop( void ) return ret; } -void cHierDbPath::SetCaseSensitive( bool bCaseSensitive ) +void cHierDbPath::SetCaseSensitive(bool bCaseSensitive) { mbCaseSensitive = bCaseSensitive; } -bool cHierDbPath::IsCaseSensitive( void ) const +bool cHierDbPath::IsCaseSensitive(void) const { return mbCaseSensitive; } -void cHierDbPath::SetDelimiter( TCHAR Delimiter ) +void cHierDbPath::SetDelimiter(TCHAR Delimiter) { mDelimitingChar = Delimiter; } -TCHAR cHierDbPath::GetDelimiter( void ) const +TCHAR cHierDbPath::GetDelimiter(void) const { return mDelimitingChar; } -void cHierDbPath::Clear( void ) +void cHierDbPath::Clear(void) { mCurrPath.clear(); - ASSERT( mCurrPath.empty() ); + ASSERT(mCurrPath.empty()); } /////////////////////////////////////////////////////////////////////////////// // AsString -- Returns a TSTRING representation of the current path -TSTRING cHierDbPath::AsString( void ) const +TSTRING cHierDbPath::AsString(void) const { TSTRING ret = _T(""); - if(mCurrPath.size() == 1) + if (mCurrPath.size() == 1) { ret = *(mCurrPath.begin()); ret += mDelimitingChar; @@ -157,12 +156,12 @@ TSTRING cHierDbPath::AsString( void ) const // The loop adds delimiting characters until the last element in the // sequence is reached, so we don't have a trailing character. - while(it != mCurrPath.end() ) + while (it != mCurrPath.end()) { // the loop is constructed in this odd fashion because I don't want a trailing mDelimiter ret += (*it); ++it; - if(it != mCurrPath.end()) + if (it != mCurrPath.end()) ret += mDelimitingChar; } @@ -172,8 +171,7 @@ TSTRING cHierDbPath::AsString( void ) const /////////////////////////////////////////////////////////////////////////////// // GetSize: Returns the number of substrings in the sequence -int cHierDbPath::GetSize( void ) const +int cHierDbPath::GetSize(void) const { return mCurrPath.size(); } - diff --git a/src/db/hierdbpath.h b/src/db/hierdbpath.h index ab0aea3..e9fcb54 100644 --- a/src/db/hierdbpath.h +++ b/src/db/hierdbpath.h @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// hierdbpath.h : +// hierdbpath.h : // #ifndef __HIERDBPATH_H @@ -40,7 +40,7 @@ #include "core/tchar.h" #endif -#include +#include /////////////////////////////////////////////////////////////////////////////// // cHierDbPath: @@ -52,44 +52,43 @@ class cHierDbPath { public: // Ctor, Dtor: - cHierDbPath(); //empty constructor: + cHierDbPath(); //empty constructor: // Default delimiter = '/', default case-sensitivity = false - cHierDbPath( TCHAR delChar, bool bCaseSensitive ); + cHierDbPath(TCHAR delChar, bool bCaseSensitive); ~cHierDbPath(); // Copy Ctor: - cHierDbPath ( const cHierDbPath& rhs ); + cHierDbPath(const cHierDbPath& rhs); - cHierDbPath& operator=( const cHierDbPath& rhs ); + cHierDbPath& operator=(const cHierDbPath& rhs); - void SetDelimiter ( TCHAR cDelimiter ); - TCHAR GetDelimiter ( void ) const; - void SetCaseSensitive ( bool bCaseSensitive ); - bool IsCaseSensitive ( void ) const; + void SetDelimiter(TCHAR cDelimiter); + TCHAR GetDelimiter(void) const; + void SetCaseSensitive(bool bCaseSensitive); + bool IsCaseSensitive(void) const; - void Clear ( void ); - void Push ( const TSTRING& str ); - // Pushes a substring onto the end of the path( using str ); - TSTRING Pop ( void ); - // Pops a substring off of the end of the path, and returns it. - // mCurrPath is altered by removing the substring. + void Clear(void); + void Push(const TSTRING& str); + // Pushes a substring onto the end of the path( using str ); + TSTRING Pop(void); + // Pops a substring off of the end of the path, and returns it. + // mCurrPath is altered by removing the substring. - TSTRING AsString ( void ) const; - // Returns a TSTRING representation of mCurrPath. + TSTRING AsString(void) const; + // Returns a TSTRING representation of mCurrPath. - int GetSize ( void ) const; - // Returns the number of substrings in the path. + int GetSize(void) const; + // Returns the number of substrings in the path. typedef std::vector DbPath; -private: - bool mbCaseSensitive; - TCHAR mDelimitingChar; +private: + bool mbCaseSensitive; + TCHAR mDelimitingChar; - DbPath mCurrPath; - // Data structure for holding the path. + DbPath mCurrPath; + // Data structure for holding the path. }; #endif //__HIERDBPATH_H - diff --git a/src/db/stddb.cpp b/src/db/stddb.cpp index 22bd5cc..7309934 100644 --- a/src/db/stddb.cpp +++ b/src/db/stddb.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,5 +37,3 @@ // #include "stddb.h" - -// eof: stddb.cpp diff --git a/src/db/stddb.h b/src/db/stddb.h index 301ed7a..41ab74c 100644 --- a/src/db/stddb.h +++ b/src/db/stddb.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // // Name....: stddb.h // Date....: 05/07/99 -// Creator.: +// Creator.: // // @@ -42,4 +42,3 @@ #include "core/stdcore.h" #endif //__STDDB_H - diff --git a/src/fco/Makefile.am b/src/fco/Makefile.am index f4c498d..cb5f50f 100644 --- a/src/fco/Makefile.am +++ b/src/fco/Makefile.am @@ -1,8 +1,9 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libfco.a +libfco_adir=. libfco_a_SOURCES = \ fco.cpp fcocompare.cpp fcodatasourceiter.cpp \ fcodatasourceiterimpl.cpp fcoerrors.cpp fconame.cpp \ @@ -11,8 +12,22 @@ libfco_a_SOURCES = \ fcospecimpl.cpp fcospeclist.cpp fcospecutil.cpp fcostrings.cpp \ fcoundefprop.cpp genreinfo.cpp genrespeclist.cpp \ genreswitcher.cpp signature.cpp stdfco.cpp twfactory.cpp - -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit + +libfco_a_HEADERS = \ + fco.h fcocompare.h fcodatasource.h fcodatasourceiter.h \ + fcodatasourceiterimpl.h fcoerrors.h fcogenre.h fconame.h \ + fconameinfo.h fconametbl.h fconametranslator.h fcoprop.h \ + fcopropcalc.h fcopropdisplayer.h fcopropimpl.h fcopropset.h \ + fcopropvector.h fcosetimpl.h fcosetws.h \ + fcospec.h fcospecattr.h fcospechelper.h fcospecimpl.h \ + fcospeclist.h fcospecutil.h fcostrings.h fcoundefprop.h \ + fcovisitor.h genreinfo.h genrespeclist.h genreswitcher.h \ + iterproxy.h parsergenreutil.h propset.h signature.h \ + stdfco.h twfactory.h + + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libfco_a_OBJECTS) diff --git a/src/fco/Makefile.in b/src/fco/Makefile.in index b816489..0300072 100644 --- a/src/fco/Makefile.in +++ b/src/fco/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libfco_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/fco -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libfco_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libfco_a_AR = $(AR) $(ARFLAGS) libfco_a_LIBADD = am_libfco_a_OBJECTS = fco.$(OBJEXT) fcocompare.$(OBJEXT) \ @@ -64,23 +122,95 @@ am_libfco_a_OBJECTS = fco.$(OBJEXT) fcocompare.$(OBJEXT) \ genreswitcher.$(OBJEXT) signature.$(OBJEXT) stdfco.$(OBJEXT) \ twfactory.$(OBJEXT) libfco_a_OBJECTS = $(am_libfco_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libfco_a_SOURCES) DIST_SOURCES = $(libfco_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libfco_adir)" +HEADERS = $(libfco_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -96,7 +226,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -104,6 +234,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -115,6 +246,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -131,21 +263,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -175,15 +310,20 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libfco.a +libfco_adir = . libfco_a_SOURCES = \ fco.cpp fcocompare.cpp fcodatasourceiter.cpp \ fcodatasourceiterimpl.cpp fcoerrors.cpp fconame.cpp \ @@ -193,6 +333,19 @@ libfco_a_SOURCES = \ fcoundefprop.cpp genreinfo.cpp genrespeclist.cpp \ genreswitcher.cpp signature.cpp stdfco.cpp twfactory.cpp +libfco_a_HEADERS = \ + fco.h fcocompare.h fcodatasource.h fcodatasourceiter.h \ + fcodatasourceiterimpl.h fcoerrors.h fcogenre.h fconame.h \ + fconameinfo.h fconametbl.h fconametranslator.h fcoprop.h \ + fcopropcalc.h fcopropdisplayer.h fcopropimpl.h fcopropset.h \ + fcopropvector.h fcosetimpl.h fcosetws.h \ + fcospec.h fcospecattr.h fcospechelper.h fcospecimpl.h \ + fcospeclist.h fcospecutil.h fcostrings.h fcoundefprop.h \ + fcovisitor.h genreinfo.h genrespeclist.h genreswitcher.h \ + iterproxy.h parsergenreutil.h propset.h signature.h \ + stdfco.h twfactory.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -201,15 +354,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/fco/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/fco/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/fco/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/fco/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -226,13 +378,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libfco.a: $(libfco_a_OBJECTS) $(libfco_a_DEPENDENCIES) - -rm -f libfco.a - $(libfco_a_AR) libfco.a $(libfco_a_OBJECTS) $(libfco_a_LIBADD) - $(RANLIB) libfco.a + +libfco.a: $(libfco_a_OBJECTS) $(libfco_a_DEPENDENCIES) $(EXTRA_libfco_a_DEPENDENCIES) + $(AM_V_at)-rm -f libfco.a + $(AM_V_AR)$(libfco_a_AR) libfco.a $(libfco_a_OBJECTS) $(libfco_a_LIBADD) + $(AM_V_at)$(RANLIB) libfco.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -241,91 +395,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libfco_aHEADERS: $(libfco_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libfco_a_HEADERS)'; test -n "$(libfco_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libfco_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libfco_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libfco_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libfco_adir)" || exit $$?; \ + done + +uninstall-libfco_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libfco_a_HEADERS)'; test -n "$(libfco_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libfco_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libfco_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -336,16 +520,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -365,18 +556,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libfco_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -395,22 +606,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libfco_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libfco_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libfco_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libfco_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/fco/fco.cpp b/src/fco/fco.cpp index 85a88ed..15a3b23 100644 --- a/src/fco/fco.cpp +++ b/src/fco/fco.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,16 +38,16 @@ // #include "stdfco.h" -#include "fco.h" // for: cFCO -#include "core/core.h" // for: cCore -#include "fcoerrors.h" // for: fco error table +#include "fco.h" // for: cFCO +#include "core/core.h" // for: cCore +#include "fcoerrors.h" // for: fco error table -TSS_ImplementPackage( cFCO ) +TSS_ImplementPackage(cFCO) cFCO::cFCO() { - TSS_Dependency ( cCore ); - TSS_REGISTER_PKG_ERRORS ( fco ); + TSS_Dependency(cCore); + TSS_REGISTER_PKG_ERRORS(fco); } //============================================================================= @@ -56,5 +56,3 @@ cFCO::cFCO() iFCO::~iFCO() { } - -// eof: fco.cpp diff --git a/src/fco/fco.h b/src/fco/fco.h index b6db14e..7cc96cb 100644 --- a/src/fco/fco.h +++ b/src/fco/fco.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,7 +34,7 @@ // Date....: 05/07/99 // Creator.: Robert DiFalco (rdifalco) // -// package: cFCO -- FCO package data access +// package: cFCO -- FCO package data access // interface iFCO -- abstract first class object // interface iFCOSet -- abstract set of iFCOs // interface iFCOIter -- iterator over an iFCOSet @@ -43,22 +43,22 @@ #ifndef __FCO_H #define __FCO_H -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#include "core/package.h" // for: TSS_DeclarePackage +#include "core/package.h" // for: TSS_DeclarePackage #ifndef __SREFCOUNTOBJ_H -#include "core/srefcountobj.h" // for: iSerRefCountObj +#include "core/srefcountobj.h" // for: iSerRefCountObj #endif -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Forward Declarations -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -class cFCO; // cFCO is the Package Representation +class cFCO; // cFCO is the Package Representation class iFCO; class cFCOName; class cFCOPropVector; @@ -72,71 +72,72 @@ class iFCOPropDisplayer; //============================================================================= // cFCO -- First Class Object Package //============================================================================= -// SYNOPSIS: -// +// SYNOPSIS: +// // CONSTRAINTS: -// +// // INVARIANTS: -// // -TSS_BeginPackage( cFCO ) +// +TSS_BeginPackage(cFCO) TSS_DECLARE_STRINGTABLE; - public: - - cFCO(); // Used to construct dependencies - -TSS_EndPackage( cFCO ) - - -//============================================================================= -// iFCO -- First Class Object Interface -//============================================================================= -// SYNOPSIS: -// -// CONSTRAINTS: -// -// INVARIANTS: -// -// -class iFCO : public iSerRefCountObj +public: +cFCO(); // Used to construct dependencies + +TSS_EndPackage(cFCO) + + + //============================================================================= + // iFCO -- First Class Object Interface + //============================================================================= + // SYNOPSIS: + // + // CONSTRAINTS: + // + // INVARIANTS: + // + // + class iFCO : public iSerRefCountObj { public: virtual void SetName(const cFCOName& name) = 0; - virtual const cFCOName& GetName() const = 0; - // returns the name that uniquely identifies the fco in whatever system - // it lives in. Reference is valid as long as the fco exists + virtual const cFCOName& GetName() const = 0; + // returns the name that uniquely identifies the fco in whatever system + // it lives in. Reference is valid as long as the fco exists - virtual const iFCOPropSet* GetPropSet() const = 0; - virtual iFCOPropSet* GetPropSet() = 0; - // returns a pointer to the FCO's property set. It is to be destroyed - // by the FCO and is only guarenteed to be valid through the life of the - // fco. + virtual const iFCOPropSet* GetPropSet() const = 0; + virtual iFCOPropSet* GetPropSet() = 0; + // returns a pointer to the FCO's property set. It is to be destroyed + // by the FCO and is only guarenteed to be valid through the life of the + // fco. - virtual uint32 GetCaps() const = 0; - // returns a bitmask that indicates properties that this object has. - // see the enum below for what the caps can contain + virtual uint32 GetCaps() const = 0; + // returns a bitmask that indicates properties that this object has. + // see the enum below for what the caps can contain virtual iFCO* Clone() const = 0; - // return a copy of the fco, with a reference count of 1. - // note that this will return an iFCO with _no_ children. If you want the - // child information, it should be copied manually + // return a copy of the fco, with a reference count of 1. + // note that this will return an iFCO with _no_ children. If you want the + // child information, it should be copied manually virtual void AcceptVisitor(iFCOVisitor* pVisitor) = 0; - // visitor interface + // visitor interface - virtual void TraceContents(int debugLevel = -1) const {} - // spit the contents of the fco to debug out. -1 means to use D_DEBUG + virtual void TraceContents(int debugLevel = -1) const + { + } + // spit the contents of the fco to debug out. -1 means to use D_DEBUG //-------------------------------- // GetCaps() enumeration //-------------------------------- enum Caps { - CAP_CAN_HAVE_CHILDREN = 0x1, - CAP_CAN_HAVE_PARENT = 0x2, - CAP_GENRE_SPECIFIC = 0x4 // start the genre-specific caps here. + CAP_CAN_HAVE_CHILDREN = 0x1, + CAP_CAN_HAVE_PARENT = 0x2, + CAP_GENRE_SPECIFIC = 0x4 // start the genre-specific caps here. }; protected: @@ -146,69 +147,69 @@ class iFCO : public iSerRefCountObj class iFCOIter { public: - virtual void SeekBegin() const = 0; - // seeks to the beginning of the set - virtual bool Done() const = 0; - // returns true if the iterator has gone past the end of the set - virtual bool IsEmpty() const = 0; - // is the set empty? - virtual void Next() const = 0; - // seek to the next element in the set - - virtual const iFCO* FCO() const = 0; - virtual iFCO* FCO() = 0; - // methods for getting the FCO that the iterator is currently pointing at - - virtual bool SeekToFCO(const cFCOName& name) const = 0; - // seeks the iterator to the fco specified by "name". If an fco by that name doesn't exist, - // false is returned and the iterator points at the end of the list (Done() will return true - - virtual void Remove() = 0; - virtual void Remove() const = 0; - // removes the fco pointed to by the iter. Behavior is undefined if the set is empty. - // after the erase, the iterator points to the next element in the list - - virtual void DestroyIter() const = 0; - // call this instead of delete()ing it. Since the FCOSet created this iterator, - // destruction with this method allows the object to "give" itself back to the - // FCOSet. + virtual void SeekBegin() const = 0; + // seeks to the beginning of the set + virtual bool Done() const = 0; + // returns true if the iterator has gone past the end of the set + virtual bool IsEmpty() const = 0; + // is the set empty? + virtual void Next() const = 0; + // seek to the next element in the set + + virtual const iFCO* FCO() const = 0; + virtual iFCO* FCO() = 0; + // methods for getting the FCO that the iterator is currently pointing at + + virtual bool SeekToFCO(const cFCOName& name) const = 0; + // seeks the iterator to the fco specified by "name". If an fco by that name doesn't exist, + // false is returned and the iterator points at the end of the list (Done() will return true + + virtual void Remove() = 0; + virtual void Remove() const = 0; + // removes the fco pointed to by the iter. Behavior is undefined if the set is empty. + // after the erase, the iterator points to the next element in the list + + virtual void DestroyIter() const = 0; + // call this instead of delete()ing it. Since the FCOSet created this iterator, + // destruction with this method allows the object to "give" itself back to the + // FCOSet. protected: - virtual ~iFCOIter() {}; + virtual ~iFCOIter(){}; }; class iFCOSet : public iTypedSerializable { public: - virtual ~iFCOSet() {}; + virtual ~iFCOSet(){}; - virtual const iFCOIter* Lookup(const cFCOName& name) const = 0; - virtual iFCOIter* Lookup(const cFCOName& name) = 0; - // returns a pointer to the FCO specified by "name" if it exists - // in the set, otherwise returns NULL. This will always map uniquely to a - // single FCO, since it is an error to have multiple FCOs with the same name in the set. + virtual const iFCOIter* Lookup(const cFCOName& name) const = 0; + virtual iFCOIter* Lookup(const cFCOName& name) = 0; + // returns a pointer to the FCO specified by "name" if it exists + // in the set, otherwise returns NULL. This will always map uniquely to a + // single FCO, since it is an error to have multiple FCOs with the same name in the set. - virtual const iFCOIter* GetIter() const = 0; - virtual iFCOIter* GetIter() = 0; - // returns an iterator on the set + virtual const iFCOIter* GetIter() const = 0; + virtual iFCOIter* GetIter() = 0; + // returns an iterator on the set virtual void Insert(iFCO* pFCO) = 0; - // inserts an fco into the set. The set will increment the reference count of the fco, and - // release it when the fco is removed from the set of the set is destroyed. + // inserts an fco into the set. The set will increment the reference count of the fco, and + // release it when the fco is removed from the set of the set is destroyed. virtual void Clear() = 0; - // clears out all the elements from the set + // clears out all the elements from the set virtual bool IsEmpty() const = 0; - virtual int Size() const = 0; - - virtual void TraceContents(int debugLevel = -1) const {} - // traces the contents of the spec to wherever cDebug is pointing; not pure - // virtual so that one is not forced to implement it. - // -1 means to use D_DEBUG + virtual int Size() const = 0; + virtual void TraceContents(int debugLevel = -1) const + { + } + // traces the contents of the spec to wherever cDebug is pointing; not pure + // virtual so that one is not forced to implement it. + // -1 means to use D_DEBUG }; -#endif//__FCO_H - +#endif //__FCO_H diff --git a/src/fco/fcocompare.cpp b/src/fco/fcocompare.cpp index 52465ef..b0d873b 100644 --- a/src/fco/fcocompare.cpp +++ b/src/fco/fcocompare.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,53 +44,49 @@ cFCOCompare::cFCOCompare() { - } -cFCOCompare::cFCOCompare( const cFCOPropVector& propsToCompare) -: mPropsToCmp( propsToCompare ) +cFCOCompare::cFCOCompare(const cFCOPropVector& propsToCompare) : mPropsToCmp(propsToCompare) { - } cFCOCompare::~cFCOCompare() { - } /////////////////////////////////////////////////////////////////////////////// -// Compare +// Compare /////////////////////////////////////////////////////////////////////////////// -uint32 cFCOCompare::Compare(const iFCO* pFco1, const iFCO* pFco2) +uint32 cFCOCompare::Compare(const iFCO* pFco1, const iFCO* pFco2) { ASSERT(pFco1 != 0); ASSERT(pFco2 != 0); // first, make sure the fcos are of the same type... - if(pFco1->GetType() != pFco2->GetType()) + if (pFco1->GetType() != pFco2->GetType()) { - ASSERT( false ); - INTERNAL_ERROR( "fcocompare.cpp" ); + ASSERT(false); + INTERNAL_ERROR("fcocompare.cpp"); } - - const iFCOPropSet* ps1 = pFco1->GetPropSet(); - const iFCOPropSet* ps2 = pFco2->GetPropSet(); - const cFCOPropVector& v1 = pFco1->GetPropSet()->GetValidVector(); - const cFCOPropVector& v2 = pFco2->GetPropSet()->GetValidVector(); + + const iFCOPropSet* ps1 = pFco1->GetPropSet(); + const iFCOPropSet* ps2 = pFco2->GetPropSet(); + const cFCOPropVector& v1 = pFco1->GetPropSet()->GetValidVector(); + const cFCOPropVector& v2 = pFco2->GetPropSet()->GetValidVector(); uint32 result = 0; - mInvalidProps.SetSize( v1.GetSize() ); - mUnequalProps.SetSize( v1.GetSize() ); + mInvalidProps.SetSize(v1.GetSize()); + mUnequalProps.SetSize(v1.GetSize()); mInvalidProps.Clear(); mUnequalProps.Clear(); // finally, comapre all the properties - for(int i=0; iGetPropAt(i)->Compare(ps2->GetPropAt(i), iFCOProp::OP_EQ) != iFCOProp::CMP_TRUE) + if (ps1->GetPropAt(i)->Compare(ps2->GetPropAt(i), iFCOProp::OP_EQ) != iFCOProp::CMP_TRUE) { // they are not equal! mUnequalProps.AddItem(i); @@ -108,9 +104,8 @@ uint32 cFCOCompare::Compare(const iFCO* pFco1, const iFCO* pFco2) } } - if( ! result ) + if (!result) result = EQUAL; return result; } - diff --git a/src/fco/fcocompare.h b/src/fco/fcocompare.h index b7a6175..85e6116 100644 --- a/src/fco/fcocompare.h +++ b/src/fco/fcocompare.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // fcocompare.h -// +// // iFCOCompare -- interface for object that compares FCO properties #ifndef __FCOCOMPARE_H #define __FCOCOMPARE_H @@ -47,37 +47,37 @@ class cFCOCompare public: enum Result { - EQUAL = 1, - PROPS_UNEQUAL = 2, - PROPS_NOT_ALL_VALID = 4 + EQUAL = 1, + PROPS_UNEQUAL = 2, + PROPS_NOT_ALL_VALID = 4 }; cFCOCompare(); - cFCOCompare( const cFCOPropVector& propsToCompare); + explicit cFCOCompare(const cFCOPropVector& propsToCompare); virtual ~cFCOCompare(); - void SetPropsToCmp(const cFCOPropVector& pv); - const cFCOPropVector& GetPropsToCmp() const; - // gets and sets the property vector that indicates what properties the - // object will consider in the comparisons. + void SetPropsToCmp(const cFCOPropVector& pv); + const cFCOPropVector& GetPropsToCmp() const; + // gets and sets the property vector that indicates what properties the + // object will consider in the comparisons. - uint32 Compare(const iFCO* pFco1, const iFCO* pFco2) ; - // compares fco1 and fco2, only considering the properties specified set with - // SetPropsToCmp(). The result of the comparison is a bitmask that is currently either - // EQUAL or a combination of PROPS_NOT_ALL_VALID and PROPS_UNEQUAL. You can discover which - // properties caused these return flags with the GetXXXProps() methods below. - // NOTE -- in integrity checking, the old fco should be the first parameter and the new fco the - // second (to support growing files properly) + uint32 Compare(const iFCO* pFco1, const iFCO* pFco2); + // compares fco1 and fco2, only considering the properties specified set with + // SetPropsToCmp(). The result of the comparison is a bitmask that is currently either + // EQUAL or a combination of PROPS_NOT_ALL_VALID and PROPS_UNEQUAL. You can discover which + // properties caused these return flags with the GetXXXProps() methods below. + // NOTE -- in integrity checking, the old fco should be the first parameter and the new fco the + // second (to support growing files properly) const cFCOPropVector& GetInvalidProps() const; - // only meaningful if the last Compare() returned PROPS_NOT_ALL_VALID + // only meaningful if the last Compare() returned PROPS_NOT_ALL_VALID const cFCOPropVector& GetUnequalProps() const; - // only meaningful if the last Compare() returned PROPS_UNEQUAL + // only meaningful if the last Compare() returned PROPS_UNEQUAL private: - cFCOPropVector mPropsToCmp; - cFCOPropVector mInvalidProps; - cFCOPropVector mUnequalProps; + cFCOPropVector mPropsToCmp; + cFCOPropVector mInvalidProps; + cFCOPropVector mUnequalProps; }; ///////////////////////////////////////////////////////////// @@ -104,4 +104,3 @@ inline const cFCOPropVector& cFCOCompare::GetUnequalProps() const #endif //__FCOCOMPARE_H - diff --git a/src/fco/fcodatasource.h b/src/fco/fcodatasource.h index 1cbebb1..a69e31c 100644 --- a/src/fco/fcodatasource.h +++ b/src/fco/fcodatasource.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,8 +43,13 @@ class cFCOErrorQueue; class iFCODataSource { public: - enum { CHILDREN_NONE = 0, - CHILDREN_ALL = -1 }; + enum + { + CHILDREN_NONE = 0, + CHILDREN_ALL = -1 + }; + + virtual ~iFCODataSource() = 0; // NOTE -- in the act of creating fcos, there are certain properties that we can obtain "for free" just // by the act of querying the system we are generating fcos for (for example, a stat() call is required @@ -53,28 +58,27 @@ class iFCODataSource // is not desireable, you should call iFCO::GetPropSet()->Clear() to invalidate all the properties. virtual iFCO* CreateFCO(const cFCOName& name, int recurseDepth, cFCOErrorQueue* pQueue = 0) const = 0; - // creates the FCO specified by "name", returns NULL if the object doesn't exist - // on the system the data source is bound to. recurseDepth is how deep the child - // tree should be built; 0 means get no children, and -1 means all the children - // All errors that occur will be reported to the passed in error bucket; it is ok to pass - // NULL if you don't care about errors. + // creates the FCO specified by "name", returns NULL if the object doesn't exist + // on the system the data source is bound to. recurseDepth is how deep the child + // tree should be built; 0 means get no children, and -1 means all the children + // All errors that occur will be reported to the passed in error bucket; it is ok to pass + // NULL if you don't care about errors. virtual bool GetChildren(iFCO* pFCO, int recurseDepth, cFCOErrorQueue* pQueue = 0) const = 0; - // given a pointer to an FCO, this will populate it with children for as many levels - // as specified by recursedepth. The passed in FCO should have no children; it is - // undefined what will happen to existing children after this function returns. - // All errors that occur will be reported to the passed in error bucket; it is ok to pass - // NULL if you don't care about errors. + // given a pointer to an FCO, this will populate it with children for as many levels + // as specified by recursedepth. The passed in FCO should have no children; it is + // undefined what will happen to existing children after this function returns. + // All errors that occur will be reported to the passed in error bucket; it is ok to pass + // NULL if you don't care about errors. // cErrorBucket error numbers... // the data source owns all error numbers from 100-199 enum ErrorNum { - ERR_READDIR_FAIL = 100, - ERR_GETFILETYPE_FAIL = 101, + ERR_READDIR_FAIL = 100, + ERR_GETFILETYPE_FAIL = 101, ERR_NUM_ERRORS }; }; #endif - diff --git a/src/fco/fcodatasourceiter.cpp b/src/fco/fcodatasourceiter.cpp index cdf64b2..b2cf161 100644 --- a/src/fco/fcodatasourceiter.cpp +++ b/src/fco/fcodatasourceiter.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,28 +40,30 @@ #include "stdfco.h" #include "fcodatasourceiter.h" +#if HAVE_STRINGS_H // for strcasecmp on RTEMS +#include +#endif + //========================================================================= // METHOD CODE //========================================================================= -iFCODataSourceIter::Relationship iFCODataSourceIter::Compare( const TCHAR* str1, const TCHAR* str2 ) const +iFCODataSourceIter::Relationship iFCODataSourceIter::Compare(const TCHAR* str1, const TCHAR* str2) const { int cmpResult; - if( IsCaseSensitive() ) + if (IsCaseSensitive()) { - cmpResult = _tcscmp( str1, str2 ); + cmpResult = _tcscmp(str1, str2); } else { - cmpResult = _tcsicmp( str1, str2 ); + cmpResult = _tcsicmp(str1, str2); } - if ( cmpResult < 0 ) + if (cmpResult < 0) return REL_LT; - else if ( cmpResult > 0 ) + else if (cmpResult > 0) return REL_GT; else return REL_EQ; - } - diff --git a/src/fco/fcodatasourceiter.h b/src/fco/fcodatasourceiter.h index a8658b7..8f025e3 100644 --- a/src/fco/fcodatasourceiter.h +++ b/src/fco/fcodatasourceiter.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -85,8 +85,8 @@ class eFCODataSourceIter : public eError eFCODataSourceIter(int errorNum, const TSTRING& msg) : eError( errorNum, msg ) {} }; */ -TSS_EXCEPTION( eFCODataSourceIter, eError ) -TSS_EXCEPTION( eFCODataSourceIterDupeFCO, eFCODataSourceIter ) +TSS_EXCEPTION(eFCODataSourceIter, eError) +TSS_EXCEPTION(eFCODataSourceIterDupeFCO, eFCODataSourceIter) //----------------------------------------------------------------------------- // iFCODataSourceIter @@ -94,100 +94,103 @@ TSS_EXCEPTION( eFCODataSourceIterDupeFCO, eFCODataSourceIter ) class iFCODataSourceIter { public: - // // constructor // - iFCODataSourceIter() {} - virtual ~iFCODataSourceIter() {} + iFCODataSourceIter() + { + } + virtual ~iFCODataSourceIter() + { + } virtual iFCODataSourceIter* CreateCopy() const = 0; - // this creates a new iterator that is an exact copy of myself; it is the caller's responsibility - // to delete the return value of this method + // this creates a new iterator that is an exact copy of myself; it is the caller's responsibility + // to delete the return value of this method - virtual const TCHAR* GetShortName() const = 0; - virtual cFCOName GetName() const = 0; - virtual cFCOName GetParentName() const = 0; - // this returns the current node name, the fully qualified node name, and the node's parent's name - // respectively. The first two methods return undefined strings if Done() is true. + virtual const TCHAR* GetShortName() const = 0; + virtual cFCOName GetName() const = 0; + virtual cFCOName GetParentName() const = 0; + // this returns the current node name, the fully qualified node name, and the node's parent's name + // respectively. The first two methods return undefined strings if Done() is true. // // traverse up and down the hierarchy // - virtual bool AtRoot() const = 0; //throw (eError) - virtual bool CanDescend() const = 0; //throw (eError) - virtual void Descend() = 0; //throw (eError) = 0 - virtual void Ascend() = 0; //throw (eError) = 0 - + virtual bool AtRoot() const = 0; //throw (eError) + virtual bool CanDescend() const = 0; //throw (eError) + virtual void Descend() = 0; //throw (eError) = 0 + virtual void Ascend() = 0; //throw (eError) = 0 + // // traverse my peers (objects in the same directory as me) // - virtual void SeekBegin() = 0; - virtual bool Done() const = 0; - virtual void Next() = 0; + virtual void SeekBegin() = 0; + virtual bool Done() const = 0; + virtual void Next() = 0; // // actually getting the fco // - virtual iFCO* CreateFCO() = 0; //throw (eError) = 0 - virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true) = 0; //throw (eFCODataSourceIter) = 0 - // I actually think that this method should just set Done() == true if the + virtual iFCO* CreateFCO() = 0; //throw (eError) = 0 + virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true) = 0; //throw (eFCODataSourceIter) = 0 + // I actually think that this method should just set Done() == true if the // object doesn't exist, besides adding something to the error bucket. // bCreatePeers is a hint to the iterator. Set it to false if you are only interested in the named // FCO and/or its children. If it is set to false, the iterator may opt to not create the named // FCO's peers, if that will speed up the operation. - virtual void SetErrorBucket( cErrorBucket* pBucket) = 0; - // call this to set the error queue; internal errors that occur while generating fcos - // will have their messages posted to the error queue. To remove the error queue, call - // this with NULL as the single parameter + virtual void SetErrorBucket(cErrorBucket* pBucket) = 0; + // call this to set the error queue; internal errors that occur while generating fcos + // will have their messages posted to the error queue. To remove the error queue, call + // this with NULL as the single parameter - virtual bool SeekTo( const TCHAR* shortName ) = 0; - // this looks among my peers for an entry named shortName. It takes case-sensitiveness - // into account. If the object is not found, Done() is true after this and false is returned. + virtual bool SeekTo(const TCHAR* shortName) = 0; + // this looks among my peers for an entry named shortName. It takes case-sensitiveness + // into account. If the object is not found, Done() is true after this and false is returned. virtual bool IsCaseSensitive() const = 0; - // override this to indicate whether the underlying data source is case sensitive + // override this to indicate whether the underlying data source is case sensitive enum IterFlags { DO_NOT_MODIFY_OBJECTS = 0x00000001 // reset any object properties that may have been altered due to iteration }; - virtual int GetIterFlags() const = 0; - virtual void SetIterFlags(int i) = 0; - // any flags needed for iteration. - + virtual int GetIterFlags() const = 0; + virtual void SetIterFlags(int i) = 0; + // any flags needed for iteration. + //TODO - should the iterator have insertion or deletion methods? // It seems to me that insertion is necessary for rapid database creation, but deletion is - // probably not necessary (although nice for symmetry). It also seems that we would want the - // + // probably not necessary (although nice for symmetry). It also seems that we would want the + // //------------------------------------------------------------------------- // non-pure virtual methods //------------------------------------------------------------------------- - + // // getting my relationship to other data source iters... // - enum Relationship + enum Relationship { - REL_LT, //less than - REL_EQ, //equal - REL_GT //greater than + REL_LT, //less than + REL_EQ, //equal + REL_GT //greater than }; Relationship GetRelationship(const iFCODataSourceIter& rhs) const; - // this returns the relationship of the currently pointed-at item in my list to - // the current one in the rhs's list. It is assumed that the parent name is the same - // for both sides, asserted that both sides are not Done(), and asserted that - // the case-sensitiveness of both sides is the same. - // - // TODO -- If I implement this with string compares of the short name, is this - // going to be too slow? If so, I might need to add the GetShortHash() method - // to this interface that would return some simple hash of the short name. - Relationship Compare( const TCHAR* str1, const TCHAR* str2 ) const; - // this compares str1 to str2 and returns lt, eq, or gt. All iterators should use - // this method to order the short names of the objects that they iterate over. + // this returns the relationship of the currently pointed-at item in my list to + // the current one in the rhs's list. It is assumed that the parent name is the same + // for both sides, asserted that both sides are not Done(), and asserted that + // the case-sensitiveness of both sides is the same. + // + // TODO -- If I implement this with string compares of the short name, is this + // going to be too slow? If so, I might need to add the GetShortHash() method + // to this interface that would return some simple hash of the short name. + Relationship Compare(const TCHAR* str1, const TCHAR* str2) const; + // this compares str1 to str2 and returns lt, eq, or gt. All iterators should use + // this method to order the short names of the objects that they iterate over. }; @@ -197,11 +200,9 @@ class iFCODataSourceIter inline iFCODataSourceIter::Relationship iFCODataSourceIter::GetRelationship(const iFCODataSourceIter& rhs) const { - ASSERT( IsCaseSensitive() == - rhs.IsCaseSensitive() ); + ASSERT(IsCaseSensitive() == rhs.IsCaseSensitive()); - return ( Compare( GetShortName(), rhs.GetShortName() ) ); + return (Compare(GetShortName(), rhs.GetShortName())); } #endif //__FCODATASOURCEITER_H - diff --git a/src/fco/fcodatasourceiterimpl.cpp b/src/fco/fcodatasourceiterimpl.cpp index a21fa80..fce3972 100644 --- a/src/fco/fcodatasourceiterimpl.cpp +++ b/src/fco/fcodatasourceiterimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,8 +51,7 @@ // METHOD CODE //========================================================================= -cFCODataSourceIterImpl::cFCODataSourceIterImpl() - : mFlags(0) +cFCODataSourceIterImpl::cFCODataSourceIterImpl() : mpErrorBucket(0), mParentName(), mFlags(0) { } @@ -65,17 +64,17 @@ cFCODataSourceIterImpl::~cFCODataSourceIterImpl() /////////////////////////////////////////////////////////////////////////////// // operator = /////////////////////////////////////////////////////////////////////////////// -cFCODataSourceIterImpl& cFCODataSourceIterImpl::operator=( const cFCODataSourceIterImpl& rhs ) +cFCODataSourceIterImpl& cFCODataSourceIterImpl::operator=(const cFCODataSourceIterImpl& rhs) { ClearList(); - mPeers = rhs.mPeers; - mParentName = rhs.mParentName; - mpErrorBucket = rhs.mpErrorBucket; - mFlags = rhs.mFlags; + mPeers = rhs.mPeers; + mParentName = rhs.mParentName; + mpErrorBucket = rhs.mpErrorBucket; + mFlags = rhs.mFlags; // // we need to addref all of the fcos we just got... // - for( FCOList::const_iterator i = mPeers.begin(); i != mPeers.end(); i++ ) + for (FCOList::const_iterator i = mPeers.begin(); i != mPeers.end(); ++i) { (*i)->AddRef(); } @@ -84,14 +83,14 @@ cFCODataSourceIterImpl& cFCODataSourceIterImpl::operator=( const cFCODataSourceI // TODO -- if we ever change the mPeers data structure from a vector, this will // have to change (luckily, the compiler should catch this!) // - if( rhs.Done() ) + if (rhs.Done()) { mCurPos = mPeers.end(); } else { int offset = rhs.mCurPos - rhs.mPeers.begin(); - mCurPos = mPeers.begin() + offset; + mCurPos = mPeers.begin() + offset; } return *this; @@ -101,106 +100,106 @@ cFCODataSourceIterImpl& cFCODataSourceIterImpl::operator=( const cFCODataSourceI /////////////////////////////////////////////////////////////////////////////// // GetShortName /////////////////////////////////////////////////////////////////////////////// -const TCHAR* cFCODataSourceIterImpl::GetShortName() const +const TCHAR* cFCODataSourceIterImpl::GetShortName() const { - ASSERT( ! Done() ); + ASSERT(!Done()); - return ( (*mCurPos)->GetName().GetShortName() ); + return ((*mCurPos)->GetName().GetShortName()); } /////////////////////////////////////////////////////////////////////////////// // GetName /////////////////////////////////////////////////////////////////////////////// -cFCOName cFCODataSourceIterImpl::GetName() const +cFCOName cFCODataSourceIterImpl::GetName() const { - ASSERT( ! Done() ); - - return ( (*mCurPos)->GetName() ); + ASSERT(!Done()); + + return ((*mCurPos)->GetName()); } /////////////////////////////////////////////////////////////////////////////// // GetParentName /////////////////////////////////////////////////////////////////////////////// -cFCOName cFCODataSourceIterImpl::GetParentName() const +cFCOName cFCODataSourceIterImpl::GetParentName() const { - return mParentName; + return mParentName; } /////////////////////////////////////////////////////////////////////////////// // GetParentName /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::AtRoot() const //throw (eError) +bool cFCODataSourceIterImpl::AtRoot() const //throw (eError) { - return ( mParentName.GetSize() == 0 ); + return (mParentName.GetSize() == 0); } /////////////////////////////////////////////////////////////////////////////// // CanDescend /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::CanDescend() const //throw (eError) +bool cFCODataSourceIterImpl::CanDescend() const //throw (eError) { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) { return false; } - return ( (*mCurPos)->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN ); + return ((*mCurPos)->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN); } /////////////////////////////////////////////////////////////////////////////// // Descend /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::Descend() //throw (eError) +void cFCODataSourceIterImpl::Descend() //throw (eError) { - ASSERT( CanDescend() ); - + ASSERT(CanDescend()); + mParentName = GetName(); - GeneratePeers( ); + GeneratePeers(); } /////////////////////////////////////////////////////////////////////////////// // Ascend /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::Ascend() //throw (eError) +void cFCODataSourceIterImpl::Ascend() //throw (eError) { - ASSERT( ! AtRoot() ); - + ASSERT(!AtRoot()); + cFCOName name = mParentName; - SeekToFCO( name ); // I do this because SeekToFCO modifies mCwd and takes a reference parameter. + SeekToFCO(name); // I do this because SeekToFCO modifies mCwd and takes a reference parameter. } /////////////////////////////////////////////////////////////////////////////// // SeekBegin /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::SeekBegin() +void cFCODataSourceIterImpl::SeekBegin() { - mCurPos = mPeers.begin(); + mCurPos = mPeers.begin(); } /////////////////////////////////////////////////////////////////////////////// // Done /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::Done() const +bool cFCODataSourceIterImpl::Done() const { - return ( mCurPos == mPeers.end() ); + return (mCurPos == mPeers.end()); } /////////////////////////////////////////////////////////////////////////////// // Next /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::Next() +void cFCODataSourceIterImpl::Next() { - mCurPos++; + ++mCurPos; } /////////////////////////////////////////////////////////////////////////////// // CreateFCO /////////////////////////////////////////////////////////////////////////////// -iFCO* cFCODataSourceIterImpl::CreateFCO() //throw (eError) +iFCO* cFCODataSourceIterImpl::CreateFCO() //throw (eError) { - ASSERT( ! Done() ); - InitializeTypeInfo( *mCurPos ); + ASSERT(!Done()); + InitializeTypeInfo(*mCurPos); (*mCurPos)->AddRef(); return *mCurPos; } @@ -208,34 +207,34 @@ iFCO* cFCODataSourceIterImpl::CreateFCO() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // SeekToFCO /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::SeekToFCO(const cFCOName& name, bool bCreatePeers) // throw (eFCODataSourceIter) +void cFCODataSourceIterImpl::SeekToFCO(const cFCOName& name, bool bCreatePeers) // throw (eFCODataSourceIter) { - ASSERT( name.GetSize() > 0 ); - ASSERT( name.IsCaseSensitive() == IsCaseSensitive() ); + ASSERT(name.GetSize() > 0); + ASSERT(name.IsCaseSensitive() == IsCaseSensitive()); // // get the parent name and pop the short child name // cFCOName parentName = name; - - parentName.Pop(); // RAD:05/10/1999 -- Used to assign result to "shortname" - if( parentName.GetSize() == 0 ) + parentName.Pop(); // RAD:05/10/1999 -- Used to assign result to "shortname" + + if (parentName.GetSize() == 0) { // we are going to the root directory... // note that we are not responsible for iterating over the root nodes (for example, // all of the drive letters in NT or all the hive names in the registry) // - mParentName.Clear(); + mParentName.Clear(); ClearList(); - iFCO* pObj = CreateObject( name, bCreatePeers ); - if( ! pObj ) + iFCO* pObj = CreateObject(name, bCreatePeers); + if (!pObj) { // error creating object; just return. return; } - InsertIntoPeers( pObj ); + InsertIntoPeers(pObj); mCurPos = mPeers.begin(); return; } @@ -243,14 +242,14 @@ void cFCODataSourceIterImpl::SeekToFCO(const cFCOName& name, bool bCreatePeers) { // if we are not creating our peers, simply create the single object and return... // - if( ! bCreatePeers ) + if (!bCreatePeers) { ClearList(); - mParentName = parentName; - iFCO* pNewObj = CreateObject( name, false ); - if( pNewObj ) + mParentName = parentName; + iFCO* pNewObj = CreateObject(name, false); + if (pNewObj) { - InsertIntoPeers( pNewObj ); + InsertIntoPeers(pNewObj); mCurPos = mPeers.begin(); } return; @@ -265,15 +264,16 @@ void cFCODataSourceIterImpl::SeekToFCO(const cFCOName& name, bool bCreatePeers) GeneratePeers(); } - SeekToPeerByName( (*mCurPos)->GetName().GetShortName() ); + if (mCurPos != mPeers.end() && *mCurPos) + SeekToPeerByName((*mCurPos)->GetName().GetShortName()); } /////////////////////////////////////////////////////////////////////////////// // IsCaseSensitive /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::IsCaseSensitive() const +bool cFCODataSourceIterImpl::IsCaseSensitive() const { - return mParentName.IsCaseSensitive(); + return mParentName.IsCaseSensitive(); } /////////////////////////////////////////////////////////////////////////////// @@ -281,7 +281,7 @@ bool cFCODataSourceIterImpl::IsCaseSensitive() const /////////////////////////////////////////////////////////////////////////////// void cFCODataSourceIterImpl::ClearList() { - for( mCurPos = mPeers.begin(); mCurPos != mPeers.end(); mCurPos++ ) + for (mCurPos = mPeers.begin(); mCurPos != mPeers.end(); ++mCurPos) { (*mCurPos)->Release(); } @@ -297,32 +297,32 @@ void cFCODataSourceIterImpl::ClearList() void cFCODataSourceIterImpl::GeneratePeers() { ///TODO -- BIG BIG TODO -- I need to implement some lazy evaluation for these - // fcos so that when I seek to a start point, I don't stat everything in the + // fcos so that when I seek to a start point, I don't stat everything in the // same directory as myself. - // NOTE: This might be alleviated by differentiating between seeks that need + // NOTE: This might be alleviated by differentiating between seeks that need // peers and ones that do not (or maybe lazy evaluation of the peers) ClearList(); - // + // // read all of the children of the parent... // std::vector vChildrenNames; - GetChildrenNames( mParentName.AsString(), vChildrenNames ); + GetChildrenNames(mParentName.AsString(), vChildrenNames); // // insert the children into the set... // std::vector::iterator i; - cFCOName curName = mParentName; - for( i = vChildrenNames.begin(); i != vChildrenNames.end(); i++) + cFCOName curName = mParentName; + for (i = vChildrenNames.begin(); i != vChildrenNames.end(); ++i) { - curName.Push( *i ); - - iFCO* pNewObj = CreateObject( curName, true ); - if( pNewObj ) + curName.Push(*i); + + iFCO* pNewObj = CreateObject(curName, true); + if (pNewObj) { - if( ! InsertIntoPeers( pNewObj ) ) + if (!InsertIntoPeers(pNewObj)) { // no need for an error msg; that is handled by InsertIntoPeers; // just release the object. @@ -339,12 +339,12 @@ void cFCODataSourceIterImpl::GeneratePeers() /////////////////////////////////////////////////////////////////////////////// // TraceContents /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::SeekTo( const TCHAR* shortName ) +bool cFCODataSourceIterImpl::SeekTo(const TCHAR* shortName) { - FCOList::iterator i = UpperBound( shortName ); - if( i != mPeers.end() ) + FCOList::iterator i = UpperBound(shortName); + if (i != mPeers.end()) { - if( REL_EQ == Compare( shortName, (*i)->GetName().GetShortName() ) ) + if (REL_EQ == Compare(shortName, (*i)->GetName().GetShortName())) { mCurPos = i; return true; @@ -360,58 +360,58 @@ bool cFCODataSourceIterImpl::SeekTo( const TCHAR* shortName ) /////////////////////////////////////////////////////////////////////////////// void cFCODataSourceIterImpl::TraceContents(int dl) const { - if( dl == -1 ) + if (dl == -1) dl = cDebug::D_DEBUG; cDebug d("cFCODataSourceIterImpl::TraceContents"); - d.Trace( dl, "FCO Iterator; parent = %s\n", mParentName.AsString().c_str() ); - d.Trace( dl, "---- Peers ---- (current has a * by it)\n" ); + d.Trace(dl, "FCO Iterator; parent = %s\n", mParentName.AsString().c_str()); + d.Trace(dl, "---- Peers ---- (current has a * by it)\n"); int cnt = 0; - for( FCOList::const_iterator iter = mPeers.begin(); iter != mPeers.end(); iter++, cnt++ ) + for (FCOList::const_iterator iter = mPeers.begin(); iter != mPeers.end(); ++iter, ++cnt) { - d.Trace( dl, "[%d]%c\t:%s\n", cnt, iter == mCurPos ? _T('*') : _T(' '), (*iter)->GetName().AsString().c_str() ); + d.Trace(dl, "[%d]%c\t:%s\n", cnt, iter == mCurPos ? _T('*') : _T(' '), (*iter)->GetName().AsString().c_str()); } - d.Trace( dl, "--------------- \n" ); + d.Trace(dl, "--------------- \n"); } /////////////////////////////////////////////////////////////////////////////// // InsertIntoPeers /////////////////////////////////////////////////////////////////////////////// -// inserts the fco into peers. +// inserts the fco into peers. // Sorted in increasing order by short name of the FCO. -bool cFCODataSourceIterImpl::InsertIntoPeers( iFCO* pFCO ) +bool cFCODataSourceIterImpl::InsertIntoPeers(iFCO* pFCO) { - FCOList::iterator i = UpperBound( pFCO->GetName().GetShortName() ); - - if( i != mPeers.end() ) + FCOList::iterator i = UpperBound(pFCO->GetName().GetShortName()); + + if (i != mPeers.end()) { // never insert two objects that have the same name... // - if( REL_EQ == Compare( pFCO->GetName().GetShortName(), (*i)->GetName().GetShortName() ) ) + if (REL_EQ == Compare(pFCO->GetName().GetShortName(), (*i)->GetName().GetShortName())) { - mpErrorBucket->AddError( eFCODataSourceIterDupeFCO( pFCO->GetName().AsString(), eError::NON_FATAL ) ); + mpErrorBucket->AddError(eFCODataSourceIterDupeFCO(pFCO->GetName().AsString(), eError::NON_FATAL)); return false; } else - mPeers.insert( i, pFCO ); + mPeers.insert(i, pFCO); } else - mPeers.push_back( pFCO ); + mPeers.push_back(pFCO); - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// // SeekToPeerByName /////////////////////////////////////////////////////////////////////////////// -void cFCODataSourceIterImpl::SeekToPeerByName( const TCHAR* pchName ) -{ - FCOList::iterator i = UpperBound( pchName ); - if( i != mPeers.end() ) +void cFCODataSourceIterImpl::SeekToPeerByName(const TCHAR* pchName) +{ + FCOList::iterator i = UpperBound(pchName); + if (i != mPeers.end()) { - if( REL_EQ == Compare( pchName, (*i)->GetName().GetShortName() ) ) + if (REL_EQ == Compare(pchName, (*i)->GetName().GetShortName())) { mCurPos = i; return; @@ -425,26 +425,25 @@ void cFCODataSourceIterImpl::SeekToPeerByName( const TCHAR* pchName ) // CompareShortName /////////////////////////////////////////////////////////////////////////////// -bool cFCODataSourceIterImpl::CompareForUpperBound( const iFCO* pFCO, const TCHAR* pchName ) const +bool cFCODataSourceIterImpl::CompareForUpperBound(const iFCO* pFCO, const TCHAR* pchName) const { - return( Compare( pFCO->GetName().GetShortName(), pchName ) == REL_LT ); + return (Compare(pFCO->GetName().GetShortName(), pchName) == REL_LT); } /////////////////////////////////////////////////////////////////////////////// -// cFCODataSourceIterImplCallCompare -// -- used to sneak a pointer-to-member-function where a +// cFCODataSourceIterImplCallCompare +// -- used to sneak a pointer-to-member-function where a // pointer-to-non-member-function is expected /////////////////////////////////////////////////////////////////////////////// class cFCODataSourceIterImplCallCompare { public: - cFCODataSourceIterImplCallCompare( const cFCODataSourceIterImpl* pcls ) - : pc( pcls ) {}; - - bool operator()( const iFCO* a1, const TCHAR* a2 ) + explicit cFCODataSourceIterImplCallCompare(const cFCODataSourceIterImpl* pcls) : pc(pcls){}; + + bool operator()(const iFCO* a1, const TCHAR* a2) { - return pc->CompareForUpperBound( a1, a2 ); + return pc->CompareForUpperBound(a1, a2); } private: @@ -455,9 +454,8 @@ class cFCODataSourceIterImplCallCompare // UpperBound /////////////////////////////////////////////////////////////////////////////// -cFCODataSourceIterImpl::FCOList::iterator cFCODataSourceIterImpl::UpperBound( const TCHAR* pchShortName ) +cFCODataSourceIterImpl::FCOList::iterator cFCODataSourceIterImpl::UpperBound(const TCHAR* pchShortName) { - cFCODataSourceIterImplCallCompare comp( this ); - return ::UpperBound( mPeers.begin(), mPeers.end(), pchShortName, comp ); + cFCODataSourceIterImplCallCompare comp(this); + return ::UpperBound(mPeers.begin(), mPeers.end(), pchShortName, comp); } - diff --git a/src/fco/fcodatasourceiterimpl.h b/src/fco/fcodatasourceiterimpl.h index 83ac1c8..7a619a9 100644 --- a/src/fco/fcodatasourceiterimpl.h +++ b/src/fco/fcodatasourceiterimpl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,55 +53,58 @@ class cFCODataSourceIterImpl : public iFCODataSourceIter public: cFCODataSourceIterImpl(); virtual ~cFCODataSourceIterImpl(); - cFCODataSourceIterImpl& operator=( const cFCODataSourceIterImpl& rhs ); + cFCODataSourceIterImpl& operator=(const cFCODataSourceIterImpl& rhs); + + virtual const TCHAR* GetShortName() const; + virtual cFCOName GetName() const; + virtual cFCOName GetParentName() const; - virtual const TCHAR* GetShortName() const; - virtual cFCOName GetName() const; - virtual cFCOName GetParentName() const; + virtual bool AtRoot() const; //throw (eError); + virtual bool CanDescend() const; //throw (eError); + virtual void Descend(); //throw (eError); + virtual void Ascend(); //throw (eError); - virtual bool AtRoot() const; //throw (eError); - virtual bool CanDescend() const; //throw (eError); - virtual void Descend(); //throw (eError); - virtual void Ascend(); //throw (eError); - - virtual void SeekBegin(); - virtual bool Done() const; - virtual void Next(); + virtual void SeekBegin(); + virtual bool Done() const; + virtual void Next(); - virtual iFCO* CreateFCO(); //throw (eError); - virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true); //throw (eFCODataSourceIter); + virtual iFCO* CreateFCO(); //throw (eError); + virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true); //throw (eFCODataSourceIter); + + virtual void SetErrorBucket(cErrorBucket* pBucket) + { + mpErrorBucket = pBucket; + } + virtual bool SeekTo(const TCHAR* shortName); + virtual bool IsCaseSensitive() const; + + virtual int GetIterFlags() const; + virtual void SetIterFlags(int i); - virtual void SetErrorBucket( cErrorBucket* pBucket ) { mpErrorBucket = pBucket; } - virtual bool SeekTo( const TCHAR* shortName ); - virtual bool IsCaseSensitive() const; - - virtual int GetIterFlags() const; - virtual void SetIterFlags(int i); - // // must override this functions // - virtual iFCODataSourceIter* CreateCopy() const = 0; + virtual iFCODataSourceIter* CreateCopy() const = 0; - // debug functions + // debug functions virtual void TraceContents(int dl = -1) const; - - + + // // util function for sorting/searching // - bool CompareForUpperBound( const iFCO* pFCO, const TCHAR* pchName ) const; - // compares shortname of FCO to pchName. returns < == or > 0 as strcmp does. + bool CompareForUpperBound(const iFCO* pFCO, const TCHAR* pchName) const; + // compares shortname of FCO to pchName. returns < == or > 0 as strcmp does. protected: - cFCODataSourceIterImpl( const cFCODataSourceIterImpl& ); + cFCODataSourceIterImpl(const cFCODataSourceIterImpl&); //TODO -- turn this into a set? // - typedef std::vector FCOList; // sorted in increasing order by name of the FCO - + typedef std::vector FCOList; // sorted in increasing order by name of the FCO + cErrorBucket* mpErrorBucket; cFCOName mParentName; FCOList mPeers; @@ -112,56 +115,54 @@ class cFCODataSourceIterImpl : public iFCODataSourceIter // helper methods //------------------------------------------------------------------------- void GeneratePeers(); - // used to implement Descend() -- also used by SeekToFCO() ... it takes the value of - // mParentName and fills out mPeers and sets mCurPos to mPeers.begin() - // TODO -- this fills out the error queue if the readdir() or any stats fail. + // used to implement Descend() -- also used by SeekToFCO() ... it takes the value of + // mParentName and fills out mPeers and sets mCurPos to mPeers.begin() + // TODO -- this fills out the error queue if the readdir() or any stats fail. void ClearList(); - // releases everything in the list, empties the list, and sets mCurPos to end() - - bool InsertIntoPeers( iFCO* pFCO ); - // inserts the fco into peers. Peers sorted in increasing order by name of the FCO. - // Uses binary search to find location into which to insert. - // mCurPos is not guaranteed to be valid after this call due to possible list reallocation. - // If an entry with the same name already exists, the fco is not added, an error is added to the error - // bucket, and false is returned. Otherwise, true is always returned. - - void SeekToPeerByName( const TCHAR* pchName ); - // seeks the iter to the peer with this name. Done() will be true if the function cannot find the peer - // Uses binary search algorithm. - - FCOList::iterator UpperBound( const TCHAR* pchShortName ); - // same as std::upper_bound except it calls CompareForUpperBound() to - // do its comparison. - - + // releases everything in the list, empties the list, and sets mCurPos to end() + + bool InsertIntoPeers(iFCO* pFCO); + // inserts the fco into peers. Peers sorted in increasing order by name of the FCO. + // Uses binary search to find location into which to insert. + // mCurPos is not guaranteed to be valid after this call due to possible list reallocation. + // If an entry with the same name already exists, the fco is not added, an error is added to the error + // bucket, and false is returned. Otherwise, true is always returned. + + void SeekToPeerByName(const TCHAR* pchName); + // seeks the iter to the peer with this name. Done() will be true if the function cannot find the peer + // Uses binary search algorithm. + + FCOList::iterator UpperBound(const TCHAR* pchShortName); + // same as std::upper_bound except it calls CompareForUpperBound() to + // do its comparison. + + // // must override these functions // - virtual void GetChildrenNames( const TSTRING& strParentName, std::vector& vChildrenNames ) = 0; - // retrieves the names of all the children of the named parent - // strParent name is of the form returned by cFCOName::AsString. Note that it is not very efficient - // to do it this way for registry objects -- 4 Mar 99 mdb - - virtual iFCO* CreateObject(const cFCOName& name, bool bCreatingPeers ) = 0; - // this method is called when creating the heirarchy. at minimum it needs to create an empty iFCO - // with the correct name. if NULL is returned, the iterator does not go any deeper into the FCO. - // you may also use this call to set some properties of the FCO. For instance, - // FS will record the device number of a file if we are creating peers, and it's CreateObject will - // fail if it's peers have a different device number. - // Must set the object type in this function - // - // If bCreatingPeers is false, then this method needs to verify that the object actually exists, and - // return 0 if it does not. (if bCreatingPeers is true, we got the name from the OS, so we assume it - // exists) + virtual void GetChildrenNames(const TSTRING& strParentName, std::vector& vChildrenNames) = 0; + // retrieves the names of all the children of the named parent + // strParent name is of the form returned by cFCOName::AsString. Note that it is not very efficient + // to do it this way for registry objects -- 4 Mar 99 mdb + + virtual iFCO* CreateObject(const cFCOName& name, bool bCreatingPeers) = 0; + // this method is called when creating the heirarchy. at minimum it needs to create an empty iFCO + // with the correct name. if NULL is returned, the iterator does not go any deeper into the FCO. + // you may also use this call to set some properties of the FCO. For instance, + // FS will record the device number of a file if we are creating peers, and it's CreateObject will + // fail if it's peers have a different device number. + // Must set the object type in this function + // + // If bCreatingPeers is false, then this method needs to verify that the object actually exists, and + // return 0 if it does not. (if bCreatingPeers is true, we got the name from the OS, so we assume it + // exists) virtual bool InitializeTypeInfo(iFCO* pFCO) = 0; - // initializes the minimal amout of information about the fco to know what "type" it is. If any OS calls - // fail, the error bucket should be filled up and false should be returned. - // - // this method should check whether the properties are already valid and do nothing if they already are; - // this has the potential to be called multiple times, so we need to be efficient. - - + // initializes the minimal amout of information about the fco to know what "type" it is. If any OS calls + // fail, the error bucket should be filled up and false should be returned. + // + // this method should check whether the properties are already valid and do nothing if they already are; + // this has the potential to be called multiple times, so we need to be efficient. }; //========================================================================= @@ -173,10 +174,9 @@ inline int cFCODataSourceIterImpl::GetIterFlags() const return mFlags; } -inline void cFCODataSourceIterImpl::SetIterFlags( int i ) +inline void cFCODataSourceIterImpl::SetIterFlags(int i) { mFlags = i; } #endif //__FCODATASOURCEITERIMPL_H - diff --git a/src/fco/fcoerrors.cpp b/src/fco/fcoerrors.cpp index 2117a5d..4838c19 100644 --- a/src/fco/fcoerrors.cpp +++ b/src/fco/fcoerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,10 +40,9 @@ #include "fcodatasourceiter.h" -TSS_BEGIN_ERROR_REGISTRATION( fco ) +TSS_BEGIN_ERROR_REGISTRATION(fco) -TSS_REGISTER_ERROR( eFCODataSourceIter(), _T("Data source error.") ) -TSS_REGISTER_ERROR( eFCODataSourceIterDupeFCO(), _T("Duplicate object encountered.") ) +TSS_REGISTER_ERROR(eFCODataSourceIter(), _T("Data source error.")) +TSS_REGISTER_ERROR(eFCODataSourceIterDupeFCO(), _T("Duplicate object encountered.")) TSS_END_ERROR_REGISTRATION() - diff --git a/src/fco/fcoerrors.h b/src/fco/fcoerrors.h index 89b4978..4feea79 100644 --- a/src/fco/fcoerrors.h +++ b/src/fco/fcoerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( fco ) +TSS_DECLARE_ERROR_REGISTRATION(fco) #endif //__FCOERRORS_H - diff --git a/src/fco/fcogenre.h b/src/fco/fcogenre.h index 704a0f1..bf3efc9 100644 --- a/src/fco/fcogenre.h +++ b/src/fco/fcogenre.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -62,11 +62,11 @@ class cGenre //----------------------------------------- enum Platform { - PLATFORM_MASK_INVALID = 0x00000000, - PLATFORM_MASK_NT = 0x00010000, - PLATFORM_MASK_UNIX = 0x00020000 + PLATFORM_MASK_INVALID = 0x00000000, + PLATFORM_MASK_NT = 0x00010000, + PLATFORM_MASK_UNIX = 0x00020000 }; - + //-------------------------------------------------------------------- // Valid Genres -- dynamic so not compiled except for 'invalid' value //-------------------------------------------------------------------- @@ -83,20 +83,19 @@ class cGenre GENRE_NTREG = 0x00010002, GENRE_FS = 0x00020001, */ - GENRE_INVALID = 0x00000000 + GENRE_INVALID = 0x00000000 }; - + //---------------------------------------- // don't let C++ create default functions //---------------------------------------- cGenre(); - ~cGenre(); - cGenre( const cGenre& ); - cGenre& operator=( const cGenre& ); + ~cGenre(); + cGenre(const cGenre&); + cGenre& operator=(const cGenre&); cGenre* operator&(); const cGenre* operator&() const; }; // eoc: cGenre #endif // __FCOGENRE_H - diff --git a/src/fco/fconame.cpp b/src/fco/fconame.cpp index 4cda54a..8621651 100644 --- a/src/fco/fconame.cpp +++ b/src/fco/fconame.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,21 +44,24 @@ #include //############################################################################# -// cFCOName_i -- an implementation of a cFCOName -- this object is refrence +// cFCOName_i -- an implementation of a cFCOName -- this object is refrence // counted (so copies are cheap) and contains a linked list of cFCOTableNodes // as well as the static instance of the cFCONameTbl. //############################################################################# class cFCOName_i : public cRefCountObj { public: - cFCOName::ListType mNames; + cFCOName::ListType mNames; - ~cFCOName_i() { ClearList(); } + ~cFCOName_i() + { + ClearList(); + } void ClearList(); - // releases all the names in mNames and clears the list + // releases all the names in mNames and clears the list // the single name table - static cFCONameTbl msNameTbl; + static cFCONameTbl msNameTbl; }; /////////////////////////////////////////////////// @@ -67,7 +70,7 @@ class cFCOName_i : public cRefCountObj inline void cFCOName_i::ClearList() { cFCOName::ListType::iterator i; - for(i = mNames.begin(); i != mNames.end(); ++i) + for (i = mNames.begin(); i != mNames.end(); ++i) (*i)->Release(); mNames.clear(); } @@ -92,161 +95,180 @@ void cFCOName::ClearNameTable() /////////////////////////////////////////////////////////////////////////////// // ctor, dtor /////////////////////////////////////////////////////////////////////////////// -cFCOName::cFCOName(iFCONameInfo* pNI) : - iTypedSerializable(), mpPathName(0), mDelimiter('/') +cFCOName::cFCOName(iFCONameInfo* pNI) : iTypedSerializable(), mpPathName(0), mDelimiter('/') { SetNameInfo(pNI); mpPathName = new cFCOName_i; -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); cDebug d("cFCOName::cFCOName(iFCONameInfo*)"); - d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); -#endif + d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), + this, + mpPathName, + mDebugStrName.c_str(), + mpPathName->GetRefCount()); +#endif } -cFCOName::cFCOName(const cFCOName& rhs) : - iTypedSerializable(), - mpPathName(rhs.mpPathName), - mDelimiter(rhs.mDelimiter), - mbCaseSensitive(rhs.mbCaseSensitive) +cFCOName::cFCOName(const cFCOName& rhs) + : iTypedSerializable(), mpPathName(rhs.mpPathName), mDelimiter(rhs.mDelimiter), mbCaseSensitive(rhs.mbCaseSensitive) { mpPathName->AddRef(); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); cDebug d("cFCOName::cFCOName(cFCOName&)"); - d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); -#endif + d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), + this, + mpPathName, + mDebugStrName.c_str(), + mpPathName->GetRefCount()); +#endif } -cFCOName::cFCOName(const TSTRING& rhs, iFCONameInfo* pNI) : - iTypedSerializable(), mpPathName(0), mDelimiter('/') -{ +cFCOName::cFCOName(const TSTRING& rhs, iFCONameInfo* pNI) : iTypedSerializable(), mpPathName(0), mDelimiter('/') +{ SetNameInfo(pNI); mpPathName = new cFCOName_i; ParseString(rhs.c_str()); - -#ifdef _DEBUG + +#ifdef DEBUG mDebugStrName = AsString(); cDebug d("cFCOName::cFCOName(cFCOName&,iFCONameInfo*)"); - d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); -#endif + d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), + this, + mpPathName, + mDebugStrName.c_str(), + mpPathName->GetRefCount()); +#endif } -cFCOName::cFCOName(const TCHAR* rhs, iFCONameInfo* pNI) : - iTypedSerializable(), mpPathName(0), mDelimiter('/') +cFCOName::cFCOName(const TCHAR* rhs, iFCONameInfo* pNI) : iTypedSerializable(), mpPathName(0), mDelimiter('/') { SetNameInfo(pNI); mpPathName = new cFCOName_i; ParseString(rhs); - -#ifdef _DEBUG + +#ifdef DEBUG mDebugStrName = AsString(); cDebug d("cFCOName::cFCOName(cFCOName&,iFCONameInfo*)"); - d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); -#endif + d.TraceNever(_T("constructing %X:%X %s (refcount=%d)\n"), + this, + mpPathName, + mDebugStrName.c_str(), + mpPathName->GetRefCount()); +#endif } cFCOName::~cFCOName() { -#ifdef _DEBUG +#ifdef DEBUG cDebug d("cFCOName::~cFCOName()"); - d.TraceNever(_T("destructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); -#endif + d.TraceNever( + _T("destructing %X:%X %s (refcount=%d)\n"), this, mpPathName, mDebugStrName.c_str(), mpPathName->GetRefCount()); +#endif mpPathName->Release(); } void cFCOName::SetNameInfo(iFCONameInfo* pNI) -{ - if( pNI ) +{ + if (pNI) { mbCaseSensitive = pNI->IsCaseSensitive(); - mDelimiter = pNI->GetDelimitingChar(); + mDelimiter = pNI->GetDelimitingChar(); } else { mbCaseSensitive = iTWFactory::GetInstance()->GetNameInfo()->IsCaseSensitive(); - mDelimiter = iTWFactory::GetInstance()->GetNameInfo()->GetDelimitingChar(); + mDelimiter = iTWFactory::GetInstance()->GetNameInfo()->GetDelimitingChar(); } -#ifdef _DEBUG - if( mpPathName != NULL ) // this could be called from the constructor before this is initialized. +#ifdef DEBUG + if (mpPathName != NULL) // this could be called from the constructor before this is initialized. mDebugStrName = AsString(); -#endif +#endif } /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -void cFCOName::operator = (const cFCOName& rhs) +cFCOName& cFCOName::operator=(const cFCOName& rhs) { mpPathName->Release(); // TODO -- I am sure this won't work (const-ness) - mpPathName = rhs.mpPathName; + mpPathName = rhs.mpPathName; mpPathName->AddRef(); mDelimiter = rhs.mDelimiter; mbCaseSensitive = rhs.mbCaseSensitive; -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif + return *this; } -void cFCOName::operator = (const TSTRING& rhs) + +cFCOName& cFCOName::operator=(const TSTRING& rhs) { *this = rhs.c_str(); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif + return *this; } -void cFCOName::operator = (const TCHAR* rhs) +cFCOName& cFCOName::operator=(const TCHAR* rhs) { // if I have the only handle on this vector, I can reuse it // otherwise, I have to release it. - if(mpPathName->GetRefCount() != 1) + if (mpPathName->GetRefCount() != 1) { mpPathName->Release(); mpPathName = new cFCOName_i; } ParseString(rhs); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif + return *this; } -void cFCOName::ParseString( const TCHAR* pszin ) +void cFCOName::ParseString(const TCHAR* pszin) { - ASSERT(mpPathName != 0); - ASSERT(pszin != 0); - - mpPathName->ClearList(); - - const TCHAR* at = (pszin + 0); - const TCHAR* begin = at; - const TCHAR* end = at; - int components = 0; + ASSERT(mpPathName != 0); + ASSERT(pszin != 0); + + mpPathName->ClearList(); + + const TCHAR* at = (pszin + 0); + const TCHAR* begin = at; + const TCHAR* end = at; + int components = 0; + + while (*end) + ++end; - while (*end) - ++end; + while (at < end) + { + while (*at && !(*at == mDelimiter) && (at < end)) + at++; - while (at < end) - { - while (*at && !(*at == mDelimiter) && (at < end)) - at++; + TSTRING name(begin, at); - TSTRING name(begin, at); +//NOTE: To be truly standards compliant we ought to turn >2 slashes into 1, not 2. +#if SUPPORTS_DOUBLE_SLASH_PATH + if (name.length() > 0 || components < 2) +#else + if (name.length() > 0 || components == 0) +#endif + { + cFCONameTblNode* pNode = cFCOName_i::msNameTbl.CreateNode(name); - if (name.length() > 0 || components == 0) - { - cFCONameTblNode* pNode = - cFCOName_i::msNameTbl.CreateNode(name); - - mpPathName->mNames.push_back(pNode); - } + mpPathName->mNames.push_back(pNode); + } - components++; - at++; - begin=at; - //begin = (at = tss::strinc(at)); - } + components++; + at++; + begin = at; + //begin = (at = tss::strinc(at)); + } } @@ -263,10 +285,10 @@ TSTRING cFCOName::AsString() const // if I don't, it appears as an empty string // 15 Oct -- I also had to add a yucky hack for c:\ in windows // - // 13 Jan 99 mdb -- I have decided that all fconames that are one item long should be + // 13 Jan 99 mdb -- I have decided that all fconames that are one item long should be // considered "root items" and should thus be displayed with a trailing delimiting character. // - if(mpPathName->mNames.size() == 1) + if (mpPathName->mNames.size() == 1) { str = (*mpPathName->mNames.begin())->GetString(); str += mDelimiter; @@ -274,17 +296,17 @@ TSTRING cFCOName::AsString() const } // end ugly root dir hacks ... ListType::iterator i = mpPathName->mNames.begin(); - while(i != mpPathName->mNames.end()) + while (i != mpPathName->mNames.end()) { TSTRING current = (*i)->GetString(); // the loop is constructed in this odd fashion because I don't want a trailing mDelimiter str += current; - i++; + ++i; - if(i != mpPathName->mNames.end() && current != "/") + if (i != mpPathName->mNames.end() && current != "/") str += mDelimiter; } - + return str; } @@ -293,11 +315,11 @@ TSTRING cFCOName::AsString() const /////////////////////////////////////////////////////////////////////////////// const TCHAR* cFCOName::GetShortName() const { - ASSERT( ! mpPathName->mNames.empty() ); - if( mpPathName->mNames.empty() ) + ASSERT(!mpPathName->mNames.empty()); + if (mpPathName->mNames.empty()) return 0; - return ( mpPathName->mNames.back()->GetString() ); + return (mpPathName->mNames.back()->GetString()); } /////////////////////////////////////////////////////////////////////////////// @@ -307,13 +329,13 @@ void cFCOName::Clear() { //TODO -- I could probably implement this a little cleaner... // - while( ! mpPathName->mNames.empty() ) + while (!mpPathName->mNames.empty()) { Pop(); } -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif } @@ -325,29 +347,29 @@ cFCOName::Relationship cFCOName::GetRelationship(const cFCOName& rhs) const ListType::iterator myIter, rhsIter; // get the easy equality out of the case first... - if(mpPathName == rhs.mpPathName) + if (mpPathName == rhs.mpPathName) return REL_EQUAL; // if either name is case sensitive, we will do a case sensitive compare bool bCaseSensitive = (IsCaseSensitive() || rhs.IsCaseSensitive()); bool bEqual; - for(myIter = mpPathName->mNames.begin(), rhsIter = rhs.mpPathName->mNames.begin(); - (myIter != mpPathName->mNames.end() && rhsIter != rhs.mpPathName->mNames.end()); - myIter++, rhsIter++) + for (myIter = mpPathName->mNames.begin(), rhsIter = rhs.mpPathName->mNames.begin(); + (myIter != mpPathName->mNames.end() && rhsIter != rhs.mpPathName->mNames.end()); + ++myIter, ++rhsIter) { - if(bCaseSensitive) + if (bCaseSensitive) bEqual = (*myIter == *rhsIter); else bEqual = ((*myIter)->GetLowercaseNode() == (*rhsIter)->GetLowercaseNode()); - if(! bEqual) + if (!bEqual) return REL_UNRELATED; } // if we got this far, one is above another, or they are equal... - if((myIter == mpPathName->mNames.end()) && (rhsIter == rhs.mpPathName->mNames.end())) + if ((myIter == mpPathName->mNames.end()) && (rhsIter == rhs.mpPathName->mNames.end())) return REL_EQUAL; - else if(myIter == mpPathName->mNames.end()) + else if (myIter == mpPathName->mNames.end()) // I am shorter; I am above rhs return REL_ABOVE; else @@ -355,41 +377,36 @@ cFCOName::Relationship cFCOName::GetRelationship(const cFCOName& rhs) const } - /////////////////////////////////////////////////////////////////////////////// // Read // TODO -- serialize the hash table and nodes instead of reading and writing // as a string /////////////////////////////////////////////////////////////////////////////// -void cFCOName::Read(iSerializer* pSerializer, int32 version) +void cFCOName::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("FCO Name Read"))); TSTRING str; pSerializer->ReadString(str); - + int16 dummy = 0; // serialize the delimiter -#ifdef _UNICODE - pSerializer->ReadInt16( (int16&)mDelimiter ); -#else - pSerializer->ReadInt16( dummy ); // delimiter, but it's always '/' anyway in OST. - mDelimiter = '/'; -#endif + pSerializer->ReadInt16(dummy); // delimiter, but it's always '/' anyway in OST. + mDelimiter = '/'; // read the case-sensitiveness pSerializer->ReadInt16(dummy); - if(dummy == 0) + if (dummy == 0) mbCaseSensitive = false; else mbCaseSensitive = true; ParseString(str.c_str()); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif } /////////////////////////////////////////////////////////////////////////////// @@ -402,14 +419,9 @@ void cFCOName::Write(iSerializer* pSerializer) const pSerializer->WriteString(AsString()); // serialize the delimiter -#ifdef _UNICODE - pSerializer->WriteInt16(mDelimiter); -#else - unsigned short wc = (unsigned short)'/'; + unsigned short wc = (unsigned short)'/'; pSerializer->WriteInt16(wc); -#endif - - pSerializer->WriteInt16( mbCaseSensitive ? (int16)1 : (int16)0); + pSerializer->WriteInt16(mbCaseSensitive ? (int16)1 : (int16)0); } /////////////////////////////////////////////////////////////////////////////// @@ -418,19 +430,18 @@ void cFCOName::Write(iSerializer* pSerializer) const /////////////////////////////////////////////////////////////////////////////// void cFCOName::CopyOnModify() { - if(mpPathName->GetRefCount() > 1) + if (mpPathName->GetRefCount() > 1) { - cFCOName_i* pOld= mpPathName; - mpPathName = new cFCOName_i; + cFCOName_i* pOld = mpPathName; + mpPathName = new cFCOName_i; ListType::iterator i; - for(i = pOld->mNames.begin(); i != pOld->mNames.end(); ++i) + for (i = pOld->mNames.begin(); i != pOld->mNames.end(); ++i) { (*i)->AddRef(); mpPathName->mNames.push_back(*i); } pOld->Release(); } - } /////////////////////////////////////////////////////////////////////////////// @@ -443,15 +454,15 @@ void cFCOName::Push(const TSTRING& str) cFCONameTblNode* pNode = cFCOName_i::msNameTbl.CreateNode(str); mpPathName->mNames.push_back(pNode); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif } /////////////////////////////////////////////////////////////////////////////// // Pop /////////////////////////////////////////////////////////////////////////////// -const TCHAR* cFCOName::Pop() +const TCHAR* cFCOName::Pop() { // we must copy the fconame if there is more than one refrence to it... CopyOnModify(); @@ -465,33 +476,33 @@ const TCHAR* cFCOName::Pop() ASSERT(pNode->GetRefCount() > 1); const TCHAR* ret = pNode->GetString(); pNode->Release(); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif return ret; } /////////////////////////////////////////////////////////////////////////////// // PopFront /////////////////////////////////////////////////////////////////////////////// -const TCHAR* cFCOName::PopFront() +const TCHAR* cFCOName::PopFront() { // we must copy the fconame if there is more than one reference to it... CopyOnModify(); ASSERT(GetSize() > 0); - cFCONameTblNode* pNode = mpPathName->mNames.front(); - cFCOName::ListType::iterator i = mpPathName->mNames.begin(); - mpPathName->mNames.erase( i ); + cFCONameTblNode* pNode = mpPathName->mNames.front(); + cFCOName::ListType::iterator i = mpPathName->mNames.begin(); + mpPathName->mNames.erase(i); // I do this assertion because it should also be in the hash table ASSERT(pNode->GetRefCount() > 1); const TCHAR* ret = pNode->GetString(); pNode->Release(); -#ifdef _DEBUG +#ifdef DEBUG mDebugStrName = AsString(); -#endif +#endif return ret; } @@ -506,7 +517,7 @@ int cFCOName::GetSize() const /////////////////////////////////////////////////////////////////////////////// // operator< -- provides an arbitrary ordering to cFCONames. The algorithm I chose -// is like strcmp, except instead of comparing characters, I compare +// is like strcmp, except instead of comparing characters, I compare // cFCONameTblNode* addresses /////////////////////////////////////////////////////////////////////////////// bool cFCOName::operator<(const cFCOName& rhs) const @@ -517,16 +528,16 @@ bool cFCOName::operator<(const cFCOName& rhs) const bool bCaseSensitive = (IsCaseSensitive() || rhs.IsCaseSensitive()); // get the easy equality out of the case first... - if(mpPathName == rhs.mpPathName) + if (mpPathName == rhs.mpPathName) return false; - for(myIter = mpPathName->mNames.begin(), rhsIter = rhs.mpPathName->mNames.begin(); - (myIter != mpPathName->mNames.end() && rhsIter != rhs.mpPathName->mNames.end()); - myIter++, rhsIter++) + for (myIter = mpPathName->mNames.begin(), rhsIter = rhs.mpPathName->mNames.begin(); + (myIter != mpPathName->mNames.end() && rhsIter != rhs.mpPathName->mNames.end()); + ++myIter, ++rhsIter) { - if(bCaseSensitive) + if (bCaseSensitive) { - if (*myIter > *rhsIter) + if (*myIter > *rhsIter) return false; else if (*myIter < *rhsIter) return true; @@ -534,7 +545,7 @@ bool cFCOName::operator<(const cFCOName& rhs) const else { // not case sensitive - if ((*myIter)->GetLowercaseNode() > (*rhsIter)->GetLowercaseNode()) + if ((*myIter)->GetLowercaseNode() > (*rhsIter)->GetLowercaseNode()) return false; else if ((*myIter)->GetLowercaseNode() < (*rhsIter)->GetLowercaseNode()) return true; @@ -543,10 +554,10 @@ bool cFCOName::operator<(const cFCOName& rhs) const } // if we got this far, one is above another, or they are equal... - if(rhsIter == rhs.mpPathName->mNames.end()) + if (rhsIter == rhs.mpPathName->mNames.end()) // either I am longer of we are equal; so return false return false; - + return true; } @@ -558,8 +569,7 @@ bool cFCOName::operator<(const cFCOName& rhs) const /////////////////////////////////////////////////////////////////////////////// // cFCONameIter /////////////////////////////////////////////////////////////////////////////// -cFCONameIter::cFCONameIter(const cFCOName& name) -: mName(name) +cFCONameIter::cFCONameIter(const cFCOName& name) : mName(name) { SeekBegin(); } @@ -569,7 +579,6 @@ cFCONameIter::cFCONameIter(const cFCOName& name) /////////////////////////////////////////////////////////////////////////////// cFCONameIter::~cFCONameIter() { - } /////////////////////////////////////////////////////////////////////////////// @@ -593,7 +602,7 @@ void cFCONameIter::SeekBegin() /////////////////////////////////////////////////////////////////////////////// void cFCONameIter::Next() { - mIter++; + ++mIter; } /////////////////////////////////////////////////////////////////////////////// @@ -601,7 +610,7 @@ void cFCONameIter::Next() /////////////////////////////////////////////////////////////////////////////// bool cFCONameIter::Done() const { - return ( mIter == mName.mpPathName->mNames.end() ); + return (mIter == mName.mpPathName->mNames.end()); } /////////////////////////////////////////////////////////////////////////////// @@ -609,7 +618,7 @@ bool cFCONameIter::Done() const /////////////////////////////////////////////////////////////////////////////// const TCHAR* cFCONameIter::GetName() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->GetString(); } @@ -619,7 +628,7 @@ const TCHAR* cFCONameIter::GetName() const /////////////////////////////////////////////////////////////////////////////// void cFCONameIter::Prev() { - mIter--; + --mIter; } /////////////////////////////////////////////////////////////////////////////// @@ -627,18 +636,16 @@ void cFCONameIter::Prev() /////////////////////////////////////////////////////////////////////////////// int cFCONameIter::Index() const { - ASSERT( ! Done() ); - return ( mIter - mName.mpPathName->mNames.begin() ); + ASSERT(!Done()); + return (mIter - mName.mpPathName->mNames.begin()); } /////////////////////////////////////////////////////////////////////////////// // SeekTo /////////////////////////////////////////////////////////////////////////////// -void cFCONameIter::SeekTo( int index ) +void cFCONameIter::SeekTo(int index) { - ASSERT( (index >= 0) && (index < mName.GetSize()) ); + ASSERT((index >= 0) && (index < mName.GetSize())); - mIter = ( mName.mpPathName->mNames.begin() + index ); + mIter = (mName.mpPathName->mNames.begin() + index); } - - diff --git a/src/fco/fconame.h b/src/fco/fconame.h index 0c6f05c..a5e607e 100644 --- a/src/fco/fconame.h +++ b/src/fco/fconame.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -58,104 +58,104 @@ class cFCOName : public iTypedSerializable public: typedef cFCONameIter iterator; - cFCOName(iFCONameInfo* iNI = NULL); + explicit cFCOName(iFCONameInfo* iNI = NULL); cFCOName(const cFCOName& rhs); - explicit cFCOName(const TSTRING& rhs, iFCONameInfo* iNI = NULL); + explicit cFCOName(const TSTRING& rhs, iFCONameInfo* iNI = NULL); explicit cFCOName(const TCHAR* rhs, iFCONameInfo* iNI = NULL); - // these ctors are explicit because it is expensive to create these things, so we don't want to - // do it unexpectedly + // these ctors are explicit because it is expensive to create these things, so we don't want to + // do it unexpectedly virtual ~cFCOName(); - void operator = (const cFCOName& rhs); - void operator = (const TSTRING& rhs); - void operator = (const TCHAR* rhs); - - bool operator < (const cFCOName& rhs) const; - // defines an arbitrary order for cFCONames. This is so that names can - // be stored in trees and other ordered data structures in order to facilitate - // fast lookups. - - bool operator == (const cFCOName& rhs) const; - bool operator != (const cFCOName& rhs) const; - bool IsEqual (const cFCOName& rhs) const; - // both of these are synonyms for (GetRelationship(rhs) == REL_EQUAL) - - TSTRING AsString() const; - // return a string representation of the string - - bool IsCaseSensitive() const; - void SetCaseSensitive(bool val); - // determines how name comparisons are done. If two cFCONames are compared who are - // both case insensitive, a case insensitive compare is done. If both are case sensitive, - // a case sensitive compare is done. If one is and one isn't case sensitive (? TODO: what - // is the right thing to do in this case? ASSERT(0)? do a case sensitive compare??) - TCHAR GetDelimiter() const; - void SetDelimiter(TCHAR delimiter); - // defines what the path-delimiting character is - - void Push(const TSTRING& str); - // pushes the named string onto the end of the path. A delimiter is implicitely placed between the old end - // and the new string. if debug is defined, it is asserted that the new string does not contain the - // delimiting character - const TCHAR* Pop(); - // removes the last part of the path from the name and returns it. ASSERTS and returns an undefined value if - // the path is empty - const TCHAR* PopFront(); - // removes the first part of the path from the name and returns it. ASSERTS and returns an undefined value if - // the path is empty - void Clear(); - // removes all elements from the name; after this, GetSize() == 0. - const TCHAR* GetShortName() const; - // this will return the final string in the vector. It will assert that the name is not empty. - int GetSize() const; - // returns the number of path items (strings between delimiters) that are in the fco name. It is always equal - // to the number of delimiters in the path plus one. - + cFCOName& operator=(const cFCOName& rhs); + cFCOName& operator=(const TSTRING& rhs); + cFCOName& operator=(const TCHAR* rhs); + + bool operator<(const cFCOName& rhs) const; + // defines an arbitrary order for cFCONames. This is so that names can + // be stored in trees and other ordered data structures in order to facilitate + // fast lookups. + + bool operator==(const cFCOName& rhs) const; + bool operator!=(const cFCOName& rhs) const; + bool IsEqual(const cFCOName& rhs) const; + // both of these are synonyms for (GetRelationship(rhs) == REL_EQUAL) + + TSTRING AsString() const; + // return a string representation of the string + + bool IsCaseSensitive() const; + void SetCaseSensitive(bool val); + // determines how name comparisons are done. If two cFCONames are compared who are + // both case insensitive, a case insensitive compare is done. If both are case sensitive, + // a case sensitive compare is done. If one is and one isn't case sensitive (? TODO: what + // is the right thing to do in this case? ASSERT(0)? do a case sensitive compare??) + TCHAR GetDelimiter() const; + void SetDelimiter(TCHAR delimiter); + // defines what the path-delimiting character is + + void Push(const TSTRING& str); + // pushes the named string onto the end of the path. A delimiter is implicitely placed between the old end + // and the new string. if debug is defined, it is asserted that the new string does not contain the + // delimiting character + const TCHAR* Pop(); + // removes the last part of the path from the name and returns it. ASSERTS and returns an undefined value if + // the path is empty + const TCHAR* PopFront(); + // removes the first part of the path from the name and returns it. ASSERTS and returns an undefined value if + // the path is empty + void Clear(); + // removes all elements from the name; after this, GetSize() == 0. + const TCHAR* GetShortName() const; + // this will return the final string in the vector. It will assert that the name is not empty. + int GetSize() const; + // returns the number of path items (strings between delimiters) that are in the fco name. It is always equal + // to the number of delimiters in the path plus one. + enum Relationship { - REL_BELOW, // an fco is below another (/etc/passwd is below /etc) - REL_ABOVE, // an fco is above another (/etc is above /etc/passwd) - REL_EQUAL, // the fcos are equal (/etc/passwd is equal to /etc/passwd) - REL_UNRELATED // the fcos are unrelated (/var/spool/mail is unrelated to /var/log/pig.log) + REL_BELOW, // an fco is below another (/etc/passwd is below /etc) + REL_ABOVE, // an fco is above another (/etc is above /etc/passwd) + REL_EQUAL, // the fcos are equal (/etc/passwd is equal to /etc/passwd) + REL_UNRELATED // the fcos are unrelated (/var/spool/mail is unrelated to /var/log/pig.log) }; Relationship GetRelationship(const cFCOName& rhs) const; - // returns the relationship of _this_ name to the one passed in (ie -- if REL_BELOW is returned, - // this fco name is below the one passed in) + // returns the relationship of _this_ name to the one passed in (ie -- if REL_BELOW is returned, + // this fco name is below the one passed in) - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) ////////////////////////////////// // Debugging method ////////////////////////////////// static void ClearNameTable(); - // this method should _only_ be called when the program is exiting, and you are positively sure you - // will not be using or creating any more cFCONames. Violating this rule will result in unpredictable - // results. This clears out the cFCOName internal name table, making memory leaks easier to find. + // this method should _only_ be called when the program is exiting, and you are positively sure you + // will not be using or creating any more cFCONames. Violating this rule will result in unpredictable + // results. This clears out the cFCOName internal name table, making memory leaks easier to find. protected: friend class cFCOName_i; friend class cFCONameIter; void ParseString(const TCHAR* str); - // helper function that takes the pathname pointer to by str and fills out mpPathName + // helper function that takes the pathname pointer to by str and fills out mpPathName void CopyOnModify(); - // if the fconame is modified and mpPathName is shared by more than one object, this will - // release mpPathName and create a new one, so we don't change any other object's data + // if the fconame is modified and mpPathName is shared by more than one object, this will + // release mpPathName and create a new one, so we don't change any other object's data void SetNameInfo(iFCONameInfo* pNI); - // sets the delimiter and case sensitiveness to the name info's + // sets the delimiter and case sensitiveness to the name info's - cFCOName_i* mpPathName; - TCHAR mDelimiter; // the delimiting character in names (ie -- in file systems, it is '/') - bool mbCaseSensitive; // determines whether name compares are case sensitive of not + cFCOName_i* mpPathName; + TCHAR mDelimiter; // the delimiting character in names (ie -- in file systems, it is '/') + bool mbCaseSensitive; // determines whether name compares are case sensitive of not // this is what type of structure holds the elements of the name // typedef std::vector ListType; -#ifdef _DEBUG - TSTRING mDebugStrName; // so we can see this guy's value in the debug window -#endif +#ifdef DEBUG + TSTRING mDebugStrName; // so we can see this guy's value in the debug window +#endif }; //----------------------------------------------------------------------------- @@ -165,30 +165,31 @@ class cFCONameIter_i; class cFCONameIter { public: - cFCONameIter(const cFCOName& name); + explicit cFCONameIter(const cFCOName& name); ~cFCONameIter(); - int GetSize() const; // returns the number of entries in the fco name - void SeekBegin(); - void Next(); - void Prev(); - bool Done() const; + int GetSize() const; // returns the number of entries in the fco name + void SeekBegin(); + void Next(); + void Prev(); + bool Done() const; - int Index() const; - // return the current offset from the beginning of the short name list - void SeekTo( int index ); - // seeks to the given index. asserts that the index is appropriate for the - // current fco name. + int Index() const; + // return the current offset from the beginning of the short name list + void SeekTo(int index); + // seeks to the given index. asserts that the index is appropriate for the + // current fco name. + + const TCHAR* GetName() const; - const TCHAR* GetName() const; private: - void operator=(const cFCONameIter& rhs); // not impl - cFCONameIter(const cFCONameIter& rhs); // not impl + void operator=(const cFCONameIter& rhs); // not impl + cFCONameIter(const cFCONameIter& rhs); // not impl // the data... // - const cFCOName& mName; - cFCOName::ListType::const_iterator mIter; + const cFCOName& mName; + cFCOName::ListType::const_iterator mIter; }; //############################################################################# @@ -224,9 +225,8 @@ inline bool cFCOName::operator==(const cFCOName& rhs) const } inline bool cFCOName::operator!=(const cFCOName& rhs) const { - return (! IsEqual(rhs)); + return (!IsEqual(rhs)); } #endif //__FCONAME_H - diff --git a/src/fco/fconameinfo.h b/src/fco/fconameinfo.h index a277764..4a6e439 100644 --- a/src/fco/fconameinfo.h +++ b/src/fco/fconameinfo.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,11 +45,12 @@ class iFCONameInfo { public: - virtual bool IsCaseSensitive() const = 0; - virtual TCHAR GetDelimitingChar() const = 0; - virtual ~iFCONameInfo() {} + virtual bool IsCaseSensitive() const = 0; + virtual TCHAR GetDelimitingChar() const = 0; + virtual ~iFCONameInfo() + { + } }; #endif - diff --git a/src/fco/fconametbl.cpp b/src/fco/fconametbl.cpp index 26646d4..19f628a 100644 --- a/src/fco/fconametbl.cpp +++ b/src/fco/fconametbl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,33 +39,30 @@ //############################################################################# // cFCONameTblNode //############################################################################# -// uncomment this to allocate fconametblnodes from a pool. -//cObjectPoolBase cFCONameTblNode::msAllocator(sizeof(cFCONameTblNode), 1000); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -// grow heap for allocating strings +// grow heap for allocating strings // uncomment this stuff to use the grow heap... // #include "core/growheap.h" // TODO:BAM -- maybe make a PAGE_SIZE in platform.h -enum -{ - FCONAME_HEAP_INITIAL_SIZE = 0x1000, // 4k - FCONAME_HEAP_GROW_BY = 0x1000 +enum +{ + FCONAME_HEAP_INITIAL_SIZE = 0x1000, // 4k + FCONAME_HEAP_GROW_BY = 0x1000 }; -static cGrowHeap gFCONameHeap( FCONAME_HEAP_INITIAL_SIZE, FCONAME_HEAP_GROW_BY, _T("FCO Name") ); +static cGrowHeap gFCONameHeap(FCONAME_HEAP_INITIAL_SIZE, FCONAME_HEAP_GROW_BY, _T("FCO Name")); inline void* util_AllocMem(int size) { - return gFCONameHeap.Malloc( size ); + return gFCONameHeap.Malloc(size); } inline void util_FreeMem(void* pData) { - } // @@ -89,11 +86,11 @@ inline void util_FreeMem(void* pData) void cFCONameTblNode::SetLowercaseNode(cFCONameTblNode* pNewNode) { - ASSERT(pNewNode != 0); // doesn't make sense to set this to NULL + ASSERT(pNewNode != 0); // doesn't make sense to set this to NULL - if(mpLowerNode) + if (mpLowerNode) mpLowerNode->Release(); - if(pNewNode == this) + if (pNewNode == this) { // we can't store a pointer to ourselves, since reference counting doesn't go well // with circular pointers, so we will represent this with a NULL pointer @@ -106,32 +103,31 @@ void cFCONameTblNode::SetLowercaseNode(cFCONameTblNode* pNewNode) void cFCONameTblNode::SetString(const TSTRING& newStr) { - if( mpString != NULL ) + if (mpString != NULL) { delete [] mpString; mpString = NULL; } - - mpString = (TCHAR*)util_AllocMem( sizeof(TCHAR)*(newStr.length()+1) ); - _tcscpy( mpString, newStr.c_str() ); + + size_t alloc_size = sizeof(TCHAR) * (newStr.length() + 1); + mpString = (TCHAR*)util_AllocMem(alloc_size); + strncpy(mpString, newStr.c_str(), alloc_size); // NOTE -- the lower case pointer is now invalid. } -cFCONameTblNode::cFCONameTblNode(const TSTRING& name, const cFCONameTblNode* node) : - mpString(NULL), - mpLowerNode(node) +cFCONameTblNode::cFCONameTblNode(const TSTRING& name, const cFCONameTblNode* node) : mpString(NULL), mpLowerNode(node) { - SetString( name ); + SetString(name); } cFCONameTblNode::~cFCONameTblNode() { - if(mpLowerNode) + if (mpLowerNode) mpLowerNode->Release(); - if(mpString != NULL) + if (mpString != NULL) { - util_FreeMem( mpString ); + util_FreeMem(mpString); mpString = NULL; } } @@ -150,14 +146,13 @@ void cFCONameTblNode::Delete() const /////////////////////////////////////////////////////////////////////////////// // ctor, dtor /////////////////////////////////////////////////////////////////////////////// -cFCONameTbl::cFCONameTbl(int defSize) : - mTable(defSize) +cFCONameTbl::cFCONameTbl(int defSize) : mTable(defSize) { } cFCONameTbl::~cFCONameTbl() { -#ifdef _DEBUG +#ifdef DEBUG cDebug d("cFCONameTbl::~cFCONameTbl()"); d.TraceDebug("Tracing cFCONameTblNode hash table statistics:\n"); mTable.TraceDiagnostics(); @@ -171,34 +166,34 @@ cFCONameTbl::~cFCONameTbl() cFCONameTblNode* cFCONameTbl::CreateNode(const TSTRING& nodeName) { - cFCONameTblNode* pNode, *pLowerNode; - if(mTable.Lookup(nodeName.c_str(), pNode)) + cFCONameTblNode *pNode, *pLowerNode; + if (mTable.Lookup(nodeName.c_str(), pNode)) { // this already exists in the table; just return the existing node pNode->AddRef(); return pNode; } - pNode = new(util_AllocMem(sizeof(cFCONameTblNode))) cFCONameTblNode(nodeName, NULL); + pNode = new (util_AllocMem(sizeof(cFCONameTblNode))) cFCONameTblNode(nodeName, NULL); mTable.Insert(pNode->GetString(), pNode); // fill out the lower-case info - TSTRING lowStr = pNode->GetString(); + TSTRING lowStr = pNode->GetString(); TSTRING::iterator i; // TODO:BAM -- does this have any meaning in mb? - for(i = lowStr.begin(); i != lowStr.end(); ++i) + for (i = lowStr.begin(); i != lowStr.end(); ++i) { - *i = _totlower(*i); + *i = tolower(*i); } // see if this exists in the table (it could potentially look up itself!) - if(mTable.Lookup(lowStr.c_str(), pLowerNode)) + if (mTable.Lookup(lowStr.c_str(), pLowerNode)) { pNode->SetLowercaseNode(pLowerNode); } else { // we know that the original string is not lower case if we got to this point - pLowerNode = new(util_AllocMem(sizeof(cFCONameTblNode))) cFCONameTblNode(lowStr, NULL); + pLowerNode = new (util_AllocMem(sizeof(cFCONameTblNode))) cFCONameTblNode(lowStr, NULL); pLowerNode->SetLowercaseNode(pLowerNode); pNode->SetLowercaseNode(pLowerNode); mTable.Insert(pLowerNode->GetString(), pLowerNode); @@ -214,13 +209,12 @@ cFCONameTblNode* cFCONameTbl::CreateNode(const TSTRING& nodeName) void cFCONameTbl::Clear() { cHashTableIter iter(mTable); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - cFCONameTblNode* p = iter.Val(); - if (p) - p->Release(); + cFCONameTblNode* p = iter.Val(); + if (p) + p->Release(); } mTable.Clear(); } - diff --git a/src/fco/fconametbl.h b/src/fco/fconametbl.h index 9e7d71a..1be76e0 100644 --- a/src/fco/fconametbl.h +++ b/src/fco/fconametbl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,19 +46,10 @@ #include "core/hashtable.h" #endif -// uncomment this to allocate fconametblnodes from a pool. -/* -#ifndef __OBJECTPOOL_H -#include "objectpool.h" -#endif -*/ -// end TODO - - class cFCONameTbl_i; /////////////////////////////////////////////////////////////////////////////// -// cFCONameTblNode -- a node in the cFCONameTbl, this class has the following +// cFCONameTblNode -- a node in the cFCONameTbl, this class has the following // properties: // (1) it is reference counted, so ambiguity over who owns it doesn't exist // (2) it keeps track of a case-sensitive character string @@ -69,23 +60,24 @@ class cFCONameTbl_i; /////////////////////////////////////////////////////////////////////////////// class cFCONameTblNode : public cRefCountObj { -friend class cFCONameTbl; + friend class cFCONameTbl; + public: - bool operator== (const cFCONameTblNode& rhs) const; - bool operator!= (const cFCONameTblNode& rhs) const; - // for efficency, op== is defined as (this == &rhs) - - const cFCONameTblNode* GetLowercaseNode() const; - void SetLowercaseNode(cFCONameTblNode* pNewNode); - // gets and sets the lowercase node pointer. Might point to itself if the string - // this node contains is totally lower case. - - TCHAR* GetString() const; - // gets the string associated with this node - void SetString(const TSTRING& newStr); - // sets the string associated with this node - // TODO -- this is a very dangerous operation to do; do we ever want the client - // to be able to do this (that is, should this method exist)? + bool operator==(const cFCONameTblNode& rhs) const; + bool operator!=(const cFCONameTblNode& rhs) const; + // for efficency, op== is defined as (this == &rhs) + + const cFCONameTblNode* GetLowercaseNode() const; + void SetLowercaseNode(cFCONameTblNode* pNewNode); + // gets and sets the lowercase node pointer. Might point to itself if the string + // this node contains is totally lower case. + + TCHAR* GetString() const; + // gets the string associated with this node + void SetString(const TSTRING& newStr); + // sets the string associated with this node + // TODO -- this is a very dangerous operation to do; do we ever want the client + // to be able to do this (that is, should this method exist)? // uncomment to allocate these from a pool // static cObjectPoolBase msAllocator; @@ -98,14 +90,14 @@ friend class cFCONameTbl; cFCONameTblNode(const TSTRING& name, const cFCONameTblNode* node); ~cFCONameTblNode(); virtual void Delete() const; - // overridden from cRefCountObj; this is done so that if we are alloced - // from a memory pool, we can be deleted appropriately. + // overridden from cRefCountObj; this is done so that if we are alloced + // from a memory pool, we can be deleted appropriately. private: cFCONameTblNode(const cFCONameTblNode& rhs); // not impl - cFCONameTblNode& operator= (const cFCONameTblNode& rhs);// not impl - - TCHAR* mpString; - const cFCONameTblNode* mpLowerNode; + cFCONameTblNode& operator=(const cFCONameTblNode& rhs); // not impl + + TCHAR* mpString; + const cFCONameTblNode* mpLowerNode; }; /////////////////////////////////////////////////////////////////////////////// @@ -113,24 +105,24 @@ friend class cFCONameTbl; // (1) serves as a factory for cFCONameTableNodes, returning objects that have // properly filled out mpLowerNode fields // (2) Keeps track of all nodes created; two successive calls to create "aBc" will -// return the same pointer; a call to create "abc" will return a pointer to the +// return the same pointer; a call to create "abc" will return a pointer to the // Node("aBc")->GetLowercaseNode() /////////////////////////////////////////////////////////////////////////////// class cFCONameTbl { public: - cFCONameTbl(int defSize = HASH_VERY_LARGE); - // defSize is the initial hash table size + explicit cFCONameTbl(int defSize = HASH_VERY_LARGE); + // defSize is the initial hash table size ~cFCONameTbl(); cFCONameTblNode* CreateNode(const TSTRING& nodeName); - // if the named node already exists in the table, it returns a pointer to the - // existing node; otherwise, it creates the node and its lower case representation, - // (if the lowercase node doesn't already exist),adds them to the table - // and returns a pointer to them. The returned object has been AddRef()ed + // if the named node already exists in the table, it returns a pointer to the + // existing node; otherwise, it creates the node and its lower case representation, + // (if the lowercase node doesn't already exist),adds them to the table + // and returns a pointer to them. The returned object has been AddRef()ed void Clear(); - // clears out all the entries in the table + // clears out all the entries in the table /////////////////////////////////////////////////////////////////////////////// // cCharCmp -- class used with the hash table that does a string compare @@ -140,15 +132,16 @@ class cFCONameTbl public: bool operator()(const TCHAR* lhs, const TCHAR* rhs) { - return (_tcscmp(lhs,rhs) == 0); + return (_tcscmp(lhs, rhs) == 0); } }; + private: // TODO -- it is not evident what type the KEY_TYPE should be for the hash tbl; if it is // a string, we will be storing two copies of all the strings! If it is a const TCHAR*, then // the equality operator won't work (maybe we should template the hash table with the operators // needed for the hash as well) - cHashTable mTable; + cHashTable mTable; }; //############################################################################# @@ -158,18 +151,18 @@ class cFCONameTbl //////////////////////// // cFCONameTblNode //////////////////////// -inline bool cFCONameTblNode::operator== (const cFCONameTblNode& rhs) const +inline bool cFCONameTblNode::operator==(const cFCONameTblNode& rhs) const { return (this == &rhs); } -inline bool cFCONameTblNode::operator!= (const cFCONameTblNode& rhs) const +inline bool cFCONameTblNode::operator!=(const cFCONameTblNode& rhs) const { return (this != &rhs); } -inline const cFCONameTblNode* cFCONameTblNode::GetLowercaseNode() const +inline const cFCONameTblNode* cFCONameTblNode::GetLowercaseNode() const { // if mpLowerNode == NULL, then we assume that we are the lowercase node. - if(! mpLowerNode) + if (!mpLowerNode) return this; return mpLowerNode; } @@ -181,4 +174,3 @@ inline TCHAR* cFCONameTblNode::GetString() const #endif - diff --git a/src/fco/fconametranslator.h b/src/fco/fconametranslator.h index 0c6e0f1..9c89cb0 100644 --- a/src/fco/fconametranslator.h +++ b/src/fco/fconametranslator.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -59,32 +59,33 @@ class iFCONameTranslator public: // // basic functionality - // - virtual TSTRING ToStringRaw( const cFCOName& name ) const = 0; - // provides a "raw" representation of the fco name as a string. This uses only the - // information contained in the cFCOName to construct the string (ie -- no genre specific - // info) + // + virtual TSTRING ToStringRaw(const cFCOName& name) const = 0; + // provides a "raw" representation of the fco name as a string. This uses only the + // information contained in the cFCOName to construct the string (ie -- no genre specific + // info) + + virtual TSTRING ToStringAPI(const cFCOName& name) const = 0; + // returns a string representation of the name that can be passed to system API calls. Note + // that this is not possible to do in all genres ( for example, the NT registry ) - virtual TSTRING ToStringAPI( const cFCOName& name ) const = 0; - // returns a string representation of the name that can be passed to system API calls. Note - // that this is not possible to do in all genres ( for example, the NT registry ) + virtual TSTRING ToStringDisplay(const cFCOName& name, bool bUnique = false) const = 0; + // this function converts an fconame into a string suitable for printing to user. + // Every character in the string will be able to be converted to a multi-byte character + // + // If unique is set, the string will also have the following attributes: + // The returned string will have leading and trailing quotes. + // The string returned must be able to be unambiguously translatable back into an FCO name + // equal to the one that created the string. To use mathematical language, the function that + // maps cFCONames to TSTRINGS must be "one to one" and "onto". - virtual TSTRING ToStringDisplay( const cFCOName& name, bool bUnique = false ) const = 0; - // this function converts an fconame into a string suitable for printing to user. - // Every character in the string will be able to be converted to a multi-byte character - // - // If unique is set, the string will also have the following attributes: - // The returned string will have leading and trailing quotes. - // The string returned must be able to be unambiguously translatable back into an FCO name - // equal to the one that created the string. To use mathematical language, the function that - // maps cFCONames to TSTRINGS must be "one to one" and "onto". + virtual bool DisplayStringToFCOName(const TSTRING& str, cFCOName& name) const = 0; + // this function converts strings from FCONameToDisplayString back into an fconame + // returns false if can't convert. - virtual bool DisplayStringToFCOName( const TSTRING& str, cFCOName& name ) const = 0; - // this function converts strings from FCONameToDisplayString back into an fconame - // returns false if can't convert. - - virtual ~iFCONameTranslator() {} + virtual ~iFCONameTranslator() + { + } }; #endif //__FCONAMETRANSLATOR_H - diff --git a/src/fco/fcoprop.h b/src/fco/fcoprop.h index df74f7d..d3519d8 100644 --- a/src/fco/fcoprop.h +++ b/src/fco/fcoprop.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,31 +51,32 @@ class iFCOProp : public iTypedSerializable public: enum Op { - OP_EQ = 1, // == - OP_NE = 2, // != - OP_GT = 4, // > - OP_LT = 8, // < - OP_GE = 16, // >= - OP_LE = 32 // <= + OP_EQ = 1, // == + OP_NE = 2, // != + OP_GT = 4, // > + OP_LT = 8, // < + OP_GE = 16, // >= + OP_LE = 32 // <= }; enum CmpResult { - CMP_TRUE = 1, - CMP_FALSE = 2, + CMP_TRUE = 1, + CMP_FALSE = 2, CMP_WRONG_PROP_TYPE = 3, - CMP_UNSUPPORTED = 4 + CMP_UNSUPPORTED = 4 }; - + virtual TSTRING AsString() const = 0; - // returns a string representation of the property + // returns a string representation of the property virtual CmpResult Compare(const iFCOProp* rhs, Op op) const = 0; - virtual void Copy(const iFCOProp* rhs) = 0; - // change my value so that it is the same as the passed in property. - // this will assert() that the two properties are of the same type. + virtual void Copy(const iFCOProp* rhs) = 0; + // change my value so that it is the same as the passed in property. + // this will assert() that the two properties are of the same type. protected: - virtual ~iFCOProp() {} + virtual ~iFCOProp() + { + } }; #endif //__FCOPROP_H - diff --git a/src/fco/fcopropcalc.h b/src/fco/fcopropcalc.h index b74cb4a..c820c93 100644 --- a/src/fco/fcopropcalc.h +++ b/src/fco/fcopropcalc.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,7 @@ class iFCOVisitor; class iFCOSet; class cErrorBucket; - // cErrorBucket error numbers... +// cErrorBucket error numbers... /* // the prop calculator owns all error numbers from 200-299 enum ErrorNum { @@ -55,45 +55,47 @@ class cErrorBucket; class iFCOPropCalc { public: - virtual void SetPropVector(const cFCOPropVector& pv) = 0; - virtual const cFCOPropVector& GetPropVector() const = 0; - // gets and sets the property vector that indicates what properties the - // calculator will evaluate for each fco that it visits + virtual void SetPropVector(const cFCOPropVector& pv) = 0; + virtual const cFCOPropVector& GetPropVector() const = 0; + // gets and sets the property vector that indicates what properties the + // calculator will evaluate for each fco that it visits - virtual iFCOVisitor* GetVisitor() = 0; - virtual const iFCOVisitor* GetVisitor() const = 0; - // returns 'this' if the class that implements this interface also implements - // iFCOVisitor, which will almost always be the case. Otherwise, these methods - // should return NULL + virtual iFCOVisitor* GetVisitor() = 0; + virtual const iFCOVisitor* GetVisitor() const = 0; + // returns 'this' if the class that implements this interface also implements + // iFCOVisitor, which will almost always be the case. Otherwise, these methods + // should return NULL - virtual void SetErrorBucket(cErrorBucket* pBucket) = 0; - virtual const cErrorBucket* GetErrorBucket() const = 0; + virtual void SetErrorBucket(cErrorBucket* pBucket) = 0; + virtual const cErrorBucket* GetErrorBucket() const = 0; // this enum lists all the ways that the prop calc can behave when calculating a property // that already has a valid value in an fco. The default behavior is PROP_LEAVE - enum CollisionAction + enum CollisionAction { - PROP_OVERWRITE, // overwite the existing value with a newly calculated one - PROP_LEAVE, // leave the existing property value (default) + PROP_OVERWRITE, // overwite the existing value with a newly calculated one + PROP_LEAVE, // leave the existing property value (default) PROP_NUMITEMS }; - virtual CollisionAction GetCollisionAction() const = 0; + virtual CollisionAction GetCollisionAction() const = 0; virtual void SetCollisionAction(CollisionAction a) = 0; - // these methods get and set the collision action for the property calculator + // these methods get and set the collision action for the property calculator + - enum CalcFlags { - DO_NOT_MODIFY_PROPERTIES = 0x00000001 // reset any properties that may have been altered due to measurement + DO_NOT_MODIFY_PROPERTIES = 0x00000001, // reset any properties that may have been altered due to measurement + DIRECT_IO = 0x00000002 // use direct i/o when scanning files }; - virtual int GetCalcFlags() const = 0; - virtual void SetCalcFlags(int i) = 0; - // any calculation flags needed for calculation. - virtual ~iFCOPropCalc() {} + virtual int GetCalcFlags() const = 0; + virtual void SetCalcFlags(int i) = 0; + // any calculation flags needed for calculation. + virtual ~iFCOPropCalc() + { + } }; -#endif //__FCOPROPCALC_H - +#endif //__FCOPROPCALC_H diff --git a/src/fco/fcopropdisplayer.h b/src/fco/fcopropdisplayer.h index 496429b..e3d33c5 100644 --- a/src/fco/fcopropdisplayer.h +++ b/src/fco/fcopropdisplayer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,10 +52,10 @@ class cFCOName; ////////////////////// // // In most cases, iFCOProp::AsString() is simply a 'dump' of the prop's -// internals. In order to display this property in a meaningful way to the -// user, it was decided that an auxillary class was needed to perform any +// internals. In order to display this property in a meaningful way to the +// user, it was decided that an auxillary class was needed to perform any // formatting needed for displaying a property. -// +// // The premise here is that it is a good idea to separate the data in the // database from its text representation. The text representation of an FCO // property may require information in addition to the property itself. For @@ -64,33 +64,33 @@ class cFCOName; // stored as an int ) must be sent through ctime() or a similar // number-to-string function, in order to be meaningful to the user. // -// This class's job is to encapsulate the knowledge of how to turn the database -// representation of an FCO property into a text representation. The -// information needed may static, and known at compile time ( which can be as -// simple as knowing which system call to call for a certain property, such as -// ctime() for a time value ), or dynamically acquired information ( such as +// This class's job is to encapsulate the knowledge of how to turn the database +// representation of an FCO property into a text representation. The +// information needed may static, and known at compile time ( which can be as +// simple as knowing which system call to call for a certain property, such as +// ctime() for a time value ), or dynamically acquired information ( such as // uid, which requires uid-to-username mapping information from the system ). // ////////////////////////////// // Major Functionality: ////////////////////////////// // -// The main interface of this class is the PropAsString function, which -// returns a formatted string representing the property. +// The main interface of this class is the PropAsString function, which +// returns a formatted string representing the property. // -// Dynamic information is collected throught the InitForFCO or InitForProp, -// InitForProp simply being a subfunction of InitForFCO. +// Dynamic information is collected throught the InitForFCO or InitForProp, +// InitForProp simply being a subfunction of InitForFCO. // -// This class also contains functionality to display an FCO and a few +// This class also contains functionality to display an FCO and a few // pre-defined properites. This function, GetDetails(), was designed to mimic -// a Unix 'ls -l listing' of the properties of the FCO. GetDetailsHeader() +// a Unix 'ls -l listing' of the properties of the FCO. GetDetailsHeader() // prints out the header for the listing. // ////////////////////////////// // Minor Functionality: ////////////////////////////// // -// See implementation comments. +// See implementation comments. // ////////////////////////////// // Relationships @@ -100,17 +100,17 @@ class cFCOName; // Typical Usage: ////////////////////////////// // -// (1) At some time after the construction of an FCO, some component of +// (1) At some time after the construction of an FCO, some component of // tripwire will call InitForFCO() with the propdisplayer (PD) -// appropriate for the genre of the FCO. This retrieves and stores +// appropriate for the genre of the FCO. This retrieves and stores // any information needed for displaying the FCO. // (2) Later, when a property of the FCO needs to be displayed, -// the client will call PropAsString(). For any property that the +// the client will call PropAsString(). For any property that the // PD does not know how to convert, the PD will simply return the // result of the prop's AsString() function. So it is safe to call // PropAsString() for all properties, even those it does not know // how to display. -// (3) Merge() is used to consolidate PD information into one PD. So +// (3) Merge() is used to consolidate PD information into one PD. So // when performing a database update, the DB's PD will have to be // merged with the report's PD. // @@ -118,59 +118,58 @@ class cFCOName; class iFCOPropDisplayer : public iTypedSerializable { public: - virtual ~iFCOPropDisplayer() {}; + virtual ~iFCOPropDisplayer(){}; virtual iFCOPropDisplayer* Clone() const = 0; - virtual void Merge( const iFCOPropDisplayer* const ppd ) = 0; - // adds all prop display info from rhs to this. it is an error to merge two prop diplayers of different derived types + virtual void Merge(const iFCOPropDisplayer* const ppd) = 0; + // adds all prop display info from rhs to this. it is an error to merge two prop diplayers of different derived types virtual const cFCOPropVector& GetPropsConverted() const = 0; - // returns vector where if a given prop in the vector is valid, then this class - // can do a PropAsString that's different from the prop's own AsString() - - virtual TSTRING PropAsString( const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0) const = 0; - virtual TSTRING PropAsString( const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0) = 0; - // returns a more readable value than iFCOProp::AsString() (which simply returns a text version - // of the prop's value), (e.g. instead of calling fsprop(ATIME)::AsString() and getting 4578295721, - // you can call PropAsString to get "Sun Sep 26 1998" or the like.) If the displayer doesn't - // know how to display the property, simply returns iFCOProp::AsString() - // The non-const version will attempt to initialize the property if Lazy is set to true. - - // iOffset and iWidth should be used for multi-line properties; they only have meaning for lines - // after the first, so most single-line properties should ignore them. - // iOffset is the offset from ^ which each new line should start. - // iWidth is the space that the new line has ( uses setw( iWidth ) ). - - // the TSTRING returned should be convertable to a narrow string (that is, if there's any way that - // the prop could have funky wide chars, the string is put through cDisplayEncoder ) - - virtual bool IsMultiLineProp( int propID ) const = 0; - // returns true if PropAsString can return a string with \n's. - - virtual TSTRING& GetDetails( const iFCO* const pfco, TSTRING& strBuf ) const = 0; - // Returns a string with some of the FCO's genre specific properties. So, the - // output will look somewhat like the UNIX "ls -l" command except that the FCO name - // is not output - - virtual TSTRING& GetDetailsHeader( TSTRING& strBuf, int iMargin ) const = 0; - // describes output of GetDetails and is formatted just like it. To be used as a header. - // since the header is a two-lined output, it needs a margin for the second line - - virtual void InitForProp( const iFCO* const pFCO, const int propIdx ) = 0; - // InitForProp() is called to initialize the class's data structures to convert the passed - // property only. This can be used if there is only a small subset of the total system - // information that will actually be used, saving on memory and disk usage. - - virtual void InitForFCO( const iFCO* const ifco ) = 0; - // calls InitForProp on all valid props in ifco - - virtual void SetLazy( const bool bLazy = true ) = 0; - virtual bool GetLazy() const = 0; - // Get/SetLazy() is used for the lazy evaluation of the class's conversion data; if SetLazy(true) is called, - // then all PropAsString() calls will have an implicit InitForProp()call, if it is needed, before the conversion. + // returns vector where if a given prop in the vector is valid, then this class + // can do a PropAsString that's different from the prop's own AsString() + + virtual TSTRING PropAsString(const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0) const = 0; + virtual TSTRING PropAsString(const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0) = 0; + // returns a more readable value than iFCOProp::AsString() (which simply returns a text version + // of the prop's value), (e.g. instead of calling fsprop(ATIME)::AsString() and getting 4578295721, + // you can call PropAsString to get "Sun Sep 26 1998" or the like.) If the displayer doesn't + // know how to display the property, simply returns iFCOProp::AsString() + // The non-const version will attempt to initialize the property if Lazy is set to true. + + // iOffset and iWidth should be used for multi-line properties; they only have meaning for lines + // after the first, so most single-line properties should ignore them. + // iOffset is the offset from ^ which each new line should start. + // iWidth is the space that the new line has ( uses setw( iWidth ) ). + + // the TSTRING returned should be convertable to a narrow string (that is, if there's any way that + // the prop could have funky wide chars, the string is put through cDisplayEncoder ) + + virtual bool IsMultiLineProp(int propID) const = 0; + // returns true if PropAsString can return a string with \n's. + + virtual TSTRING& GetDetails(const iFCO* const pfco, TSTRING& strBuf) const = 0; + // Returns a string with some of the FCO's genre specific properties. So, the + // output will look somewhat like the UNIX "ls -l" command except that the FCO name + // is not output + + virtual TSTRING& GetDetailsHeader(TSTRING& strBuf, int iMargin) const = 0; + // describes output of GetDetails and is formatted just like it. To be used as a header. + // since the header is a two-lined output, it needs a margin for the second line + + virtual void InitForProp(const iFCO* const pFCO, const int propIdx) = 0; + // InitForProp() is called to initialize the class's data structures to convert the passed + // property only. This can be used if there is only a small subset of the total system + // information that will actually be used, saving on memory and disk usage. + + virtual void InitForFCO(const iFCO* const ifco) = 0; + // calls InitForProp on all valid props in ifco + + virtual void SetLazy(const bool bLazy = true) = 0; + virtual bool GetLazy() const = 0; + // Get/SetLazy() is used for the lazy evaluation of the class's conversion data; if SetLazy(true) is called, + // then all PropAsString() calls will have an implicit InitForProp()call, if it is needed, before the conversion. }; #endif //__FCOPROPDISPLAYER_H - diff --git a/src/fco/fcopropimpl.cpp b/src/fco/fcopropimpl.cpp index 157d071..42022ef 100644 --- a/src/fco/fcopropimpl.cpp +++ b/src/fco/fcopropimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,13 +52,12 @@ iFCOProp::CmpResult DefaultCompare(const TYPE* lhs, const iFCOProp* rhs, iFCOPro // compares with undefined props are not equal if (rhs->GetType() == cFCOUndefinedProp::GetInstance()->GetType()) { - return (op == iFCOProp::OP_EQ) ? iFCOProp::CMP_FALSE : - (op == iFCOProp::OP_NE) ? iFCOProp::CMP_TRUE : - iFCOProp::CMP_WRONG_PROP_TYPE; + return (op == iFCOProp::OP_EQ) ? iFCOProp::CMP_FALSE : + (op == iFCOProp::OP_NE) ? iFCOProp::CMP_TRUE : iFCOProp::CMP_WRONG_PROP_TYPE; } // first, make sure we are the right type... - if(rhs->GetType() != lhs->GetType()) + if (rhs->GetType() != lhs->GetType()) { return iFCOProp::CMP_WRONG_PROP_TYPE; } @@ -69,7 +68,7 @@ iFCOProp::CmpResult DefaultCompare(const TYPE* lhs, const iFCOProp* rhs, iFCOPro // finally, do the comparison... bool bResult; - switch(op) + switch (op) { case iFCOProp::OP_EQ: bResult = (lhs->GetValue() == newRhs->GetValue()); @@ -95,15 +94,15 @@ iFCOProp::CmpResult DefaultCompare(const TYPE* lhs, const iFCOProp* rhs, iFCOPro throw INTERNAL_ERROR("fcopropimpl.cpp"); } - return bResult? iFCOProp::CMP_TRUE : iFCOProp::CMP_FALSE; + return bResult ? iFCOProp::CMP_TRUE : iFCOProp::CMP_FALSE; } -template +template /*static*/ void DefaultCopy(TYPE* lhs, const iFCOProp* rhs) { // first, make sure we are the right type... - if(rhs->GetType() != lhs->GetType()) + if (rhs->GetType() != lhs->GetType()) { ASSERT(false); return; @@ -126,12 +125,12 @@ TSTRING cFCOPropInt32::AsString() const //TODO:mdb -- implement this through twlocale! // TOSTRINGSTREAM ostr; - ostr.imbue( std::locale::classic() ); - ostr << mValue ; + ostr.imbue(std::locale::classic()); + ostr << mValue; return TSTRING(ostr.str()); } -iFCOProp::CmpResult cFCOPropInt32::Compare(const iFCOProp* rhs, iFCOProp::Op op) const +iFCOProp::CmpResult cFCOPropInt32::Compare(const iFCOProp* rhs, iFCOProp::Op op) const { return DefaultCompare(this, rhs, op); } @@ -155,7 +154,6 @@ void cFCOPropInt32::Copy(const iFCOProp* rhs) } - //##################################### // cFCOPropInt64 //##################################### @@ -167,12 +165,12 @@ TSTRING cFCOPropInt64::AsString() const //TODO:mdb -- implement this through twlocale! // TOSTRINGSTREAM ostr; - ostr.imbue( std::locale::classic() ); + ostr.imbue(std::locale::classic()); ostr << (int32)mValue; return TSTRING(ostr.str()); } -iFCOProp::CmpResult cFCOPropInt64::Compare(const iFCOProp* rhs, iFCOProp::Op op) const +iFCOProp::CmpResult cFCOPropInt64::Compare(const iFCOProp* rhs, iFCOProp::Op op) const { return DefaultCompare(this, rhs, op); } @@ -207,12 +205,12 @@ TSTRING cFCOPropUint64::AsString() const //TODO:mdb -- implement this through twlocale! // TOSTRINGSTREAM ostr; - ostr.imbue( std::locale::classic() ); - ostr << (int32)mValue ; + ostr.imbue(std::locale::classic()); + ostr << (int32)mValue; return TSTRING(ostr.str()); } -iFCOProp::CmpResult cFCOPropUint64::Compare(const iFCOProp* rhs, iFCOProp::Op op) const +iFCOProp::CmpResult cFCOPropUint64::Compare(const iFCOProp* rhs, iFCOProp::Op op) const { return DefaultCompare(this, rhs, op); } @@ -247,7 +245,7 @@ TSTRING cFCOPropTSTRING::AsString() const return mValue; } -iFCOProp::CmpResult cFCOPropTSTRING::Compare(const iFCOProp* rhs, iFCOProp::Op op) const +iFCOProp::CmpResult cFCOPropTSTRING::Compare(const iFCOProp* rhs, iFCOProp::Op op) const { return DefaultCompare(this, rhs, op); } @@ -257,12 +255,12 @@ void cFCOPropTSTRING::Read(iSerializer* pSerializer, int32 version) if (version > 0) ThrowAndAssert(eSerializerVersionMismatch(_T("String Property Read"))); - pSerializer->ReadString( mValue ); + pSerializer->ReadString(mValue); } void cFCOPropTSTRING::Write(iSerializer* pSerializer) const { - pSerializer->WriteString( mValue ); + pSerializer->WriteString(mValue); } void cFCOPropTSTRING::Copy(const iFCOProp* rhs) @@ -275,13 +273,11 @@ void cFCOPropTSTRING::Copy(const iFCOProp* rhs) //############################################################################# iFCOProp::CmpResult cFCOPropGrowingFile::Compare(const iFCOProp* rhs, Op op) const { - // here is how the hack works: we want OP_EQ to return true if the file has grown (if rhs's - // size is bigger than or equal to mine) Therefore, equality is defined as my size being + // here is how the hack works: we want OP_EQ to return true if the file has grown (if rhs's + // size is bigger than or equal to mine) Therefore, equality is defined as my size being // smaller than or equal to the rhs's size - if(op == OP_EQ) + if (op == OP_EQ) return cFCOPropInt64::Compare(rhs, OP_LE); else return cFCOPropInt64::Compare(rhs, op); } - - diff --git a/src/fco/fcopropimpl.h b/src/fco/fcopropimpl.h index 87cdfa9..6044663 100644 --- a/src/fco/fcopropimpl.h +++ b/src/fco/fcopropimpl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,90 +46,113 @@ ///////////////////////////////////////////////////////////////// // Another in my collection of macros, this just saves // some redundant typing on my part. -#define PROP_DATA(TYPE)\ - private:\ - TYPE mValue;\ - public:\ - typedef TYPE ValueType;\ - TYPE GetValue() const { return mValue; }\ - void SetValue(const TYPE& v) { mValue = v; } +#define PROP_DATA(TYPE) \ +private: \ + TYPE mValue; \ + \ +public: \ + typedef TYPE ValueType; \ + TYPE GetValue() const \ + { \ + return mValue; \ + } \ + void SetValue(const TYPE& v) \ + { \ + mValue = v; \ + } //////////////////////////////////////////////////////////////// class cFCOPropInt32 : public iFCOProp { public: - PROP_DATA(int32) // see macro above - DECLARE_TYPEDSERIALIZABLE() // type information + PROP_DATA(int32) // see macro above + DECLARE_TYPEDSERIALIZABLE() // type information + + cFCOPropInt32() : mValue(0) + { + } + virtual ~cFCOPropInt32() + { + } - cFCOPropInt32() : mValue(0) {} - virtual ~cFCOPropInt32() {} - // from iFCOProp - virtual TSTRING AsString() const; + virtual TSTRING AsString() const; virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; - virtual void Copy(const iFCOProp* rhs); - + virtual void Copy(const iFCOProp* rhs); + // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) }; class cFCOPropInt64 : public iFCOProp { public: - PROP_DATA(int64) // see macro above - DECLARE_TYPEDSERIALIZABLE() // type information + PROP_DATA(int64) // see macro above + DECLARE_TYPEDSERIALIZABLE() // type information + + cFCOPropInt64() : mValue(0) + { + } + virtual ~cFCOPropInt64() + { + } - cFCOPropInt64() : mValue(0) {} - virtual ~cFCOPropInt64() {} - // from iFCOProp - virtual TSTRING AsString() const; + virtual TSTRING AsString() const; virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; - virtual void Copy(const iFCOProp* rhs); - + virtual void Copy(const iFCOProp* rhs); + // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) }; class cFCOPropUint64 : public iFCOProp { public: - PROP_DATA(uint64) // see macro above - DECLARE_TYPEDSERIALIZABLE() // type information + PROP_DATA(uint64) // see macro above + DECLARE_TYPEDSERIALIZABLE() // type information + + cFCOPropUint64() : mValue(0) + { + } + virtual ~cFCOPropUint64() + { + } - cFCOPropUint64() : mValue(0) {} - virtual ~cFCOPropUint64() {} - // from iFCOProp - virtual TSTRING AsString() const; + virtual TSTRING AsString() const; virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; - virtual void Copy(const iFCOProp* rhs); + virtual void Copy(const iFCOProp* rhs); // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) }; class cFCOPropTSTRING : public iFCOProp { public: - PROP_DATA(TSTRING) // see macro above - DECLARE_TYPEDSERIALIZABLE() // type information + PROP_DATA(TSTRING) // see macro above + DECLARE_TYPEDSERIALIZABLE() // type information + + cFCOPropTSTRING() : mValue(_T("")) + { + } + virtual ~cFCOPropTSTRING() + { + } - cFCOPropTSTRING() : mValue(_T("")) {} - virtual ~cFCOPropTSTRING() {} - // from iFCOProp - virtual TSTRING AsString() const; + virtual TSTRING AsString() const; virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; - virtual void Copy(const iFCOProp* rhs); + virtual void Copy(const iFCOProp* rhs); // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) }; /////////////////////////////////////////////////////////////////////////////// @@ -145,4 +168,3 @@ class cFCOPropGrowingFile : public cFCOPropInt64 }; #endif //__FCOPROPIMPL_H - diff --git a/src/fco/fcopropset.h b/src/fco/fcopropset.h index 8932045..cdfce69 100644 --- a/src/fco/fcopropset.h +++ b/src/fco/fcopropset.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,43 +51,47 @@ class iFCOProp; class iFCOPropSet : public iTypedSerializable { public: - enum { PROP_NOT_FOUND = -1 }; + enum + { + PROP_NOT_FOUND = -1 + }; virtual const cFCOPropVector& GetValidVector() const = 0; - // returns a vector that indicates which properties have valid values associated with them. + // returns a vector that indicates which properties have valid values associated with them. virtual int GetNumProps() const = 0; - // returns the number of properties this set has + // returns the number of properties this set has virtual int GetPropIndex(const TCHAR* name) const = 0; - // maps a property name to an index number. If the property doesn't exist in the set, -1 is returned. - // the return value is guarenteed to be in the range -1 <= x < GetNumProps() + // maps a property name to an index number. If the property doesn't exist in the set, -1 is returned. + // the return value is guarenteed to be in the range -1 <= x < GetNumProps() virtual TSTRING GetPropName(int index) const = 0; - // returns the name associated with the property at the given index. Return result is - // undefined if index is not in the range 0 <= index < GetNumProps() + // returns the name associated with the property at the given index. Return result is + // undefined if index is not in the range 0 <= index < GetNumProps() - virtual const iFCOProp* GetPropAt(int index) const = 0; - virtual iFCOProp* GetPropAt(int index) = 0; - // returns a pointer to the property specified by index. Again, - // the return result is undefined if 0 <= index < GetNumProps() + virtual const iFCOProp* GetPropAt(int index) const = 0; + virtual iFCOProp* GetPropAt(int index) = 0; + // returns a pointer to the property specified by index. Again, + // the return result is undefined if 0 <= index < GetNumProps() - virtual void InvalidateProp (int index) = 0; + virtual void InvalidateProp(int index) = 0; virtual void InvalidateProps(const cFCOPropVector& propsToInvalidate) = 0; - virtual void InvalidateAll () = 0; - // invalidates one, some, or all of the properties in this set + virtual void InvalidateAll() = 0; + // invalidates one, some, or all of the properties in this set virtual void CopyProps(const iFCOPropSet* pSrc, const cFCOPropVector& propsToCopy) = 0; - // copies the all the properties named in propsToCopy from pSrc to this prop set. - // this method will assert that pSrc is of the same type as this. All the properties - // in propsToCopy should be valid in pSrc. + // copies the all the properties named in propsToCopy from pSrc to this prop set. + // this method will assert that pSrc is of the same type as this. All the properties + // in propsToCopy should be valid in pSrc. virtual void TraceContents(int dl = -1) const = 0; - // sends the contents of this property set to wherever cDebug is pointing. + // sends the contents of this property set to wherever cDebug is pointing. protected: - virtual ~iFCOPropSet() {} + virtual ~iFCOPropSet() + { + } }; #endif //__FCOPROPSET_H - diff --git a/src/fco/fcopropsetimpl.cpp b/src/fco/fcopropsetimpl.cpp deleted file mode 100644 index aa1a8a6..0000000 --- a/src/fco/fcopropsetimpl.cpp +++ /dev/null @@ -1,212 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// propsetimpl.cpp - -#include "stdfs.h" -#include "propsetimpl.h" - -#include "core/debug.h" -#include "core/serializer.h" -#include "core/errorutil.h" -#include "fco/fcoundefprop.h" - - /////////////////////////////////////////////////////////////////////////////// -// TraceContents -/////////////////////////////////////////////////////////////////////////////// -void cPropSetImpl::TraceContents(int dl) const -{ - if(dl < 0) - dl = cDebug::D_DEBUG; - - cDebug d("cPropSetImpl::TraceContents"); - - TOSTRINGSTREAM ostr; - ostr << _T("File Sysytem Prop Set: "); - for(int i=0; iGetType() == CLASS_TYPE(cPropSetImpl)); - - // first, modify my valid vector... - mValidProps |= propsToCopy; - - for(int i=0; i < GetNumFSProps(); i++) - { - if(propsToCopy.ContainsItem(i)) - { - ASSERT( pSrc->GetValidVector().ContainsItem( i ) ); - const iFCOProp* pProp = pSrc->GetPropAt(i); - - if (pProp->GetType() != cFCOUndefinedProp::GetInstance()->GetType()) - { - GetPropAt(i)->Copy( pProp ); - mUndefinedProps.RemoveItem(i); - } - else - mUndefinedProps.AddItem(i); - } - } -} - - -/////////////////////////////////////////////////////////////////////////////// -// Invalidate -/////////////////////////////////////////////////////////////////////////////// -void cPropSetImpl::InvalidateProp(int index) -{ - ASSERT((index >= 0) && (index < GetNumProps())); - mValidProps.RemoveItem(index); -} - -void cPropSetImpl::InvalidateAll() -{ - mValidProps.Clear(); -} - -void cPropSetImpl::InvalidateProps(const cFCOPropVector& propsToInvalidate) -{ - cFCOPropVector inBoth = mValidProps; - inBoth &= propsToInvalidate; - mValidProps ^= inBoth; -} - -/////////////////////////////////////////////////////////////////////////////// -// GetNumFSProps -/////////////////////////////////////////////////////////////////////////////// -int cPropSetImpl::GetNumFSProps() -{ - return PROP_NUMITEMS; -} - -/////////////////////////////////////////////////////////////////////////////// -// ctors. dtor, operator= -/////////////////////////////////////////////////////////////////////////////// -cPropSetImpl::cPropSetImpl() : - mValidProps(cPropSetImpl::PROP_NUMITEMS), - mUndefinedProps(cPropSetImpl::PROP_NUMITEMS) -{ - // TODO: do I want to zero out all the property values here? -} - -cPropSetImpl::~cPropSetImpl() -{ - -} - -cPropSetImpl::cPropSetImpl(const cPropSetImpl& rhs) : - mValidProps(cPropSetImpl::PROP_NUMITEMS) -{ - *this = rhs; -} - -const cPropSetImpl& cPropSetImpl::operator=(const cPropSetImpl& rhs) -{ - mValidProps = rhs.GetValidVector(); - mUndefinedProps = rhs.mUndefinedProps; - - for(int i=0; i < PROP_NUMITEMS; i++) - if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) - GetPropAt(i)->Copy( ((cPropSetImpl&)rhs).GetPropAt(i) ); // call non-const GetPropAt for rhs - // don't want it to assert ContainsItem - return *this; -} - -const cFCOPropVector& cPropSetImpl::GetValidVector() const -{ - return mValidProps; -} - -int cPropSetImpl::GetNumProps() const -{ - return PROP_NUMITEMS; -} - -/* -int cPropSetImpl::GetPropIndex(const TCHAR* name) const -{ - for(int i=0; i= 0) && (index < GetNumProps())); - return TSS_GetString( cFS, cPropSetImpl_PropNames[index]); -} - - */ -void cPropSetImpl::Read(iSerializer* pSerializer, int32 version) -{ - if (version > Version()) - ThrowAndAssert(eSerializerVersionMismatch(_T("Property Set Read"))); - - mValidProps.Read(pSerializer); - mUndefinedProps.Read(pSerializer); - - for (int i=0; i < PROP_NUMITEMS; i++) - { - if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) - GetPropAt(i)->Read(pSerializer); - } -} - -void cPropSetImpl::Write(iSerializer* pSerializer) const -{ - mValidProps.Write(pSerializer); - mUndefinedProps.Write(pSerializer); - - for (int i=0; i < PROP_NUMITEMS; i++) - { - if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) - GetPropAt(i)->Write(pSerializer); - } -} - - diff --git a/src/fco/fcopropsetimpl.h b/src/fco/fcopropsetimpl.h deleted file mode 100644 index 244b9ba..0000000 --- a/src/fco/fcopropsetimpl.h +++ /dev/null @@ -1,78 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// fspropsetimpl.h -- file system objects' property set objects -// -// cPropSetImpl -- base class for all prop sets -// contains common implementation - -#ifndef __FSPROPSETIMPL_H -#define __FSPROPSETIMPL_H - -#ifndef __FCOPROPSET_H -#include "fco/fcopropset.h" -#endif -#ifndef __PROPSET_H -#include "fco/propset.h" -#endif - -/////////////////////////////////////////////////////////////////////////////// -// cPropSetImpl -/////////////////////////////////////////////////////////////////////////////// -class cPropSetImpl : public iFCOPropSet -{ -public: - cFSPropSet(); - cFSPropSet(const cFSPropSet& rhs); - virtual ~cFSPropSet(); - - const cFSPropSet& operator=(const cFSPropSet& rhs); - - virtual const cFCOPropVector& GetValidVector() const ; - virtual int GetNumProps () const ; - virtual int GetPropIndex(const TCHAR* name) const; - virtual TSTRING GetPropName (int index) const; - virtual const iFCOProp* GetPropAt(int index) const; - virtual iFCOProp* GetPropAt(int index) ; - virtual void InvalidateProp(int index); - virtual void InvalidateProps(const cFCOPropVector& propsToInvalidate) ; - virtual void InvalidateAll(); - virtual void CopyProps(const iFCOPropSet* pSrc, const cFCOPropVector& propsToCopy); - -private: - cFCOPropVector mValidProps; // all the properties that have been evaluated - cFCOPropVector mUndefinedProps; // properties that have been measured but have undefined values -}; - - -#endif // #ifndef __FSPROPSETIMPL_H - diff --git a/src/fco/fcopropvector.cpp b/src/fco/fcopropvector.cpp index 000ed41..6a8d7cb 100644 --- a/src/fco/fcopropvector.cpp +++ b/src/fco/fcopropvector.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,8 +39,8 @@ #include "core/debug.h" #include "core/errorutil.h" -int cFCOPropVector::msBitlength(sizeof (uint32) * 8); - //msBitlength is common to all objects of class. +int cFCOPropVector::msBitlength(sizeof(uint32) * 8); +//msBitlength is common to all objects of class. /////////////////////////////////////////////////////////////////////////////// // Constructor -- Sets mSize. Default = 32. @@ -54,26 +54,28 @@ cFCOPropVector::cFCOPropVector(int size) : iSerializable() } /////////////////////////////////////////////////////////////////////////////// -// Destructor -- +// Destructor -- /////////////////////////////////////////////////////////////////////////////// cFCOPropVector::~cFCOPropVector() { - if (mpBuf!=NULL) + if (mpBuf != NULL) delete mpBuf; } /////////////////////////////////////////////////////////////////////////////// // Copy Constructor /////////////////////////////////////////////////////////////////////////////// -cFCOPropVector::cFCOPropVector(const cFCOPropVector &rhs) : iSerializable() +cFCOPropVector::cFCOPropVector(const cFCOPropVector& rhs) : iSerializable() { mSize = rhs.mSize; mMask = rhs.mMask; - if (rhs.mpBuf != NULL) { - mpBuf = new std::vector; + if (rhs.mpBuf != NULL) + { + mpBuf = new std::vector; *mpBuf = *(rhs.mpBuf); } - else mpBuf = NULL; + else + mpBuf = NULL; } /////////////////////////////////////////////////////////////////////////////// @@ -81,10 +83,11 @@ cFCOPropVector::cFCOPropVector(const cFCOPropVector &rhs) : iSerializable() /////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::operator==(const cFCOPropVector& rhs) const { - if (this != &rhs) { - if ((mpBuf == NULL) && (rhs.mpBuf==NULL)) + if (this != &rhs) + { + if ((mpBuf == NULL) && (rhs.mpBuf == NULL)) return (mMask == rhs.mMask); - else if((mpBuf == NULL) && (rhs.mpBuf!=NULL)) + else if ((mpBuf == NULL) && (rhs.mpBuf != NULL)) { if (rhs.isExtended()) return false; @@ -96,7 +99,7 @@ bool cFCOPropVector::operator==(const cFCOPropVector& rhs) const if ((*this).isExtended()) return false; else - return (((*mpBuf)[0])==rhs.mMask); + return (((*mpBuf)[0]) == rhs.mMask); } else return (*mpBuf == *(rhs.mpBuf)); @@ -107,30 +110,29 @@ bool cFCOPropVector::operator==(const cFCOPropVector& rhs) const bool cFCOPropVector::operator!=(const cFCOPropVector& rhs) const { - return (! (*this == rhs)); + return (!(*this == rhs)); } - cFCOPropVector& cFCOPropVector::operator=(const cFCOPropVector& rhs) { if (this != &rhs) { - if ((rhs.mpBuf!=NULL) && (mpBuf!=NULL)) - *mpBuf= *(rhs.mpBuf); - else if ((rhs.mpBuf!=NULL) && (mpBuf==NULL)) + if ((rhs.mpBuf != NULL) && (mpBuf != NULL)) + *mpBuf = *(rhs.mpBuf); + else if ((rhs.mpBuf != NULL) && (mpBuf == NULL)) { - mpBuf = new std::vector; + mpBuf = new std::vector; *mpBuf = *(rhs.mpBuf); } - else if((rhs.mpBuf==NULL) && (mpBuf!=NULL)) + else if ((rhs.mpBuf == NULL) && (mpBuf != NULL)) { delete mpBuf; mpBuf = NULL; } mSize = rhs.mSize; mMask = rhs.mMask; - }//end if + } //end if return *this; } @@ -159,9 +161,9 @@ cFCOPropVector cFCOPropVector::operator^(const cFCOPropVector& rhs) const cFCOPropVector& cFCOPropVector::operator&=(const cFCOPropVector& rhs) { // make sure I am big enough - if(GetSize() < rhs.GetSize()) + if (GetSize() < rhs.GetSize()) SetSize(rhs.GetSize()); - if(mpBuf == 0) + if (mpBuf == 0) { ASSERT(GetSize() <= 32); mMask &= rhs.mMask; @@ -173,7 +175,7 @@ cFCOPropVector& cFCOPropVector::operator&=(const cFCOPropVector& rhs) } else { - for(unsigned int i=0; i < rhs.mpBuf->size(); ++i) + for (unsigned int i = 0; i < rhs.mpBuf->size(); ++i) (*mpBuf)[i] &= (*rhs.mpBuf)[i]; } return *this; @@ -182,9 +184,9 @@ cFCOPropVector& cFCOPropVector::operator&=(const cFCOPropVector& rhs) cFCOPropVector& cFCOPropVector::operator|=(const cFCOPropVector& rhs) { // make sure I am big enough - if(GetSize() < rhs.GetSize()) + if (GetSize() < rhs.GetSize()) SetSize(rhs.GetSize()); - if(mpBuf == 0) + if (mpBuf == 0) { ASSERT(GetSize() <= 32); mMask |= rhs.mMask; @@ -196,7 +198,7 @@ cFCOPropVector& cFCOPropVector::operator|=(const cFCOPropVector& rhs) } else { - for(unsigned int i=0; i < rhs.mpBuf->size(); ++i) + for (unsigned int i = 0; i < rhs.mpBuf->size(); ++i) (*mpBuf)[i] |= (*rhs.mpBuf)[i]; } return *this; @@ -205,9 +207,9 @@ cFCOPropVector& cFCOPropVector::operator|=(const cFCOPropVector& rhs) cFCOPropVector& cFCOPropVector::operator^=(const cFCOPropVector& rhs) { // make sure I am big enough - if(GetSize() < rhs.GetSize()) + if (GetSize() < rhs.GetSize()) SetSize(rhs.GetSize()); - if(mpBuf == 0) + if (mpBuf == 0) { ASSERT(GetSize() <= 32); mMask ^= rhs.mMask; @@ -219,14 +221,13 @@ cFCOPropVector& cFCOPropVector::operator^=(const cFCOPropVector& rhs) } else { - for(unsigned int i=0; i < rhs.mpBuf->size(); ++i) + for (unsigned int i = 0; i < rhs.mpBuf->size(); ++i) (*mpBuf)[i] ^= (*rhs.mpBuf)[i]; } return *this; } - //END OPERATORS /////////////////////////////////////////////////////////////////////////////// @@ -238,7 +239,7 @@ int cFCOPropVector::GetSize(void) const } /////////////////////////////////////////////////////////////////////////////// -// SetSize -- Sets the maximum NUMBER of items that can be stored +// SetSize -- Sets the maximum NUMBER of items that can be stored // in vector. **IMPORTANT** : If max is less than current size of mask+buff, // the set is truncated and extra information is lost. /////////////////////////////////////////////////////////////////////////////// @@ -248,25 +249,29 @@ int cFCOPropVector::SetSize(int max) return mSize = msBitlength; else if ((max <= msBitlength) && (mpBuf != NULL)) { - return mSize = (*mpBuf).capacity()*msBitlength; - //new operation already performed, stick with mpBuf. + return mSize = (*mpBuf).capacity() * msBitlength; + //new operation already performed, stick with mpBuf. } else if ((mpBuf == NULL) && (max > msBitlength)) { mpBuf = new std::vector; - (*mpBuf).resize (((max/msBitlength)+1), 0); - (*mpBuf)[0] = mMask; + (*mpBuf).resize(((max / msBitlength) + 1), 0); + (*mpBuf)[0] = mMask; return mSize = ((*mpBuf).capacity() * msBitlength); } - else //mpBuf!=NULL && max>msBitlength + else //mpBuf!=NULL && max>msBitlength { - (*mpBuf).resize (((max/msBitlength)+1), 0); - return mSize = ((*mpBuf).capacity() * msBitlength); + if (mpBuf) + { + (*mpBuf).resize(((max / msBitlength) + 1), 0); + mSize = ((*mpBuf).capacity() * msBitlength); + } + return mSize; } } /////////////////////////////////////////////////////////////////////////////// -// AddItem -- Adds an item to the bitset by 'anding' it on. Behavior is +// AddItem -- Adds an item to the bitset by 'anding' it on. Behavior is // undefined if i >= GetSize. Returns true if set contains item after change. /////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::AddItem(int i) @@ -276,30 +281,30 @@ bool cFCOPropVector::AddItem(int i) if (mpBuf == NULL) { ASSERT(mSize <= 32); - mMask |= 1<<(i); + mMask |= 1 << (i); } else { - ((*mpBuf)[(i)/msBitlength]) |= 1<<((i) % msBitlength); + ((*mpBuf)[(i) / msBitlength]) |= 1 << ((i) % msBitlength); } return ContainsItem(i); } /////////////////////////////////////////////////////////////////////////////// -// AddItemAndGrow -- Like AddItem except that if i >= GetSize, resizes vector. +// AddItemAndGrow -- Like AddItem except that if i >= GetSize, resizes vector. // Returns true if set contains item after change. /////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::AddItemAndGrow(int i) { - if(i >= GetSize()) - SetSize( i ); + if (i >= GetSize()) + SetSize(i); - return AddItem( i ); + return AddItem(i); } /////////////////////////////////////////////////////////////////////////////// -// RemoveItem -- Removes an item from the vector. Vector is unchanged if +// RemoveItem -- Removes an item from the vector. Vector is unchanged if // i >= GetMaxItem. Returns true if set does not contain item after change. /////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::RemoveItem(int i) @@ -309,39 +314,39 @@ bool cFCOPropVector::RemoveItem(int i) if (!ContainsItem(i)) return true; if (mpBuf == NULL) - mMask ^= 1<<(i); + mMask ^= 1 << (i); else { - ((*mpBuf)[(i)/msBitlength]) ^= 1<<((i) % msBitlength); + ((*mpBuf)[(i) / msBitlength]) ^= 1 << ((i) % msBitlength); } return !ContainsItem(i); } /////////////////////////////////////////////////////////////////////////////// -// ContainsItem -- Returns boolean value if bit value is in the vector. +// ContainsItem -- Returns boolean value if bit value is in the vector. // Fails if mMask+mBuf is < i. -/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::ContainsItem(int i) const { - if (i > mSize-1) + if (i > mSize - 1) return false; else if (mpBuf == NULL) { - return ((mMask & (1<<(i))) != 0); + return ((mMask & (1 << (i))) != 0); } else { - return ((((*mpBuf)[(i)/msBitlength]) & (1<<((i) % msBitlength))) != 0); + return ((((*mpBuf)[(i) / msBitlength]) & (1 << ((i) % msBitlength))) != 0); } } -/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// // Clear -- removes all items from the vector -/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// void cFCOPropVector::Clear(void) { mMask = 0; - if(mpBuf) + if (mpBuf) { std::fill(mpBuf->begin(), mpBuf->end(), 0); } @@ -350,7 +355,7 @@ void cFCOPropVector::Clear(void) /////////////////////////////////////////////////////////////////////////////// // isExtended -- Returns true if Vector is USING mpBuf beyond [0]. It -// is assumed that {mpBuf [i] |i>0} is being used if i has non-zero value. +// is assumed that {mpBuf [i] |i>0} is being used if i has non-zero value. /////////////////////////////////////////////////////////////////////////////// bool cFCOPropVector::isExtended(void) const { @@ -362,27 +367,28 @@ bool cFCOPropVector::isExtended(void) const return false; else { - int sum = 0; - for (int i=(*mpBuf).size(); i >= 2; i--) + uint32 sum = 0; + for (uint32 i = (*mpBuf).size() - 1; i >= 2; i--) sum += ((*mpBuf)[i]); - return (sum == 0); + return (sum != 0); } } } // TO DO: temp function, will delete after testing... DA -void cFCOPropVector::check (cDebug& d) const +void cFCOPropVector::check(cDebug& d) const { d.TraceDetail("mSize = %i \n", mSize); d.TraceDetail("msBitlength = %i \n", msBitlength); d.TraceDetail("mMask = %u \n", mMask); - if (mpBuf!=NULL) { - d.TraceDetail("*mpBuf has size %i \n", (*mpBuf).size() ); - for (unsigned int i = 0; i<(*mpBuf).size(); ++i) - d.TraceDetail("mpBuf element %i = %u \n", i, (*mpBuf)[i] ); + if (mpBuf != NULL) + { + d.TraceDetail("*mpBuf has size %i \n", (*mpBuf).size()); + for (unsigned int i = 0; i < (*mpBuf).size(); ++i) + d.TraceDetail("mpBuf element %i = %u \n", i, (*mpBuf)[i]); } -}//end check +} //end check void cFCOPropVector::Read(iSerializer* pSerializer, int32 version) @@ -390,7 +396,6 @@ void cFCOPropVector::Read(iSerializer* pSerializer, int32 version) if (version > 0) ThrowAndAssert(eSerializerVersionMismatch(_T("Property Vector Read"))); - int i; int32 newSize; pSerializer->ReadInt32(newSize); ASSERT(newSize > 0); @@ -405,19 +410,17 @@ void cFCOPropVector::Read(iSerializer* pSerializer, int32 version) } else { - for (i=0; i <= mSize / msBitlength; ++i) + for (int i = 0; i <= mSize / msBitlength; ++i) { int32 mask; pSerializer->ReadInt32(mask); (*mpBuf)[i] = mask; } } - } void cFCOPropVector::Write(iSerializer* pSerializer) const { - int i; pSerializer->WriteInt32(mSize); if (mpBuf == NULL) @@ -426,10 +429,9 @@ void cFCOPropVector::Write(iSerializer* pSerializer) const } else { - for (i=0; i <= mSize / msBitlength; ++i) + for (int i = 0; i <= mSize / msBitlength; ++i) pSerializer->WriteInt32((*mpBuf)[i]); } - } @@ -438,17 +440,16 @@ void cFCOPropVector::Write(iSerializer* pSerializer) const /////////////////////////////////////////////////////////////////////////////// void cFCOPropVector::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; - cDebug d("cFCOPropVector::TraceContents"); + cDebug d("cFCOPropVector::TraceContents"); TOSTRINGSTREAM ostr; - for(int i=0; i GetSize() - bool AddItemAndGrow (int i); - // Adds the item i to the vector. if (i > GetSize()), grows the vector - bool RemoveItem (int i); - // Removes an item from the set if it is in the set. Returns true if the - // item is not in the set prior to call. - bool ContainsItem (int i) const; - // returns true if the item is in the set. Returns false if i>GetSize. - void Clear (void); - // removes all items from the vector... - void check (cDebug& d) const; - // Temp function for testing purposes. Outputs vector info. TO DO: - // Get rid of this when it's no longer useful! DA - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + int GetSize(void) const; + // returns the number of items that can be stored in the vector. + // This will be some multiple of 32. (item 0 exists). The higest number this + // vector can store is GetSize()-1 + int SetSize(int max); + // sets the maximum item that can be stored in the vector. This function + // is only useful if one wants to extend the maximum size of the bitset. + // It will NOT truncate a bitset, i.e., once the vector mpBuf is allocated + // it will not be deallocated. The return value is one more than the highest + // value that can be stored in the vector (0 can be stored) + bool AddItem(int i); + // Adds the item i to the vector. Behavior is undefined if i > GetSize() + bool AddItemAndGrow(int i); + // Adds the item i to the vector. if (i > GetSize()), grows the vector + bool RemoveItem(int i); + // Removes an item from the set if it is in the set. Returns true if the + // item is not in the set prior to call. + bool ContainsItem(int i) const; + // returns true if the item is in the set. Returns false if i>GetSize. + void Clear(void); + // removes all items from the vector... + void check(cDebug& d) const; + // Temp function for testing purposes. Outputs vector info. TO DO: + // Get rid of this when it's no longer useful! DA + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) // iSerializable interface - void TraceContents (int dl = -1) const; - // debugging utility; traces out the contents of the vector + void TraceContents(int dl = -1) const; + // debugging utility; traces out the contents of the vector private: - bool isExtended (void) const; - // Helper function that discerns if an object is using mpBuf beyond [0] + bool isExtended(void) const; + // Helper function that discerns if an object is using mpBuf beyond [0] - int mSize; - static int msBitlength; - uint32 mMask; - std::vector *mpBuf; + int mSize; + static int msBitlength; + uint32 mMask; + std::vector* mpBuf; }; #endif //__FCOPROPVECTOR_H - diff --git a/src/fco/fcosetimpl.cpp b/src/fco/fcosetimpl.cpp index 2324ee0..9012c70 100644 --- a/src/fco/fcosetimpl.cpp +++ b/src/fco/fcosetimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -80,14 +80,16 @@ cFCOSetImpl::cFCOSetImpl(const cFCOSetImpl& rhs) : iFCOSet() /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -void cFCOSetImpl::operator=(const cFCOSetImpl& rhs) +cFCOSetImpl& cFCOSetImpl::operator=(const cFCOSetImpl& rhs) { std::set::const_iterator i; - for(i = rhs.mFCOSet.begin(); i != rhs.mFCOSet.end(); ++i) + for (i = rhs.mFCOSet.begin(); i != rhs.mFCOSet.end(); ++i) { i->mpFCO->AddRef(); mFCOSet.insert(cFCONode(i->mpFCO)); } + + return *this; } /////////////////////////////////////////////////////////////////////////////// @@ -97,7 +99,7 @@ void cFCOSetImpl::Clear() { // release our grip on all the fcos. std::set::iterator i; - for(i = mFCOSet.begin(); i != mFCOSet.end(); ++i) + for (i = mFCOSet.begin(); i != mFCOSet.end(); ++i) { i->mpFCO->Release(); } @@ -115,12 +117,12 @@ bool cFCOSetImpl::IsEmpty() const /////////////////////////////////////////////////////////////////////////////// // Lookup -- TODO: figure out how I can implement const and non-const versions -// without duplicating code. +// without duplicating code. /////////////////////////////////////////////////////////////////////////////// const iFCOIter* cFCOSetImpl::Lookup(const cFCOName& name) const { const cFCOIterImpl* pIter = CreateIterator(this); - if(! pIter->SeekToFCO(name)) + if (!pIter->SeekToFCO(name)) { pIter->DestroyIter(); pIter = NULL; @@ -131,7 +133,7 @@ const iFCOIter* cFCOSetImpl::Lookup(const cFCOName& name) const iFCOIter* cFCOSetImpl::Lookup(const cFCOName& name) { cFCOIterImpl* pIter = CreateIterator(this); - if(! pIter->SeekToFCO(name)) + if (!pIter->SeekToFCO(name)) { pIter->DestroyIter(); pIter = NULL; @@ -158,7 +160,7 @@ void cFCOSetImpl::ReturnIter(const cFCOIterImpl* pIter) const } /////////////////////////////////////////////////////////////////////////////// -// Insertion +// Insertion /////////////////////////////////////////////////////////////////////////////// void cFCOSetImpl::Insert(iFCO* pFCO) { @@ -169,12 +171,12 @@ void cFCOSetImpl::Insert(iFCO* pFCO) p = mFCOSet.insert(cFCONode(pFCO)); // if the element already existed in the set, p.second is false. ASSERT(p.second); - if(p.second) + if (p.second) pFCO->AddRef(); } /////////////////////////////////////////////////////////////////////////////// -// AcceptSerializer +// AcceptSerializer /////////////////////////////////////////////////////////////////////////////// void cFCOSetImpl::Read(iSerializer* pSerializer, int32 version) { @@ -183,10 +185,10 @@ void cFCOSetImpl::Read(iSerializer* pSerializer, int32 version) Clear(); - int i; + int i; int32 size; pSerializer->ReadInt32(size); - + // TODO -- don't assert; throw an exception or noop -- mdb //ASSERT(size >= 0); @@ -202,24 +204,24 @@ void cFCOSetImpl::Write(iSerializer* pSerializer) const pSerializer->WriteInt32(mFCOSet.size()); std::set::const_iterator itr; - for( itr = mFCOSet.begin(); itr != mFCOSet.end(); itr++) + for (itr = mFCOSet.begin(); itr != mFCOSet.end(); ++itr) { pSerializer->WriteObjectDynCreate(itr->mpFCO); } } /////////////////////////////////////////////////////////////////////////////// -// TraceContents +// TraceContents /////////////////////////////////////////////////////////////////////////////// void cFCOSetImpl::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; - cDebug d("cFCOSetImpl::TraceContents"); + cDebug d("cFCOSetImpl::TraceContents"); std::set::const_iterator i; - int count = 0; - for(i = mFCOSet.begin(); i != mFCOSet.end(); ++i, ++count) + int count = 0; + for (i = mFCOSet.begin(); i != mFCOSet.end(); ++i, ++count) { d.Trace(dl, "[FCO %d]\n", count); i->mpFCO->TraceContents(dl); @@ -234,16 +236,12 @@ void cFCOSetImpl::TraceContents(int dl) const /////////////////////////////////////////////////////////////////////////////// // ctor and dtor /////////////////////////////////////////////////////////////////////////////// -cFCOIterImpl::cFCOIterImpl(cFCOSetImpl* pSet) : - mpSet(pSet), - mIter() +cFCOIterImpl::cFCOIterImpl(cFCOSetImpl* pSet) : mpSet(pSet), mIter() { mIter = mpSet->mFCOSet.begin(); } -cFCOIterImpl::cFCOIterImpl(const cFCOSetImpl* pSet) : - mpSet((cFCOSetImpl *)pSet), - mIter() +cFCOIterImpl::cFCOIterImpl(const cFCOSetImpl* pSet) : mpSet((cFCOSetImpl*)pSet), mIter() { mIter = mpSet->mFCOSet.begin(); } @@ -284,7 +282,7 @@ bool cFCOIterImpl::IsEmpty() const void cFCOIterImpl::Next() const { ASSERT(mpSet != 0); - mIter++; + ++mIter; } @@ -321,5 +319,3 @@ void cFCOIterImpl::DestroyIter() const ASSERT(mpSet != 0); mpSet->ReturnIter(this); } - - diff --git a/src/fco/fcosetimpl.h b/src/fco/fcosetimpl.h index 942ba8c..69b7b3f 100644 --- a/src/fco/fcosetimpl.h +++ b/src/fco/fcosetimpl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -54,29 +54,32 @@ class cFCOSetImpl : public iFCOSet public: cFCOSetImpl(); - cFCOSetImpl(const cFCOSetImpl& rhs); + cFCOSetImpl(const cFCOSetImpl& rhs); virtual ~cFCOSetImpl(); - void operator=(const cFCOSetImpl& rhs); - - virtual const iFCOIter* Lookup(const cFCOName& name) const; - virtual iFCOIter* Lookup(const cFCOName& name); - virtual const iFCOIter* GetIter() const; - virtual iFCOIter* GetIter(); - virtual void Insert(iFCO* pFCO); - virtual void Clear(); - virtual bool IsEmpty() const; - virtual int Size() const { return mFCOSet.size(); }; - virtual void TraceContents(int dl = -1) const; + cFCOSetImpl& operator=(const cFCOSetImpl& rhs); + + virtual const iFCOIter* Lookup(const cFCOName& name) const; + virtual iFCOIter* Lookup(const cFCOName& name); + virtual const iFCOIter* GetIter() const; + virtual iFCOIter* GetIter(); + virtual void Insert(iFCO* pFCO); + virtual void Clear(); + virtual bool IsEmpty() const; + virtual int Size() const + { + return mFCOSet.size(); + }; + virtual void TraceContents(int dl = -1) const; // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) private: - void ReturnIter(const cFCOIterImpl* pIter) const; - // returns the iterator to its owner; the reciprocal action - // to Lookup() or GetIter(); called by the iterator when it is destroyed + void ReturnIter(const cFCOIterImpl* pIter) const; + // returns the iterator to its owner; the reciprocal action + // to Lookup() or GetIter(); called by the iterator when it is destroyed - // class we store in the set below; it is a hack that allows us to + // class we store in the set below; it is a hack that allows us to // look up iFCOs using cFCONames in a std::set class cFCONode { @@ -84,16 +87,37 @@ class cFCOSetImpl : public iFCOSet iFCO* mpFCO; const cFCOName* mpFCOName; - cFCONode() : mpFCO(0), mpFCOName(0) {} - cFCONode(iFCO* pFCO) : mpFCO(pFCO), mpFCOName(&pFCO->GetName()) {} - cFCONode(const cFCOName& name) : mpFCO(0), mpFCOName(&name) {} - cFCONode(const cFCONode& rhs) : mpFCO(rhs.mpFCO), mpFCOName(rhs.mpFCOName) {} - bool operator < (const cFCONode& rhs) const { if(mpFCOName) return (*mpFCOName < *rhs.mpFCOName); else return false; } - bool operator ==(const cFCONode& rhs) const { if(mpFCOName) return (*mpFCOName == *rhs.mpFCOName); else return false; } + cFCONode() : mpFCO(0), mpFCOName(0) + { + } + //TODO: make the iFCO* constructor explicit + cFCONode(iFCO* pFCO) : mpFCO(pFCO), mpFCOName(&pFCO->GetName()) + { + } + explicit cFCONode(const cFCOName& name) : mpFCO(0), mpFCOName(&name) + { + } + cFCONode(const cFCONode& rhs) : mpFCO(rhs.mpFCO), mpFCOName(rhs.mpFCOName) + { + } + bool operator<(const cFCONode& rhs) const + { + if (mpFCOName) + return (*mpFCOName < *rhs.mpFCOName); + else + return false; + } + bool operator==(const cFCONode& rhs) const + { + if (mpFCOName) + return (*mpFCOName == *rhs.mpFCOName); + else + return false; + } }; std::set mFCOSet; - // this is what actually stores the iFCOs. + // this is what actually stores the iFCOs. }; class cFCOIterImpl : public iFCOIter @@ -101,29 +125,29 @@ class cFCOIterImpl : public iFCOIter friend class cFCOSetImpl; public: - cFCOIterImpl(cFCOSetImpl* pSet); - cFCOIterImpl(const cFCOSetImpl* pSet); - - virtual void SeekBegin() const; - virtual bool Done() const; - virtual bool IsEmpty() const; - virtual void Next() const; - virtual const iFCO* FCO() const; - virtual iFCO* FCO(); - virtual bool SeekToFCO(const cFCOName& name) const; - - virtual void Remove(); - virtual void Remove() const; - virtual void DestroyIter() const; + explicit cFCOIterImpl(cFCOSetImpl* pSet); + explicit cFCOIterImpl(const cFCOSetImpl* pSet); + + virtual void SeekBegin() const; + virtual bool Done() const; + virtual bool IsEmpty() const; + virtual void Next() const; + virtual const iFCO* FCO() const; + virtual iFCO* FCO(); + virtual bool SeekToFCO(const cFCOName& name) const; + + virtual void Remove(); + virtual void Remove() const; + virtual void DestroyIter() const; + private: - virtual ~cFCOIterImpl() ; + virtual ~cFCOIterImpl(); - cFCOSetImpl* mpSet; - mutable std::set::iterator mIter; - // the definition of a const iterator is not that its position cannot change, - // but that it cannot modify the set it is iterating over, hence the "mutable" + cFCOSetImpl* mpSet; + mutable std::set::iterator mIter; + // the definition of a const iterator is not that its position cannot change, + // but that it cannot modify the set it is iterating over, hence the "mutable" }; #endif //__FCOSETIMPL_H - diff --git a/src/fco/fcosetws.h b/src/fco/fcosetws.h index 8f3f8be..dd91bc1 100644 --- a/src/fco/fcosetws.h +++ b/src/fco/fcosetws.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,86 +53,83 @@ class cFCOSetWS : public cFCOSetImpl { public: cFCOSetWS(const iFCOSpec* pSpec); - // all FCOs that are inserted will be ASSERTed to be contained in this spec. - // the class will AddRef() the spec, so the sanity of this class can be subverted - // by changing the contents of the spec after this set is created - cFCOSetWS(const cFCOSetWS& rhs); + // all FCOs that are inserted will be ASSERTed to be contained in this spec. + // the class will AddRef() the spec, so the sanity of this class can be subverted + // by changing the contents of the spec after this set is created + cFCOSetWS(const cFCOSetWS& rhs); virtual ~cFCOSetWS(); - void operator=(const cFCOSetWS& rhs); + void operator=(const cFCOSetWS& rhs); void SetSpec(const iFCOSpec* pSpec); - // this may only be called if the set is empty (useful if you want to construct a - // set but you don't have the spec yet. The spec must be set before Insert() is called. + // this may only be called if the set is empty (useful if you want to construct a + // set but you don't have the spec yet. The spec must be set before Insert() is called. + + virtual void Insert(iFCO* pFCO); - virtual void Insert(iFCO* pFCO); private: const iFCOSpec* mpSpec; }; //############################################################################# // inline implementation -inline cFCOSetWS::cFCOSetWS(const iFCOSpec* pSpec) : - cFCOSetImpl(), - mpSpec(pSpec) +inline cFCOSetWS::cFCOSetWS(const iFCOSpec* pSpec) : cFCOSetImpl(), mpSpec(pSpec) { - if(mpSpec) + if (mpSpec) mpSpec->AddRef(); } -inline cFCOSetWS::cFCOSetWS(const cFCOSetWS& rhs) : - cFCOSetImpl(rhs), - mpSpec(rhs.mpSpec) +inline cFCOSetWS::cFCOSetWS(const cFCOSetWS& rhs) : cFCOSetImpl(rhs), mpSpec(rhs.mpSpec) { - if(mpSpec) + if (mpSpec) mpSpec->AddRef(); } inline cFCOSetWS::~cFCOSetWS() { - if(mpSpec) + if (mpSpec) mpSpec->Release(); } inline void cFCOSetWS::operator=(const cFCOSetWS& rhs) { mpSpec = rhs.mpSpec; - if(mpSpec) + if (mpSpec) mpSpec->AddRef(); - cFCOSetImpl::operator=(rhs); + cFCOSetImpl::operator=(rhs); } inline void cFCOSetWS::SetSpec(const iFCOSpec* pSpec) { - if(mpSpec) + if (mpSpec) mpSpec->Release(); mpSpec = pSpec; - if(mpSpec) + if (mpSpec) mpSpec->AddRef(); } inline void cFCOSetWS::Insert(iFCO* pFCO) { // here is the only real work this class does! -#ifdef _DEBUG +#ifdef DEBUG // TODO -- note that this doesn't do any checking if the spec is NULL. I // am not sure if this is the right thing to do or not. - if(mpSpec) + if (mpSpec) { ASSERT(mpSpec->SpecContainsFCO(pFCO->GetName())); - if(! mpSpec->SpecContainsFCO(pFCO->GetName())) + if (!mpSpec->SpecContainsFCO(pFCO->GetName())) { cDebug d("cFCOSetWS::Insert"); - d.TraceError("*** Insert of FCO %s not appropriate for spec %s\n", pFCO->GetName().AsString().c_str(), mpSpec->GetName().c_str()); + d.TraceError("*** Insert of FCO %s not appropriate for spec %s\n", + pFCO->GetName().AsString().c_str(), + mpSpec->GetName().c_str()); d.TraceError("*** Spec contents:\n"); mpSpec->TraceContents(cDebug::D_ERROR); } } -#endif // _DEBUG +#endif // DEBUG cFCOSetImpl::Insert(pFCO); } - #endif //__FCOSETWS_H - diff --git a/src/fco/fcospec.cpp b/src/fco/fcospec.cpp index e281c77..60a4718 100644 --- a/src/fco/fcospec.cpp +++ b/src/fco/fcospec.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,20 +45,23 @@ /////////////////////////////////////////////////////////////////////////////// -// cDefaultSpecMask -- an implementation of iFCOSpecMask that implements the +// cDefaultSpecMask -- an implementation of iFCOSpecMask that implements the // default mask /////////////////////////////////////////////////////////////////////////////// class cDefaultSpecMask : public iFCOSpecMask { public: - cDefaultSpecMask() {} + cDefaultSpecMask() + { + } virtual const TSTRING& GetName() const; - virtual bool Accept(const iFCO* pFCO) const; + virtual bool Accept(const iFCO* pFCO) const; + private: static const TSTRING mName; }; -const TSTRING cDefaultSpecMask::mName(_T("Default")); +const TSTRING cDefaultSpecMask::mName(_T("Default")); const TSTRING& cDefaultSpecMask::GetName() const { @@ -79,5 +82,3 @@ const iFCOSpecMask* iFCOSpecMask::GetDefaultMask() { return &defaultSpecMask; } - - diff --git a/src/fco/fcospec.h b/src/fco/fcospec.h index 6b7b9f2..d0df17f 100644 --- a/src/fco/fcospec.h +++ b/src/fco/fcospec.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,13 +40,13 @@ #ifndef __TCHAR_H #include "core/tchar.h" -#endif +#endif #ifndef __FCO_H #include "fco.h" -#endif +#endif #ifndef __TYPED_H #include "typed.h" -#endif +#endif class iFCOSpecIter; class iFCOSpecMask; @@ -56,83 +56,88 @@ class iFCOSpecHelper; class iFCOSpec : public iSerRefCountObj { public: - virtual ~iFCOSpec() {} - + virtual ~iFCOSpec() + { + } + virtual const TSTRING& GetName() const = 0; - // returns the name of this FCOSpec + // returns the name of this FCOSpec virtual void SetName(const TSTRING& name) = 0; - // sets the spec's name + // sets the spec's name virtual iFCOSpec* Clone() const = 0; - // makes a copy of this FCO. This method is needed because it is sometimes necessary - // for clients who only know about the base class interface to make copies of the object. + // makes a copy of this FCO. This method is needed because it is sometimes necessary + // for clients who only know about the base class interface to make copies of the object. virtual bool SpecContainsFCO(const cFCOName& name) const = 0; - // returns true if the fco is below the spec's start point and above its terminator. - + // returns true if the fco is below the spec's start point and above its terminator. + virtual const cFCOName& GetStartPoint() const = 0; - // Returns the name of the fco that is the "root node" for the FCO set that will - // be produced by the spec. + // Returns the name of the fco that is the "root node" for the FCO set that will + // be produced by the spec. - virtual void SetStartPoint(const cFCOName& name) = 0; // throw (eError); + virtual void SetStartPoint(const cFCOName& name) = 0; // throw (eError); // sets the start point, as described in GetStartPoint() above. If a start point is added that is not // above all the existing stop points, an eError is thrown. - virtual void SetHelper( iFCOSpecHelper* pHelper ) = 0; - virtual const iFCOSpecHelper* GetHelper() const = 0; - // gets and sets the spec's helper class, which holds the start point and manages the spec's - // terminating criterion (stop points, etc.) + virtual void SetHelper(iFCOSpecHelper* pHelper) = 0; + virtual const iFCOSpecHelper* GetHelper() const = 0; + // gets and sets the spec's helper class, which holds the start point and manages the spec's + // terminating criterion (stop points, etc.) virtual const cFCOPropVector& GetPropVector(const iFCOSpecMask* pFCOSpecMask) const = 0; - // returns the property vector associated with the given mask. Result is undefined - // if the mask isn't a part of the FCOSpec + // returns the property vector associated with the given mask. Result is undefined + // if the mask isn't a part of the FCOSpec virtual bool SetPropVector(const iFCOSpecMask* pMask, const cFCOPropVector& vector) = 0; - // sets the property vector associated with a specific mask. The pointer to the mask must - // be the same as one of the pointers that the spec contains (that is, the spec "owns" the - // masks, and the pointer passed into this method was acquired from GetSpecMask() below. - // Returns false if pMask isn't in the spec. - + // sets the property vector associated with a specific mask. The pointer to the mask must + // be the same as one of the pointers that the spec contains (that is, the spec "owns" the + // masks, and the pointer passed into this method was acquired from GetSpecMask() below. + // Returns false if pMask isn't in the spec. + virtual const iFCOSpecMask* GetSpecMask(const iFCO* pFCO) const = 0; - // returns the FCOSpecMask associated with the FCO that the iterator is - // pointing at + // returns the FCOSpecMask associated with the FCO that the iterator is + // pointing at const cFCOPropVector& GetPropVector(const iFCO* pFCO) const; - // inline convenience function that calls GetPropVector(GetSpecMask(pFCO)) + // inline convenience function that calls GetPropVector(GetSpecMask(pFCO)) // TODO -- add methods for manipulating the internal FCOSpecMask set /////////////////////////////// // New for 2.1 // - virtual bool ShouldStopDescent( const cFCOName& name ) const = 0; - // this method returns true if the named fco is not a part of the spec. More - // specifically, it only returns true for all of the fcos on the "border" - // between being in and out of the spec. This will assert that the name is - // below the start point. + virtual bool ShouldStopDescent(const cFCOName& name) const = 0; + // this method returns true if the named fco is not a part of the spec. More + // specifically, it only returns true for all of the fcos on the "border" + // between being in and out of the spec. This will assert that the name is + // below the start point. // /////////////////////////////// - virtual void TraceContents(int dl = -1) const {} - // traces the contents of the spec to wherever cDebug is pointing; not pure - // virtual so that one is not forced to implement it. - + virtual void TraceContents(int dl = -1) const + { + } + // traces the contents of the spec to wherever cDebug is pointing; not pure + // virtual so that one is not forced to implement it. }; class iFCOSpecMask { public: - virtual ~iFCOSpecMask() {} + virtual ~iFCOSpecMask() + { + } virtual const TSTRING& GetName() const = 0; - // return the name of this mask + // return the name of this mask virtual bool Accept(const iFCO* pFCO) const = 0; - // returns true if the fco matches the criterion in the SpecMask + // returns true if the fco matches the criterion in the SpecMask static const iFCOSpecMask* GetDefaultMask(); - // returns the "default mask" that all iFCOSpecs must have. The default - // mask matches every FCO and is called "Default". There is no need to - // destroy the returned pointer + // returns the "default mask" that all iFCOSpecs must have. The default + // mask matches every FCO and is called "Default". There is no need to + // destroy the returned pointer }; //############################################################################# @@ -144,4 +149,3 @@ inline const cFCOPropVector& iFCOSpec::GetPropVector(const iFCO* pFCO) const #endif //__FCOSPEC_H - diff --git a/src/fco/fcospecattr.cpp b/src/fco/fcospecattr.cpp index 341c671..527b1e2 100644 --- a/src/fco/fcospecattr.cpp +++ b/src/fco/fcospecattr.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,11 +47,11 @@ void cFCOSpecAttr::Read(iSerializer* pSerializer, int32 version) pSerializer->ReadString(mName); pSerializer->ReadInt32(mSeverity); - int32 size; + int32 size; TSTRING str; pSerializer->ReadInt32(size); mEmailAddrs.clear(); - for(int i=0; i < size; i++) + for (int i = 0; i < size; i++) { pSerializer->ReadString(str); mEmailAddrs.push_back(str); @@ -68,7 +68,7 @@ void cFCOSpecAttr::Write(iSerializer* pSerializer) const pSerializer->WriteInt32(mEmailAddrs.size()); std::list::const_iterator i; - for(i = mEmailAddrs.begin(); i != mEmailAddrs.end(); ++i) + for (i = mEmailAddrs.begin(); i != mEmailAddrs.end(); ++i) pSerializer->WriteString(*i); } @@ -78,18 +78,21 @@ void cFCOSpecAttr::Write(iSerializer* pSerializer) const void cFCOSpecAttr::TraceContents(int dl) const { cDebug d("cFCOSpecAttr::TraceContents"); - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; - d.Trace(dl,"--- cFCOSpecAttr ---\n"); + d.Trace(dl, "--- cFCOSpecAttr ---\n"); d.Trace(dl, "Name: %s Severity: %d\n", mName.c_str(), mSeverity); d.Trace(dl, "Email addresses:\n"); std::list::const_iterator i; - for(i = mEmailAddrs.begin(); i != mEmailAddrs.end(); ++i) + for (i = mEmailAddrs.begin(); i != mEmailAddrs.end(); ++i) { d.Trace(dl, "\t%s\n", i->c_str()); } } - +bool cFCOSpecAttr::operator==(const cFCOSpecAttr& rhs) const +{ + return ((mEmailAddrs == rhs.mEmailAddrs) && (mName == rhs.mName) && (mSeverity == rhs.mSeverity)); +} diff --git a/src/fco/fcospecattr.h b/src/fco/fcospecattr.h index 9e0cba7..3618601 100644 --- a/src/fco/fcospecattr.h +++ b/src/fco/fcospecattr.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,30 +60,32 @@ class cFCOSpecAttr : public iSerRefCountObj /////////////////////// // the attributes /////////////////////// - const TSTRING& GetName() const; - void SetName(const TSTRING& name); - - int32 GetSeverity() const; - void SetSeverity(int32 s); + const TSTRING& GetName() const; + void SetName(const TSTRING& name); - int GetNumEmail() const; - void AddEmail(const TSTRING& str); - // adds an email address for report notification. This class makes no attempt - // to catch and prune identical entries in the email list. + int32 GetSeverity() const; + void SetSeverity(int32 s); - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + int GetNumEmail() const; + void AddEmail(const TSTRING& str); + // adds an email address for report notification. This class makes no attempt + // to catch and prune identical entries in the email list. + + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) void TraceContents(int dl = -1) const; + bool operator==(const cFCOSpecAttr& rhs) const; + DECLARE_SERREFCOUNT() private: - cFCOSpecAttr (const cFCOSpecAttr& rhs); // not impl - void operator= (const cFCOSpecAttr& rhs); // not impl + cFCOSpecAttr(const cFCOSpecAttr& rhs); // not impl + void operator=(const cFCOSpecAttr& rhs); // not impl - std::list mEmailAddrs; // the email addresses of people to be notified - TSTRING mName; // the name of the spec - int32 mSeverity; // the severity level + std::list mEmailAddrs; // the email addresses of people to be notified + TSTRING mName; // the name of the spec + int32 mSeverity; // the severity level friend class cFCOSpecAttrEmailIter; }; @@ -94,32 +96,31 @@ class cFCOSpecAttr : public iSerRefCountObj class cFCOSpecAttrEmailIter { public: - cFCOSpecAttrEmailIter(const cFCOSpecAttr& attr); + explicit cFCOSpecAttrEmailIter(const cFCOSpecAttr& attr); ~cFCOSpecAttrEmailIter(); - void SeekBegin() const; - bool Done() const; - bool IsEmpty() const; - void Next() const; + void SeekBegin() const; + bool Done() const; + bool IsEmpty() const; + void Next() const; const TSTRING& EmailAddress() const; + private: - const std::list& mSet; - mutable std::list::const_iterator mIter; + const std::list& mSet; + mutable std::list::const_iterator mIter; }; //############################################################################# // inline implementation -inline cFCOSpecAttr::cFCOSpecAttr() : - mName(_T("Unnamed")), - mSeverity(0) +inline cFCOSpecAttr::cFCOSpecAttr() : mName(_T("Unnamed")), mSeverity(0) { } inline cFCOSpecAttr::~cFCOSpecAttr() { } -inline const TSTRING& cFCOSpecAttr::GetName() const +inline const TSTRING& cFCOSpecAttr::GetName() const { return mName; } @@ -148,8 +149,7 @@ inline int cFCOSpecAttr::GetNumEmail() const /////////////// // iterator /////////////// -inline cFCOSpecAttrEmailIter::cFCOSpecAttrEmailIter(const cFCOSpecAttr& attr) : - mSet(attr.mEmailAddrs) +inline cFCOSpecAttrEmailIter::cFCOSpecAttrEmailIter(const cFCOSpecAttr& attr) : mSet(attr.mEmailAddrs) { mIter = mSet.begin(); } @@ -157,7 +157,7 @@ inline cFCOSpecAttrEmailIter::cFCOSpecAttrEmailIter(const cFCOSpecAttr& attr) : inline cFCOSpecAttrEmailIter::~cFCOSpecAttrEmailIter() { } -inline void cFCOSpecAttrEmailIter::SeekBegin() const +inline void cFCOSpecAttrEmailIter::SeekBegin() const { mIter = mSet.begin(); } @@ -171,15 +171,13 @@ inline bool cFCOSpecAttrEmailIter::IsEmpty() const } inline void cFCOSpecAttrEmailIter::Next() const { - mIter++; + ++mIter; } inline const TSTRING& cFCOSpecAttrEmailIter::EmailAddress() const { - ASSERT(! Done()); + ASSERT(!Done()); return *mIter; } - #endif //__FCOSPECATTR_H - diff --git a/src/fco/fcospechelper.cpp b/src/fco/fcospechelper.cpp index d701b70..745243c 100644 --- a/src/fco/fcospechelper.cpp +++ b/src/fco/fcospechelper.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,7 +46,7 @@ /////////////////////////////////////////////////////////////////////////////// // Read /////////////////////////////////////////////////////////////////////////////// -void iFCOSpecHelper::Read (iSerializer* pSerializer, int32 version) +void iFCOSpecHelper::Read(iSerializer* pSerializer, int32 version) { // read the start point pSerializer->ReadObject(&mStartPoint); @@ -62,7 +62,6 @@ void iFCOSpecHelper::Write(iSerializer* pSerializer) const } - //############################################################################# // cFCOSpecStopPointSet //############################################################################# @@ -72,10 +71,8 @@ IMPLEMENT_TYPEDSERIALIZABLE(cFCOSpecStopPointSet, _T("cFCOSpecStopPointSet"), 0, /////////////////////////////////////////////////////////////////////////////// // cFCOSpecStopPointSet /////////////////////////////////////////////////////////////////////////////// -cFCOSpecStopPointSet::cFCOSpecStopPointSet() -: mRecurseDepth( cFCOSpecStopPointSet::RECURSE_INFINITE ) +cFCOSpecStopPointSet::cFCOSpecStopPointSet() : mRecurseDepth(cFCOSpecStopPointSet::RECURSE_INFINITE) { - } /////////////////////////////////////////////////////////////////////////////// @@ -85,7 +82,7 @@ bool cFCOSpecStopPointSet::ContainsFCO(const cFCOName& name) const { // make sure name is at or below start point cFCOName::Relationship rel = name.GetRelationship(GetStartPoint()); - if((rel != cFCOName::REL_BELOW) && (rel != cFCOName::REL_EQUAL)) + if ((rel != cFCOName::REL_BELOW) && (rel != cFCOName::REL_EQUAL)) return false; // chack all the stop points @@ -93,7 +90,7 @@ bool cFCOSpecStopPointSet::ContainsFCO(const cFCOName& name) const for (itr = mStopPoints.begin(); itr != mStopPoints.end(); ++itr) { rel = name.GetRelationship(*itr); - if((rel == cFCOName::REL_BELOW) || (rel == cFCOName::REL_EQUAL)) + if ((rel == cFCOName::REL_BELOW) || (rel == cFCOName::REL_EQUAL)) return false; } @@ -109,43 +106,41 @@ void cFCOSpecStopPointSet::SetStartPoint(const cFCOName& startPoint) // make sure the start point is above all stop points... std::set::iterator i; - for(i = mStopPoints.begin(); i != mStopPoints.end(); ++i) - { - if(i->GetRelationship(startPoint) != cFCOName::REL_BELOW) + for (i = mStopPoints.begin(); i != mStopPoints.end(); ++i) + { + if (i->GetRelationship(startPoint) != cFCOName::REL_BELOW) { TOSTRINGSTREAM str; - str << "Bad start point [" - << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( startPoint ) + str << "Bad start point [" << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(startPoint) << "] added to spec with stop point " - << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( *i ) - << std::ends; + << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(*i) << std::ends; d.TraceError("%s\n", str.str().c_str()); throw eSerializerInputStreamFmt(str.str().c_str()); } } - // ok, it is acceptable to add this + // ok, it is acceptable to add this inherited::SetStartPoint(startPoint); } /////////////////////////////////////////////////////////////////////////////// -// ShouldStopDescent -- this returns true if we have just crossed the +// ShouldStopDescent -- this returns true if we have just crossed the // "boundary" between what is in and what is out of the spec's set. For // StopPointSets, this means that the fco name matches a stop point /////////////////////////////////////////////////////////////////////////////// -bool cFCOSpecStopPointSet::ShouldStopDescent(const cFCOName& name) const +bool cFCOSpecStopPointSet::ShouldStopDescent(const cFCOName& name) const { cDebug d("cFCOSpecStopPointSet::ShouldStopDescent"); // // first, check the recurse depth... // - if( GetRecurseDepth() != RECURSE_INFINITE ) + if (GetRecurseDepth() != RECURSE_INFINITE) { - if( (name.GetSize() - mStartPoint.GetSize()) > GetRecurseDepth() ) + if ((name.GetSize() - mStartPoint.GetSize()) > GetRecurseDepth()) return true; } - + std::set::const_iterator i = mStopPoints.find(name); return (i != mStopPoints.end()); @@ -157,12 +152,11 @@ bool cFCOSpecStopPointSet::ShouldStopDescent(const cFCOName& name) const void cFCOSpecStopPointSet::TraceContents(int dl) const { cDebug d("cFCOSpecStopPointSet::TraceContents"); - if(dl == -1) + if (dl == -1) dl = cDebug::D_DEBUG; d.Trace(dl, _T("Start Point:\t%s\n"), mStartPoint.AsString().c_str()); - for(std::set::const_iterator i = mStopPoints.begin(); - i != mStopPoints.end(); ++i) + for (std::set::const_iterator i = mStopPoints.begin(); i != mStopPoints.end(); ++i) { d.Trace(dl, _T("Stop Point :\t%s\n"), i->AsString().c_str()); } @@ -176,42 +170,45 @@ void cFCOSpecStopPointSet::Add(const cFCOName& name) cDebug d("cFCOSpecImpl::AddStopPoint"); // first, make sure this stop point is below the start point - if(name.GetRelationship(mStartPoint) != cFCOName::REL_BELOW) + if (name.GetRelationship(mStartPoint) != cFCOName::REL_BELOW) { d.TraceError("Attempt to add stop point that is not below start point!\n"); d.TraceError("\tstart point = %s stop point = %s\n", mStartPoint.AsString().c_str(), name.AsString().c_str()); TOSTRINGSTREAM str; - str << "Attempt to add stop point that is not below start point!" - << " start point = " - << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( mStartPoint ) - << " stop point = " - << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( name ) - << std::ends; + str << "Attempt to add stop point that is not below start point!" + << " start point = " << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(mStartPoint) + << " stop point = " << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(name) << std::ends; d.TraceError(_T("%s\n"), str.str().c_str()); throw eSerializerInputStreamFmt(str.str().c_str()); } std::set::iterator i; - for(i = mStopPoints.begin(); i != mStopPoints.end(); ) + for (i = mStopPoints.begin(); i != mStopPoints.end();) { cFCOName::Relationship rel = name.GetRelationship(*i); - switch(rel) + switch (rel) { case cFCOName::REL_EQUAL: - d.TraceDebug(_T("Attempt to add stop point %s that already exists in spec %s\n"), name.AsString().c_str(), mStartPoint.AsString().c_str()); + d.TraceDebug(_T("Attempt to add stop point %s that already exists in spec %s\n"), + name.AsString().c_str(), + mStartPoint.AsString().c_str()); return; case cFCOName::REL_BELOW: - d.TraceDebug(_T("Attempt to add stop point %s to spec %s, but stop point %s already exists!\n"), - name.AsString().c_str(), mStartPoint.AsString().c_str(), i->AsString().c_str()); + d.TraceDebug(_T("Attempt to add stop point %s to spec %s, but stop point %s already exists!\n"), + name.AsString().c_str(), + mStartPoint.AsString().c_str(), + i->AsString().c_str()); return; - case cFCOName::REL_ABOVE: + case cFCOName::REL_ABOVE: // this stop point will replace the encountered stop point, so remove it! - d.TraceDebug(_T("Attempt to add stop point %s to spec %s, so removing stop point %s\n"), - name.AsString().c_str(), mStartPoint.AsString().c_str(), i->AsString().c_str()); + d.TraceDebug(_T("Attempt to add stop point %s to spec %s, so removing stop point %s\n"), + name.AsString().c_str(), + mStartPoint.AsString().c_str(), + i->AsString().c_str()); // we have to be careful we don't decrement past the beginning of the set! - if(i == mStopPoints.begin()) + if (i == mStopPoints.begin()) { mStopPoints.erase(i); i = mStopPoints.begin(); @@ -221,7 +218,7 @@ void cFCOSpecStopPointSet::Add(const cFCOName& name) break; default: - i++; + ++i; } } @@ -250,13 +247,13 @@ iFCOSpecHelper* cFCOSpecStopPointSet::Clone() const /////////////////////////////////////////////////////////////////////////////// // Read /////////////////////////////////////////////////////////////////////////////// -void cFCOSpecStopPointSet::Read (iSerializer* pSerializer, int32 version) +void cFCOSpecStopPointSet::Read(iSerializer* pSerializer, int32 version) { // read the start point //pSerializer->ReadObject(&mStartPoint); inherited::Read(pSerializer, version); - // read all the stop points + // read all the stop points int32 size; pSerializer->ReadInt32(size); ASSERT(size >= 0); @@ -266,7 +263,6 @@ void cFCOSpecStopPointSet::Read (iSerializer* pSerializer, int32 version) pSerializer->ReadObject(&fcoName); mStopPoints.insert(fcoName); } - } /////////////////////////////////////////////////////////////////////////////// @@ -294,25 +290,24 @@ void cFCOSpecStopPointSet::Write(iSerializer* pSerializer) const iFCOSpecHelper::CompareResult cFCOSpecStopPointSet::Compare(const iFCOSpecHelper* pRhs) const { // if different types, order on mType address :-) - if(pRhs->GetType() != GetType()) + if (pRhs->GetType() != GetType()) return ((&pRhs->GetType() < &GetType()) ? CMP_LT : CMP_GT); const cFCOSpecStopPointSet* pStopPtSet = static_cast(pRhs); - if(GetStartPoint() != pStopPtSet->GetStartPoint()) + if (GetStartPoint() != pStopPtSet->GetStartPoint()) return ((GetStartPoint() < pStopPtSet->GetStartPoint()) ? CMP_LT : CMP_GT); - if(GetSize() != pStopPtSet->GetSize()) + if (GetSize() != pStopPtSet->GetSize()) return ((GetSize() < pStopPtSet->GetSize()) ? CMP_LT : CMP_GT); - std::set::const_iterator myIter = mStopPoints.begin(), - rhsIter = pStopPtSet->mStopPoints.begin(); - for(; myIter != mStopPoints.end(); myIter++, rhsIter++) + std::set::const_iterator myIter = mStopPoints.begin(), rhsIter = pStopPtSet->mStopPoints.begin(); + for (; myIter != mStopPoints.end(); ++myIter, ++rhsIter) { - if(*myIter != *rhsIter) + if (*myIter != *rhsIter) return ((*myIter < *rhsIter) ? CMP_LT : CMP_GT); } - // they must be equal! + // they must be equal! return CMP_EQ; } @@ -345,13 +340,13 @@ iFCOSpecHelper* cFCOSpecNoChildren::Clone() const bool cFCOSpecNoChildren::ShouldStopDescent(const cFCOName& name) const { // we should stop for everything except the start point... - return ( name != GetStartPoint() ); + return (name != GetStartPoint()); } /////////////////////////////////////////////////////////////////////////////// // Read /////////////////////////////////////////////////////////////////////////////// -void cFCOSpecNoChildren::Read (iSerializer* pSerializer, int32 version) +void cFCOSpecNoChildren::Read(iSerializer* pSerializer, int32 version) { inherited::Read(pSerializer, version); } @@ -370,10 +365,10 @@ void cFCOSpecNoChildren::Write(iSerializer* pSerializer) const iFCOSpecHelper::CompareResult cFCOSpecNoChildren::Compare(const iFCOSpecHelper* pRhs) const { // if different types, order on mType address :-) - if(pRhs->GetType() != GetType()) + if (pRhs->GetType() != GetType()) return ((&pRhs->GetType() < &GetType()) ? CMP_LT : CMP_GT); - if(GetStartPoint() != pRhs->GetStartPoint()) + if (GetStartPoint() != pRhs->GetStartPoint()) return ((GetStartPoint() < pRhs->GetStartPoint()) ? CMP_LT : CMP_GT); return CMP_EQ; @@ -385,10 +380,8 @@ iFCOSpecHelper::CompareResult cFCOSpecNoChildren::Compare(const iFCOSpecHelper* void cFCOSpecNoChildren::TraceContents(int dl) const { cDebug d("cFCOSpecNoChildren::TraceContents"); - if(dl == -1) + if (dl == -1) dl = cDebug::D_DEBUG; d.Trace(dl, "Single FCO Spec (all children are stop points): %s\n", mStartPoint.AsString().c_str()); } - - diff --git a/src/fco/fcospechelper.h b/src/fco/fcospechelper.h index c9f13e8..353446e 100644 --- a/src/fco/fcospechelper.h +++ b/src/fco/fcospechelper.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -55,29 +55,29 @@ class iSerializer; // iFCOSpecHelper -- interface for managing a spec's start point and stop // criterion /////////////////////////////////////////////////////////////////////////////// -class iFCOSpecHelper : public iTypedSerializable +class iFCOSpecHelper : public iTypedSerializable { public: - virtual void SetStartPoint(const cFCOName& startPoint);// throw (eError); - virtual const cFCOName& GetStartPoint() const; - // gets and sets the start point. SetStartPoint will throw an eError if the start point - // is inappropriate + virtual void SetStartPoint(const cFCOName& startPoint); // throw (eError); + virtual const cFCOName& GetStartPoint() const; + // gets and sets the start point. SetStartPoint will throw an eError if the start point + // is inappropriate virtual bool ContainsFCO(const cFCOName& name) const = 0; - // returns true if the named fco is below the start point and "above" its terminating - // criterion + // returns true if the named fco is below the start point and "above" its terminating + // criterion virtual iFCOSpecHelper* Clone() const = 0; - // return a cloned copy of yourself; the clone will need to be deleted by the caller. + // return a cloned copy of yourself; the clone will need to be deleted by the caller. virtual bool ShouldStopDescent(const cFCOName& name) const = 0; - // used by the iFCODataSource interface of iFCOSpec, this is called for each fco that is - // encountered. Really, ContainsFCO() could be used to reach the same ends, but - // this might/should be faster. + // used by the iFCODataSource interface of iFCOSpec, this is called for each fco that is + // encountered. Really, ContainsFCO() could be used to reach the same ends, but + // this might/should be faster. - virtual void Read (iSerializer* pSerializer, int32 version = 0); + virtual void Read(iSerializer* pSerializer, int32 version = 0); virtual void Write(iSerializer* pSerializer) const; - // these just serialize the start point. + // these just serialize the start point. enum CompareResult { @@ -86,22 +86,27 @@ class iFCOSpecHelper : public iTypedSerializable CMP_GT = 1 }; virtual CompareResult Compare(const iFCOSpecHelper* pRhs) const = 0; - // these are needed to define an ordering of specs. + // these are needed to define an ordering of specs. - virtual void TraceContents(int dl = -1) const {} + virtual void TraceContents(int dl = -1) const + { + } + + virtual ~iFCOSpecHelper() + { + } - virtual ~iFCOSpecHelper() {} protected: - cFCOName mStartPoint; + cFCOName mStartPoint; }; /////////////////////////////////////////////////////////////////////////////// -// cFCOSpecStopPoints -- a spec helper that uses a set of stop points. +// cFCOSpecStopPoints -- a spec helper that uses a set of stop points. // to determine where the spec ends. // NOTE -- stop points are stored internally in an order defined by cFCOName::operator< // All iterations over the stop points will be in this order. // -// This class also keeps track of a "maximum recurse depth", where all +// This class also keeps track of a "maximum recurse depth", where all // calls to ShouldStopDescent() return true when the name is more than // the maximum depth below the start point. /////////////////////////////////////////////////////////////////////////////// @@ -110,47 +115,59 @@ class cFCOSpecStopPointSet : public iFCOSpecHelper public: cFCOSpecStopPointSet(); - virtual void SetStartPoint(const cFCOName& startPoint); - virtual bool ContainsFCO(const cFCOName& name) const; - virtual bool ShouldStopDescent(const cFCOName& name) const ; - virtual void TraceContents(int dl= -1) const; - virtual iFCOSpecHelper* Clone() const; + virtual void SetStartPoint(const cFCOName& startPoint); + virtual bool ContainsFCO(const cFCOName& name) const; + virtual bool ShouldStopDescent(const cFCOName& name) const; + virtual void TraceContents(int dl = -1) const; + virtual iFCOSpecHelper* Clone() const; int GetSize() const; - // returns the number of stop points this contains + // returns the number of stop points this contains virtual void Clear(); - // clears the set of stop points. + // clears the set of stop points. virtual void Add(const cFCOName& name); // throw(eError) // adds a stop point. Stop points may be removed and iterated through using - // the iterator below. + // the iterator below. // If the stop point is above or below any existing stop points, the "lower" stop - // point will be replaced with the higher one. Thus, at any given time, + // point will be replaced with the higher one. Thus, at any given time, // all stop points are unrelated (retrun REL_UNRELATED from cFCOName::GetRelation) // // recurse depth // - enum { RECURSE_INFINITE = -1 }; - void SetRecurseDepth( int depth ) { mRecurseDepth = depth; } - int GetRecurseDepth() const { return mRecurseDepth; } - // gets and sets the maximum recurse depth. If a name passed to ShouldStopDescent() is deeper than - // the maximum recurse depth, true is returned. For example, if there are no stop points and the - // start point is /etc, if the recurse depth is 1, then /etc/dog will be processed but /etc/dog/bark - // will not. RECURSE_INFINITE can be passed in to indicate there is no maximum recurse depth. + enum + { + RECURSE_INFINITE = -1 + }; + void SetRecurseDepth(int depth) + { + mRecurseDepth = depth; + } + int GetRecurseDepth() const + { + return mRecurseDepth; + } + // gets and sets the maximum recurse depth. If a name passed to ShouldStopDescent() is deeper than + // the maximum recurse depth, true is returned. For example, if there are no stop points and the + // start point is /etc, if the recurse depth is 1, then /etc/dog will be processed but /etc/dog/bark + // will not. RECURSE_INFINITE can be passed in to indicate there is no maximum recurse depth. // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); + virtual void Read(iSerializer* pSerializer, int32 version = 0); virtual void Write(iSerializer* pSerializer) const; virtual CompareResult Compare(const iFCOSpecHelper* pRhs) const; DECLARE_TYPEDSERIALIZABLE() - virtual ~cFCOSpecStopPointSet() {} + virtual ~cFCOSpecStopPointSet() + { + } + protected: - std::set mStopPoints; - int mRecurseDepth; + std::set mStopPoints; + int mRecurseDepth; friend class cFCOSpecStopPointIter; typedef iFCOSpecHelper inherited; @@ -159,31 +176,31 @@ class cFCOSpecStopPointSet : public iFCOSpecHelper class cFCOSpecStopPointIter { public: - cFCOSpecStopPointIter(cFCOSpecStopPointSet& set); - - void SeekBegin() const; - // seeks to the beginning of the stop point list - bool Done() const; - // returns true if the iterator has gone past the end of the set - bool IsEmpty() const; - // is the set empty? - void Next() const; - // seek to the next element in the set - - const cFCOName& StopPoint() const; - const cFCOName& StopPoint(); - // methods for getting the StopPoint that the iterator is currently pointing at - - void Remove(); - // removes the fco pointed to by the iter. Behavior is undefined if the set is empty. - // after the erase, the iterator points to the next element in the list + explicit cFCOSpecStopPointIter(cFCOSpecStopPointSet& set); + + void SeekBegin() const; + // seeks to the beginning of the stop point list + bool Done() const; + // returns true if the iterator has gone past the end of the set + bool IsEmpty() const; + // is the set empty? + void Next() const; + // seek to the next element in the set + + const cFCOName& StopPoint() const; + const cFCOName& StopPoint(); + // methods for getting the StopPoint that the iterator is currently pointing at + + void Remove(); + // removes the fco pointed to by the iter. Behavior is undefined if the set is empty. + // after the erase, the iterator points to the next element in the list private: - mutable std::set::iterator mIter; - std::set& mSet; + mutable std::set::iterator mIter; + std::set& mSet; }; /////////////////////////////////////////////////////////////////////////////// -// cFCOSpecNoChildren -- an iFCOSpecHelper that maps to a single FCO -- the +// cFCOSpecNoChildren -- an iFCOSpecHelper that maps to a single FCO -- the // start point /////////////////////////////////////////////////////////////////////////////// class cFCOSpecNoChildren : public iFCOSpecHelper @@ -192,7 +209,7 @@ class cFCOSpecNoChildren : public iFCOSpecHelper virtual bool ContainsFCO(const cFCOName& name) const; virtual iFCOSpecHelper* Clone() const; virtual bool ShouldStopDescent(const cFCOName& name) const; - virtual void Read (iSerializer* pSerializer, int32 version = 0); + virtual void Read(iSerializer* pSerializer, int32 version = 0); virtual void Write(iSerializer* pSerializer) const; virtual CompareResult Compare(const iFCOSpecHelper* pRhs) const; virtual void TraceContents(int dl = -1) const; @@ -215,7 +232,7 @@ inline void iFCOSpecHelper::SetStartPoint(const cFCOName& startPoint) } inline const cFCOName& iFCOSpecHelper::GetStartPoint() const -{ +{ return mStartPoint; } @@ -235,48 +252,46 @@ inline void cFCOSpecStopPointSet::Clear() ////////////////////////// // cFCOSpecStopPointIter ////////////////////////// -inline cFCOSpecStopPointIter::cFCOSpecStopPointIter(cFCOSpecStopPointSet& set) : - mSet(set.mStopPoints) +inline cFCOSpecStopPointIter::cFCOSpecStopPointIter(cFCOSpecStopPointSet& set) : mSet(set.mStopPoints) { mIter = mSet.begin(); } -inline void cFCOSpecStopPointIter::SeekBegin() const +inline void cFCOSpecStopPointIter::SeekBegin() const { mIter = mSet.begin(); } -inline bool cFCOSpecStopPointIter::Done() const +inline bool cFCOSpecStopPointIter::Done() const { return (mIter == mSet.end()); } -inline bool cFCOSpecStopPointIter::IsEmpty() const +inline bool cFCOSpecStopPointIter::IsEmpty() const { return (mSet.size() == 0); } -inline void cFCOSpecStopPointIter::Next() const +inline void cFCOSpecStopPointIter::Next() const { - mIter++; + ++mIter; } inline void cFCOSpecStopPointIter::Remove() { - ASSERT(! Done()); + ASSERT(!Done()); mSet.erase(mIter++); } -inline const cFCOName& cFCOSpecStopPointIter::StopPoint() const +inline const cFCOName& cFCOSpecStopPointIter::StopPoint() const { - ASSERT(! Done()); + ASSERT(!Done()); return (*mIter); } inline const cFCOName& cFCOSpecStopPointIter::StopPoint() { - ASSERT(! Done()); + ASSERT(!Done()); return (*mIter); } #endif //__FCOSPECHELPER_H - diff --git a/src/fco/fcospecimpl.cpp b/src/fco/fcospecimpl.cpp index 2e664e7..b529314 100644 --- a/src/fco/fcospecimpl.cpp +++ b/src/fco/fcospecimpl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,43 +41,36 @@ #include "fcospechelper.h" #include "core/errorutil.h" -#ifdef _DEBUG -int gFCOSpecImplCreated = 0; +#ifdef DEBUG +int gFCOSpecImplCreated = 0; int gFCOSpecImplDestroyed = 0; #endif /////////////////////////////////////////////////////////////////////////////// // ctor and dtor /////////////////////////////////////////////////////////////////////////////// -cFCOSpecImpl::cFCOSpecImpl(const TSTRING& name, void* pSrc, iFCOSpecHelper* pHelper) : - mName(name), - mpHelper(pHelper) +cFCOSpecImpl::cFCOSpecImpl(const TSTRING& name, void* pSrc, iFCOSpecHelper* pHelper) : mName(name), mpHelper(pHelper) { -#ifdef _DEBUG +#ifdef DEBUG ++gFCOSpecImplCreated; cDebug d("cFCOSpecImpl::cFCOSpecImpl()"); d.TraceDetail("Allocated cFCOSpecImpl(%p) creat=%d dest=%d\n", this, gFCOSpecImplCreated, gFCOSpecImplDestroyed); #endif } -cFCOSpecImpl::cFCOSpecImpl() : - iFCOSpec(), - mName(_T("Unnamed_FCOSpecImpl")), - mpHelper(0) +cFCOSpecImpl::cFCOSpecImpl() : iFCOSpec(), mName(_T("Unnamed_FCOSpecImpl")), mpHelper(0) { -#ifdef _DEBUG +#ifdef DEBUG ++gFCOSpecImplCreated; cDebug d("cFCOSpecImpl::cFCOSpecImpl()"); d.TraceDetail("Allocated cFCOSpecImpl(%p) creat=%d dest=%d\n", this, gFCOSpecImplCreated, gFCOSpecImplDestroyed); #endif } -cFCOSpecImpl::cFCOSpecImpl(const cFCOSpecImpl& rhs) : - iFCOSpec(), - mpHelper(0) +cFCOSpecImpl::cFCOSpecImpl(const cFCOSpecImpl& rhs) : iFCOSpec(), mpHelper(0) { *this = rhs; -#ifdef _DEBUG +#ifdef DEBUG ++gFCOSpecImplCreated; cDebug d("cFCOSpecImpl::cFCOSpecImpl()"); d.TraceDetail("Allocated cFCOSpecImpl(%p) creat=%d dest=%d\n", this, gFCOSpecImplCreated, gFCOSpecImplDestroyed); @@ -86,7 +79,7 @@ cFCOSpecImpl::cFCOSpecImpl(const cFCOSpecImpl& rhs) : cFCOSpecImpl::~cFCOSpecImpl() { -#ifdef _DEBUG +#ifdef DEBUG ++gFCOSpecImplDestroyed; cDebug d("cFCOSpecImpl::cFCOSpecImpl()"); d.TraceDetail("Deleted cFCOSpecImpl(%p) creat=%d dest=%d\n", this, gFCOSpecImplCreated, gFCOSpecImplDestroyed); @@ -100,11 +93,13 @@ IMPLEMENT_SERREFCOUNT(cFCOSpecImpl, _T("cFCOSpecImpl"), 0, 1); /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -void cFCOSpecImpl::operator=(const cFCOSpecImpl& rhs) +cFCOSpecImpl& cFCOSpecImpl::operator=(const cFCOSpecImpl& rhs) { - mName = rhs.mName; - mPropVector = rhs.mPropVector; - mpHelper = rhs.mpHelper ? rhs.mpHelper->Clone() : 0; + mName = rhs.mName; + mPropVector = rhs.mPropVector; + mpHelper = rhs.mpHelper ? rhs.mpHelper->Clone() : 0; + + return *this; } /////////////////////////////////////////////////////////////////////////////// // Clone -- make a copy of this spec @@ -112,7 +107,7 @@ void cFCOSpecImpl::operator=(const cFCOSpecImpl& rhs) iFCOSpec* cFCOSpecImpl::Clone() const { cFCOSpecImpl* pNewSpec = new cFCOSpecImpl(mName); - *pNewSpec = *this; + *pNewSpec = *this; return pNewSpec; } @@ -121,22 +116,22 @@ iFCOSpec* cFCOSpecImpl::Clone() const /////////////////////////////////////////////////////////////////////////////// void cFCOSpecImpl::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; cDebug d("cFCOSpecImpl::TraceContents"); d.Trace(dl, _T("FCOSpecImpl :\t%s\n"), mName.c_str()); mPropVector.TraceContents(dl); - if(mpHelper) + if (mpHelper) mpHelper->TraceContents(dl); else - d.Trace(dl, _T("\n") ); + d.Trace(dl, _T("\n")); // NOTE -- tracing out the data source associated with this spec has no // real value -- mdb } -const TSTRING& cFCOSpecImpl::GetName() const +const TSTRING& cFCOSpecImpl::GetName() const { return mName; } @@ -146,13 +141,13 @@ void cFCOSpecImpl::SetName(const TSTRING& name) mName = name; } -const cFCOName& cFCOSpecImpl::GetStartPoint() const +const cFCOName& cFCOSpecImpl::GetStartPoint() const { ASSERT(mpHelper != 0); return mpHelper->GetStartPoint(); } -void cFCOSpecImpl::SetStartPoint (const cFCOName& name) +void cFCOSpecImpl::SetStartPoint(const cFCOName& name) { cDebug d("cFCOSpecImpl::SetStartPoint"); @@ -160,7 +155,7 @@ void cFCOSpecImpl::SetStartPoint (const cFCOName& name) mpHelper->SetStartPoint(name); } -const cFCOPropVector& cFCOSpecImpl::GetPropVector(const iFCOSpecMask* pFCOSpecMask) const +const cFCOPropVector& cFCOSpecImpl::GetPropVector(const iFCOSpecMask* pFCOSpecMask) const { // NOTE: for now, there will only be one property vector associated with a given specifier return mPropVector; @@ -169,14 +164,14 @@ const cFCOPropVector& cFCOSpecImpl::GetPropVector(const iFCOSpecMask* pFCOSpecMa bool cFCOSpecImpl::SetPropVector(const iFCOSpecMask* pMask, const cFCOPropVector& vector) { // for now, the default mask is the only mask the spec has. - if(pMask != iFCOSpecMask::GetDefaultMask()) + if (pMask != iFCOSpecMask::GetDefaultMask()) return false; mPropVector = vector; return true; } -const iFCOSpecMask* cFCOSpecImpl::GetSpecMask(const iFCO* pFCO) const +const iFCOSpecMask* cFCOSpecImpl::GetSpecMask(const iFCO* pFCO) const { // for now, I will just return the default property mask return iFCOSpecMask::GetDefaultMask(); @@ -211,17 +206,15 @@ void cFCOSpecImpl::Write(iSerializer* pSerializer) const bool cFCOSpecImpl::SpecContainsFCO(const cFCOName& name) const { ASSERT(mpHelper != 0); - + return mpHelper->ContainsFCO(name); } /////////////////////////////////////////////////////////////////////////////// // ShouldStopDescent /////////////////////////////////////////////////////////////////////////////// -bool cFCOSpecImpl::ShouldStopDescent( const cFCOName& name ) const +bool cFCOSpecImpl::ShouldStopDescent(const cFCOName& name) const { ASSERT(mpHelper != 0); - return mpHelper->ShouldStopDescent( name ); + return mpHelper->ShouldStopDescent(name); } - - diff --git a/src/fco/fcospecimpl.h b/src/fco/fcospecimpl.h index 17cd308..c3f4eea 100644 --- a/src/fco/fcospecimpl.h +++ b/src/fco/fcospecimpl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,48 +60,47 @@ class cFCOSpecImpl : public iFCOSpec { DECLARE_SERREFCOUNT() public: - // TODO -- remove the iFCODataSource from the ctor; I am doing nothing with it right now and + // TODO -- remove the iFCODataSource from the ctor; I am doing nothing with it right now and // didn't change it simply because I don't want to touch 1000 files updateing the creation // parameters... 28 jan mdb // - cFCOSpecImpl(const TSTRING& name, /* const iFCODataSource* */ void* pSrc = 0, iFCOSpecHelper* pHelper = NULL); - // the spec will delegate fco creation to pSrc as needed. It is OK to pass NULL as the data - // source, but it must be set before this spec can be used. - // the spec will delete whatever helper it contains when it is destroyed + cFCOSpecImpl(const TSTRING& name, /* const iFCODataSource* */ void* pSrc = 0, iFCOSpecHelper* pHelper = NULL); + // the spec will delegate fco creation to pSrc as needed. It is OK to pass NULL as the data + // source, but it must be set before this spec can be used. + // the spec will delete whatever helper it contains when it is destroyed cFCOSpecImpl(const cFCOSpecImpl& rhs); cFCOSpecImpl(); - void operator=(const cFCOSpecImpl& rhs); + cFCOSpecImpl& operator=(const cFCOSpecImpl& rhs); // from iFCOSpec - virtual bool SpecContainsFCO (const cFCOName& name) const; - virtual const TSTRING& GetName () const ; - virtual void SetName (const TSTRING& name); - virtual iFCOSpec* Clone () const; - virtual const cFCOName& GetStartPoint () const ; - virtual void SetStartPoint (const cFCOName& name) ; // throw (eError); - virtual const cFCOPropVector& GetPropVector (const iFCOSpecMask* pFCOSpecMask) const ; - virtual bool SetPropVector (const iFCOSpecMask* pMask, const cFCOPropVector& vector); - virtual const iFCOSpecMask* GetSpecMask (const iFCO* pFCO) const ; - virtual void TraceContents (int dl = -1) const; - virtual bool ShouldStopDescent( const cFCOName& name ) const ; + virtual bool SpecContainsFCO(const cFCOName& name) const; + virtual const TSTRING& GetName() const; + virtual void SetName(const TSTRING& name); + virtual iFCOSpec* Clone() const; + virtual const cFCOName& GetStartPoint() const; + virtual void SetStartPoint(const cFCOName& name); // throw (eError); + virtual const cFCOPropVector& GetPropVector(const iFCOSpecMask* pFCOSpecMask) const; + virtual bool SetPropVector(const iFCOSpecMask* pMask, const cFCOPropVector& vector); + virtual const iFCOSpecMask* GetSpecMask(const iFCO* pFCO) const; + virtual void TraceContents(int dl = -1) const; + virtual bool ShouldStopDescent(const cFCOName& name) const; - virtual void SetHelper(iFCOSpecHelper* pHelper); - virtual const iFCOSpecHelper* GetHelper() const; - // helper manipulation; note that the spec will delete whatever helper it contains when it is destroyed, - // but it will not delete the current helper when SetHelper() is called. + virtual void SetHelper(iFCOSpecHelper* pHelper); + virtual const iFCOSpecHelper* GetHelper() const; + // helper manipulation; note that the spec will delete whatever helper it contains when it is destroyed, + // but it will not delete the current helper when SetHelper() is called. // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual ~cFCOSpecImpl(); - // only destroy with Release(). Don't create on the stack. + // only destroy with Release(). Don't create on the stack. private: - - TSTRING mName; - cFCOPropVector mPropVector; - iFCOSpecHelper* mpHelper; + TSTRING mName; + cFCOPropVector mPropVector; + iFCOSpecHelper* mpHelper; }; //############################################################################# @@ -120,4 +119,3 @@ inline const iFCOSpecHelper* cFCOSpecImpl::GetHelper() const #endif //__FCOSPECIMPL_H - diff --git a/src/fco/fcospeclist.cpp b/src/fco/fcospeclist.cpp index 1c1d971..583294b 100644 --- a/src/fco/fcospeclist.cpp +++ b/src/fco/fcospeclist.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -61,7 +61,7 @@ void cFCOSpecList::Clear() { std::list::iterator itr; - for (itr = mAddedList.begin(); itr != mAddedList.end(); itr++) + for (itr = mAddedList.begin(); itr != mAddedList.end(); ++itr) { itr->first->Release(); itr->second->Release(); @@ -81,7 +81,7 @@ int cFCOSpecList::Size() const return mAddedList.size(); } -const cFCOSpecList& cFCOSpecList::operator = (const cFCOSpecList& rhs) +const cFCOSpecList& cFCOSpecList::operator=(const cFCOSpecList& rhs) { Clear(); @@ -99,14 +99,13 @@ void cFCOSpecList::Add(iFCOSpec* pSpec, cFCOSpecAttr* pAttr) { std::list::iterator itr; pSpec->AddRef(); - if(pAttr == 0) + if (pAttr == 0) pAttr = new cFCOSpecAttr; else pAttr->AddRef(); - for (itr = mCanonicalList.begin(); ; ++itr) + for (itr = mCanonicalList.begin();; ++itr) { - if (itr == mCanonicalList.end() || - iFCOSpecUtil::FCOSpecLessThan(*pSpec, *itr->first)) + if (itr == mCanonicalList.end() || iFCOSpecUtil::FCOSpecLessThan(*pSpec, *itr->first)) { mCanonicalList.insert(itr, PairType(pSpec, pAttr)); mAddedList.push_back(PairType(pSpec, pAttr)); @@ -142,14 +141,14 @@ void cFCOSpecList::Read(iSerializer* pSerializer, int32 version) Clear(); - int i; + int i; int32 size; pSerializer->ReadInt32(size); for (i = 0; i < size; ++i) { - iFCOSpec* pReadInSpec = static_cast (pSerializer->ReadObjectDynCreate()); - cFCOSpecAttr* pSpecAttr = static_cast(pSerializer->ReadObjectDynCreate()); + iFCOSpec* pReadInSpec = static_cast(pSerializer->ReadObjectDynCreate()); + cFCOSpecAttr* pSpecAttr = static_cast(pSerializer->ReadObjectDynCreate()); Add(pReadInSpec, pSpecAttr); pReadInSpec->Release(); // Add() will increase the ref count by 1 pSpecAttr->Release(); @@ -176,7 +175,7 @@ void cFCOSpecList::Write(iSerializer* pSerializer) const cFCOSpecListAddedIter::cFCOSpecListAddedIter(const cFCOSpecList& list) { mpSpecList = (cFCOSpecList*)&list; - mIter = mpSpecList->mAddedList.begin(); + mIter = mpSpecList->mAddedList.begin(); } cFCOSpecListAddedIter::~cFCOSpecListAddedIter() @@ -212,7 +211,7 @@ iFCOSpec* cFCOSpecListAddedIter::Spec() { return mIter->first; } -const cFCOSpecAttr* cFCOSpecListAddedIter::Attr() const +const cFCOSpecAttr* cFCOSpecListAddedIter::Attr() const { return mIter->second; } @@ -223,13 +222,13 @@ cFCOSpecAttr* cFCOSpecListAddedIter::Attr() void cFCOSpecListAddedIter::Remove() { - ASSERT(! Done()); + ASSERT(!Done()); // the tricky part is finding the spec in the other list... std::list::iterator i; - for(i = mpSpecList->mCanonicalList.begin(); i != mpSpecList->mCanonicalList.end(); i++) + for (i = mpSpecList->mCanonicalList.begin(); i != mpSpecList->mCanonicalList.end(); ++i) { - if(i->first == mIter->first) + if (i->first == mIter->first) break; } ASSERT(i != mpSpecList->mCanonicalList.end()); @@ -248,7 +247,7 @@ void cFCOSpecListAddedIter::Remove() cFCOSpecListCanonicalIter::cFCOSpecListCanonicalIter(const cFCOSpecList& list) { mpSpecList = (cFCOSpecList*)&list; - mIter = mpSpecList->mCanonicalList.begin(); + mIter = mpSpecList->mCanonicalList.begin(); } cFCOSpecListCanonicalIter::~cFCOSpecListCanonicalIter() @@ -284,7 +283,7 @@ iFCOSpec* cFCOSpecListCanonicalIter::Spec() { return mIter->first; } -const cFCOSpecAttr* cFCOSpecListCanonicalIter::Attr() const +const cFCOSpecAttr* cFCOSpecListCanonicalIter::Attr() const { return mIter->second; } @@ -292,4 +291,3 @@ cFCOSpecAttr* cFCOSpecListCanonicalIter::Attr() { return mIter->second; } - diff --git a/src/fco/fcospeclist.h b/src/fco/fcospeclist.h index a7beff2..dee5fa4 100644 --- a/src/fco/fcospeclist.h +++ b/src/fco/fcospeclist.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,7 +39,7 @@ #ifndef __FCOSPEC_H #include "fcospec.h" -#endif +#endif #ifndef __SERIALIZABLE_H #include "serializable.h" #endif @@ -53,7 +53,7 @@ // and preservation of order of addition of items. The optimized lookup // is useful because we will want to look up specs quickly. Preserving // the order in which items were added is useful because we will use -// cFCOSpecList's in the report and database were we wish to use the +// cFCOSpecList's in the report and database were we wish to use the // added order of the list to match to other lists. /////////////////////////////////////////////////////////////////////////////// @@ -63,65 +63,66 @@ class cFCOSpecList : public iTypedSerializable friend class cFCOSpecListCanonicalIter; friend class cFCOSpecListAddedIter; + public: cFCOSpecList(); cFCOSpecList(const cFCOSpecList& rhs); virtual ~cFCOSpecList(); - const cFCOSpecList& operator = (const cFCOSpecList& rhs); + const cFCOSpecList& operator=(const cFCOSpecList& rhs); + + void Clear(); + // Clear the list of specs, deleting them all + + bool IsEmpty() const; + int Size() const; - void Clear(); - // Clear the list of specs, deleting them all - - bool IsEmpty() const; - int Size() const; - - void Add(iFCOSpec* pSpec, cFCOSpecAttr* pAttr = 0); - // Add iFCOSpec to list. The objects will be AddRef()ed by the list - // and Release()d on destruction. If pAttr == NULL, then an empty - // attribute list will be created and associated with the spec. + void Add(iFCOSpec* pSpec, cFCOSpecAttr* pAttr = 0); + // Add iFCOSpec to list. The objects will be AddRef()ed by the list + // and Release()d on destruction. If pAttr == NULL, then an empty + // attribute list will be created and associated with the spec. iFCOSpec* Lookup(iFCOSpec* pSpec) const; - // Search the list a spec that matches pSpec. This search is fairly - // low cost if pSpec points to an actual spec in this list. Otherwise - // string compares must be done to determine the result. Returns - // NULL if it is NOT in the list, otherwise a pointer to the object in - // this list that matches pSpec. Either way, if non-null is returned, the - // object was AddRef()ed + // Search the list a spec that matches pSpec. This search is fairly + // low cost if pSpec points to an actual spec in this list. Otherwise + // string compares must be done to determine the result. Returns + // NULL if it is NOT in the list, otherwise a pointer to the object in + // this list that matches pSpec. Either way, if non-null is returned, the + // object was AddRef()ed // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: typedef std::pair PairType; - mutable std::list mAddedList; // list in added order + mutable std::list mAddedList; // list in added order mutable std::list mCanonicalList; // list in well defined order }; class cFCOSpecListAddedIter { public: - cFCOSpecListAddedIter(const cFCOSpecList& list); + explicit cFCOSpecListAddedIter(const cFCOSpecList& list); ~cFCOSpecListAddedIter(); - void SeekBegin() const; - bool Done() const; - bool IsEmpty() const; - void Next() const; - void Remove(); - // removes the node the iterator is currently pointing at. - // asserts !Done() and moves the iterator to the next node, - // or to the end if it is the last node. - - const iFCOSpec* Spec() const; - iFCOSpec* Spec(); - const cFCOSpecAttr* Attr() const; - cFCOSpecAttr* Attr(); + void SeekBegin() const; + bool Done() const; + bool IsEmpty() const; + void Next() const; + void Remove(); + // removes the node the iterator is currently pointing at. + // asserts !Done() and moves the iterator to the next node, + // or to the end if it is the last node. + + const iFCOSpec* Spec() const; + iFCOSpec* Spec(); + const cFCOSpecAttr* Attr() const; + cFCOSpecAttr* Attr(); protected: - cFCOSpecList* mpSpecList; + cFCOSpecList* mpSpecList; mutable std::list::iterator mIter; }; @@ -129,32 +130,30 @@ class cFCOSpecListAddedIter class cFCOSpecListCanonicalIter { public: - cFCOSpecListCanonicalIter(const cFCOSpecList& list); + explicit cFCOSpecListCanonicalIter(const cFCOSpecList& list); ~cFCOSpecListCanonicalIter(); - void SeekBegin() const; - bool Done() const; - bool IsEmpty() const; - void Next() const; + void SeekBegin() const; + bool Done() const; + bool IsEmpty() const; + void Next() const; //void Remove(); - // TODO --implement this the same as Remove() in the - // added iter. - const iFCOSpec* Spec() const; - iFCOSpec* Spec(); - const cFCOSpecAttr* Attr() const; - cFCOSpecAttr* Attr(); + // TODO --implement this the same as Remove() in the + // added iter. + const iFCOSpec* Spec() const; + iFCOSpec* Spec(); + const cFCOSpecAttr* Attr() const; + cFCOSpecAttr* Attr(); protected: - cFCOSpecList* mpSpecList; + cFCOSpecList* mpSpecList; mutable std::list::iterator mIter; }; -inline cFCOSpecList::cFCOSpecList(const cFCOSpecList& rhs) - : iTypedSerializable() +inline cFCOSpecList::cFCOSpecList(const cFCOSpecList& rhs) : iTypedSerializable() { *this = rhs; } #endif //__FCOSPEC_H - diff --git a/src/fco/fcospecutil.cpp b/src/fco/fcospecutil.cpp index 293e721..b63059b 100644 --- a/src/fco/fcospecutil.cpp +++ b/src/fco/fcospecutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -54,5 +54,3 @@ bool iFCOSpecUtil::FCOSpecLessThan(const iFCOSpec& lhs, const iFCOSpec& rhs) // TODO -- this doesn't take spec masks into account! return (lhs.GetHelper()->Compare(rhs.GetHelper()) == iFCOSpecHelper::CMP_LT); } - - diff --git a/src/fco/fcospecutil.h b/src/fco/fcospecutil.h index 0f2f236..d18acad 100644 --- a/src/fco/fcospecutil.h +++ b/src/fco/fcospecutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,31 +46,29 @@ class iFCOSpecUtil { public: static bool FCOSpecEqual(const iFCOSpec& lhs, const iFCOSpec& rhs); - // Checks that the start point and all stop points are equal. - // Note: This may not make sense if the FCO spacs are of differing types, but in - // the name of simple implementation we define this as equality. + // Checks that the start point and all stop points are equal. + // Note: This may not make sense if the FCO spacs are of differing types, but in + // the name of simple implementation we define this as equality. static bool FCOSpecLessThan(const iFCOSpec& lhs, const iFCOSpec& rhs); - // Defines an order of FCOSpecs. A FCOSpec is less than another if and only if - // the string concatination of start point and an ordered list of stop point - // are less than the other. + // Defines an order of FCOSpecs. A FCOSpec is less than another if and only if + // the string concatination of start point and an ordered list of stop point + // are less than the other. static bool SpecsOverlap(const iFCOSpec* pSpec1, const iFCOSpec* pSpec2); - // returns true if the specs "overlap", meaning there exists an fco which is contained - // in both specs. This is true if one specs's start point is contained in the other spec. + // returns true if the specs "overlap", meaning there exists an fco which is contained + // in both specs. This is true if one specs's start point is contained in the other spec. }; /////////////////////////////////////////////////////////////////////////////// // inline implementation /////////////////////////////////////////////////////////////////////////////// -// SpecsOverlap -- returns true if one of the specs contains the other's +// SpecsOverlap -- returns true if one of the specs contains the other's // start point /////////////////////////////////////////////////////////////////////////////// inline bool iFCOSpecUtil::SpecsOverlap(const iFCOSpec* pSpec1, const iFCOSpec* pSpec2) { - return (pSpec1->SpecContainsFCO(pSpec2->GetStartPoint()) || - pSpec2->SpecContainsFCO(pSpec1->GetStartPoint())); + return (pSpec1->SpecContainsFCO(pSpec2->GetStartPoint()) || pSpec2->SpecContainsFCO(pSpec1->GetStartPoint())); } #endif - diff --git a/src/fco/fcostrings.cpp b/src/fco/fcostrings.cpp index 369f528..97aff32 100644 --- a/src/fco/fcostrings.cpp +++ b/src/fco/fcostrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,17 +40,12 @@ #include "fcostrings.h" -TSS_BeginStringtable( cFCO ) - - TSS_StringEntry( fco::STR_GENRE_FS, _T("FS") ), - TSS_StringEntry( fco::STR_GENRE_NTFS, _T("NTFS") ), - TSS_StringEntry( fco::STR_GENRE_NTREG, _T("NTReg") ), - TSS_StringEntry( fco::STR_GENRE_FS_V, _T("Unix File System") ), - TSS_StringEntry( fco::STR_GENRE_NTFS_V, _T("Windows NT File System") ), - TSS_StringEntry( fco::STR_GENRE_NTREG_V, _T("Windows NT Registry") ), - TSS_StringEntry( fco::STR_UNDEFINED, _T("n/a") ), - -TSS_EndStringtable( cFCO ) +TSS_BeginStringtable(cFCO) + TSS_StringEntry(fco::STR_GENRE_FS, _T("FS")), + TSS_StringEntry(fco::STR_GENRE_NTFS, _T("NTFS")), TSS_StringEntry(fco::STR_GENRE_NTREG, _T("NTReg")), + TSS_StringEntry(fco::STR_GENRE_FS_V, _T("Unix File System")), + TSS_StringEntry(fco::STR_GENRE_NTFS_V, _T("Windows NT File System")), + TSS_StringEntry(fco::STR_GENRE_NTREG_V, _T("Windows NT Registry")), TSS_StringEntry(fco::STR_UNDEFINED, _T("n/a")), -// eof: fcostrings.cpp + TSS_EndStringtable(cFCO) diff --git a/src/fco/fcostrings.h b/src/fco/fcostrings.h index 30683c0..add5987 100644 --- a/src/fco/fcostrings.h +++ b/src/fco/fcostrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,17 +40,12 @@ #include "fco.h" -TSS_BeginStringIds( fco ) - +TSS_BeginStringIds(fco) + STR_GENRE_FS, - STR_GENRE_NTFS, - STR_GENRE_NTREG, - STR_GENRE_FS_V, - STR_GENRE_NTFS_V, - STR_GENRE_NTREG_V, + STR_GENRE_NTFS, STR_GENRE_NTREG, STR_GENRE_FS_V, STR_GENRE_NTFS_V, STR_GENRE_NTREG_V, STR_UNDEFINED -TSS_EndStringIds( fco ) + TSS_EndStringIds(fco) #endif //__FCOSTRINGS_H - diff --git a/src/fco/fcoundefprop.cpp b/src/fco/fcoundefprop.cpp index 2de785f..bba0c8c 100644 --- a/src/fco/fcoundefprop.cpp +++ b/src/fco/fcoundefprop.cpp @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // // Name....: fcoundefprop.cpp // Date....: 05/07/99 -// Creator.: +// Creator.: // // The undefined FCO property // @@ -45,12 +45,11 @@ //============================================================================= // cFCOUndefinedProp // -// This class exists only as a singleton. iFCOPropSet derived classes will return a +// This class exists only as a singleton. iFCOPropSet derived classes will return a // pointer to the singleton for properties that are undefined. //============================================================================= -IMPLEMENT_TYPEDSERIALIZABLE( - cFCOUndefinedProp, _T( "cFCOUndefinedProp" ), 0, 1 ); +IMPLEMENT_TYPEDSERIALIZABLE(cFCOUndefinedProp, _T( "cFCOUndefinedProp" ), 0, 1); ////////////////////////////////////////////////////////////////////////////// // Singleton interface @@ -75,45 +74,36 @@ cFCOUndefinedProp::cFCOUndefinedProp() { } -cFCOUndefinedProp::~cFCOUndefinedProp() +cFCOUndefinedProp::~cFCOUndefinedProp() { } TSTRING cFCOUndefinedProp::AsString() const { - return TSS_GetString( cFCO, fco::STR_UNDEFINED ); + return TSS_GetString(cFCO, fco::STR_UNDEFINED); } -iFCOProp::CmpResult -cFCOUndefinedProp::Compare( const iFCOProp* rhs, iFCOProp::Op op ) const +iFCOProp::CmpResult cFCOUndefinedProp::Compare(const iFCOProp* rhs, iFCOProp::Op op) const { - if ( op == iFCOProp::OP_GT || - op == iFCOProp::OP_LT || - op == iFCOProp::OP_GE || - op == iFCOProp::OP_LE ) + if (op == iFCOProp::OP_GT || op == iFCOProp::OP_LT || op == iFCOProp::OP_GE || op == iFCOProp::OP_LE) { // It is not very well-defined what we should do if you are testing inequality - // on an undefined property. In 2.1 we never compare inequality so this should + // on an undefined property. In 2.1 we never compare inequality so this should // not happen. This changes some code will need to be re-written. - ASSERTMSG( - false, - "cFCOUndefinedProp does not support >, <, >=, or <= compares!" ); + ASSERTMSG(false, "cFCOUndefinedProp does not support >, <, >=, or <= compares!"); return iFCOProp::CMP_UNSUPPORTED; } - ASSERT( op == iFCOProp::OP_EQ || op == iFCOProp::OP_NE ); + ASSERT(op == iFCOProp::OP_EQ || op == iFCOProp::OP_NE); - if ( rhs->GetType() != GetType() ) + if (rhs->GetType() != GetType()) { // undefined prop is unequal to all other props - return - ( op == iFCOProp::OP_EQ ) - ? iFCOProp::CMP_FALSE - : iFCOProp::CMP_TRUE; + return (op == iFCOProp::OP_EQ) ? iFCOProp::CMP_FALSE : iFCOProp::CMP_TRUE; } - else if ( op == iFCOProp::OP_EQ ) + else if (op == iFCOProp::OP_EQ) { return iFCOProp::CMP_TRUE; } @@ -125,17 +115,15 @@ cFCOUndefinedProp::Compare( const iFCOProp* rhs, iFCOProp::Op op ) const void cFCOUndefinedProp::Read(iSerializer* pSerializer, int32 version) { - ThrowAndAssert( INTERNAL_ERROR("fcoundefprop.cpp") ); + ThrowAndAssert(INTERNAL_ERROR("fcoundefprop.cpp")); } void cFCOUndefinedProp::Write(iSerializer* pSerializer) const { - ThrowAndAssert( INTERNAL_ERROR("fcoundefprop.cpp") ); + ThrowAndAssert(INTERNAL_ERROR("fcoundefprop.cpp")); } void cFCOUndefinedProp::Copy(const iFCOProp* rhs) { - ThrowAndAssert( INTERNAL_ERROR("fcoundefprop.cpp") ); + ThrowAndAssert(INTERNAL_ERROR("fcoundefprop.cpp")); } - -// eof: fcoundefprop.cpp diff --git a/src/fco/fcoundefprop.h b/src/fco/fcoundefprop.h index 1c94f28..1a3dbe6 100644 --- a/src/fco/fcoundefprop.h +++ b/src/fco/fcoundefprop.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,38 +42,35 @@ //============================================================================= // cFCOUndefinedProp // -// This class exists only as a singleton. iFCOPropSet derived classes will return a +// This class exists only as a singleton. iFCOPropSet derived classes will return a // pointer to the singleton for properties that are undefined. //============================================================================= class cFCOUndefinedProp : public iFCOProp { public: - DECLARE_TYPEDSERIALIZABLE() // type information + DECLARE_TYPEDSERIALIZABLE() // type information static cFCOUndefinedProp* GetInstance(); - // access to the singleton - + // access to the singleton + // from iFCOProp - virtual TSTRING AsString() const; + virtual TSTRING AsString() const; virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; - virtual void Copy(const iFCOProp* rhs); - -private: + virtual void Copy(const iFCOProp* rhs); +private: friend struct cFCOUndefinedPropProxy; cFCOUndefinedProp(); virtual ~cFCOUndefinedProp(); - // don't new or construct these on the stack + // don't new or construct these on the stack // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eInternal) - virtual void Write(iSerializer* pSerializer) const; // throw (eInternal) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eInternal) + virtual void Write(iSerializer* pSerializer) const; // throw (eInternal) // These functions should never be called, and they will throw and eInternal if they are. }; - #endif // __FCOUNDEFPROP_H - diff --git a/src/fco/fcovisitor.h b/src/fco/fcovisitor.h index 3977e50..8c38410 100644 --- a/src/fco/fcovisitor.h +++ b/src/fco/fcovisitor.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // fcovisitor.h // -// iFCOVisitor -- top-level visitor interface. Right now, this only contains +// iFCOVisitor -- top-level visitor interface. Right now, this only contains // GetGenre(), which returns the visitor's type #ifndef __FCOVISITOR_H #define __FCOVISITOR_H @@ -42,7 +42,7 @@ #endif /////////////////////////////////////////////////////////////////////////////// -// IMPORTANT! -- Note that although the concept of "genre" is the same as in the +// IMPORTANT! -- Note that although the concept of "genre" is the same as in the // design document, a genre seems to be fundamentally equivalent to a cType // as defined in typed.h. Therefore, the elements in the visitor pattern will // do their safe cast based on the visitor's iTyped interface. @@ -50,11 +50,10 @@ class iFCOVisitor : public iTyped { public: - // it is sad to note that without genres, iFCOVisitor now has _nothing_! ... + // it is sad to note that without genres, iFCOVisitor now has _nothing_! ... // never a good sign -mdb protected: - virtual ~iFCOVisitor() {}; + virtual ~iFCOVisitor(){}; }; #endif - diff --git a/src/fco/genreinfo.cpp b/src/fco/genreinfo.cpp index 10594d5..da525e2 100644 --- a/src/fco/genreinfo.cpp +++ b/src/fco/genreinfo.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,13 +40,10 @@ #include "genreinfo.h" // after registering, cGenreInfo will own the iTWFactory* -cGenreInfo::cGenreInfo( cGenre::Genre id, const TSTRING& sSN, const TSTRING& sLN, iTWFactory* pF ) - : m_ID( id ), - m_sShortName( sSN ), - m_sLongName( sLN ), - m_pFactory( pF ) +cGenreInfo::cGenreInfo(cGenre::Genre id, const TSTRING& sSN, const TSTRING& sLN, iTWFactory* pF) + : m_ID(id), m_sShortName(sSN), m_sLongName(sLN), m_pFactory(pF) { - ASSERT( IsValid() ); + ASSERT(IsValid()); } cGenreInfo::~cGenreInfo() @@ -55,14 +52,6 @@ cGenreInfo::~cGenreInfo() bool cGenreInfo::IsValid() const { - return( - ( m_ID != cGenre::GENRE_INVALID ) - && - ( m_pFactory != NULL ) - && - ( ! m_sShortName.empty() ) - && - ( ! m_sLongName.empty() ) - ); + return ((m_ID != cGenre::GENRE_INVALID) && (m_pFactory != NULL) && (!m_sShortName.empty()) && + (!m_sLongName.empty())); } - diff --git a/src/fco/genreinfo.h b/src/fco/genreinfo.h index a2024e7..c38d689 100644 --- a/src/fco/genreinfo.h +++ b/src/fco/genreinfo.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -57,27 +57,26 @@ //========================================================================= // -// GenreInfo -- contains all info about genres except +// GenreInfo -- contains all info about genres except // for whether or not it is the default genre for the system // class cGenreInfo { public: - cGenreInfo( cGenre::Genre id, const TSTRING& sSN, const TSTRING& sLN, iTWFactory* pF ); - // after registering, cGenreInfo will own the iTWFactory* + cGenreInfo(cGenre::Genre id, const TSTRING& sSN, const TSTRING& sLN, iTWFactory* pF); + // after registering, cGenreInfo will own the iTWFactory* virtual ~cGenreInfo(); - bool IsValid() const; - // makes sure all fields have valid values + bool IsValid() const; + // makes sure all fields have valid values // // data members // - cGenre::Genre m_ID; - TSTRING m_sShortName; - TSTRING m_sLongName; - iTWFactory* m_pFactory; + cGenre::Genre m_ID; + TSTRING m_sShortName; + TSTRING m_sLongName; + iTWFactory* m_pFactory; }; #endif //__GENREINFO_H - diff --git a/src/fco/genrespeclist.cpp b/src/fco/genrespeclist.cpp index 17f2b49..2e78054 100644 --- a/src/fco/genrespeclist.cpp +++ b/src/fco/genrespeclist.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,9 +49,9 @@ cGenreSpecListPair::~cGenreSpecListPair() { } -cGenreSpecListPair& cGenreSpecListPair::operator = (const cGenreSpecListPair& rhs) +cGenreSpecListPair& cGenreSpecListPair::operator=(const cGenreSpecListPair& rhs) { - mGenre = rhs.mGenre; + mGenre = rhs.mGenre; mSpecList = rhs.mSpecList; return *this; } @@ -80,13 +80,11 @@ void cGenreSpecListPair::SetSpecList(const cFCOSpecList& speclist) // class cGenreSpecListVector //============================================================================= -cGenreSpecListVector::cGenreSpecListVector() - : std::vector() +cGenreSpecListVector::cGenreSpecListVector() : std::vector() { } -cGenreSpecListVector::cGenreSpecListVector(const cGenreSpecListVector& rhs) - : std::vector() +cGenreSpecListVector::cGenreSpecListVector(const cGenreSpecListVector& rhs) : std::vector() { *this = rhs; } @@ -95,10 +93,8 @@ cGenreSpecListVector::~cGenreSpecListVector() { } -cGenreSpecListVector& cGenreSpecListVector::operator = (const cGenreSpecListVector& rhs) +cGenreSpecListVector& cGenreSpecListVector::operator=(const cGenreSpecListVector& rhs) { - ((std::vector*)this)->operator = (rhs); + ((std::vector*)this)->operator=(rhs); return *this; } - - diff --git a/src/fco/genrespeclist.h b/src/fco/genrespeclist.h index da1e646..38d8ca1 100644 --- a/src/fco/genrespeclist.h +++ b/src/fco/genrespeclist.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -61,17 +61,17 @@ class cGenreSpecListPair cGenreSpecListPair(const cGenreSpecListPair& rhs); ~cGenreSpecListPair(); - cGenreSpecListPair& operator = (const cGenreSpecListPair& rhs); + cGenreSpecListPair& operator=(const cGenreSpecListPair& rhs); - cGenre::Genre GetGenre() const; - cFCOSpecList& GetSpecList(); + cGenre::Genre GetGenre() const; + cFCOSpecList& GetSpecList(); - void SetGenre(cGenre::Genre genre); - void SetSpecList(const cFCOSpecList& speclist); + void SetGenre(cGenre::Genre genre); + void SetSpecList(const cFCOSpecList& speclist); private: - cGenre::Genre mGenre; - cFCOSpecList mSpecList; + cGenre::Genre mGenre; + cFCOSpecList mSpecList; }; inline cGenreSpecListPair::cGenreSpecListPair(const cGenreSpecListPair& rhs) @@ -90,8 +90,7 @@ class cGenreSpecListVector : public std::vector cGenreSpecListVector(const cGenreSpecListVector& rhs); ~cGenreSpecListVector(); - cGenreSpecListVector& operator = (const cGenreSpecListVector& rhs); + cGenreSpecListVector& operator=(const cGenreSpecListVector& rhs); }; #endif - diff --git a/src/fco/genreswitcher.cpp b/src/fco/genreswitcher.cpp index 594c26a..f621e41 100644 --- a/src/fco/genreswitcher.cpp +++ b/src/fco/genreswitcher.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,6 +43,10 @@ #include "genreinfo.h" #include "core/errorutil.h" +#if HAVE_STRINGS_H // for strcasecmp on RTEMS +#include +#endif + //========================================================================= // STATIC MEMBERS //========================================================================= @@ -58,9 +62,7 @@ return &s_Instance; } -cGenreSwitcher::cGenreSwitcher() - : m_pDefaultGenre( NULL ), - m_curGenre( cGenre::GENRE_INVALID ) +cGenreSwitcher::cGenreSwitcher() : m_pDefaultGenre(NULL), m_curGenre(cGenre::GENRE_INVALID) { } @@ -70,9 +72,9 @@ cGenreSwitcher::~cGenreSwitcher() // set the current genre // thows an eError if newGenre is invalid -void cGenreSwitcher::SelectGenre( cGenre::Genre g ) +void cGenreSwitcher::SelectGenre(cGenre::Genre g) { - iTWFactory::SetFactory( GetFactoryForGenre( g ) ); + iTWFactory::SetFactory(GetFactoryForGenre(g)); m_curGenre = g; } @@ -85,47 +87,46 @@ cGenre::Genre cGenreSwitcher::GetDefaultGenre() { cGenre::Genre defGenre = cGenre::GENRE_INVALID; - if( m_pDefaultGenre != NULL ) + if (m_pDefaultGenre != NULL) defGenre = m_pDefaultGenre->m_ID; - - ASSERT( defGenre != cGenre::GENRE_INVALID ); + + ASSERT(defGenre != cGenre::GENRE_INVALID); return defGenre; } -void cGenreSwitcher::RegisterGenre( const cGenreInfo* pGI, RegisterFlags flags /* = REGISTER_FLAGS_NONE */ ) +void cGenreSwitcher::RegisterGenre(const cGenreInfo* pGI, RegisterFlags flags /* = REGISTER_FLAGS_NONE */) { cDebug d("cGenreSwitcher::RegisterGenre"); - d.TraceDebug( _T("ID: %x, long name: %s, short name: %s\n"), pGI->m_ID, pGI->m_sLongName.c_str(), pGI->m_sShortName.c_str() ); - // - // validate params - // - ASSERT( NULL != pGI ); - ASSERT( pGI->IsValid() ); + ASSERT(NULL != pGI); + ASSERT(pGI->IsValid()); + + d.TraceDebug( + _T("ID: %x, long name: %s, short name: %s\n"), pGI->m_ID, pGI->m_sLongName.c_str(), pGI->m_sShortName.c_str()); // // can only be one of each genre ID // - if( m_vGenres.find( pGI ) != m_vGenres.end() ) + if (m_vGenres.find(pGI) != m_vGenres.end()) { // TODO: correct behavior? Should this be allowable/ignored? - THROW_INTERNAL( "genreswitcher.cpp" ); // Attempt to register duplicate genre ID. + THROW_INTERNAL("genreswitcher.cpp"); // Attempt to register duplicate genre ID. } // // save genre info // - m_vGenres.push_back( pGI ); + m_vGenres.push_back(pGI); // // set default genre if appropriate // - if( flags & REGISTER_FLAGS_DEFAULT ) + if (flags & REGISTER_FLAGS_DEFAULT) { // can only be one default genre // TODO: should we allow more than one lib to vie for default genre on a platform? - if( NULL != m_pDefaultGenre ) - THROW_INTERNAL( "genreswitcher.cpp" ); // "Two genres claim default genre status." ); + if (NULL != m_pDefaultGenre) + THROW_INTERNAL("genreswitcher.cpp"); // "Two genres claim default genre status." ); // save as default genre m_pDefaultGenre = pGI; @@ -133,72 +134,67 @@ void cGenreSwitcher::RegisterGenre( const cGenreInfo* pGI, RegisterFlags flags / } -bool cGenreSwitcher::IsGenreRegistered( cGenre::Genre g ) +bool cGenreSwitcher::IsGenreRegistered(cGenre::Genre g) { - return( m_vGenres.find( g ) != m_vGenres.end() ); + return (m_vGenres.find(g) != m_vGenres.end()); } -bool cGenreSwitcher::IsGenreAppropriate( cGenre::Genre g ) +bool cGenreSwitcher::IsGenreAppropriate(cGenre::Genre g) { -#if IS_UNIX - const uint32 platformMask = cGenre::PLATFORM_MASK_UNIX; - #else - #error who am I? - #endif - - return( ( platformMask & g ) != 0 ); + const uint32 platformMask = cGenre::PLATFORM_MASK_UNIX; + return ((platformMask & g) != 0); } -iTWFactory* cGenreSwitcher::GetFactoryForGenre( cGenre::Genre g ) +iTWFactory* cGenreSwitcher::GetFactoryForGenre(cGenre::Genre g) { - cGenreInfoVec::const_iterator i = m_vGenres.find( g ); + cGenreInfoVec::const_iterator i = m_vGenres.find(g); - if( i == m_vGenres.end() ) + if (i == m_vGenres.end()) { - ThrowAndAssert( INTERNAL_ERROR( "Switch to invalid genre factory") ); + ThrowAndAssert(INTERNAL_ERROR("Switch to invalid genre factory")); } - - ASSERT( (*i)->m_pFactory != NULL ); - return( (*i)->m_pFactory ); + + ASSERT((*i)->m_pFactory != NULL); + return ((*i)->m_pFactory); } // Convert an enum to a string. Verbose flag specifies // whether to return "NTReg" or "NT Registry". -const TCHAR* cGenreSwitcher::GenreToString( cGenre::Genre g, bool verbose) +const TCHAR* cGenreSwitcher::GenreToString(cGenre::Genre g, bool verbose) { - cGenreInfoVec::const_iterator i = m_vGenres.find( g ); - if( i != m_vGenres.end() ) + cGenreInfoVec::const_iterator i = m_vGenres.find(g); + if (i != m_vGenres.end()) { - ASSERT( (*i)->m_ID != cGenre::GENRE_INVALID ); - return( verbose ? (*i)->m_sLongName.c_str() : (*i)->m_sShortName.c_str() ); + ASSERT((*i)->m_ID != cGenre::GENRE_INVALID); + return (verbose ? (*i)->m_sLongName.c_str() : (*i)->m_sShortName.c_str()); } // didn't recognize genre ID - ASSERT( false ); - return( NULL ); + ASSERT(false); + return (NULL); } -// Narrow and wide character conversions. These functions will be -// able to intelligently handle case sesitivity and verbose or narrow +// Narrow and wide character conversions. These functions will be +// able to intelligently handle case sesitivity and verbose or narrow // versions of the string. // GENRE_INVALID will be returned on error. -cGenre::Genre cGenreSwitcher::StringToGenre( const TCHAR* sz ) -{ +cGenre::Genre cGenreSwitcher::StringToGenre(const TCHAR* sz) +{ // must convert to TSTRING - TSTRING sGenre( sz ); + TSTRING sGenre(sz); - cGenreInfoVec::const_iterator i = m_vGenres.find( sGenre ); - if( i != m_vGenres.end() ) + cGenreInfoVec::const_iterator i = m_vGenres.find(sGenre); + if (i != m_vGenres.end()) { - return( (*i)->m_ID ); + return ((*i)->m_ID); } - return( cGenre::GENRE_INVALID ); + return (cGenre::GENRE_INVALID); } /* TODO: This is old code - dmb @@ -223,43 +219,41 @@ cGenre::Genre cGenreSwitcher::StringToGenre( const wchar_t* wsz ) // returns true if there is a cGenreInfo stored in _vGenres that has an ID which // matches this pGI's ID -cGenreInfoVec::const_iterator cGenreInfoVec::find( cGenre::Genre g ) const +cGenreInfoVec::const_iterator cGenreInfoVec::find(cGenre::Genre g) const { const_iterator i; - for( i = begin(); i != end(); i++ ) + for (i = begin(); i != end(); ++i) { - ASSERT( (*i)->m_ID != cGenre::GENRE_INVALID ); + ASSERT((*i)->m_ID != cGenre::GENRE_INVALID); - if( g == (*i)->m_ID ) + if (g == (*i)->m_ID) return i; } return i; } -cGenreInfoVec::const_iterator cGenreInfoVec::find( const cGenreInfo* pGI ) const +cGenreInfoVec::const_iterator cGenreInfoVec::find(const cGenreInfo* pGI) const { - ASSERT( NULL != pGI ); - return( find( pGI->m_ID ) ); + ASSERT(NULL != pGI); + return (find(pGI->m_ID)); } // sGenre can be either short or long name -cGenreInfoVec::const_iterator cGenreInfoVec::find( const TSTRING& sGenre ) const +cGenreInfoVec::const_iterator cGenreInfoVec::find(const TSTRING& sGenre) const { const_iterator i; - for( i = begin(); i != end(); i++ ) + for (i = begin(); i != end(); ++i) { - ASSERT( (*i)->m_ID != cGenre::GENRE_INVALID ); - + ASSERT((*i)->m_ID != cGenre::GENRE_INVALID); + // // compare against long and short name // - if (_tcsicmp(sGenre.c_str(), (*i)->m_sLongName.c_str()) == 0 || + if (_tcsicmp(sGenre.c_str(), (*i)->m_sLongName.c_str()) == 0 || _tcsicmp(sGenre.c_str(), (*i)->m_sShortName.c_str()) == 0) break; } - return( i ); + return (i); } - - diff --git a/src/fco/genreswitcher.h b/src/fco/genreswitcher.h index 121b56c..086eda9 100644 --- a/src/fco/genreswitcher.h +++ b/src/fco/genreswitcher.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -56,28 +56,28 @@ //------------------------------------------------- // -// class cGenreInfoVec -- +// class cGenreInfoVec -- // //------------------------------------------------- -class cGenreInfoVec : public std::vector< const cGenreInfo* > +class cGenreInfoVec : public std::vector { public: //------------------------------------------------------------- // Util Functions //------------------------------------------------------------- - const_iterator find( const cGenreInfo* pGI ) const; - // returns true if there is a cGenreInfo stored in m_vGenres that has an ID which - // matches this pGI's ID - const_iterator find( cGenre::Genre g ) const; - // finds by genre ID - const_iterator find( const TSTRING& sGenre ) const; - // finds both long and short names + const_iterator find(const cGenreInfo* pGI) const; + // returns true if there is a cGenreInfo stored in m_vGenres that has an ID which + // matches this pGI's ID + const_iterator find(cGenre::Genre g) const; + // finds by genre ID + const_iterator find(const TSTRING& sGenre) const; + // finds both long and short names }; //------------------------------------------------- // -// class cGenreSwitcher -- +// class cGenreSwitcher -- // //------------------------------------------------- @@ -87,75 +87,77 @@ class cGenreInfoVec : public std::vector< const cGenreInfo* > class cGenreSwitcher { public: - //------------------------------------------------------------- // Singleton Manipulation //------------------------------------------------------------- - static cGenreSwitcher* GetInstance(); + static cGenreSwitcher* GetInstance(); //------------------------------------------------------------- // Genre Selection //------------------------------------------------------------- - void SelectGenre(cGenre::Genre newGenre); - // set the current genre - // thows an eError if newGenre is invalid - - cGenre::Genre CurrentGenre(); - // returs the current genre, or cGenre::GENRE_INVALID if no genre - // has be selected since construction - - iTWFactory* GetFactoryForGenre( cGenre::Genre ); - // returns the tw factory appropriate for the given genre - // throws eError if genre is invalid. - - cGenre::Genre GetDefaultGenre(); - // returns ID of default registered genre - + void SelectGenre(cGenre::Genre newGenre); + // set the current genre + // thows an eError if newGenre is invalid + + cGenre::Genre CurrentGenre(); + // returs the current genre, or cGenre::GENRE_INVALID if no genre + // has be selected since construction + + iTWFactory* GetFactoryForGenre(cGenre::Genre); + // returns the tw factory appropriate for the given genre + // throws eError if genre is invalid. + + cGenre::Genre GetDefaultGenre(); + // returns ID of default registered genre + //------------------------------------------------------------- // Genre Checking //------------------------------------------------------------- - bool IsGenreAppropriate( cGenre::Genre g ); - // is this genre supposed to be used with this platform? - bool IsGenreRegistered( cGenre::Genre g ); - // is this genre recognized? + bool IsGenreAppropriate(cGenre::Genre g); + // is this genre supposed to be used with this platform? + bool IsGenreRegistered(cGenre::Genre g); + // is this genre recognized? //------------------------------------------------------------- // Genre Name/ID Conversion //------------------------------------------------------------- - const TCHAR* GenreToString( cGenre::Genre genre, bool verbose = false ); - // Convert an enum to a string. Verbose flag specifies - // whether to return "NTReg" or "NT Registry". - // NULL will be returned on error. + const TCHAR* GenreToString(cGenre::Genre genre, bool verbose = false); + // Convert an enum to a string. Verbose flag specifies + // whether to return "NTReg" or "NT Registry". + // NULL will be returned on error. - cGenre::Genre StringToGenre( const TCHAR* sz ); + cGenre::Genre StringToGenre(const TCHAR* sz); // TODO: remove this - dmb cGenre::Genre StringToGenre( const wchar_t* wsz ); - // Narrow and wide character conversions. These functions will be - // able to intelligently handle case sesitivity and verbose or narrow - // versions of the string. - // GENRE_INVALID will be returned on error. - + // Narrow and wide character conversions. These functions will be + // able to intelligently handle case sesitivity and verbose or narrow + // versions of the string. + // GENRE_INVALID will be returned on error. + //------------------------------------------------------------- // Genre Registration //------------------------------------------------------------- - enum RegisterFlags { REGISTER_FLAGS_NONE = 0x00, REGISTER_FLAGS_DEFAULT = 0x01 }; - void RegisterGenre( const cGenreInfo* pGI, RegisterFlags flags = REGISTER_FLAGS_NONE ); - // cGenreSwitcher does not own the cGenreInfo + enum RegisterFlags + { + REGISTER_FLAGS_NONE = 0x00, + REGISTER_FLAGS_DEFAULT = 0x01 + }; + void RegisterGenre(const cGenreInfo* pGI, RegisterFlags flags = REGISTER_FLAGS_NONE); + // cGenreSwitcher does not own the cGenreInfo + + ~cGenreSwitcher(); - ~cGenreSwitcher(); private: - //------------------------------------------------------------- // Ctor and Dtor -- only access to cGenreSwitcher is through GetInstance() //------------------------------------------------------------- cGenreSwitcher(); - + //------------------------------------------------------------- // Private Data Members //------------------------------------------------------------- - const cGenreInfo* m_pDefaultGenre; // points to the default registered genre - cGenreInfoVec m_vGenres; // stores all registered genre information - cGenre::Genre m_curGenre; // points to the current genre + const cGenreInfo* m_pDefaultGenre; // points to the default registered genre + cGenreInfoVec m_vGenres; // stores all registered genre information + cGenre::Genre m_curGenre; // points to the current genre }; #endif //__GENRESWITCHER_H - diff --git a/src/fco/iterproxy.h b/src/fco/iterproxy.h index 7743392..09a7c3b 100644 --- a/src/fco/iterproxy.h +++ b/src/fco/iterproxy.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // iterproxy.h -// +// // cIterProxy<> -- smart pointer for iterator classes used in tripwire. the // iterator must support being destroyed with a member function called // ReleaseIter() @@ -46,23 +46,42 @@ // mpIter == NULL. //////////////////////////////////////////////////// -template -class cIterProxy +template class cIterProxy { public: - cIterProxy(TYPE* pIter = NULL) : mpIter(pIter) {}; - cIterProxy(const TYPE* pIter) : mpIter((TYPE*)pIter) {}; - ~cIterProxy() { if (mpIter) mpIter->DestroyIter(); } - operator TYPE*() { return mpIter; } - operator const TYPE*() const { return mpIter; } - TYPE* operator->() { return mpIter; } - const TYPE* operator->() const { return mpIter; } - TYPE* operator=(TYPE* rhs) { mpIter = rhs; return mpIter; } + //TODO: Can these 2 constructors be made explicit? + cIterProxy(TYPE* pIter = NULL) : mpIter(pIter){}; + cIterProxy(const TYPE* pIter) : mpIter((TYPE*)pIter){}; + ~cIterProxy() + { + if (mpIter) + mpIter->DestroyIter(); + } + operator TYPE*() + { + return mpIter; + } + operator const TYPE*() const + { + return mpIter; + } + TYPE* operator->() + { + return mpIter; + } + const TYPE* operator->() const + { + return mpIter; + } + TYPE* operator=(TYPE* rhs) + { + mpIter = rhs; + return mpIter; + } + private: TYPE* mpIter; }; - #endif - diff --git a/src/fco/parsergenreutil.h b/src/fco/parsergenreutil.h index 6b6edfd..c594d9b 100644 --- a/src/fco/parsergenreutil.h +++ b/src/fco/parsergenreutil.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////// // parsergenreutil.h -// +// // iParserGenreUtil holds parser utility functions for which genre-specific // information is needed. // @@ -49,27 +49,29 @@ class cFCOName; //========================================================================= // DECLARATION OF CLASSES //========================================================================= - + class iParserGenreUtil { public: - virtual ~iParserGenreUtil() {} - virtual bool MapStringToProperty( const TSTRING& str, int& propIndex ) const = 0; - // maps the given string to an index into a property vector for the genre - virtual void AddSubTypeProps( cFCOPropVector& v ) const = 0; - // adds all properties that define object sub-type in genre (e.g. PROP_FILETYPE in FS) - virtual void InterpretFCOName( const std::list& l, cFCOName& nameOut ) const = 0; // throw( eParserGenreUtil ) - // given the input string list from the policy file, creates the cFCOName - virtual bool EnumPredefinedVariables( int index, TSTRING&, TSTRING& ) const = 0; - // set index to 0 before first call, then increment for each subsequent call. - // returns true if more var/val pairs - virtual bool IsAbsolutePath( const TSTRING& strPath ) const = 0; - // returns true if the path is an absolute path, and false if it's relative. + virtual ~iParserGenreUtil() + { + } + virtual bool MapStringToProperty(const TSTRING& str, int& propIndex) const = 0; + // maps the given string to an index into a property vector for the genre + virtual void AddSubTypeProps(cFCOPropVector& v) const = 0; + // adds all properties that define object sub-type in genre (e.g. PROP_FILETYPE in FS) + virtual void InterpretFCOName(const std::list& l, + cFCOName& nameOut) const = 0; // throw( eParserGenreUtil ) + // given the input string list from the policy file, creates the cFCOName + virtual bool EnumPredefinedVariables(int index, TSTRING&, TSTRING&) const = 0; + // set index to 0 before first call, then increment for each subsequent call. + // returns true if more var/val pairs + virtual bool IsAbsolutePath(const TSTRING& strPath) const = 0; + // returns true if the path is an absolute path, and false if it's relative. virtual bool HasSingleLetterProps() const = 0; - // returns true if this genre uses single-letter to represent object properties - // in the policy language and the command line. If it returns false, the genre - // uses &-separated words. + // returns true if this genre uses single-letter to represent object properties + // in the policy language and the command line. If it returns false, the genre + // uses &-separated words. }; #endif //__PARSERGENREUTIL_H - diff --git a/src/fco/propset.h b/src/fco/propset.h index be6ef67..fe094ee 100644 --- a/src/fco/propset.h +++ b/src/fco/propset.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,25 +45,54 @@ // PROPERTY() is used for properties whose values can be set by a passed in argument // PROPERTY_OBJ() is used other properties whose value must be set using the object // -// These macro's are different because it does not make sense to set a +// These macro's are different because it does not make sense to set a // signature value (at least in the MD5 case where it takes a 128 bit number!). /////////////////////////////////////////////////////////////////////////////// -#define PROPERTY(TYPE, NAME, INDEX)\ -private:\ - TYPE m##NAME;\ -public:\ -void Set##NAME (TYPE::ValueType value) { mValidProps.AddItem(INDEX); m##NAME.SetValue(value); }\ -TYPE::ValueType Get##NAME () const { ASSERT(mValidProps.ContainsItem(INDEX)); return m##NAME.GetValue(); }\ -void SetUndefined##NAME () { mValidProps.AddItem(INDEX); mUndefinedProps.AddItem(INDEX); } +#define PROPERTY(TYPE, NAME, INDEX) \ +private: \ + TYPE m##NAME; \ + \ +public: \ + void Set##NAME(TYPE::ValueType value) \ + { \ + mValidProps.AddItem(INDEX); \ + m##NAME.SetValue(value); \ + } \ + TYPE::ValueType Get##NAME() const \ + { \ + ASSERT(mValidProps.ContainsItem(INDEX)); \ + return m##NAME.GetValue(); \ + } \ + void SetUndefined##NAME() \ + { \ + mValidProps.AddItem(INDEX); \ + mUndefinedProps.AddItem(INDEX); \ + } -#define PROPERTY_OBJ(TYPE, NAME, INDEX)\ -private:\ - TYPE m##NAME;\ -public:\ -TYPE* Get##NAME () { return &m##NAME; }\ -void SetValid##NAME (bool valid) { if (valid) mValidProps.AddItem(INDEX); else mValidProps.RemoveItem(INDEX); }\ -void SetDefined##NAME (bool defined) { SetValid##NAME(true); if (!defined) mUndefinedProps.AddItem(INDEX); else mUndefinedProps.RemoveItem(INDEX); } +#define PROPERTY_OBJ(TYPE, NAME, INDEX) \ +private: \ + TYPE m##NAME; \ + \ +public: \ + TYPE* Get##NAME() \ + { \ + return &m##NAME; \ + } \ + void SetValid##NAME(bool valid) \ + { \ + if (valid) \ + mValidProps.AddItem(INDEX); \ + else \ + mValidProps.RemoveItem(INDEX); \ + } \ + void SetDefined##NAME(bool defined) \ + { \ + SetValid##NAME(true); \ + if (!defined) \ + mUndefinedProps.AddItem(INDEX); \ + else \ + mUndefinedProps.RemoveItem(INDEX); \ + } /////////////////////////////////////////////////////////////////////////////// #endif - diff --git a/src/fco/signature.cpp b/src/fco/signature.cpp index 15991fc..f937586 100644 --- a/src/fco/signature.cpp +++ b/src/fco/signature.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,10 +41,11 @@ #include #include "fcoundefprop.h" #include "core/archive.h" +#include "core/debug.h" #ifndef HAVE_OPENSSL_MD5_H -# ifdef HAVE_STRINGS_H -# include /* for bcopy(), this is only needed for Solaris */ -# endif +# ifdef HAVE_STRINGS_H +# include /* for bcopy(), this is only needed for Solaris */ +# endif #endif using namespace std; @@ -54,13 +55,13 @@ using namespace std; // The standard "digits" for base64 are "[A-Z][a-z][0-9]+/" // (see RFC 2045 at http://sunsite.doc.ic.ac.uk/rfc/rfc2045.txt). // However, Tripwire 1.3 used a different set of characters. -// +// // In order to more closely follow the standard I changed our // encoding to the standard. dmb 09-30-1998 // static char base64vec[] = - //"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:."; - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + //"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:."; + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /////////////////////////////////////////////////////////////////////////////// // class iSignature -- Interface all signatures will implement. @@ -69,8 +70,7 @@ static char base64vec[] = iFCOProp::CmpResult iSignature::Compare(const iFCOProp* rhs, Op op) const { // make sure we support this operation - if(op != iFCOProp::OP_EQ && - op != iFCOProp::OP_NE) + if (op != iFCOProp::OP_EQ && op != iFCOProp::OP_NE) { ASSERT(false); return iFCOProp::CMP_UNSUPPORTED; @@ -83,7 +83,7 @@ iFCOProp::CmpResult iSignature::Compare(const iFCOProp* rhs, Op op) const } // make sure we are the right type... - if(this->GetType() != rhs->GetType()) + if (this->GetType() != rhs->GetType()) { ASSERT(false); return iFCOProp::CMP_WRONG_PROP_TYPE; @@ -97,47 +97,54 @@ iFCOProp::CmpResult iSignature::Compare(const iFCOProp* rhs, Op op) const return (op == iFCOProp::OP_NE) ? iFCOProp::CMP_TRUE : iFCOProp::CMP_FALSE; } -bool cArchiveSigGen::mHex = false; +bool cArchiveSigGen::s_hex = false; +bool cArchiveSigGen::s_direct = false; -void cArchiveSigGen::AddSig( iSignature* pSig ) +void cArchiveSigGen::AddSig(iSignature* pSig) { - mSigList.push_back( pSig ); + mSigList.push_back(pSig); } - -void cArchiveSigGen::CalculateSignatures( cArchive& a ) + +void cArchiveSigGen::CalculateSignatures(cArchive& a) { - byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; - const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; - int cbRead; + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE * 2]; + int cbRead; container_type::size_type i; + byte* pBuf = abBuf; + + if (s_direct) + { + unsigned long mod = (unsigned long)abBuf % iSignature::SUGGESTED_BLOCK_SIZE; + unsigned long offset = (iSignature::SUGGESTED_BLOCK_SIZE - mod); + pBuf = abBuf + offset; + } // init hash - for( i = 0; i < mSigList.size(); i++ ) + for (i = 0; i < mSigList.size(); i++) mSigList[i]->Init(); // hash data do { - cbRead = a.ReadBlob( abBuf, cbToRead ); + cbRead = a.ReadBlob(pBuf, iSignature::SUGGESTED_BLOCK_SIZE); - for( i = 0; i < mSigList.size(); i++ ) - mSigList[i]->Update( abBuf, cbRead ); - } - while( cbRead == cbToRead ); + for (i = 0; i < mSigList.size(); i++) + mSigList[i]->Update(pBuf, cbRead); + } while (cbRead == iSignature::SUGGESTED_BLOCK_SIZE); // finalize hash - for( i = 0; i < mSigList.size(); i++ ) + for (i = 0; i < mSigList.size(); i++) mSigList[i]->Finit(); } bool cArchiveSigGen::Hex() { - return mHex; + return s_hex; } void cArchiveSigGen::SetHex(bool hex) { - mHex = hex; + s_hex = hex; } /////////////////////////////////////////////////////////////////////////////// @@ -150,42 +157,42 @@ void cArchiveSigGen::SetHex(bool hex) char* btob64(const register byte* pcbitvec, register char* pcout, int numbits) { register unsigned int val; - register int offset; - uint8 *pcorig = (uint8 *) pcout; + register int offset; + uint8* pcorig = (uint8*)pcout; - ASSERT( sizeof( uint8 ) == sizeof( byte ) ); /* everything breaks otherwise */ + ASSERT(sizeof(uint8) == sizeof(byte)); /* everything breaks otherwise */ assert(numbits > 0); val = *pcbitvec; - offset = numbits % 6; /* how many bits initially? */ - if (offset) + offset = numbits % 6; /* how many bits initially? */ + if (offset) { - val >>= (8 - offset); - *pcout++ = base64vec[val & 0x1f]; + val >>= (8 - offset); + *pcout++ = base64vec[val & 0x1f]; } - for ( numbits -= offset; numbits > 0; offset += 6, numbits -= 6) - { - val = *pcbitvec; - if (offset > 2) + for (numbits -= offset; numbits > 0; offset += 6, numbits -= 6) { - offset -= 8; - val <<= 8; - val |= *++pcbitvec; - } - val >>= (2-offset); - - *pcout++ = base64vec[val & 0x3f]; + val = *pcbitvec; + if (offset > 2) + { + offset -= 8; + val <<= 8; + val |= *++pcbitvec; + } + val >>= (2 - offset); + + *pcout++ = base64vec[val & 0x3f]; } *pcout = '\0'; - - return (char *) pcorig; + + return (char*)pcorig; } /////////////////////////////////////////////////////////////////////////////// -// pltob64 -- walk through a vector of int32s, convert them to +// pltob64 -- walk through a vector of int32s, convert them to // network byte ordering, and then convert to base 64 // this is the preferred interface to btob64. /////////////////////////////////////////////////////////////////////////////// @@ -193,27 +200,28 @@ char* btob64(const register byte* pcbitvec, register char* pcout, int numbits) #define NUMTMPLONGS 1000 char* pltob64(uint32* pl, char* pcout, int numlongs) { - register int i; - register uint32 *plto; - uint32 larray[NUMTMPLONGS]; + register int i; + register uint32* plto; + uint32 larray[NUMTMPLONGS]; assert(numlongs < NUMTMPLONGS); /* we use our own ntohl() routines, but we have to do it in-place */ - memcpy((char *) larray, (char *) pl, numlongs*sizeof(uint32)); + memcpy((char*)larray, (char*)pl, numlongs * sizeof(uint32)); - for (i = 0, plto = larray; i < numlongs; i++) { - *plto = tw_htonl(*plto); - ++plto; + for (i = 0, plto = larray; i < numlongs; i++) + { + *plto = tw_htonl(*plto); + ++plto; } - return btob64((byte*) larray, (char *) pcout, numlongs*sizeof(uint32)*8); + return btob64((byte*)larray, (char*)pcout, numlongs * sizeof(uint32) * 8); } /////////////////////////////////////////////////////////////////////////////// // class cNullSignature -- The signature that is always 0 /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cNullSignature, _T("cNullSignature"), 0, 1) +IMPLEMENT_TYPEDSERIALIZABLE(cNullSignature, _T("cNullSignature"), 0, 1) cNullSignature::cNullSignature() { @@ -227,7 +235,7 @@ void cNullSignature::Init() { } -void cNullSignature::Update( const byte* const pbData, int cbDataLen ) +void cNullSignature::Update(const byte* const pbData, int cbDataLen) { } @@ -248,17 +256,17 @@ TSTRING cNullSignature::AsStringHex() const } -bool cNullSignature::IsEqual(const iSignature& rhs) const +bool cNullSignature::IsEqual(const iSignature& rhs) const { return true; } -void cNullSignature::Read(iSerializer* pSerializer, int32 version) +void cNullSignature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("Null Signature Read"))); -#ifdef _DEBUG +#ifdef DEBUG int16 ret; pSerializer->ReadInt16(ret); ASSERT(ret == 123); @@ -267,7 +275,7 @@ void cNullSignature::Read(iSerializer* pSerializer, int32 version) void cNullSignature::Write(iSerializer* pSerializer) const { -#ifdef _DEBUG +#ifdef DEBUG pSerializer->WriteInt16(123); #endif } @@ -287,7 +295,7 @@ void cNullSignature::Copy(const iFCOProp* rhs) // in an archive. Useful as an example if nothing else. /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cChecksumSignature, _T("cChecksumSignature"), 0, 1) +IMPLEMENT_TYPEDSERIALIZABLE(cChecksumSignature, _T("cChecksumSignature"), 0, 1) cChecksumSignature::cChecksumSignature() { @@ -296,17 +304,16 @@ cChecksumSignature::cChecksumSignature() cChecksumSignature::~cChecksumSignature() { - } void cChecksumSignature::Init() { } -void cChecksumSignature::Update( const byte* const pbDataC, int cbDataLen ) +void cChecksumSignature::Update(const byte* const pbDataC, int cbDataLen) { byte* pbData = (byte*)pbDataC; - for( int i = 0; i < cbDataLen; i++, pbData++ ) + for (int i = 0; i < cbDataLen; i++, pbData++) mChecksum += *pbData; } @@ -318,20 +325,17 @@ void cChecksumSignature::Finit() TSTRING cChecksumSignature::AsString() const { TSTRING ret; - char *ps_signature; - char buf[100]; - uint32 local[2]; + char* ps_signature; + char buf[100]; + uint32 local[2]; local[0] = (uint32)(mChecksum >> 32); // note we put the MSB first local[1] = (uint32)(mChecksum); ps_signature = pltob64(local, buf, 2); - //ps_signature holds base64 representation of mCRC -#ifdef _UNICODE - ret.resize(strlen(ps_signature)); - mbstowcs((TCHAR*)ret.data(), ps_signature, strlen(ps_signature)); -#else + //ps_signature holds base64 representation of mCRC + ret.append(ps_signature); -#endif + return ret; } @@ -339,21 +343,21 @@ TSTRING cChecksumSignature::AsStringHex() const { TOSTRINGSTREAM ss; - ss.imbue( std::locale::classic() ); - ss.setf( ios::hex, ios::basefield ); - - ASSERT( false ); - ss << (size_t)(uint32) mChecksum; // TODO:BAM -- this is truncating a 64-bit value to 32 bits! + ss.imbue(std::locale::classic()); + ss.setf(ios::hex, ios::basefield); + + ASSERT(false); + ss << (size_t)(uint32)mChecksum; // TODO:BAM -- this is truncating a 64-bit value to 32 bits! return ss.str(); } - + bool cChecksumSignature::IsEqual(const iSignature& rhs) const { return mChecksum == ((cChecksumSignature&)rhs).mChecksum; } -void cChecksumSignature::Read(iSerializer* pSerializer, int32 version) +void cChecksumSignature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("Checksum Signature Read"))); @@ -379,7 +383,7 @@ void cChecksumSignature::Copy(const iFCOProp* rhs) // class cCRC32Signature -- A CRC32 signature /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cCRC32Signature, _T("cCRC32Signature"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cCRC32Signature, _T("cCRC32Signature"), 0, 1); cCRC32Signature::cCRC32Signature() { @@ -391,41 +395,36 @@ cCRC32Signature::~cCRC32Signature() void cCRC32Signature::Init() { - crcInit( mCRCInfo ); + crcInit(mCRCInfo); } -void cCRC32Signature::Update( const byte* const pbData, int cbDataLen ) +void cCRC32Signature::Update(const byte* const pbData, int cbDataLen) { - ASSERT( sizeof( byte ) == sizeof( uint8 ) ); - crcUpdate( mCRCInfo, (uint8*)pbData, cbDataLen ); + ASSERT(sizeof(byte) == sizeof(uint8)); + crcUpdate(mCRCInfo, (uint8*)pbData, cbDataLen); } void cCRC32Signature::Finit() { - crcFinit( mCRCInfo ); + crcFinit(mCRCInfo); } /////////////////////////////////////////////////////////////////////////////// -// AsString -- Returns a TSTRING that holds the base64 representation of +// AsString -- Returns a TSTRING that holds the base64 representation of // mCRC TSTRING cCRC32Signature::AsString() const { if (cArchiveSigGen::Hex()) return AsStringHex(); - + TSTRING ret; - char *ps_signature; - char buf[100]; - uint32 local = mCRCInfo.crc; + char* ps_signature; + char buf[100]; + uint32 local = mCRCInfo.crc; ps_signature = pltob64(&local, buf, 1); //ps_signature holds base64 representation of mCRCInfo.crc -#ifdef _UNICODE - ret.resize(strlen(ps_signature)); - mbstowcs((TCHAR*)ret.data(), ps_signature, strlen(ps_signature)); -#else ret.append(ps_signature); -#endif return ret; } @@ -433,8 +432,8 @@ TSTRING cCRC32Signature::AsStringHex() const { TOSTRINGSTREAM ss; - ss.imbue( std::locale::classic() ); - ss.setf( ios::hex, ios::basefield ); + ss.imbue(std::locale::classic()); + ss.setf(ios::hex, ios::basefield); ss << (size_t)mCRCInfo.crc; @@ -449,7 +448,7 @@ bool cCRC32Signature::IsEqual(const iSignature& rhs) const return (mCRCInfo.crc == ((cCRC32Signature&)rhs).mCRCInfo.crc); } -void cCRC32Signature::Read(iSerializer* pSerializer, int32 version) +void cCRC32Signature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("CRC32 Read"))); @@ -475,12 +474,16 @@ void cCRC32Signature::Copy(const iFCOProp* rhs) // class cMD5Signature -- A MD5 signature /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cMD5Signature, _T("cMD5Signature"), 0, 1) +IMPLEMENT_TYPEDSERIALIZABLE(cMD5Signature, _T("cMD5Signature"), 0, 1) cMD5Signature::cMD5Signature() { - memset( mMD5Info.digest, 0, sizeof( mMD5Info.digest ) ); - memset( md5_digest, 0, MD5_DIGEST_LENGTH ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + memset(mMD5Info.data, 0, sizeof(mMD5Info.data)); +#else + memset(mMD5Info.digest, 0, sizeof(mMD5Info.digest)); +#endif + memset(md5_digest, 0, MD5_DIGEST_LENGTH); } cMD5Signature::~cMD5Signature() @@ -489,28 +492,34 @@ cMD5Signature::~cMD5Signature() void cMD5Signature::Init() { -#ifdef HAVE_OPENSSL_MD5_H - MD5_Init( &mMD5Info ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_MD5_Init(&mMD5Info); +#elif HAVE_OPENSSL_MD5_H + MD5_Init(&mMD5Info); #else - MD5Init( &mMD5Info ); + MD5Init(&mMD5Info); #endif } -void cMD5Signature::Update( const byte* const pbData, int cbDataLen ) +void cMD5Signature::Update(const byte* const pbData, int cbDataLen) { -#ifdef HAVE_OPENSSL_MD5_H - MD5_Update( &mMD5Info, (uint8*)pbData, cbDataLen ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_MD5_Update(&mMD5Info, (uint8*)pbData, cbDataLen); +#elif HAVE_OPENSSL_MD5_H + MD5_Update(&mMD5Info, (uint8*)pbData, cbDataLen); #else - MD5Update( &mMD5Info, (uint8*)pbData, cbDataLen ); + MD5Update(&mMD5Info, (uint8*)pbData, cbDataLen); #endif } void cMD5Signature::Finit() { -#ifdef HAVE_OPENSSL_MD5_H - MD5_Final( md5_digest, &mMD5Info ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_MD5_Final(md5_digest, &mMD5Info); +#elif HAVE_OPENSSL_MD5_H + MD5_Final(md5_digest, &mMD5Info); #else - MD5Final( &mMD5Info ); + MD5Final(&mMD5Info); bcopy(mMD5Info.digest, md5_digest, MD5_DIGEST_LENGTH); #endif } @@ -521,23 +530,16 @@ TSTRING cMD5Signature::AsString() const { if (cArchiveSigGen::Hex()) return AsStringHex(); - + TSTRING ret; - char buf[24]; + char buf[24]; - ASSERT( sizeof( uint8 ) == sizeof( byte ) ); /* everything breaks otherwise */ - btob64((byte*)md5_digest, buf, SIG_BYTE_SIZE*8); - //converting to base64 representation. + ASSERT(sizeof(uint8) == sizeof(byte)); /* everything breaks otherwise */ + btob64((byte*)md5_digest, buf, SIG_BYTE_SIZE * 8); + //converting to base64 representation. -#ifdef _UNICODE //making it TSTRING sensitive - int length; - length = strlen(buf); - ret.resize(length); - mbstowcs((TCHAR*) ret.data(), buf, length); -#else ret.append(buf); -#endif - + return ret; } @@ -546,14 +548,14 @@ TSTRING cMD5Signature::AsStringHex() const TSTRING ret; TCHAR stringBuffer[128]; - TCHAR sigStringOut[128]; + TCHAR sigStringOut[129]; sigStringOut[0] = '\0'; - uint8 *dbuf = (uint8 *)md5_digest; + uint8* dbuf = (uint8*)md5_digest; - for(int i = 0; i < SIG_BYTE_SIZE; ++i) + for (int i = 0; i < SIG_BYTE_SIZE; ++i) { - _stprintf(stringBuffer, _T("%02lx"), (unsigned long)dbuf[i]); - _tcscat(sigStringOut, stringBuffer); + snprintf(stringBuffer, 128, _T("%02lx"), (unsigned long)dbuf[i]); + strncat(sigStringOut, stringBuffer, 128); } ret.append(sigStringOut); @@ -564,12 +566,13 @@ bool cMD5Signature::IsEqual(const iSignature& rhs) const { if (this == &rhs) return true; - else { + else + { return (memcmp(md5_digest, ((cMD5Signature&)rhs).md5_digest, SIG_BYTE_SIZE) == 0); } } -void cMD5Signature::Read(iSerializer* pSerializer, int32 version) +void cMD5Signature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("MD5 Read"))); @@ -595,89 +598,92 @@ void cMD5Signature::Copy(const iFCOProp* rhs) // class cSHASignature -- Implementation for cSHASignature: /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cSHASignature, _T("cSHASignature"), 0, 1) +IMPLEMENT_TYPEDSERIALIZABLE(cSHASignature, _T("cSHASignature"), 0, 1) cSHASignature::cSHASignature() { - memset( &mSHAInfo, 0, sizeof( mSHAInfo ) ); -#ifdef HAVE_OPENSSL_SHA_H - memset( sha_digest, 0, SHA_DIGEST_LENGTH ); + memset(&mSHAInfo, 0, sizeof(mSHAInfo)); + +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + memset(sha_digest, 0, CC_SHA1_DIGEST_LENGTH); +#elif HAVE_OPENSSL_SHA_H + memset(sha_digest, 0, SHA_DIGEST_LENGTH); #endif } cSHASignature::~cSHASignature() -{} +{ +} void cSHASignature::Init() { -#ifdef HAVE_OPENSSL_SHA_H - SHA1_Init( &mSHAInfo ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_SHA1_Init(&mSHAInfo); +#elif HAVE_OPENSSL_SHA_H + SHA1_Init(&mSHAInfo); #else - shsInit( &mSHAInfo ); + shsInit(&mSHAInfo); #endif } -void cSHASignature::Update( const byte* const pbData, int cbDataLen ) -{ - ASSERT( sizeof( byte ) == sizeof( uint8 ) ); -#ifdef HAVE_OPENSSL_SHA_H - SHA1_Update( &mSHAInfo, (uint8*)pbData, cbDataLen ); +void cSHASignature::Update(const byte* const pbData, int cbDataLen) +{ + ASSERT(sizeof(byte) == sizeof(uint8)); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_SHA1_Update(&mSHAInfo, (uint8*)pbData, cbDataLen); +#elif HAVE_OPENSSL_SHA_H + SHA1_Update(&mSHAInfo, (uint8*)pbData, cbDataLen); #else - shsUpdate( &mSHAInfo, (uint8*)pbData, cbDataLen ); + shsUpdate(&mSHAInfo, (uint8*)pbData, cbDataLen); #endif } void cSHASignature::Finit() { -#ifdef HAVE_OPENSSL_SHA_H - SHA1_Final( (unsigned char *)sha_digest, &mSHAInfo ); +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_SHA1_Final((unsigned char*)sha_digest, &mSHAInfo); +#elif HAVE_OPENSSL_SHA_H + SHA1_Final((unsigned char*)sha_digest, &mSHAInfo); #else - shsFinal( &mSHAInfo ); + shsFinal(&mSHAInfo); #endif } //////////////////////////////////////////////////////////////////////////////// // AsString -- Converts to Base64 representation and returns a TSTRING -#ifdef HAVE_OPENSSL_SHA_H +#if defined(HAVE_OPENSSL_SHA_H) || defined(HAVE_COMMONCRYPTO_COMMONDIGEST_H) TSTRING cSHASignature::AsString(void) const { if (cArchiveSigGen::Hex()) return AsStringHex(); - + TSTRING ret; - char* ps_signature; - char buf[100]; - - ps_signature = btob64((uint8*)sha_digest, buf, SIG_UINT32_SIZE*sizeof(uint32)*8); + char* ps_signature; + char buf[100]; + + ps_signature = btob64((uint8*)sha_digest, buf, SIG_UINT32_SIZE * sizeof(uint32) * 8); //converting to base64 representation. -#ifdef _UNICODE //making it TSTRING sensitive - int length; - length = strlen(ps_signature); - ret.resize(length); - mbstowcs((TCHAR*) ret.data(), ps_signature, length); -#else ret.append(ps_signature); -#endif return ret; } TSTRING cSHASignature::AsStringHex() const { TSTRING ret; - + TCHAR stringBuffer[128]; - TCHAR sigStringOut[128]; + TCHAR sigStringOut[129]; sigStringOut[0] = '\0'; - uint8 *dbuf = (uint8 *)sha_digest; - - for (int i=0; i < SIG_UINT32_SIZE*(int)sizeof(uint32); ++i) + uint8* dbuf = (uint8*)sha_digest; + + for (int i = 0; i < SIG_UINT32_SIZE * (int)sizeof(uint32); ++i) { - _stprintf(stringBuffer, _T("%02x"), dbuf[i]); - _tcscat(sigStringOut, stringBuffer); + snprintf(stringBuffer, 128, _T("%02x"), dbuf[i]); + strncat(sigStringOut, stringBuffer, 128); } ret.append(sigStringOut); - + return ret; } @@ -686,13 +692,13 @@ TSTRING cSHASignature::AsStringHex() const void cSHASignature::Copy(const iFCOProp* rhs) { ASSERT(GetType() == rhs->GetType()); - for (int i = 0; i(rhs))->sha_digest)[i]; } /////////////////////////////////////////////////////////////////////////////// // Serializer Implementation: Read and Write -void cSHASignature::Read (iSerializer* pSerializer, int32 version) +void cSHASignature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("SHA Read"))); @@ -713,7 +719,8 @@ bool cSHASignature::IsEqual(const iSignature& rhs) const { if (this == &rhs) return true; - else { + else + { return (memcmp(sha_digest, ((cSHASignature&)rhs).sha_digest, SIG_UINT32_SIZE * sizeof(uint32)) == 0); } } @@ -724,22 +731,16 @@ TSTRING cSHASignature::AsString(void) const { if (cArchiveSigGen::Hex()) return AsStringHex(); - + TSTRING ret; char* ps_signature; char buf[100]; - buf[99]=0; - + buf[99] = 0; + ps_signature = pltob64((uint32*)mSHAInfo.digest, buf, SIG_UINT32_SIZE); //converting to base64 representation. - -#ifdef _UNICODE //making it TSTRING sensitive - int length = strlen(ps_signature); - ret.resize(length); - mbstowcs((TCHAR*) ret.data(), ps_signature, length); -#else + ret.append(ps_signature); -#endif return ret; //return ret; } @@ -747,18 +748,18 @@ TSTRING cSHASignature::AsString(void) const TSTRING cSHASignature::AsStringHex() const { TSTRING ret; - + TCHAR stringBuffer[128]; - TCHAR sigStringOut[128]; + TCHAR sigStringOut[129]; sigStringOut[0] = '\0'; - - for (int i=0; i < SIG_UINT32_SIZE; ++i) + + for (int i = 0; i < SIG_UINT32_SIZE; ++i) { - _stprintf(stringBuffer, _T("%08x"), mSHAInfo.digest[i]); - _tcscat(sigStringOut, stringBuffer); + snprintf(stringBuffer, 128, _T("%08x"), mSHAInfo.digest[i]); + strncat(sigStringOut, stringBuffer, 128); } ret.append(sigStringOut); - + return ret; } @@ -767,13 +768,13 @@ TSTRING cSHASignature::AsStringHex() const void cSHASignature::Copy(const iFCOProp* rhs) { ASSERT(GetType() == rhs->GetType()); - for (int i = 0; i(rhs))->mSHAInfo.digest)[i]; } /////////////////////////////////////////////////////////////////////////////// // Serializer Implementation: Read and Write -void cSHASignature::Read (iSerializer* pSerializer, int32 version) +void cSHASignature::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("SHA Read"))); @@ -794,39 +795,41 @@ bool cSHASignature::IsEqual(const iSignature& rhs) const { if (this == &rhs) return true; - else { + else + { return (memcmp(mSHAInfo.digest, ((cSHASignature&)rhs).mSHAInfo.digest, SIG_UINT32_SIZE * sizeof(uint32)) == 0); } } #endif /////////////////////////////////////////////////////////////////////////////// -// class cHAVALSignature -- +// class cHAVALSignature -- /////////////////////////////////////////////////////////////////////////////// -IMPLEMENT_TYPEDSERIALIZABLE(cHAVALSignature, _T("cHAVALSignature"), 0, 1) +IMPLEMENT_TYPEDSERIALIZABLE(cHAVALSignature, _T("cHAVALSignature"), 0, 1) cHAVALSignature::cHAVALSignature() -{ - memset( mSignature, 0, sizeof( mSignature ) ); +{ + memset(mSignature, 0, sizeof(mSignature)); } cHAVALSignature::~cHAVALSignature() -{} +{ +} void cHAVALSignature::Init() { - haval_start( &mHavalState ); + haval_start(&mHavalState); } -void cHAVALSignature::Update( const byte* const pbData, int cbDataLen ) +void cHAVALSignature::Update(const byte* const pbData, int cbDataLen) { - haval_hash( &mHavalState, (uint8*)pbData, cbDataLen ); + haval_hash(&mHavalState, (uint8*)pbData, cbDataLen); } void cHAVALSignature::Finit() { - haval_end( &mHavalState, mSignature ); + haval_end(&mHavalState, mSignature); } /////////////////////////////////////////////////////////////////////////////// @@ -835,37 +838,29 @@ TSTRING cHAVALSignature::AsString() const { if (cArchiveSigGen::Hex()) return AsStringHex(); - + TSTRING ret; - char buf[24]; + char buf[24]; btob64((byte*)mSignature, buf, 128); //converting to base64 representation. -#ifdef _UNICODE //making it TSTRING sensitive - int length; - length = strlen(buf); - ret.resize(length); - mbstowcs((TCHAR*) ret.data(), buf, length); -#else ret.append(buf); -#endif - return ret; } -TSTRING cHAVALSignature::AsStringHex() const +TSTRING cHAVALSignature::AsStringHex() const { TSTRING ret; TCHAR stringBuffer[128]; - TCHAR sigStringOut[128]; + TCHAR sigStringOut[129]; sigStringOut[0] = _T('\0'); - for (int i=0; i < SIG_BYTE_SIZE; ++i) + for (int i = 0; i < SIG_BYTE_SIZE; ++i) { - _stprintf(stringBuffer, _T("%02x"), mSignature[i]); - _tcscat(sigStringOut, stringBuffer); + snprintf(stringBuffer, 128, _T("%02x"), mSignature[i]); + strncat(sigStringOut, stringBuffer, 128); } ret.append(sigStringOut); @@ -897,11 +892,12 @@ void cHAVALSignature::Write(iSerializer* pSerializer) const /////////////////////////////////////////////////////////////////////////////// // Equal -- Tests for equality given a base pointer. -bool cHAVALSignature::IsEqual(const iSignature & rhs) const +bool cHAVALSignature::IsEqual(const iSignature& rhs) const { if (this == &rhs) return true; - else { + else + { return (memcmp(mSignature, ((cHAVALSignature&)rhs).mSignature, SIG_BYTE_SIZE) == 0); } } diff --git a/src/fco/signature.h b/src/fco/signature.h index 61fd50d..b502f3f 100644 --- a/src/fco/signature.h +++ b/src/fco/signature.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,31 +52,36 @@ #include "core/crc32.h" #ifdef HAVE_OPENSSL_MD5_H -# include -# define digest data +#include +# define digest data #else -# include "core/md5.h" -# ifndef MD5_DIGEST_LENGTH -# define MD5_DIGEST_LENGTH 16 -# endif +#include "core/md5.h" +# ifndef MD5_DIGEST_LENGTH +# define MD5_DIGEST_LENGTH 16 +# endif #endif #ifdef HAVE_OPENSSL_SHA_H -# include +#include #else -# include "core/sha.h" -# define SHA_CTX SHS_INFO -# ifndef SHA_DIGEST_LENGTH -# define SHA_DIGEST_LENGTH 20 -# endif +#include "core/sha.h" +# define SHA_CTX SHS_INFO +# ifndef SHA_DIGEST_LENGTH +# define SHA_DIGEST_LENGTH 20 +# endif #endif +/*Use OSX CommonCrypto lib if available*/ +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H +#include +#endif + + #include "core/haval.h" // TODO: figure out a way to do this without including these headers. // pool of objects? - /////////////////////////////////////////////////////////////////////////////// // class iSignatrue -- Interface all signatures will implement. /////////////////////////////////////////////////////////////////////////////// @@ -87,78 +92,90 @@ class iSignature : public iFCOProp // // ctors and dtors // - virtual ~iSignature() {}; - iSignature() {}; - + virtual ~iSignature(){}; + iSignature(){}; + // // enums // - enum { SUGGESTED_BLOCK_SIZE = 0x1000 }; // best size of block to hash at a time + enum + { + SUGGESTED_BLOCK_SIZE = 0x1000 + }; // best size of block to hash at a time // // basic functionality // - virtual void Init () = 0; - // call before beginning hashing - virtual void Update( const byte* const pbData, int cbDataLen ) = 0; - // may be called multiple times -- best to call with blocks of size SUGGESTED_BLOCK_SIZE, - // but can handle any size data. - virtual void Finit () = 0; - // call to finish hashing - - virtual TSTRING AsStringHex() const = 0; + virtual void Init() = 0; + // call before beginning hashing + virtual void Update(const byte* const pbData, int cbDataLen) = 0; + // may be called multiple times -- best to call with blocks of size SUGGESTED_BLOCK_SIZE, + // but can handle any size data. + virtual void Finit() = 0; + // call to finish hashing + + virtual TSTRING AsStringHex() const = 0; // // from iFCOProp // - virtual CmpResult Compare( const iFCOProp* rhs, Op op ) const; + virtual CmpResult Compare(const iFCOProp* rhs, Op op) const; protected: - // // don't let C++ create these functions // - iSignature( const iSignature& ); - iSignature& operator=( const iSignature& ); + iSignature(const iSignature&); + iSignature& operator=(const iSignature&); // // private util functions // - virtual bool IsEqual( const iSignature& rhs ) const = 0; + virtual bool IsEqual(const iSignature& rhs) const = 0; }; /////////////////////////////////////////////////////////////////////////////// // class cArchiveSigGen -- utility class to facilitate archive hashing // -// Stores a list of signatures (added by AddSig()), and when +// Stores a list of signatures (added by AddSig()), and when // CalculateSignatures is called, makes ONE sweep through the archive, // calculating hashes for all signatures in the list. /////////////////////////////////////////////////////////////////////////////// class cArchiveSigGen { public: - cArchiveSigGen() {}; + cArchiveSigGen(){}; - void AddSig( iSignature* pSig ); - // adds a signature to the list + void AddSig(iSignature* pSig); + // adds a signature to the list - void CalculateSignatures( cArchive& a ); - // produces signature of archive for all signatures in the list - // remember to rewind archive! + void CalculateSignatures(cArchive& a); + // produces signature of archive for all signatures in the list + // remember to rewind archive! static bool Hex(); static void SetHex(bool); - -private: + + static bool UseDirectIO() + { + return s_direct; + } + static void SetUseDirectIO(bool b) + { + s_direct = b; + } + +private: // don't let C++ create these functions - cArchiveSigGen( const cArchiveSigGen& ); - cArchiveSigGen& operator=( const cArchiveSigGen& ); + cArchiveSigGen(const cArchiveSigGen&); + cArchiveSigGen& operator=(const cArchiveSigGen&); + + typedef std::vector container_type; + container_type mSigList; - typedef std::vector< iSignature* > container_type; - container_type mSigList; - - static bool mHex; + static bool s_direct; + static bool s_hex; }; @@ -174,18 +191,18 @@ class cNullSignature : public iSignature cNullSignature(); virtual ~cNullSignature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: - virtual bool IsEqual(const iSignature& rhs) const; + virtual bool IsEqual(const iSignature& rhs) const; }; /////////////////////////////////////////////////////////////////////////////// @@ -201,20 +218,20 @@ class cChecksumSignature : public iSignature cChecksumSignature(); virtual ~cChecksumSignature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: - virtual bool IsEqual(const iSignature& rhs) const; + virtual bool IsEqual(const iSignature& rhs) const; - uint64 mChecksum; + uint64 mChecksum; }; /////////////////////////////////////////////////////////////////////////////// @@ -229,20 +246,20 @@ class cCRC32Signature : public iSignature cCRC32Signature(); virtual ~cCRC32Signature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: - virtual bool IsEqual(const iSignature& rhs) const; - + virtual bool IsEqual(const iSignature& rhs) const; + CRC_INFO mCRCInfo; }; @@ -258,22 +275,30 @@ class cMD5Signature : public iSignature cMD5Signature(); virtual ~cMD5Signature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) protected: - enum { SIG_BYTE_SIZE = MD5_DIGEST_LENGTH }; - - virtual bool IsEqual(const iSignature& rhs) const; - MD5_CTX mMD5Info; - uint8 md5_digest[MD5_DIGEST_LENGTH]; + enum + { + SIG_BYTE_SIZE = MD5_DIGEST_LENGTH + }; + + virtual bool IsEqual(const iSignature& rhs) const; +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + CC_MD5_CTX mMD5Info; + uint8 md5_digest[CC_MD5_DIGEST_LENGTH]; +#else + MD5_CTX mMD5Info; + uint8 md5_digest[MD5_DIGEST_LENGTH]; +#endif }; /////////////////////////////////////////////////////////////////////////////// @@ -287,26 +312,32 @@ class cSHASignature : public iSignature cSHASignature(); virtual ~cSHASignature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - virtual void Read (iSerializer* pSerializer, int32 version = 0); - virtual void Write(iSerializer* pSerializer) const; + virtual void Read(iSerializer* pSerializer, int32 version = 0); + virtual void Write(iSerializer* pSerializer) const; protected: - - virtual bool IsEqual(const iSignature& rhs) const; - -#ifdef HAVE_OPENSSL_SHA_H - enum { SIG_UINT32_SIZE = SHA_DIGEST_LENGTH/4 }; - SHA_CTX mSHAInfo; - uint32 sha_digest[SHA_DIGEST_LENGTH/4]; + virtual bool IsEqual(const iSignature& rhs) const; + +#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H + enum {SIG_UINT32_SIZE = CC_SHA1_DIGEST_LENGTH / 4}; + CC_SHA1_CTX mSHAInfo; + uint32 sha_digest[SIG_UINT32_SIZE]; +#elif HAVE_OPENSSL_SHA_H + enum {SIG_UINT32_SIZE = SHA_DIGEST_LENGTH / 4}; + SHA_CTX mSHAInfo; + uint32 sha_digest[SIG_UINT32_SIZE]; #else - enum { SIG_UINT32_SIZE = 5 }; + enum + { + SIG_UINT32_SIZE = 5 + }; SHS_INFO mSHAInfo; #endif }; @@ -323,25 +354,26 @@ class cHAVALSignature : public iSignature cHAVALSignature(); virtual ~cHAVALSignature(); - virtual void Init (); - virtual void Update( const byte* const pbData, int cbDataLen ); - virtual void Finit (); + virtual void Init(); + virtual void Update(const byte* const pbData, int cbDataLen); + virtual void Finit(); virtual TSTRING AsString() const; virtual TSTRING AsStringHex() const; virtual void Copy(const iFCOProp* rhs); - virtual void Read(iSerializer* pSerializer, int32 version = 0); - virtual void Write(iSerializer* pSerializer) const; + virtual void Read(iSerializer* pSerializer, int32 version = 0); + virtual void Write(iSerializer* pSerializer) const; protected: - enum { SIG_BYTE_SIZE = 16 }; + enum + { + SIG_BYTE_SIZE = 16 + }; - virtual bool IsEqual(const iSignature& rhs) const; - - haval_state mHavalState; - uint8 mSignature[SIG_BYTE_SIZE]; + virtual bool IsEqual(const iSignature& rhs) const; + haval_state mHavalState; + uint8 mSignature[SIG_BYTE_SIZE]; }; #endif // __SIGNATURE_H - diff --git a/src/fco/stdfco.cpp b/src/fco/stdfco.cpp index 6d6acbc..db17a46 100644 --- a/src/fco/stdfco.cpp +++ b/src/fco/stdfco.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdfco.h" - -// eof: stdfco.cpp diff --git a/src/fco/stdfco.h b/src/fco/stdfco.h index f897a01..8000dfe 100644 --- a/src/fco/stdfco.h +++ b/src/fco/stdfco.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/fco/twfactory.cpp b/src/fco/twfactory.cpp index cb0a229..1a076e5 100644 --- a/src/fco/twfactory.cpp +++ b/src/fco/twfactory.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,4 +48,3 @@ iTWFactory* iTWFactory::GetInstance() // the instance before it has been set? return mpInstance; } - diff --git a/src/fco/twfactory.h b/src/fco/twfactory.h index fe87b8c..fc663de 100644 --- a/src/fco/twfactory.h +++ b/src/fco/twfactory.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // twfactory.h // -// iTWFactory -- an interface for classes that use the abstract factory pattern +// iTWFactory -- an interface for classes that use the abstract factory pattern // to provide the appropriate instances of classes #ifndef __TWFACTORY_H #define __TWFACTORY_H @@ -57,45 +57,47 @@ class iTWFactory { public: static void SetFactory(iTWFactory* pFact); - // sets the single instance of the tripwire factory to what was passed it. The caller - // is responsible for deleting the pointer. (probably just created on the stack.) + // sets the single instance of the tripwire factory to what was passed it. The caller + // is responsible for deleting the pointer. (probably just created on the stack.) static iTWFactory* GetInstance(); - // returns the global instance of the tripwire factory - - virtual iFCOPropCalc* CreatePropCalc() const = 0; - // returns an object that can calculate properties for fcos produced by the - // DataSource. - virtual iFCOSpec* CreateSpec(const TSTRING& name, iFCOSpecHelper* pHelper = NULL) const = 0; - // creates an appropriate FCOSpec and assignes it the name and helper specified. + // returns the global instance of the tripwire factory + + virtual iFCOPropCalc* CreatePropCalc() const = 0; + // returns an object that can calculate properties for fcos produced by the + // DataSource. + virtual iFCOSpec* CreateSpec(const TSTRING& name, iFCOSpecHelper* pHelper = NULL) const = 0; + // creates an appropriate FCOSpec and assignes it the name and helper specified. - virtual iFCOPropDisplayer* CreatePropDisplayer() const = 0; - // returns a pointer to an object which knows how to display human-readable representations of an FCO's properties + virtual iFCOPropDisplayer* CreatePropDisplayer() const = 0; + // returns a pointer to an object which knows how to display human-readable representations of an FCO's properties virtual iSerRefCountObj::CreateFunc GetCreateFunc() const = 0; - // returns a pointer to a function that creates instances of the currently appropriate FCO. + // returns a pointer to a function that creates instances of the currently appropriate FCO. - virtual iParserGenreUtil* CreateParserGenreUtil() const = 0; - // returns a pointer to an object that handles all genre-dependant parser functions for the currently appropriate FCO. + virtual iParserGenreUtil* CreateParserGenreUtil() const = 0; + // returns a pointer to an object that handles all genre-dependant parser functions for the currently appropriate FCO. virtual iFCODataSourceIter* CreateDataSourceIter() const = 0; - virtual iFCONameInfo* GetNameInfo() const = 0; - // returns a pointer to a class that provides characteristics of the FCO's names in the - // current genre. Since this class will have no data, the object returned should be declared - // statically in the cpp file that implements this method, so: - // NOTE -- do _not_ delete the pointer you get back from calling this method!! + virtual iFCONameInfo* GetNameInfo() const = 0; + // returns a pointer to a class that provides characteristics of the FCO's names in the + // current genre. Since this class will have no data, the object returned should be declared + // statically in the cpp file that implements this method, so: + // NOTE -- do _not_ delete the pointer you get back from calling this method!! - virtual cFCOPropVector GetLooseDirMask() const = 0; - // ok, it sucks that this interface is polluted with this method, but I can't really come up with a - // better place for this. - // - // the property vector returned from this method indicates what properties should be _ignored_ for - // an integrity check run in "loose directory" mode. This mask will be stripped off of all fcos comapred - // where both return CAP_CAN_HAVE_CHILDREN from iFCO::GetCaps() + virtual cFCOPropVector GetLooseDirMask() const = 0; + // ok, it sucks that this interface is polluted with this method, but I can't really come up with a + // better place for this. + // + // the property vector returned from this method indicates what properties should be _ignored_ for + // an integrity check run in "loose directory" mode. This mask will be stripped off of all fcos comapred + // where both return CAP_CAN_HAVE_CHILDREN from iFCO::GetCaps() virtual iFCONameTranslator* GetNameTranslator() const = 0; - virtual ~iTWFactory() {} + virtual ~iTWFactory() + { + } private: @@ -103,4 +105,3 @@ class iTWFactory }; #endif //__TWFACTORY_H - diff --git a/src/fs/Makefile.am b/src/fs/Makefile.am index e1da0fb..d7b7ae5 100644 --- a/src/fs/Makefile.am +++ b/src/fs/Makefile.am @@ -1,15 +1,23 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libfs.a +libfs_adir=. libfs_a_SOURCES = \ fs.cpp fsdatasourceiter.cpp fserrors.cpp fsfactory.cpp \ fsnametranslator.cpp fsobject.cpp fsparserutil.cpp \ fspropcalc.cpp fspropdisplayer.cpp fspropset.cpp \ fsstrings.cpp fsvisitor.cpp stdfs.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +libfs_a_HEADERS = \ + fs.h fsdatasourceiter.h fserrors.h fsfactory.h \ + fsnametranslator.h fsobject.h fsparserutil.h \ + fspropcalc.h fspropdisplayer.h fspropset.h fsstrings.h \ + fsvisitor.h stdfs.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libfs_a_OBJECTS) diff --git a/src/fs/Makefile.in b/src/fs/Makefile.in index e4d81d1..21c6d25 100644 --- a/src/fs/Makefile.in +++ b/src/fs/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libfs_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/fs -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libfs_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libfs_a_AR = $(AR) $(ARFLAGS) libfs_a_LIBADD = am_libfs_a_OBJECTS = fs.$(OBJEXT) fsdatasourceiter.$(OBJEXT) \ @@ -59,23 +117,95 @@ am_libfs_a_OBJECTS = fs.$(OBJEXT) fsdatasourceiter.$(OBJEXT) \ fspropdisplayer.$(OBJEXT) fspropset.$(OBJEXT) \ fsstrings.$(OBJEXT) fsvisitor.$(OBJEXT) stdfs.$(OBJEXT) libfs_a_OBJECTS = $(am_libfs_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libfs_a_SOURCES) DIST_SOURCES = $(libfs_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libfs_adir)" +HEADERS = $(libfs_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -91,7 +221,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -99,6 +229,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -110,6 +241,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -126,21 +258,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -170,21 +305,33 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libfs.a +libfs_adir = . libfs_a_SOURCES = \ fs.cpp fsdatasourceiter.cpp fserrors.cpp fsfactory.cpp \ fsnametranslator.cpp fsobject.cpp fsparserutil.cpp \ fspropcalc.cpp fspropdisplayer.cpp fspropset.cpp \ fsstrings.cpp fsvisitor.cpp stdfs.cpp +libfs_a_HEADERS = \ + fs.h fsdatasourceiter.h fserrors.h fsfactory.h \ + fsnametranslator.h fsobject.h fsparserutil.h \ + fspropcalc.h fspropdisplayer.h fspropset.h fsstrings.h \ + fsvisitor.h stdfs.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -193,15 +340,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/fs/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/fs/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/fs/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/fs/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -218,13 +364,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libfs.a: $(libfs_a_OBJECTS) $(libfs_a_DEPENDENCIES) - -rm -f libfs.a - $(libfs_a_AR) libfs.a $(libfs_a_OBJECTS) $(libfs_a_LIBADD) - $(RANLIB) libfs.a + +libfs.a: $(libfs_a_OBJECTS) $(libfs_a_DEPENDENCIES) $(EXTRA_libfs_a_DEPENDENCIES) + $(AM_V_at)-rm -f libfs.a + $(AM_V_AR)$(libfs_a_AR) libfs.a $(libfs_a_OBJECTS) $(libfs_a_LIBADD) + $(AM_V_at)$(RANLIB) libfs.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -233,91 +381,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libfs_aHEADERS: $(libfs_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libfs_a_HEADERS)'; test -n "$(libfs_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libfs_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libfs_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libfs_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libfs_adir)" || exit $$?; \ + done + +uninstall-libfs_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libfs_a_HEADERS)'; test -n "$(libfs_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libfs_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libfs_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -328,16 +506,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -357,18 +542,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libfs_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -387,22 +592,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libfs_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libfs_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libfs_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libfs_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/fs/fs.cpp b/src/fs/fs.cpp index 76d64c0..30287a0 100644 --- a/src/fs/fs.cpp +++ b/src/fs/fs.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,20 +52,14 @@ // For some stupid linker reason, this object does not get constructed under // AIX. The cheap fix is to move this call to here from fspropdisplayer.cpp #include "fspropdisplayer.h" -IMPLEMENT_TYPEDSERIALIZABLE( cFSPropDisplayer, _T("FSPropDisplayer"), 0, 1 ); +IMPLEMENT_TYPEDSERIALIZABLE(cFSPropDisplayer, _T("FSPropDisplayer"), 0, 1); #endif -TSS_ImplementPackage( cFS ) +TSS_ImplementPackage(cFS) cFS::cFS() - : fsFactory(), - fsGenre( - GenreID(), - _T("FS"), - _T("Unix File System"), - &fsFactory - ) + : fsFactory(), fsGenre(GenreID(), _T("FS"), _T("Unix File System"), &fsFactory) { // // set up dependencies @@ -80,10 +74,9 @@ cFS::cFS() // TODO:BAM -- we include FS in the Win32 build but we don't want // it to be the default genre for that build // Remove this ifdef when we remove FS from the Win32 build - cGenreSwitcher::GetInstance()->RegisterGenre( &fsGenre, flags ); + cGenreSwitcher::GetInstance()->RegisterGenre(&fsGenre, flags); // register errors... // - TSS_REGISTER_PKG_ERRORS( fs ) + TSS_REGISTER_PKG_ERRORS(fs) } - diff --git a/src/fs/fs.h b/src/fs/fs.h index 6231810..8662ed7 100644 --- a/src/fs/fs.h +++ b/src/fs/fs.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,27 +42,32 @@ //--Requirements -#include "core/package.h" // for: Packaging Abstraction -#include "fco/genreinfo.h" // for: cGenreInfo -#include "fsfactory.h" // for: cFSFactory +#include "core/package.h" // for: Packaging Abstraction +#include "fco/genreinfo.h" // for: cGenreInfo +#include "fsfactory.h" // for: cFSFactory //--Classes -TSS_BeginPackage( cFS ) +TSS_BeginPackage(cFS) TSS_DECLARE_STRINGTABLE; - - public: - cFS(); - static cGenre::Genre GenreID() { return GENRE_ID; }; - private: - enum { GENRE_ID = 0x00020001 }; +public: +cFS(); +static cGenre::Genre GenreID() +{ + return GENRE_ID; +}; - cFSFactory fsFactory; - cGenreInfo fsGenre; +private: +enum +{ + GENRE_ID = 0x00020001 +}; -TSS_EndPackage( cFS ) +cFSFactory fsFactory; +cGenreInfo fsGenre; -#endif //#ifndef __FS_H +TSS_EndPackage(cFS) +#endif //#ifndef __FS_H diff --git a/src/fs/fsdatasourceiter.cpp b/src/fs/fsdatasourceiter.cpp index c6a6419..26acf15 100644 --- a/src/fs/fsdatasourceiter.cpp +++ b/src/fs/fsdatasourceiter.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,7 +42,6 @@ #include "fsdatasourceiter.h" #include "fco/fcodatasourceiter.h" #include "fsobject.h" -#include "core/fsservices.h" #include "core/errorbucket.h" #include "core/corestrings.h" #include "core/usernotify.h" @@ -59,27 +58,27 @@ cFSDataSourceIter::cFSDataSourceIter() : cFCODataSourceIterImpl(), mDev(0) { // set the case sensitiveness of the parent... // - mParentName.SetCaseSensitive( iTWFactory::GetInstance()->GetNameInfo()->IsCaseSensitive() ); + mParentName.SetCaseSensitive(iTWFactory::GetInstance()->GetNameInfo()->IsCaseSensitive()); } cFSDataSourceIter::~cFSDataSourceIter() { } -cFSDataSourceIter::cFSDataSourceIter( const cFSDataSourceIter& rhs ) : cFCODataSourceIterImpl(), mDev(0) +cFSDataSourceIter::cFSDataSourceIter(const cFSDataSourceIter& rhs) : cFCODataSourceIterImpl(), mDev(0) { // set the case sensitiveness of the parent... // - mParentName.SetCaseSensitive( iTWFactory::GetInstance()->GetNameInfo()->IsCaseSensitive() ); + mParentName.SetCaseSensitive(iTWFactory::GetInstance()->GetNameInfo()->IsCaseSensitive()); *this = rhs; } /////////////////////////////////////////////////////////////////////////////// // operator = /////////////////////////////////////////////////////////////////////////////// -cFSDataSourceIter& cFSDataSourceIter::operator=( const cFSDataSourceIter& rhs ) +cFSDataSourceIter& cFSDataSourceIter::operator=(const cFSDataSourceIter& rhs) { - if( this == &rhs ) + if (this == &rhs) return *this; // copy base @@ -99,10 +98,16 @@ static bool gCrossFileSystems = false; gCrossFileSystems = crossFS; } +void cFSDataSourceIter::AddIterationError(const eError& e) +{ + if (mpErrorBucket) + mpErrorBucket->AddError(e); +} + /////////////////////////////////////////////////////////////////////////////// // CreateCopy /////////////////////////////////////////////////////////////////////////////// -iFCODataSourceIter* cFSDataSourceIter::CreateCopy() const +iFCODataSourceIter* cFSDataSourceIter::CreateCopy() const { return (new cFSDataSourceIter(*this)); } @@ -110,29 +115,29 @@ iFCODataSourceIter* cFSDataSourceIter::CreateCopy() const /////////////////////////////////////////////////////////////////////////////// // CreateObject -- creates the named object and fills out its properties -// appropriately. Returns NULL if any errors occur and fills up the +// appropriately. Returns NULL if any errors occur and fills up the // error queue. -// +// // This does not create the object if dev > 0 and the object's mDev is not // equal to it (thus preventing the crossing of file systems) // // TODO -- in the future, this should become some kind of lazy evaluation so // that we don't have to get all the stats() we don't need to. /////////////////////////////////////////////////////////////////////////////// -iFCO * cFSDataSourceIter::CreateObject(const cFCOName& name, bool bCreatePeers ) +iFCO* cFSDataSourceIter::CreateObject(const cFCOName& name, bool bCreatePeers) { cFSObject* pNewObj = new cFSObject(name); - if( ! bCreatePeers ) + if (!bCreatePeers) { - // when bCreatePeers is false, it means we should set mDev to the + // when bCreatePeers is false, it means we should set mDev to the // device number of the current object (ie -- it is a new "start point") // If we don't do this here, InitializeTypeInfo() will reject creating the // node. // -- 9 June 99 mdb // mDev = 0; - if( ! InitializeTypeInfo( pNewObj ) ) + if (!InitializeTypeInfo(pNewObj)) { pNewObj->Release(); return 0; @@ -143,23 +148,50 @@ iFCO * cFSDataSourceIter::CreateObject(const cFCOName& name, bool bCreatePeers ) return pNewObj; } -void cFSDataSourceIter::GetChildrenNames( const TSTRING& strParentName, std::vector& vChildrenNames ) +void cFSDataSourceIter::GetChildrenNames(const TSTRING& strParentName, std::vector& vChildrenNames) { try { - iFSServices::GetInstance()->ReadDir( strParentName, vChildrenNames, false ); + iFSServices::GetInstance()->ReadDir(strParentName, vChildrenNames, false); + } + catch (eError& e) + { + AddIterationError(eFSDataSourceIterReadDir(strParentName, e.GetMsg(), eError::NON_FATAL)); } - catch( eFSServices& e ) + catch (std::exception& e) { - cDebug d("cFSDataSourceIter::GeneratePeers"); - d.TraceError("**** ReadDir failed for %s\n", strParentName.c_str() ); + AddIterationError(eFSDataSourceIterReadDir(strParentName, e.what(), eError::NON_FATAL)); + } + catch (...) + { + AddIterationError(eFSDataSourceIterReadDir(strParentName, "unknown", eError::NON_FATAL)); + } +} - if( mpErrorBucket ) - { - eFSDataSourceIterReadDir eReadDir(e.GetMsg(), eError::NON_FATAL); - mpErrorBucket->AddError( eReadDir ); - } +bool cFSDataSourceIter::DoStat(const TSTRING& name, cFSStatArgs& statArgs) +{ + try + { + iFSServices::GetInstance()->Stat(name, statArgs); + } + catch (eError& e) + { + e.SetFatality(false); + AddIterationError(e); + return false; + } + catch (std::exception& e) + { + AddIterationError(eFSDataSourceIter(name, e.what(), eError::NON_FATAL)); + return false; } + catch (...) + { + AddIterationError(eFSDataSourceIter(name, "unknown", eError::NON_FATAL)); + return false; + } + + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -167,65 +199,50 @@ void cFSDataSourceIter::GetChildrenNames( const TSTRING& strParentName, std::vec /////////////////////////////////////////////////////////////////////////////// bool cFSDataSourceIter::InitializeTypeInfo(iFCO* pFCO) { - cFSObject* pObj = (cFSObject*)pFCO; + cFSObject* pObj = (cFSObject*)pFCO; iFCONameTranslator* pTrans = iTWFactory::GetInstance()->GetNameTranslator(); - - if( pObj->GetFSPropSet().GetValidVector().ContainsItem( cFSPropSet::PROP_FILETYPE) ) + + if (pObj->GetFSPropSet().GetValidVector().ContainsItem(cFSPropSet::PROP_FILETYPE)) return true; - // // assume invalid by default... // cFSPropSet& propSet = pObj->GetFSPropSet(); propSet.SetFileType(cFSPropSet::FT_INVALID); cFSStatArgs statArgs; - try - { - iFSServices::GetInstance()->Stat( pTrans->ToStringAPI( pObj->GetName() ), statArgs); - } - catch(eFSServices& e) - { - cDebug d("CreateObject"); - d.TraceError( "*** Stat of %s failed!!!\n", pObj->GetName().AsString().c_str() ); - if( mpErrorBucket ) - { - e.SetFatality( false ); - mpErrorBucket->AddError( e ); - } + if (!DoStat(pObj->GetName().AsString(), statArgs)) return false; - } - - // + // don't create the object if it is on a different file system... // - if( gCrossFileSystems == false && (mDev != 0) && (statArgs.dev != mDev) ) + if (gCrossFileSystems == false && (mDev != 0) && (statArgs.dev != mDev)) { - TW_NOTIFY_NORMAL( TSS_GetString( cFS, fs::STR_DIFFERENT_FILESYSTEM ).c_str(), - pTrans->ToStringDisplay( pObj->GetName() ).c_str() ); + TW_NOTIFY_NORMAL(TSS_GetString(cFS, fs::STR_DIFFERENT_FILESYSTEM).c_str(), + pTrans->ToStringDisplay(pObj->GetName()).c_str()); return false; } // // fill out all of the appropriate properties.... // - propSet.SetDev (statArgs.dev); - propSet.SetRDev (statArgs.rdev); - propSet.SetInode (statArgs.ino); - propSet.SetMode (statArgs.mode); - propSet.SetNLink (statArgs.nlink); - propSet.SetUID (statArgs.uid); - propSet.SetGID (statArgs.gid); - propSet.SetSize (statArgs.size); - propSet.SetAccessTime (statArgs.atime); - propSet.SetModifyTime (statArgs.mtime); - propSet.SetCreateTime (statArgs.ctime); - propSet.SetBlockSize (statArgs.blksize); - propSet.SetBlocks (statArgs.blocks); - propSet.SetGrowingFile (statArgs.size); + propSet.SetDev( statArgs.dev); + propSet.SetRDev( statArgs.rdev); + propSet.SetInode( statArgs.ino); + propSet.SetMode( statArgs.mode); + propSet.SetNLink( statArgs.nlink); + propSet.SetUID( statArgs.uid); + propSet.SetGID( statArgs.gid); + propSet.SetSize( statArgs.size); + propSet.SetAccessTime( statArgs.atime); + propSet.SetModifyTime( statArgs.mtime); + propSet.SetCreateTime( statArgs.ctime); + propSet.SetBlockSize( statArgs.blksize); + propSet.SetBlocks( statArgs.blocks); + propSet.SetGrowingFile(statArgs.size); // set the file type - switch(statArgs.mFileType) + switch (statArgs.mFileType) { case cFSStatArgs::TY_FILE: propSet.SetFileType(cFSPropSet::FT_FILE); @@ -254,12 +271,13 @@ bool cFSDataSourceIter::InitializeTypeInfo(iFCO* pFCO) case cFSStatArgs::TY_PORT: propSet.SetFileType(cFSPropSet::FT_PORT); break; + case cFSStatArgs::TY_NAMED: + propSet.SetFileType(cFSPropSet::FT_NAMED); + break; default: // set it to invalid propSet.SetFileType(cFSPropSet::FT_INVALID); } return true; - } - diff --git a/src/fs/fsdatasourceiter.h b/src/fs/fsdatasourceiter.h index b4f0eee..4d5b4d8 100644 --- a/src/fs/fsdatasourceiter.h +++ b/src/fs/fsdatasourceiter.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,9 +39,11 @@ // INCLUDES //========================================================================= #include "fco/fcodatasourceiterimpl.h" +#include "core/fileerror.h" +#include "core/fsservices.h" -TSS_EXCEPTION( eFSDataSourceIter, eError ) -TSS_EXCEPTION( eFSDataSourceIterReadDir, eFSDataSourceIter ) +TSS_FILE_EXCEPTION(eFSDataSourceIter, eFileError) +TSS_FILE_EXCEPTION(eFSDataSourceIterReadDir, eFSDataSourceIter) //========================================================================= @@ -49,41 +51,43 @@ TSS_EXCEPTION( eFSDataSourceIterReadDir, eFSDataSourceIter ) //========================================================================= //----------------------------------------------------------------------------- -// *** Important Note: Not crossing file system boundaries works by noting the +// *** Important Note: Not crossing file system boundaries works by noting the // device number of the object created by SeekToFCO( XXX, false ), since it -// is assumed the only time you will pass false is when you are seeking to -// the start point of a spec. +// is assumed the only time you will pass false is when you are seeking to +// the start point of a spec. // -- 20 Jan 99 mdb //----------------------------------------------------------------------------- class cFSDataSourceIter : public cFCODataSourceIterImpl { public: - cFSDataSourceIter(); - cFSDataSourceIter( const cFSDataSourceIter& rhs ); - virtual ~cFSDataSourceIter(); + cFSDataSourceIter(); + cFSDataSourceIter(const cFSDataSourceIter& rhs); + virtual ~cFSDataSourceIter(); - cFSDataSourceIter& operator=( const cFSDataSourceIter& rhs ); + cFSDataSourceIter& operator=(const cFSDataSourceIter& rhs); virtual iFCODataSourceIter* CreateCopy() const; static void SetFileSystemCrossing(bool crossFS); - // Call this to set the property where cFSDataSourceIter does not automatically recurse - // across file system boundaries. Currently this is by default is set to false. + // Call this to set the property where cFSDataSourceIter does not automatically recurse + // across file system boundaries. Currently this is by default is set to false. //void TraceContents(int dl = -1) const; private: - uint64 mDev; // the device number of the last node reached through SeekTo() - // if this is zero, then it is assumed to be uninitialized + uint64 mDev; // the device number of the last node reached through SeekTo() + // if this is zero, then it is assumed to be uninitialized //------------------------------------------------------------------------- // helper methods //------------------------------------------------------------------------- - virtual void GetChildrenNames( const TSTRING& strParentName, std::vector& vChildrenNames ); + virtual void GetChildrenNames(const TSTRING& strParentName, std::vector& vChildrenNames); + + virtual iFCO* CreateObject(const cFCOName& name, bool bCreatingPeers); + virtual bool InitializeTypeInfo(iFCO* pFCO); - virtual iFCO* CreateObject(const cFCOName& name, bool bCreatingPeers ); - virtual bool InitializeTypeInfo(iFCO* pFCO) ; + void AddIterationError(const eError& e); + bool DoStat(const TSTRING& name, cFSStatArgs& statArgs); }; #endif //__FSDATASOURCEITER_H - diff --git a/src/fs/fserrors.cpp b/src/fs/fserrors.cpp index e494057..aba7836 100644 --- a/src/fs/fserrors.cpp +++ b/src/fs/fserrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,13 +41,12 @@ #include "core/errortable.h" -TSS_BEGIN_ERROR_REGISTRATION( fs ) +TSS_BEGIN_ERROR_REGISTRATION(fs) -TSS_REGISTER_ERROR( eFSPropCalc(), _T("NTFS property calculation error.") ) +TSS_REGISTER_ERROR(eFSPropCalc(), _T("Property calculation error.")) //TSS_REGISTER_ERROR( eFSPropCalcResetAccessTime(), _T("Could not reset access time for file.") ) -TSS_REGISTER_ERROR( eFSDataSourceIter(), _T("Data source iterator error.") ) -TSS_REGISTER_ERROR( eFSDataSourceIterReadDir(), _T("Could not access directory contents.") ) +TSS_REGISTER_ERROR(eFSDataSourceIter(), _T("Data source iterator error.")) +TSS_REGISTER_ERROR(eFSDataSourceIterReadDir(), _T("Could not access directory contents.")) TSS_END_ERROR_REGISTRATION() - diff --git a/src/fs/fserrors.h b/src/fs/fserrors.h index 2369419..fe18810 100644 --- a/src/fs/fserrors.h +++ b/src/fs/fserrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( fs ) - -#endif//__FSERRORS_H +TSS_DECLARE_ERROR_REGISTRATION(fs) +#endif //__FSERRORS_H diff --git a/src/fs/fsfactory.cpp b/src/fs/fsfactory.cpp index 1874aeb..fd4b11a 100644 --- a/src/fs/fsfactory.cpp +++ b/src/fs/fsfactory.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -50,21 +50,23 @@ class cUnixNameInfo : public iFCONameInfo { public: - virtual bool IsCaseSensitive() const + virtual bool IsCaseSensitive() const { return true; } - virtual TCHAR GetDelimitingChar() const + virtual TCHAR GetDelimitingChar() const { return _T('/'); } - - virtual ~cUnixNameInfo() {} + + virtual ~cUnixNameInfo() + { + } }; -iFCOPropCalc* cFSFactory::CreatePropCalc() const +iFCOPropCalc* cFSFactory::CreatePropCalc() const { return new cFSPropCalc(); } @@ -76,7 +78,12 @@ iFCOSpec* cFSFactory::CreateSpec(const TSTRING& name, iFCOSpecHelper* pHelper) c iFCOPropDisplayer* cFSFactory::CreatePropDisplayer() const { - return new cFSPropDisplayer(); + static iFCOPropDisplayer* gPropDisplayer = 0; + + if (!gPropDisplayer) + gPropDisplayer = new cFSPropDisplayer(); + + return gPropDisplayer; } iSerRefCountObj::CreateFunc cFSFactory::GetCreateFunc() const @@ -84,42 +91,42 @@ iSerRefCountObj::CreateFunc cFSFactory::GetCreateFunc() const return cFSObject::Create; } -iParserGenreUtil* cFSFactory::CreateParserGenreUtil() const +iParserGenreUtil* cFSFactory::CreateParserGenreUtil() const { return new cFSParserUtil(); } -iFCODataSourceIter* cFSFactory::CreateDataSourceIter() const +iFCODataSourceIter* cFSFactory::CreateDataSourceIter() const { return new cFSDataSourceIter(); } -iFCONameInfo* cFSFactory::GetNameInfo() const +iFCONameInfo* cFSFactory::GetNameInfo() const { static cUnixNameInfo gUnixNameInfo; return &gUnixNameInfo; } -cFCOPropVector cFSFactory::GetLooseDirMask() const +cFCOPropVector cFSFactory::GetLooseDirMask() const { static cFCOPropVector vec; - static bool bInit = false; + static bool bInit = false; - if( ! bInit ) + if (!bInit) { - vec.AddItem( cFSPropSet::PROP_SIZE ); - vec.AddItem( cFSPropSet::PROP_NLINK ); - vec.AddItem( cFSPropSet::PROP_ATIME ); - vec.AddItem( cFSPropSet::PROP_CTIME ); - vec.AddItem( cFSPropSet::PROP_MTIME ); - vec.AddItem( cFSPropSet::PROP_BLOCKS ); - vec.AddItem( cFSPropSet::PROP_GROWING_FILE ); - vec.AddItem( cFSPropSet::PROP_CRC32 ); - vec.AddItem( cFSPropSet::PROP_MD5 ); - vec.AddItem( cFSPropSet::PROP_SHA ); - vec.AddItem( cFSPropSet::PROP_HAVAL ); - + vec.AddItem(cFSPropSet::PROP_SIZE); + vec.AddItem(cFSPropSet::PROP_NLINK); + vec.AddItem(cFSPropSet::PROP_ATIME); + vec.AddItem(cFSPropSet::PROP_CTIME); + vec.AddItem(cFSPropSet::PROP_MTIME); + vec.AddItem(cFSPropSet::PROP_BLOCKS); + vec.AddItem(cFSPropSet::PROP_GROWING_FILE); + vec.AddItem(cFSPropSet::PROP_CRC32); + vec.AddItem(cFSPropSet::PROP_MD5); + vec.AddItem(cFSPropSet::PROP_SHA); + vec.AddItem(cFSPropSet::PROP_HAVAL); + bInit = true; } diff --git a/src/fs/fsfactory.h b/src/fs/fsfactory.h index 980dda7..6d185e0 100644 --- a/src/fs/fsfactory.h +++ b/src/fs/fsfactory.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // fsfactory.h -// +// // cFSFactory -- an implementation of iTWFactory that creates file system objects #ifndef __FSFACTORY_H #define __FSFACTORY_H @@ -43,20 +43,22 @@ class cFSFactory : public iTWFactory { public: - cFSFactory() {} - virtual ~cFSFactory() {} - + cFSFactory() + { + } + virtual ~cFSFactory() + { + } + virtual iFCOPropCalc* CreatePropCalc() const; virtual iFCOSpec* CreateSpec(const TSTRING& name, iFCOSpecHelper* pHelper) const; virtual iFCOPropDisplayer* CreatePropDisplayer() const; virtual iParserGenreUtil* CreateParserGenreUtil() const; virtual iSerRefCountObj::CreateFunc GetCreateFunc() const; - virtual iFCODataSourceIter* CreateDataSourceIter() const ; - virtual iFCONameInfo* GetNameInfo() const ; - virtual cFCOPropVector GetLooseDirMask() const ; + virtual iFCODataSourceIter* CreateDataSourceIter() const; + virtual iFCONameInfo* GetNameInfo() const; + virtual cFCOPropVector GetLooseDirMask() const; virtual iFCONameTranslator* GetNameTranslator() const; - }; #endif //__FSFACTORY_H - diff --git a/src/fs/fsnametranslator.cpp b/src/fs/fsnametranslator.cpp index ebb24bd..3510746 100644 --- a/src/fs/fsnametranslator.cpp +++ b/src/fs/fsnametranslator.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,7 +53,7 @@ /////////////////////////////////////////////////////////////////////////////// // ToStringRaw /////////////////////////////////////////////////////////////////////////////// -TSTRING cFSNameTranslator::ToStringRaw( const cFCOName& name ) const +TSTRING cFSNameTranslator::ToStringRaw(const cFCOName& name) const { return name.AsString(); } @@ -61,36 +61,36 @@ TSTRING cFSNameTranslator::ToStringRaw( const cFCOName& name ) const /////////////////////////////////////////////////////////////////////////////// // ToStringAPI /////////////////////////////////////////////////////////////////////////////// -TSTRING cFSNameTranslator::ToStringAPI( const cFCOName& name ) const +TSTRING cFSNameTranslator::ToStringAPI(const cFCOName& name) const { - ASSERT( name.GetDelimiter() == _T('/') ); - + ASSERT(name.GetDelimiter() == _T('/')); + return name.AsString(); } /////////////////////////////////////////////////////////////////////////////// // ToStringDisplay /////////////////////////////////////////////////////////////////////////////// -TSTRING cFSNameTranslator::ToStringDisplay( const cFCOName& name, bool bUnique ) const +TSTRING cFSNameTranslator::ToStringDisplay(const cFCOName& name, bool bUnique) const { TSTRING strRet; - if( bUnique ) + if (bUnique) { - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - TSTRING strUnencoded = name.AsString(); - e.Encode( strUnencoded ); + cDisplayEncoder e(cDisplayEncoder::ROUNDTRIP); + TSTRING strUnencoded = name.AsString(); + e.Encode(strUnencoded); const TCHAR dq = _T('\"'); strRet += dq; strRet += strUnencoded; - strRet += dq; + strRet += dq; } else { - cDisplayEncoder e( cDisplayEncoder::NON_ROUNDTRIP ); // cDisplayEncoder + cDisplayEncoder e(cDisplayEncoder::NON_ROUNDTRIP); // cDisplayEncoder strRet = name.AsString(); - e.Encode( strRet ); + e.Encode(strRet); } return strRet; @@ -99,27 +99,27 @@ TSTRING cFSNameTranslator::ToStringDisplay( const cFCOName& name, bool bUnique ) /////////////////////////////////////////////////////////////////////////////// // DisplayStringToFCOName /////////////////////////////////////////////////////////////////////////////// -bool cFSNameTranslator::DisplayStringToFCOName( const TSTRING& strC, cFCOName& name ) const -{ - TSTRING str = strC; - const TCHAR dq = _T('\"'); +bool cFSNameTranslator::DisplayStringToFCOName(const TSTRING& strC, cFCOName& name) const +{ + TSTRING str = strC; + const TCHAR dq = _T('\"'); // do a little error checking. must have at least '""' - if( str.size() < 1 ) + if (str.size() < 1) return false; - if( dq != str[0] ) + if (dq != str[0]) return false; - if( dq != str[str.size() - 1] ) + if (dq != str[str.size() - 1]) return false; // get rid of beginning and trailing quote - str = str.substr( 1, str.size() - 2 ); + str = str.substr(1, str.size() - 2); // // undo funky wide char encoding // - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - if( ! e.Decode( str ) ) + cDisplayEncoder e(cDisplayEncoder::ROUNDTRIP); + if (!e.Decode(str)) return false; // give to cFCOName @@ -127,4 +127,3 @@ bool cFSNameTranslator::DisplayStringToFCOName( const TSTRING& strC, cFCOName& n return true; } - diff --git a/src/fs/fsnametranslator.h b/src/fs/fsnametranslator.h index 4daf9f4..59443e2 100644 --- a/src/fs/fsnametranslator.h +++ b/src/fs/fsnametranslator.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,14 +53,15 @@ class cFSNameTranslator : public iFCONameTranslator public: // // basic functionality - // - virtual TSTRING ToStringRaw( const cFCOName& name ) const; - virtual TSTRING ToStringAPI( const cFCOName& name ) const; - virtual TSTRING ToStringDisplay( const cFCOName& name, bool bUnique = false ) const; - virtual bool DisplayStringToFCOName( const TSTRING& str, cFCOName& name ) const; - - virtual ~cFSNameTranslator() {} + // + virtual TSTRING ToStringRaw(const cFCOName& name) const; + virtual TSTRING ToStringAPI(const cFCOName& name) const; + virtual TSTRING ToStringDisplay(const cFCOName& name, bool bUnique = false) const; + virtual bool DisplayStringToFCOName(const TSTRING& str, cFCOName& name) const; + + virtual ~cFSNameTranslator() + { + } }; #endif //__FSNAMETRANSLATOR_H - diff --git a/src/fs/fsobject.cpp b/src/fs/fsobject.cpp index 2d2dabb..f0c9a91 100644 --- a/src/fs/fsobject.cpp +++ b/src/fs/fsobject.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,23 +41,20 @@ #include "core/error.h" #include "core/errorutil.h" -//uncomment to allocate fsobjects from a pool -//cObjectPoolBase cFSObject::msAllocator(sizeof(cFSObject), 1000); - // FCO Type information... IMPLEMENT_SERREFCOUNT(cFSObject, _T("FSObject"), 0, 1) // Debug stuff -#ifdef _DEBUG -static int gNumFSObjectCreate = 0; -static int gNumFSObjectDestroy = 0; +#ifdef DEBUG +static int gNumFSObjectCreate = 0; +static int gNumFSObjectDestroy = 0; -void cFSObject::TraceStats() +void cFSObject::TraceStats() { cDebug d("cFSObject::TraceStats"); - d.TraceDebug("cFSObject Stats:\n\tNum Created:\t%d\n\tNum Destroyed:\t%d\n", - gNumFSObjectCreate, gNumFSObjectDestroy); + d.TraceDebug( + "cFSObject Stats:\n\tNum Created:\t%d\n\tNum Destroyed:\t%d\n", gNumFSObjectCreate, gNumFSObjectDestroy); } @@ -67,7 +64,7 @@ class cFSNameStatPrinter ~cFSNameStatPrinter() { cDebug d("cFSNameStatPrinter"); - d.TraceDebug("*** Num fs objects created: %d Num destroyed: %d ***\n", gNumFSObjectCreate, gNumFSObjectDestroy ); + d.TraceDebug("*** Num fs objects created: %d Num destroyed: %d ***\n", gNumFSObjectCreate, gNumFSObjectDestroy); } } gFSNameStatPrinter; @@ -75,35 +72,33 @@ class cFSNameStatPrinter #endif //_DEBUG -cFSObject::cFSObject(const cFCOName& name) : - mName(name) +cFSObject::cFSObject(const cFCOName& name) : mName(name) { -#ifdef _DEBUG +#ifdef DEBUG gNumFSObjectCreate++; #endif } -cFSObject::cFSObject() : - mName(_T("undefined")) +cFSObject::cFSObject() : mName(_T("undefined")) { -#ifdef _DEBUG +#ifdef DEBUG gNumFSObjectCreate++; #endif } cFSObject::~cFSObject() { -#ifdef _DEBUG +#ifdef DEBUG gNumFSObjectDestroy++; #endif } -const cFCOName& cFSObject::GetName() const +const cFCOName& cFSObject::GetName() const { return mName; } -void cFSObject::SetName(const cFCOName& name) +void cFSObject::SetName(const cFCOName& name) { mName = name; } @@ -112,12 +107,12 @@ void cFSObject::SetName(const cFCOName& name) /////////////////////////////////////////////////////////////////////////////// // GetCaps /////////////////////////////////////////////////////////////////////////////// -uint32 cFSObject::GetCaps() const +uint32 cFSObject::GetCaps() const { uint32 cap = mName.GetSize() > 1 ? CAP_CAN_HAVE_PARENT : 0; - ASSERT( GetFSPropSet().GetValidVector().ContainsItem( cFSPropSet::PROP_FILETYPE ) ); - if( GetFSPropSet().GetFileType() == cFSPropSet::FT_DIR ) + ASSERT(GetFSPropSet().GetValidVector().ContainsItem(cFSPropSet::PROP_FILETYPE)); + if (GetFSPropSet().GetFileType() == cFSPropSet::FT_DIR) { cap |= CAP_CAN_HAVE_CHILDREN; } @@ -131,7 +126,7 @@ uint32 cFSObject::GetCaps() const /////////////////////////////////////////////////////////////////////////////// void cFSObject::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; cDebug d("cFSObject::TraceContents"); @@ -157,7 +152,7 @@ iFCOPropSet* cFSObject::GetPropSet() /////////////////////////////////////////////////////////////////////////////// // Clone /////////////////////////////////////////////////////////////////////////////// -iFCO* cFSObject::Clone() const +iFCO* cFSObject::Clone() const { cFSObject* pNew = new cFSObject(GetName()); // copy all the properties... @@ -169,7 +164,7 @@ iFCO* cFSObject::Clone() const /////////////////////////////////////////////////////////////////////////////// // Visitor Interface /////////////////////////////////////////////////////////////////////////////// -void cFSObject::AcceptVisitor(iFCOVisitor* pVisitor) +void cFSObject::AcceptVisitor(iFCOVisitor* pVisitor) { // first, make sure this is the right type... ASSERT(pVisitor->GetType() == iFSVisitor::mType); @@ -183,7 +178,7 @@ void cFSObject::Read(iSerializer* pSerializer, int32 version) if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("File System Object"))); - + pSerializer->ReadObject(&mName); pSerializer->ReadObject(&mPropSet); } @@ -194,6 +189,3 @@ void cFSObject::Write(iSerializer* pSerializer) const pSerializer->WriteObject(&mName); pSerializer->WriteObject(&mPropSet); } - - - diff --git a/src/fs/fsobject.h b/src/fs/fsobject.h index eb3a09e..8c2c3e9 100644 --- a/src/fs/fsobject.h +++ b/src/fs/fsobject.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -58,44 +58,44 @@ class cFSObject : public iFCO { DECLARE_SERREFCOUNT() - + public: - cFSObject(const cFCOName& name); + explicit cFSObject(const cFCOName& name); - virtual void SetName(const cFCOName& name) ; - virtual const cFCOName& GetName() const ; + virtual void SetName(const cFCOName& name); + virtual const cFCOName& GetName() const; - virtual const iFCOPropSet* GetPropSet() const ; - virtual iFCOPropSet* GetPropSet() ; - virtual uint32 GetCaps() const ; + virtual const iFCOPropSet* GetPropSet() const; + virtual iFCOPropSet* GetPropSet(); + virtual uint32 GetCaps() const; - virtual iFCO* Clone() const ; - virtual void AcceptVisitor(iFCOVisitor* pVisitor) ; + virtual iFCO* Clone() const; + virtual void AcceptVisitor(iFCOVisitor* pVisitor); - const cFSPropSet& GetFSPropSet() const; - cFSPropSet& GetFSPropSet(); - // returns a reference to the FS property set + const cFSPropSet& GetFSPropSet() const; + cFSPropSet& GetFSPropSet(); + // returns a reference to the FS property set // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void TraceContents(int dl = -1) const; -#ifdef _DEBUG - static void TraceStats() ; - // this TRACEs statistics on FSObject usage that is pertinent to performance or mem leakage - // concerns. +#ifdef DEBUG + static void TraceStats(); + // this TRACEs statistics on FSObject usage that is pertinent to performance or mem leakage + // concerns. #endif cFSObject(); - virtual ~cFSObject(); - // only destroy by calling Release(); Also prevents creation on the - // stack. + virtual ~cFSObject(); + // only destroy by calling Release(); Also prevents creation on the + // stack. private: - cFSPropSet mPropSet; - cFCOName mName; + cFSPropSet mPropSet; + cFCOName mName; }; ////////////////////////////////////////////////////// @@ -113,4 +113,3 @@ inline cFSPropSet& cFSObject::GetFSPropSet() #endif - diff --git a/src/fs/fsparserutil.cpp b/src/fs/fsparserutil.cpp index e4f6979..b0753ed 100644 --- a/src/fs/fsparserutil.cpp +++ b/src/fs/fsparserutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,37 +52,80 @@ // PUBLIC METHOD CODE //========================================================================= -bool cFSParserUtil::MapStringToProperty( const TSTRING& str, int& propIndex ) const +bool cFSParserUtil::MapStringToProperty(const TSTRING& str, int& propIndex) const { bool fMappedChar = true; // assume we'll recognize this char // and set false if we don't // for short names - if( str.length() == 1 ) + if (str.length() == 1) { - switch( str[0] ) + switch (str[0]) { - case 'p': propIndex = cFSPropSet::PROP_MODE; break; - case 'i': propIndex = cFSPropSet::PROP_INODE; break; - case 'n': propIndex = cFSPropSet::PROP_NLINK; break; - case 'u': propIndex = cFSPropSet::PROP_UID; break; - case 'g': propIndex = cFSPropSet::PROP_GID; break; - case 's': propIndex = cFSPropSet::PROP_SIZE; break; - case 't': propIndex = cFSPropSet::PROP_FILETYPE;break; - case 'd': propIndex = cFSPropSet::PROP_DEV; break; - case 'r': propIndex = cFSPropSet::PROP_RDEV; break; - case 'b': propIndex = cFSPropSet::PROP_BLOCKS; break; - case 'a': propIndex = cFSPropSet::PROP_ATIME; break; - case 'm': propIndex = cFSPropSet::PROP_MTIME; break; - case 'c': propIndex = cFSPropSet::PROP_CTIME; break; - case 'C': propIndex = cFSPropSet::PROP_CRC32; break; - case 'M': propIndex = cFSPropSet::PROP_MD5; break; - case 'S': propIndex = cFSPropSet::PROP_SHA; break; - case 'H': propIndex = cFSPropSet::PROP_HAVAL; break; - case 'l': propIndex = cFSPropSet::PROP_GROWING_FILE; break; - default: fMappedChar = false; break; + case 'p': + propIndex = cFSPropSet::PROP_MODE; + break; + case 'i': + propIndex = cFSPropSet::PROP_INODE; + break; + case 'n': + propIndex = cFSPropSet::PROP_NLINK; + break; + case 'u': + propIndex = cFSPropSet::PROP_UID; + break; + case 'g': + propIndex = cFSPropSet::PROP_GID; + break; + case 's': + propIndex = cFSPropSet::PROP_SIZE; + break; + case 't': + propIndex = cFSPropSet::PROP_FILETYPE; + break; + case 'd': + propIndex = cFSPropSet::PROP_DEV; + break; + case 'r': + propIndex = cFSPropSet::PROP_RDEV; + break; + case 'b': + propIndex = cFSPropSet::PROP_BLOCKS; + break; + case 'a': + propIndex = cFSPropSet::PROP_ATIME; + break; + case 'm': + propIndex = cFSPropSet::PROP_MTIME; + break; + case 'c': + propIndex = cFSPropSet::PROP_CTIME; + break; + case 'C': + propIndex = cFSPropSet::PROP_CRC32; + break; + case 'M': + propIndex = cFSPropSet::PROP_MD5; + break; + case 'S': + propIndex = cFSPropSet::PROP_SHA; + break; + case 'H': + propIndex = cFSPropSet::PROP_HAVAL; + break; + case 'l': + propIndex = cFSPropSet::PROP_GROWING_FILE; + break; + default: + fMappedChar = false; + break; } } + else + fMappedChar = false; + + /* Leaving this here in case we ever want to implement long property names + else { if( 0 == str.compare( TSS_GetString( cFS, fs::STR_PARSER_PROP_MODE ) ) ) @@ -122,79 +165,95 @@ bool cFSParserUtil::MapStringToProperty( const TSTRING& str, int& propIndex ) co else fMappedChar = false; } +*/ - return( fMappedChar ); + return (fMappedChar); } -void cFSParserUtil::AddSubTypeProps( cFCOPropVector& v ) const +void cFSParserUtil::AddSubTypeProps(cFCOPropVector& v) const { - v.AddItemAndGrow( cFSPropSet::PROP_FILETYPE ); + v.AddItemAndGrow(cFSPropSet::PROP_FILETYPE); } -void cFSParserUtil::InterpretFCOName( const std::list& l, cFCOName& nameOut ) const +static inline void trim_leading_whitespace(std::string& str) +{ + str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not1(std::ptr_fun(std::isspace)))); +} + +void cFSParserUtil::InterpretFCOName(const std::list& l, cFCOName& nameOut) const { TSTRING strT; - for( std::list::const_iterator i = l.begin(); i != l.end(); i++ ) + for (std::list::const_iterator i = l.begin(); i != l.end(); ++i) strT += *i; -#ifdef __AROS__ - strT = cArosPath::AsPosix(strT); +#if USES_DEVICE_PATH + strT = cDevicePath::AsPosix(strT); #endif + //Trim any remaining whitespace before actual path, for cases like " /foo", + // otherwise it'll be flagged as a relative path. + //Don't trim trailing whitespace, since that could potentially be a valid path. + if (strT[0] != '/') + trim_leading_whitespace(strT); + // let cFCOName handle interpretation nameOut = strT; } -bool cFSParserUtil::EnumPredefinedVariables( int index, TSTRING& sName, TSTRING& sValue ) const +bool cFSParserUtil::EnumPredefinedVariables(int index, TSTRING& sName, TSTRING& sValue) const { - switch( index ) + switch (index) { case 0: - sName = TSS_GetString( cFS, fs::STR_PARSER_READONLY ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_READONLY_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_READONLY); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_READONLY_VAL); return true; case 1: - sName = TSS_GetString( cFS, fs::STR_PARSER_DYNAMIC ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_DYNAMIC_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_DYNAMIC); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_DYNAMIC_VAL); return true; case 2: - sName = TSS_GetString( cFS, fs::STR_PARSER_GROWING ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_GROWING_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_GROWING); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_GROWING_VAL); return true; case 3: - sName = TSS_GetString( cFS, fs::STR_PARSER_IGNOREALL ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_IGNOREALL_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_IGNOREALL); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_IGNOREALL_VAL); return true; case 4: - sName = TSS_GetString( cFS, fs::STR_PARSER_IGNORENONE ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_IGNORENONE_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_IGNORENONE); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_IGNORENONE_VAL); return true; case 5: - sName = TSS_GetString( cFS, fs::STR_PARSER_DEVICE ); - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_DEVICE_VAL ); + sName = TSS_GetString(cFS, fs::STR_PARSER_DEVICE); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_DEVICE_VAL); return true; case 6: - sName = TSS_GetString( cFS, fs::STR_PARSER_HOSTNAME ); + sName = TSS_GetString(cFS, fs::STR_PARSER_HOSTNAME); try { - iFSServices::GetInstance()->GetMachineName( sValue); + iFSServices::GetInstance()->GetMachineName(sValue); if (sValue.empty()) - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_HOSTNAME_VAL ); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_HOSTNAME_VAL); } - catch( eFSServices& ) + catch (eFSServices&) { - sValue = TSS_GetString( cFS, fs::STR_FS_PARSER_HOSTNAME_VAL ); + sValue = TSS_GetString(cFS, fs::STR_FS_PARSER_HOSTNAME_VAL); } return true; default: return false; } - ASSERT( false ); // unreachable code + ASSERT(false); // unreachable code } -bool cFSParserUtil::IsAbsolutePath( const TSTRING& strPath ) const +bool cFSParserUtil::IsAbsolutePath(const TSTRING& strPath) const { - // IF there's a first character AND it is ( '/' OR '\\' ), THEN it's absolute - return( strPath.size() > 0 && ( _T('/') == strPath[0] || _T('\\') == strPath[0] ) ); +#if USES_DEVICE_PATH + return cDevicePath::IsAbsolutePath(strPath); +#else + // IF there's a first character AND it's a '/', it's absolute. + return (strPath.size() > 0 && (_T('/') == strPath[0])); +#endif } diff --git a/src/fs/fsparserutil.h b/src/fs/fsparserutil.h index b0e1b7c..f65ae99 100644 --- a/src/fs/fsparserutil.h +++ b/src/fs/fsparserutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,21 +52,21 @@ class cFSParserUtil : public iParserGenreUtil { public: - virtual bool MapStringToProperty( const TSTRING& str, int& propIndex ) const; - // maps the given string to an index into a property vector for the genre - virtual void AddSubTypeProps( cFCOPropVector& v ) const; - // add props that define object sub-type in genre - virtual void InterpretFCOName( const std::list& l, cFCOName& nameOut ) const; // throw( eParserGenreUtil ) + virtual bool MapStringToProperty(const TSTRING& str, int& propIndex) const; + // maps the given string to an index into a property vector for the genre + virtual void AddSubTypeProps(cFCOPropVector& v) const; + // add props that define object sub-type in genre + virtual void InterpretFCOName(const std::list& l, cFCOName& nameOut) const; // throw( eParserGenreUtil ) // given the input string list from the policy file, creates the cFCOName - virtual bool EnumPredefinedVariables( int index, TSTRING& sName, TSTRING& sValue ) const; - // set index to 0 before first call, then increment for each subsequent call. - // returns true if more var/val pairs - virtual bool IsAbsolutePath( const TSTRING& strPath ) const; - // returns true if the path is an absolute path, and false if it's relative. + virtual bool EnumPredefinedVariables(int index, TSTRING& sName, TSTRING& sValue) const; + // set index to 0 before first call, then increment for each subsequent call. + // returns true if more var/val pairs + virtual bool IsAbsolutePath(const TSTRING& strPath) const; + // returns true if the path is an absolute path, and false if it's relative. virtual bool HasSingleLetterProps() const; - // returns true if this genre uses single-letter to represent object properties - // in the policy language and the command line. If it returns false, the genre - // uses &-separated words. + // returns true if this genre uses single-letter to represent object properties + // in the policy language and the command line. If it returns false, the genre + // uses &-separated words. }; @@ -80,4 +80,3 @@ inline bool cFSParserUtil::HasSingleLetterProps() const } #endif //__FSPARSERUTIL_H - diff --git a/src/fs/fspropcalc.cpp b/src/fs/fspropcalc.cpp index 543d3bb..29bd98f 100644 --- a/src/fs/fspropcalc.cpp +++ b/src/fs/fspropcalc.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,23 +35,17 @@ #include "stdfs.h" #include "core/debug.h" #include "core/errorbucket.h" -#include "core/fsservices.h" #include "core/errorbucket.h" #include "fco/fconame.h" #include "fco/fconametranslator.h" #include "fco/twfactory.h" -#include "core/archive.h" - #include "fspropcalc.h" #include "fsobject.h" -#if IS_UNIX #include -#endif - +#include -cFSPropCalc::cFSPropCalc() : - mCollAction(iFCOPropCalc::PROP_LEAVE), mCalcFlags(0), mpErrorBucket(0) +cFSPropCalc::cFSPropCalc() : mCollAction(iFCOPropCalc::PROP_LEAVE), mCalcFlags(0), mpErrorBucket(0) { } @@ -60,27 +54,19 @@ cFSPropCalc::~cFSPropCalc() } /////////////////////////////////////////////////////////////////////////////// -// NeedsStat -- returns true if any properties are in the vector that require +// NeedsStat -- returns true if any properties are in the vector that require // a stat() call /////////////////////////////////////////////////////////////////////////////// static bool NeedsStat(const cFCOPropVector& v) { - return ( v.ContainsItem(cFSPropSet::PROP_DEV) || - v.ContainsItem(cFSPropSet::PROP_RDEV) || - v.ContainsItem(cFSPropSet::PROP_INODE) || - v.ContainsItem(cFSPropSet::PROP_MODE) || - v.ContainsItem(cFSPropSet::PROP_NLINK) || - v.ContainsItem(cFSPropSet::PROP_UID) || - v.ContainsItem(cFSPropSet::PROP_GID) || - v.ContainsItem(cFSPropSet::PROP_SIZE) || - v.ContainsItem(cFSPropSet::PROP_ATIME) || - v.ContainsItem(cFSPropSet::PROP_MTIME) || - v.ContainsItem(cFSPropSet::PROP_CTIME) || - v.ContainsItem(cFSPropSet::PROP_BLOCK_SIZE) || - v.ContainsItem(cFSPropSet::PROP_BLOCKS) || - v.ContainsItem(cFSPropSet::PROP_FILETYPE) || - v.ContainsItem(cFSPropSet::PROP_GROWING_FILE) - ); + return (v.ContainsItem(cFSPropSet::PROP_DEV) || v.ContainsItem(cFSPropSet::PROP_RDEV) || + v.ContainsItem(cFSPropSet::PROP_INODE) || v.ContainsItem(cFSPropSet::PROP_MODE) || + v.ContainsItem(cFSPropSet::PROP_NLINK) || v.ContainsItem(cFSPropSet::PROP_UID) || + v.ContainsItem(cFSPropSet::PROP_GID) || v.ContainsItem(cFSPropSet::PROP_SIZE) || + v.ContainsItem(cFSPropSet::PROP_ATIME) || v.ContainsItem(cFSPropSet::PROP_MTIME) || + v.ContainsItem(cFSPropSet::PROP_CTIME) || v.ContainsItem(cFSPropSet::PROP_BLOCK_SIZE) || + v.ContainsItem(cFSPropSet::PROP_BLOCKS) || v.ContainsItem(cFSPropSet::PROP_FILETYPE) || + v.ContainsItem(cFSPropSet::PROP_GROWING_FILE)); } /////////////////////////////////////////////////////////////////////////////// @@ -90,269 +76,310 @@ static bool NeedsStat(const cFCOPropVector& v) /////////////////////////////////////////////////////////////////////////////// -static bool GetSymLinkStr(const cFCOName& fileName, cArchive& arch) +bool cFSPropCalc::GetSymLinkStr(const TSTRING& strName, cArchive& arch, size_t size) { -#if !IS_WIN32 -#ifdef _UNICODE -#error GetSymLinkStr in fspropcalc.cpp is not unicode compliant -#else // ifdef _UNICODE - char buf[1024]; - int rtn = readlink( iTWFactory::GetInstance()->GetNameTranslator()->ToStringAPI( fileName ).c_str(), - buf, 1024 ); - if(rtn == -1) + std::vector data(size + 1); + char* buf = &data[0]; + +#if defined(O_PATH) // A Linuxism that lets us read symlinks w/o bumping the access time. + int fd = open(strName.c_str(), (O_PATH | O_NOFOLLOW | O_NOATIME)); + int rtn = readlinkat(fd, 0, buf, size); + close(fd); +#else + int rtn = readlink(strName.c_str(), buf, size); +#endif + + if (rtn < 0) + { + // Some OSes (like HP-UX) return ERANGE if buffer is too small. + // This is nonstandard but better than the usual truncate-and-say-you-succeeded + // + if (ERANGE == errno) + return GetSymLinkStr(strName, arch, size * 2); + + return false; + } + + //Sadly if buf isn't big enough readlink 'succeeds' by truncating the string, so the only + // clue your buffer might be too small is if you maxed it out. So we try again, within reason. +#if IS_SKYOS + if ((size_t)rtn >= size - 1) //SkyOS wants space to null terminate the string it hands back, which is nice, I guess. +#else + if ((size_t)rtn == size) +#endif + { + if (size < 128 * TW_PATH_SIZE) + return GetSymLinkStr(strName, arch, size * 2); + return false; + } - // the return value is the number of characters written. - arch.WriteBlob(buf, rtn); + // the return value is the number of characters written. + arch.WriteBlob(buf, rtn); return true; - -#endif // ifdef _UNICODE -#else // if !IS_WIN32 - return false; // TODO: find better way to do this -- just a place holder -#endif // if !IS_WIN32 } +void cFSPropCalc::AddPropCalcError(const eError& e) +{ + if (mpErrorBucket) + mpErrorBucket->AddError(e); +} -/////////////////////////////////////////////////////////////////////////////// -// VisitFSObject -- this is the workhorse method that actually fills out the -// passed in FSObject' properties -/////////////////////////////////////////////////////////////////////////////// -void cFSPropCalc::VisitFSObject(cFSObject& obj) +bool cFSPropCalc::DoStat(const TSTRING& strName, cFSStatArgs& statArgs) { - cDebug d("cFSPropCalc::VisitFSObject"); - d.TraceDetail(_T("Visiting %s\n"), obj.GetName().AsString().c_str()); + cDebug d("cFSPropCalc::DoStat"); - // if we are not in overwrite mode, we need to alter the - // properties we are calculating... - cFCOPropVector propsToCheck(mPropVector); - if(mCollAction == iFCOPropCalc::PROP_LEAVE) + try { - cFCOPropVector inBoth = propsToCheck; - inBoth &= obj.GetPropSet()->GetValidVector(); - propsToCheck ^= inBoth; + d.TraceDetail("---Performing Stat()\n"); + iFSServices::GetInstance()->Stat(strName, statArgs); + } + catch (eError& e) + { + d.TraceError("Error getting stat info for %s : %s\n", strName.c_str(), e.GetMsg().c_str()); + e.SetFatality(false); + AddPropCalcError(e); + return false; + } + catch (std::exception& e) + { + d.TraceError("Error getting stat info for %s : %s\n", strName.c_str(), e.what()); + AddPropCalcError(eFSPropCalc(strName, e.what(), eError::NON_FATAL)); + return false; + } + catch (...) + { + d.TraceError("Unknown error getting stat info for %s\n", strName.c_str()); + AddPropCalcError(eFSPropCalc(strName, "unknown", eError::NON_FATAL)); + return false; } -#ifdef _DEBUG - d.TraceDetail("----->Collision Action = %s\n", mCollAction == iFCOPropCalc::PROP_LEAVE ? "Leave" : "Replace"); - d.TraceDetail("----->Object's valid properties (a):\n"); - obj.GetPropSet()->GetValidVector().TraceContents(cDebug::D_DETAIL); - d.TraceDetail("----->Properties to calculate: (b)\n"); - mPropVector.TraceContents(cDebug::D_DETAIL); - d.TraceDetail("----->Properties to change in object ((a&b)^b for Leave or b for Replace):\n"); - propsToCheck.TraceContents(cDebug::D_DETAIL); -#endif //_DEBUG + return true; +} - // only do the stat() if it is necessary - iFSServices* pFSServices = iFSServices::GetInstance(); - cFSStatArgs ss; - bool bDidStat = false; - TSTRING strName = iTWFactory::GetInstance()->GetNameTranslator()->ToStringAPI( obj.GetName() ); +bool cFSPropCalc::DoOpen(const TSTRING& strName, cFileArchive& arch) +{ + try + { + arch.OpenRead(strName.c_str(), + ((mCalcFlags & iFCOPropCalc::DIRECT_IO) ? cFileArchive::FA_SCANNING | cFileArchive::FA_DIRECT : + cFileArchive::FA_SCANNING)); + } + catch (eError&) + { + AddPropCalcError(eArchiveOpen(strName, iFSServices::GetInstance()->GetErrString(), eError::NON_FATAL)); + return false; + } + catch (std::exception& e) + { + AddPropCalcError(eArchiveOpen(strName, e.what(), eError::NON_FATAL)); + return false; + } + catch (...) + { + AddPropCalcError(eArchiveOpen(strName, "unknown", eError::NON_FATAL)); + return false; + } - // get a reference to the fco's property set - cFSPropSet& propSet = obj.GetFSPropSet(); - - // - // just return if this object is invalid - // - if( propSet.GetFileType() == cFSPropSet::FT_INVALID ) - return; + return true; +} +bool cFSPropCalc::DoHash(const TSTRING& strName, cBidirArchive* pTheArch, cArchiveSigGen& asg, cFileArchive& arch) +{ + cDebug d("cFSPropCalc::DoHash"); try { - if( NeedsStat(propsToCheck) ) - { - d.TraceDetail("---Performing Stat()\n"); - pFSServices->Stat(strName, ss); - bDidStat = true; - } + pTheArch->Seek(0, cBidirArchive::BEGINNING); + asg.CalculateSignatures(*pTheArch); + arch.Close(); } - catch(eFSServices& e) + catch (eError& e) { - d.TraceError("Error getting stat info for %s : %s\n", strName.c_str(), e.GetMsg().c_str()); - - // add this fco to the error set... - // it is assumed that the file name that the error is associated with is in the exception's - // GetMsg() - e.SetFatality( false ); - if(mpErrorBucket) - mpErrorBucket->AddError( e ); - return; + d.TraceError("Error generating hashes for %s : %s\n", strName.c_str(), e.GetMsg().c_str()); + e.SetFatality(false); + AddPropCalcError(e); + return false; + } + catch (std::exception& e) + { + d.TraceError("Error generating hashes for %s : %s\n", strName.c_str(), e.what()); + AddPropCalcError(eArchiveRead(strName, e.what(), eError::NON_FATAL)); + return false; + } + catch (...) + { + d.TraceError("Unknown error generating hashes for %s\n", strName.c_str()); + AddPropCalcError(eArchiveRead(strName, "unknown", eError::NON_FATAL)); + return false; } - // for now, I will only fill out the stat info indicated in the property vector, - // but in reality, there is no reason not to fill out everything, since we have the - // extra information for free! - if(bDidStat) + return true; +} + +void cFSPropCalc::HandleStatProperties(const cFCOPropVector& propsToCheck, const cFSStatArgs& ss, cFSPropSet& propSet) +{ + if (propsToCheck.ContainsItem(cFSPropSet::PROP_DEV)) + propSet.SetDev(ss.dev); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_RDEV)) + propSet.SetRDev(ss.rdev); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_INODE)) + propSet.SetInode(ss.ino); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_MODE)) + propSet.SetMode(ss.mode); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_NLINK)) + propSet.SetNLink(ss.nlink); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_UID)) + propSet.SetUID(ss.uid); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_GID)) + propSet.SetGID(ss.gid); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_SIZE)) + propSet.SetSize(ss.size); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_ATIME)) + propSet.SetAccessTime(ss.atime); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_MTIME)) + propSet.SetModifyTime(ss.mtime); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_CTIME)) + propSet.SetCreateTime(ss.ctime); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_BLOCK_SIZE)) + propSet.SetBlockSize(ss.blksize); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_BLOCKS)) + propSet.SetBlocks(ss.blocks); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_GROWING_FILE)) + propSet.SetGrowingFile(ss.size); + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_FILETYPE)) { - if(propsToCheck.ContainsItem(cFSPropSet::PROP_DEV)) - propSet.SetDev(ss.dev); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_RDEV)) - propSet.SetRDev(ss.rdev); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_INODE)) - propSet.SetInode(ss.ino); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_MODE)) - propSet.SetMode(ss.mode); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_NLINK)) - propSet.SetNLink(ss.nlink); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_UID)) - propSet.SetUID(ss.uid); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_GID)) - propSet.SetGID(ss.gid); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_SIZE)) - propSet.SetSize(ss.size); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_ATIME)) - propSet.SetAccessTime(ss.atime); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_MTIME)) - propSet.SetModifyTime(ss.mtime); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_CTIME)) - propSet.SetCreateTime(ss.ctime); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_BLOCK_SIZE)) - propSet.SetBlockSize(ss.blksize); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_BLOCKS)) - propSet.SetBlocks(ss.blocks); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_GROWING_FILE)) - propSet.SetGrowingFile(ss.size); - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_FILETYPE)) + // TODO -- It _really_ bites duplicating code here and in fsdatasource.cpp + // *** This _has_ to be remedied somehow! + // set the file type + switch (ss.mFileType) { - // TODO -- It _really_ bites duplicating code here and in fsdatasource.cpp - // *** This _has_ to be remedied somehow! - // set the file type - switch(ss.mFileType) - { - case cFSStatArgs::TY_FILE: - propSet.SetFileType(cFSPropSet::FT_FILE); - break; - case cFSStatArgs::TY_DIR: - propSet.SetFileType(cFSPropSet::FT_DIR); - break; - case cFSStatArgs::TY_BLOCKDEV: - propSet.SetFileType(cFSPropSet::FT_BLOCKDEV); - break; - case cFSStatArgs::TY_CHARDEV: - propSet.SetFileType(cFSPropSet::FT_CHARDEV); - break; - case cFSStatArgs::TY_SYMLINK: - propSet.SetFileType(cFSPropSet::FT_SYMLINK); - break; - case cFSStatArgs::TY_FIFO: - propSet.SetFileType(cFSPropSet::FT_FIFO); - break; - case cFSStatArgs::TY_SOCK: - propSet.SetFileType(cFSPropSet::FT_SOCK); - break; - case cFSStatArgs::TY_DOOR: - propSet.SetFileType(cFSPropSet::FT_DOOR); - break; - case cFSStatArgs::TY_PORT: - propSet.SetFileType(cFSPropSet::FT_PORT); - break; - default: - // set it to invalid - propSet.SetFileType(cFSPropSet::FT_INVALID); - } - } + case cFSStatArgs::TY_FILE: + propSet.SetFileType(cFSPropSet::FT_FILE); + break; + case cFSStatArgs::TY_DIR: + propSet.SetFileType(cFSPropSet::FT_DIR); + break; + case cFSStatArgs::TY_BLOCKDEV: + propSet.SetFileType(cFSPropSet::FT_BLOCKDEV); + break; + case cFSStatArgs::TY_CHARDEV: + propSet.SetFileType(cFSPropSet::FT_CHARDEV); + break; + case cFSStatArgs::TY_SYMLINK: + propSet.SetFileType(cFSPropSet::FT_SYMLINK); + break; + case cFSStatArgs::TY_FIFO: + propSet.SetFileType(cFSPropSet::FT_FIFO); + break; + case cFSStatArgs::TY_SOCK: + propSet.SetFileType(cFSPropSet::FT_SOCK); + break; + case cFSStatArgs::TY_DOOR: + propSet.SetFileType(cFSPropSet::FT_DOOR); + break; + case cFSStatArgs::TY_PORT: + propSet.SetFileType(cFSPropSet::FT_PORT); + break; + case cFSStatArgs::TY_NAMED: + propSet.SetFileType(cFSPropSet::FT_NAMED); + break; + default: + // set it to invalid + propSet.SetFileType(cFSPropSet::FT_INVALID); + } } +} + +void cFSPropCalc::HandleHashes(const cFCOPropVector& propsToCheck, const TSTRING& strName, cFSPropSet& propSet) +{ + bool hash_success = false; // if the file type is not a regular file, we will // not try to open the file for signature generation - ASSERT( propSet.GetValidVector().ContainsItem(cFSPropSet::PROP_FILETYPE) ); - if( propSet.GetFileType() == cFSPropSet::FT_FILE || propSet.GetFileType() == cFSPropSet::FT_SYMLINK ) + ASSERT(propSet.GetValidVector().ContainsItem(cFSPropSet::PROP_FILETYPE)); + if (propSet.GetFileType() == cFSPropSet::FT_FILE || propSet.GetFileType() == cFSPropSet::FT_SYMLINK) { - if( // if we need to open the file - propsToCheck.ContainsItem(cFSPropSet::PROP_CRC32) || - propsToCheck.ContainsItem(cFSPropSet::PROP_MD5) || - propsToCheck.ContainsItem(cFSPropSet::PROP_SHA) || - propsToCheck.ContainsItem(cFSPropSet::PROP_HAVAL) - ) + if ( // if we need to open the file + propsToCheck.ContainsItem(cFSPropSet::PROP_CRC32) || propsToCheck.ContainsItem(cFSPropSet::PROP_MD5) || + propsToCheck.ContainsItem(cFSPropSet::PROP_SHA) || propsToCheck.ContainsItem(cFSPropSet::PROP_HAVAL)) { - cFileArchive arch; - cMemoryArchive memArch; - cBidirArchive* pTheArch; - bool bInitSuccess = true; - if(propSet.GetFileType() == cFSPropSet::FT_SYMLINK) + cFileArchive arch; + cMemoryArchive memArch; + cBidirArchive* pTheArch; + hash_success = true; + + if (propSet.GetFileType() == cFSPropSet::FT_SYMLINK) { pTheArch = &memArch; - if(! GetSymLinkStr(obj.GetName(), memArch)) + if (!GetSymLinkStr(strName, memArch)) { // add it to the bucket... - if(mpErrorBucket) - mpErrorBucket->AddError( eArchiveOpen( strName, iFSServices::GetInstance()->GetErrString(), eError::NON_FATAL ) ); - bInitSuccess = false; + AddPropCalcError( + eArchiveOpen(strName, iFSServices::GetInstance()->GetErrString(), eError::NON_FATAL)); + hash_success = false; } - } else { - pTheArch = &arch; - try - { - arch.OpenRead(strName.c_str(), cFileArchive::FA_NONBLOCKING); - } - catch (eArchive&) - { - // add it to the bucket... - if(mpErrorBucket) - mpErrorBucket->AddError( eArchiveOpen( strName, iFSServices::GetInstance()->GetErrString(), eError::NON_FATAL ) ); - bInitSuccess = false; - } + pTheArch = &arch; + hash_success = DoOpen(strName, arch); } - + // // if we have successfully initialized the archive // - if (bInitSuccess) + if (hash_success) { cArchiveSigGen asg; - if(propsToCheck.ContainsItem(cFSPropSet::PROP_CRC32)) + if (propsToCheck.ContainsItem(cFSPropSet::PROP_CRC32)) { propSet.SetDefinedCRC32(true); - asg.AddSig( propSet.GetCRC32() ); + asg.AddSig(propSet.GetCRC32()); } - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_MD5)) + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_MD5)) { propSet.SetDefinedMD5(true); - asg.AddSig( propSet.GetMD5() ); + asg.AddSig(propSet.GetMD5()); } - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_SHA)) + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_SHA)) { propSet.SetDefinedSHA(true); - asg.AddSig( propSet.GetSHA() ); + asg.AddSig(propSet.GetSHA()); } - - if(propsToCheck.ContainsItem(cFSPropSet::PROP_HAVAL)) + + if (propsToCheck.ContainsItem(cFSPropSet::PROP_HAVAL)) { propSet.SetDefinedHAVAL(true); - asg.AddSig( propSet.GetHAVAL() ); + asg.AddSig(propSet.GetHAVAL()); } - + // // calculate the signatures // - pTheArch->Seek( 0, cBidirArchive::BEGINNING ); - asg.CalculateSignatures( *pTheArch ); - arch.Close(); + hash_success = DoHash(strName, pTheArch, asg, arch); } } } - else + + if (!hash_success) { // We can't calculate signatures, set them to undefined if (propsToCheck.ContainsItem(cFSPropSet::PROP_CRC32)) @@ -369,6 +396,59 @@ void cFSPropCalc::VisitFSObject(cFSObject& obj) } } +/////////////////////////////////////////////////////////////////////////////// +// VisitFSObject -- this is the workhorse method that actually fills out the +// passed in FSObject' properties +/////////////////////////////////////////////////////////////////////////////// +void cFSPropCalc::VisitFSObject(cFSObject& obj) +{ + cDebug d("cFSPropCalc::VisitFSObject"); + d.TraceDetail(_T("Visiting %s\n"), obj.GetName().AsString().c_str()); + + // if we are not in overwrite mode, we need to alter the + // properties we are calculating... + cFCOPropVector propsToCheck(mPropVector); + if (mCollAction == iFCOPropCalc::PROP_LEAVE) + { + cFCOPropVector inBoth = propsToCheck; + inBoth &= obj.GetPropSet()->GetValidVector(); + propsToCheck ^= inBoth; + } + +#ifdef DEBUG + d.TraceDetail("----->Collision Action = %s\n", mCollAction == iFCOPropCalc::PROP_LEAVE ? "Leave" : "Replace"); + d.TraceDetail("----->Object's valid properties (a):\n"); + obj.GetPropSet()->GetValidVector().TraceContents(cDebug::D_DETAIL); + d.TraceDetail("----->Properties to calculate: (b)\n"); + mPropVector.TraceContents(cDebug::D_DETAIL); + d.TraceDetail("----->Properties to change in object ((a&b)^b for Leave or b for Replace):\n"); + propsToCheck.TraceContents(cDebug::D_DETAIL); +#endif //_DEBUG + + // only do the stat() if it is necessary + cFSStatArgs ss; + TSTRING strName = iTWFactory::GetInstance()->GetNameTranslator()->ToStringAPI(obj.GetName()); + + // get a reference to the fco's property set + cFSPropSet& propSet = obj.GetFSPropSet(); + + // + // just return if this object is invalid + // + if (propSet.GetFileType() == cFSPropSet::FT_INVALID) + return; + + if (NeedsStat(propsToCheck)) + { + if (!DoStat(strName, ss)) + return; + + HandleStatProperties(propsToCheck, ss, propSet); + } + + HandleHashes(propsToCheck, strName, propSet); +} + void cFSPropCalc::SetPropVector(const cFCOPropVector& pv) { mPropVector = pv; @@ -389,12 +469,12 @@ const iFCOVisitor* cFSPropCalc::GetVisitor() const return this; } -void cFSPropCalc::SetErrorBucket(cErrorBucket* pBucket) +void cFSPropCalc::SetErrorBucket(cErrorBucket* pBucket) { mpErrorBucket = pBucket; } -const cErrorBucket* cFSPropCalc::GetErrorBucket() const +const cErrorBucket* cFSPropCalc::GetErrorBucket() const { return mpErrorBucket; } @@ -409,4 +489,3 @@ void cFSPropCalc::SetCollisionAction(CollisionAction a) ASSERT((a == iFCOPropCalc::PROP_OVERWRITE) || (a == PROP_LEAVE)); mCollAction = a; } - diff --git a/src/fs/fspropcalc.h b/src/fs/fspropcalc.h index 63f76f8..e951f9a 100644 --- a/src/fs/fspropcalc.h +++ b/src/fs/fspropcalc.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,7 +47,19 @@ #include "fco/fcopropvector.h" #endif -TSS_EXCEPTION( eFSPropCalc, eError ) +#include "fco/signature.h" +#include "core/fileerror.h" +#include "core/fsservices.h" +#include "core/archive.h" +#include "fspropset.h" + +#ifdef PATH_MAX +# define TW_PATH_SIZE PATH_MAX +#else +# define TW_PATH_SIZE 1024 +#endif + +TSS_FILE_EXCEPTION(eFSPropCalc, eFileError) //TSS_EXCEPTION( eFSPropCalcResetAccessTime, eFSPropCalc ) // this was never used class cFSPropCalc : public iFCOPropCalc, public iFSVisitor @@ -60,27 +72,38 @@ class cFSPropCalc : public iFCOPropCalc, public iFSVisitor virtual void VisitFSObject(cFSObject& obj); // from iFCOPropCalc - virtual void SetPropVector(const cFCOPropVector& pv); - virtual const cFCOPropVector& GetPropVector() const; - virtual iFCOVisitor* GetVisitor(); - virtual const iFCOVisitor* GetVisitor() const; + virtual void SetPropVector(const cFCOPropVector& pv); + virtual const cFCOPropVector& GetPropVector() const; + virtual iFCOVisitor* GetVisitor(); + virtual const iFCOVisitor* GetVisitor() const; + + virtual void SetErrorBucket(cErrorBucket* pBucket); + virtual const cErrorBucket* GetErrorBucket() const; + + virtual CollisionAction GetCollisionAction() const; + virtual void SetCollisionAction(CollisionAction a); - virtual void SetErrorBucket(cErrorBucket* pBucket) ; - virtual const cErrorBucket* GetErrorBucket() const ; + virtual int GetCalcFlags() const; + virtual void SetCalcFlags(int i); - virtual CollisionAction GetCollisionAction() const; - virtual void SetCollisionAction(CollisionAction a); + static bool GetSymLinkStr(const TSTRING& strName, cArchive& arch, size_t size = TW_PATH_SIZE); - virtual int GetCalcFlags() const; - virtual void SetCalcFlags( int i ); private: - cFSPropCalc( const cFSPropCalc& ); - void operator =( const cFSPropCalc& ); + cFSPropCalc(const cFSPropCalc&); + void operator=(const cFSPropCalc&); - cFCOPropVector mPropVector; - iFCOPropCalc::CollisionAction mCollAction; - int mCalcFlags; - cErrorBucket* mpErrorBucket; + void AddPropCalcError(const eError& e); + + bool DoStat(const TSTRING& name, cFSStatArgs& statArgs); + bool DoOpen(const TSTRING& name, cFileArchive& arch); + bool DoHash(const TSTRING& name, cBidirArchive* pTheArch, cArchiveSigGen& asg, cFileArchive& arch); + void HandleStatProperties(const cFCOPropVector& propsToCheck, const cFSStatArgs& ss, cFSPropSet& propSet); + void HandleHashes(const cFCOPropVector& propsToCheck, const TSTRING& strName, cFSPropSet& propSet); + + cFCOPropVector mPropVector; + iFCOPropCalc::CollisionAction mCollAction; + int mCalcFlags; + cErrorBucket* mpErrorBucket; }; inline int cFSPropCalc::GetCalcFlags() const @@ -88,11 +111,10 @@ inline int cFSPropCalc::GetCalcFlags() const return mCalcFlags; } -inline void cFSPropCalc::SetCalcFlags( int i ) +inline void cFSPropCalc::SetCalcFlags(int i) { mCalcFlags = i; } #endif //__FSPROPCALC_H - diff --git a/src/fs/fspropdisplayer.cpp b/src/fs/fspropdisplayer.cpp index bd314ac..4ed6215 100644 --- a/src/fs/fspropdisplayer.cpp +++ b/src/fs/fspropdisplayer.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -68,7 +68,7 @@ #if !IS_AIX // For some stupid linker reason, this object does not get constructed under // AIX. The cheap fix is to move this call to fs.cpp. -IMPLEMENT_TYPEDSERIALIZABLE( cFSPropDisplayer, _T("FSPropDisplayer"), 0, 1 ); +IMPLEMENT_TYPEDSERIALIZABLE(cFSPropDisplayer, _T("FSPropDisplayer"), 0, 1); #endif //========================================================================= @@ -83,30 +83,29 @@ IMPLEMENT_TYPEDSERIALIZABLE( cFSPropDisplayer, _T("FSPropDisplayer"), 0, 1 ); // METHOD CODE //========================================================================= -cFSPropDisplayer::cFSPropDisplayer() - : mbLazy( false ) +cFSPropDisplayer::cFSPropDisplayer() : mbLazy(false) { - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_UID ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_GID ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_ATIME ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_MTIME ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_CTIME ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_MODE ); - - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_BLOCK_SIZE ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_BLOCKS ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_SIZE ); - mpvPropsWeDisplay.AddItemAndGrow( cFSPropSet::PROP_NLINK ); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_UID); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_GID); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_ATIME); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_MTIME); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_CTIME); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_MODE); + + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_BLOCK_SIZE); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_BLOCKS); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_SIZE); + mpvPropsWeDisplay.AddItemAndGrow(cFSPropSet::PROP_NLINK); } iFCOPropDisplayer* cFSPropDisplayer::Clone() const { iFCOPropDisplayer* pNew = new cFSPropDisplayer; - pNew->Merge( this ); + pNew->Merge(this); return pNew; } -bool cFSPropDisplayer::IsMultiLineProp( int propID ) const +bool cFSPropDisplayer::IsMultiLineProp(int propID) const { // no FS props are multiline return false; @@ -115,7 +114,7 @@ bool cFSPropDisplayer::IsMultiLineProp( int propID ) const cFSPropDisplayer::~cFSPropDisplayer() { cDebug d("~cFSPropDisplayer"); - d.TraceNever( "Destructor called on object %x\n", (ptr_size_type)this); + d.TraceNever("Destructor called on object %x\n", (ptr_size_type)this); } const cFCOPropVector& cFSPropDisplayer::GetPropsConverted() const @@ -123,7 +122,7 @@ const cFCOPropVector& cFSPropDisplayer::GetPropsConverted() const return mpvPropsWeDisplay; } -void cFSPropDisplayer::SetLazy( const bool bLazy /* = true */ ) +void cFSPropDisplayer::SetLazy(const bool bLazy /* = true */) { mbLazy = bLazy; } @@ -134,58 +133,56 @@ bool cFSPropDisplayer::GetLazy() const } // adds all prop display info from rhs to this -void cFSPropDisplayer::Merge( const iFCOPropDisplayer* const ppd ) +void cFSPropDisplayer::Merge(const iFCOPropDisplayer* const ppd) { - ASSERT( ppd != 0); + ASSERT(ppd != 0); // should only merge two prop displayers of the same type - if( ppd->GetType() != this->GetType() ) - ASSERT( false ); + if (ppd->GetType() != this->GetType()) + ASSERT(false); - const cFSPropDisplayer* const pfspd = static_cast( ppd ); + const cFSPropDisplayer* const pfspd = static_cast(ppd); // merge propvectors mpvPropsWeDisplay |= pfspd->GetPropsConverted(); - - // merge mapping info - for( INT64_TO_STRING_MAP::const_iterator iterUID = pfspd->uidToUsername.begin(); + + // merge mapping info + for (INT64_TO_STRING_MAP::const_iterator iterUID = pfspd->uidToUsername.begin(); iterUID != pfspd->uidToUsername.end(); - iterUID++ - ) + ++iterUID) { - AddUsernameMapping( iterUID->first, iterUID->second ); + AddUsernameMapping(iterUID->first, iterUID->second); } - - for( INT64_TO_STRING_MAP::const_iterator iterGID = pfspd->gidToGroupname.begin(); + + for (INT64_TO_STRING_MAP::const_iterator iterGID = pfspd->gidToGroupname.begin(); iterGID != pfspd->gidToGroupname.end(); - iterGID++ - ) + ++iterGID) { - AddGroupnameMapping( iterGID->first, iterGID->second ); + AddGroupnameMapping(iterGID->first, iterGID->second); } // keep lazy flag the same } -TSTRING& cFSPropDisplayer::GetDetailsHeader( TSTRING& strBuf, int iMargin ) const +TSTRING& cFSPropDisplayer::GetDetailsHeader(TSTRING& strBuf, int iMargin) const { static cFSPropSet set; - TOSTRINGSTREAM sstr; + TOSTRINGSTREAM sstr; sstr << std::left; - sstr << _T(" ") << std::setw( PROP_MODE_WIDTH ) << set.GetPropName( cFSPropSet::PROP_MODE ); - sstr << _T(" ") << std::setw( PROP_OWNER_WIDTH ) << set.GetPropName( cFSPropSet::PROP_UID ); - sstr << _T(" ") << std::setw( PROP_SIZE_WIDTH ) << set.GetPropName( cFSPropSet::PROP_SIZE ); - sstr << _T(" ") << std::setw( PROP_MTIME_WIDTH ) << set.GetPropName( cFSPropSet::PROP_MTIME ); + sstr << _T(" ") << std::setw(PROP_MODE_WIDTH) << set.GetPropName(cFSPropSet::PROP_MODE); + sstr << _T(" ") << std::setw(PROP_OWNER_WIDTH) << set.GetPropName(cFSPropSet::PROP_UID); + sstr << _T(" ") << std::setw(PROP_SIZE_WIDTH) << set.GetPropName(cFSPropSet::PROP_SIZE); + sstr << _T(" ") << std::setw(PROP_MTIME_WIDTH) << set.GetPropName(cFSPropSet::PROP_MTIME); sstr << _T("\n"); - for( int i = 0; i < iMargin; i++ ) + for (int i = 0; i < iMargin; i++) sstr << _T(" "); - sstr << _T(" ") << std::setw( PROP_MODE_WIDTH ) << _T("------"); - sstr << _T(" ") << std::setw( PROP_OWNER_WIDTH ) << _T("----------"); - sstr << _T(" ") << std::setw( PROP_SIZE_WIDTH ) << _T("----------"); - sstr << _T(" ") << std::setw( PROP_MTIME_WIDTH ) << _T("----------"); + sstr << _T(" ") << std::setw(PROP_MODE_WIDTH) << _T("------"); + sstr << _T(" ") << std::setw(PROP_OWNER_WIDTH) << _T("----------"); + sstr << _T(" ") << std::setw(PROP_SIZE_WIDTH) << _T("----------"); + sstr << _T(" ") << std::setw(PROP_MTIME_WIDTH) << _T("----------"); strBuf = sstr.str(); return strBuf; @@ -202,34 +199,34 @@ TSTRING& cFSPropDisplayer::GetDetailsHeader( TSTRING& strBuf, int iMargin ) cons // // Argument : TSTRING& strBuf -- buffer. GetDesription will use it to allocate space. // -TSTRING& cFSPropDisplayer::GetDetails( const iFCO* const pfco, TSTRING& strBuf ) const +TSTRING& cFSPropDisplayer::GetDetails(const iFCO* const pfco, TSTRING& strBuf) const { - TOSTRINGSTREAM sstr; + TOSTRINGSTREAM sstr; const cFCOPropVector pv = pfco->GetPropSet()->GetValidVector(); sstr << std::left; - sstr << _T(" ") << std::setw( PROP_MODE_WIDTH ); - if( pv.ContainsItem( cFSPropSet::PROP_MODE ) ) - sstr << PropAsString( pfco, cFSPropSet::PROP_MODE ).c_str(); + sstr << _T(" ") << std::setw(PROP_MODE_WIDTH); + if (pv.ContainsItem(cFSPropSet::PROP_MODE)) + sstr << PropAsString(pfco, cFSPropSet::PROP_MODE).c_str(); else sstr << _T("XXXXXXXXX"); - - sstr << _T(" ") << std::setw( PROP_OWNER_WIDTH ); - if( pv.ContainsItem( cFSPropSet::PROP_UID ) ) - sstr << PropAsString( pfco, cFSPropSet::PROP_UID ).c_str(); + + sstr << _T(" ") << std::setw(PROP_OWNER_WIDTH); + if (pv.ContainsItem(cFSPropSet::PROP_UID)) + sstr << PropAsString(pfco, cFSPropSet::PROP_UID).c_str(); else sstr << _T("XXXXXXXXX"); - sstr << _T(" ") << std::setw( PROP_SIZE_WIDTH ); - if( pv.ContainsItem( cFSPropSet::PROP_SIZE ) ) - sstr << PropAsString( pfco, cFSPropSet::PROP_SIZE ).c_str(); + sstr << _T(" ") << std::setw(PROP_SIZE_WIDTH); + if (pv.ContainsItem(cFSPropSet::PROP_SIZE)) + sstr << PropAsString(pfco, cFSPropSet::PROP_SIZE).c_str(); else sstr << _T("XXX"); - - sstr << _T(" ") << std::setw( PROP_MTIME_WIDTH ); - if( pv.ContainsItem( cFSPropSet::PROP_MTIME ) ) - sstr << PropAsString( pfco, cFSPropSet::PROP_MTIME ).c_str(); + + sstr << _T(" ") << std::setw(PROP_MTIME_WIDTH); + if (pv.ContainsItem(cFSPropSet::PROP_MTIME)) + sstr << PropAsString(pfco, cFSPropSet::PROP_MTIME).c_str(); else sstr << _T("XXXXXXXXXXXXXXXXX"); @@ -238,148 +235,152 @@ TSTRING& cFSPropDisplayer::GetDetails( const iFCO* const pfco, TSTRING& strBuf ) } - -void cFSPropDisplayer::InitForFCO( const iFCO* const ifco ) +void cFSPropDisplayer::InitForFCO(const iFCO* const ifco) { - ASSERT( ifco != 0); + ASSERT(ifco != 0); - cFCOPropVector v = ifco->GetPropSet()->GetValidVector(); - int vSize = v.GetSize(); - for( int i = 0; i < vSize; i++ ) + cFCOPropVector v = ifco->GetPropSet()->GetValidVector(); + int vSize = v.GetSize(); + for (int i = 0; i < vSize; i++) { - if( v.ContainsItem( i ) ) - { - InitForProp( ifco, i ); + if (v.ContainsItem(i)) + { + InitForProp(ifco, i); } } } -void cFSPropDisplayer::InitForProp( const iFCO* const pFCO, const int propIdx) +void cFSPropDisplayer::InitForProp(const iFCO* const pFCO, const int propIdx) { - ASSERT( pFCO != 0); + ASSERT(pFCO != 0); - switch( propIdx ) + switch (propIdx) { - case cFSPropSet::PROP_UID: - { - const int64& i64UID = static_cast( pFCO->GetPropSet()->GetPropAt( cFSPropSet::PROP_UID ) )->GetValue(); + case cFSPropSet::PROP_UID: + { + const int64& i64UID = + static_cast(pFCO->GetPropSet()->GetPropAt(cFSPropSet::PROP_UID))->GetValue(); - // check if prop is in table. if it is, then don't hit the FS - TSTRING tstrDummy; - if( ! GetUsername( i64UID, tstrDummy ) ) - { - TSTRING tstrUsername; - if( iFSServices::GetInstance()->GetOwnerForFile( pFCO->GetName().AsString(), tstrUsername ) ) - AddUsernameMapping ( i64UID, tstrUsername ); - else - AddUsernameMapping ( i64UID, _T("") ); // on failure, enter error value into mapping so we don't search for this value again. - } - } - break; - case cFSPropSet::PROP_GID: + // check if prop is in table. if it is, then don't hit the FS + TSTRING tstrDummy; + if (!GetUsername(i64UID, tstrDummy)) { - const int64& i64GID = static_cast( pFCO->GetPropSet()->GetPropAt( cFSPropSet::PROP_GID ) )->GetValue(); + TSTRING tstrUsername; + if (iFSServices::GetInstance()->GetUserName(i64UID, tstrUsername)) + AddUsernameMapping(i64UID, tstrUsername); + else + AddUsernameMapping( + i64UID, + _T("")); // on failure, enter error value into mapping so we don't search for this value again. + } + } + break; + case cFSPropSet::PROP_GID: + { + const int64& i64GID = + static_cast(pFCO->GetPropSet()->GetPropAt(cFSPropSet::PROP_GID))->GetValue(); - // check if prop is in table. if it is, then don't hit the FS - TSTRING tstrDummy; - if( ! GetGroupname( i64GID, tstrDummy ) ) - { - TSTRING tstrGroupname; - if( iFSServices::GetInstance()->GetGroupForFile( pFCO->GetName().AsString(), tstrGroupname ) ) - AddGroupnameMapping( i64GID, tstrGroupname ); - else - AddGroupnameMapping( i64GID, _T("") ); // on failure, enter error value into mapping so we don't search for this value again. - } + // check if prop is in table. if it is, then don't hit the FS + TSTRING tstrDummy; + if (!GetGroupname(i64GID, tstrDummy)) + { + TSTRING tstrGroupname; + if (iFSServices::GetInstance()->GetGroupName(i64GID, tstrGroupname)) + AddGroupnameMapping(i64GID, tstrGroupname); + else + AddGroupnameMapping( + i64GID, + _T("")); // on failure, enter error value into mapping so we don't search for this value again. } - break; - default: - // right now nothing else needs to be done for the other props + } + break; + default: + // right now nothing else needs to be done for the other props break; } } -TSTRING cFSPropDisplayer::PropAsString( const iFCO* const pFCO, const int propIdx, int iOffset, int iWidth ) +TSTRING cFSPropDisplayer::PropAsString(const iFCO* const pFCO, const int propIdx, int iOffset, int iWidth) { - if( mpvPropsWeDisplay.ContainsItem( propIdx ) && mbLazy ) + if (mpvPropsWeDisplay.ContainsItem(propIdx) && mbLazy) { - InitForProp( pFCO, propIdx ); + InitForProp(pFCO, propIdx); } // run the const version of PropAsString return ((const cFSPropDisplayer*)this)->PropAsString(pFCO, propIdx, iOffset, iWidth); } -TSTRING cFSPropDisplayer::PropAsString( const iFCO* const pFCO, const int propIdx, int iOffset, int iWidth ) const +TSTRING cFSPropDisplayer::PropAsString(const iFCO* const pFCO, const int propIdx, int iOffset, int iWidth) const { TSTRING strProp = _T(""); - ASSERT( pFCO != 0); + ASSERT(pFCO != 0); // get prop pointer - const iFCOProp* pProp = pFCO->GetPropSet()->GetPropAt( propIdx ); + const iFCOProp* pProp = pFCO->GetPropSet()->GetPropAt(propIdx); // if we know how to display prop - if( pProp->GetType() != cFCOUndefinedProp::GetInstance()->GetType() && - mpvPropsWeDisplay.ContainsItem( propIdx ) ) + if (pProp->GetType() != cFCOUndefinedProp::GetInstance()->GetType() && mpvPropsWeDisplay.ContainsItem(propIdx)) { - switch( propIdx ) + switch (propIdx) { - case cFSPropSet::PROP_BLOCK_SIZE: - case cFSPropSet::PROP_BLOCKS: - case cFSPropSet::PROP_SIZE: - case cFSPropSet::PROP_NLINK: - { - const cFCOPropInt64* const pTypedProp = static_cast(pProp); - cTWLocale::FormatNumber( pTypedProp->GetValue(), strProp ); - } - break; - case cFSPropSet::PROP_ATIME: - case cFSPropSet::PROP_MTIME: - case cFSPropSet::PROP_CTIME: - { - const cFCOPropInt64* const pTypedProp = static_cast(pProp); - int64 i64 = pTypedProp->GetValue(); - cTWLocale::FormatTime( i64, strProp ); - } - break; - case cFSPropSet::PROP_MODE: - { - const cFCOPropUint64* const pTypedProp = static_cast(pProp); - ASSERT( pTypedProp != 0); + case cFSPropSet::PROP_BLOCK_SIZE: + case cFSPropSet::PROP_BLOCKS: + case cFSPropSet::PROP_SIZE: + case cFSPropSet::PROP_NLINK: + { + const cFCOPropInt64* const pTypedProp = static_cast(pProp); + cTWLocale::FormatNumber(pTypedProp->GetValue(), strProp); + } + break; + case cFSPropSet::PROP_ATIME: + case cFSPropSet::PROP_MTIME: + case cFSPropSet::PROP_CTIME: + { + const cFCOPropInt64* const pTypedProp = static_cast(pProp); + int64 i64 = pTypedProp->GetValue(); + cTWLocale::FormatTime(i64, strProp); + } + break; + case cFSPropSet::PROP_MODE: + { + const cFCOPropUint64* const pTypedProp = static_cast(pProp); + ASSERT(pTypedProp != 0); - iFSServices::GetInstance()->ConvertModeToString( pTypedProp->GetValue(), strProp ); - } - break; - case cFSPropSet::PROP_UID: + iFSServices::GetInstance()->ConvertModeToString(pTypedProp->GetValue(), strProp); + } + break; + case cFSPropSet::PROP_UID: + { + const cFCOPropInt64* const pTypedProp = static_cast(pProp); + ASSERT(pTypedProp != 0); + if (GetUsername(pTypedProp->GetValue(), strProp)) { - const cFCOPropInt64* const pTypedProp = static_cast(pProp); - ASSERT( pTypedProp != 0); - if( GetUsername( pTypedProp->GetValue(), strProp ) ) - { - TSTRINGSTREAM ostr; - ostr << strProp << _T(" (") << (int32) pTypedProp->GetValue() << _T(")"); - strProp = ostr.str(); - } - else - strProp = pProp->AsString(); + TSTRINGSTREAM ostr; + ostr << strProp << _T(" (") << (int32)pTypedProp->GetValue() << _T(")"); + strProp = ostr.str(); } - break; - case cFSPropSet::PROP_GID: + else + strProp = pProp->AsString(); + } + break; + case cFSPropSet::PROP_GID: + { + const cFCOPropInt64* const pTypedProp = static_cast(pProp); + ASSERT(pTypedProp != 0); + if (GetGroupname(pTypedProp->GetValue(), strProp)) { - const cFCOPropInt64* const pTypedProp = static_cast(pProp); - ASSERT( pTypedProp != 0); - if( GetGroupname( pTypedProp->GetValue(), strProp ) ) - { - TSTRINGSTREAM ostr; - ostr << strProp << _T(" (") << (int32) pTypedProp->GetValue() << _T(")"); - strProp = ostr.str(); - } - else - strProp = pProp->AsString(); + TSTRINGSTREAM ostr; + ostr << strProp << _T(" (") << (int32)pTypedProp->GetValue() << _T(")"); + strProp = ostr.str(); } - break; - default: - ASSERT( false ); // mpvPropsWeDisplay should contain one of the above + else + strProp = pProp->AsString(); + } + break; + default: + ASSERT(false); // mpvPropsWeDisplay should contain one of the above break; } } @@ -388,31 +389,33 @@ TSTRING cFSPropDisplayer::PropAsString( const iFCO* const pFCO, const int propId strProp = pProp->AsString(); } - return( strProp ); + return (strProp); } -void cFSPropDisplayer::Write( iSerializer* pSerializer ) const +void cFSPropDisplayer::Write(iSerializer* pSerializer) const { - mpvPropsWeDisplay.Write( pSerializer ); - pSerializer->WriteInt32( mbLazy ? 1 : 0 ); - + mpvPropsWeDisplay.Write(pSerializer); + pSerializer->WriteInt32(mbLazy ? 1 : 0); + // stuff { // write UID mapping - pSerializer->WriteInt32( uidToUsername.size() ); - for( INT64_TO_STRING_MAP::const_iterator iterUid = uidToUsername.begin(); iterUid != uidToUsername.end(); iterUid++ ) + pSerializer->WriteInt32(uidToUsername.size()); + for (INT64_TO_STRING_MAP::const_iterator iterUid = uidToUsername.begin(); iterUid != uidToUsername.end(); + ++iterUid) { - pSerializer->WriteInt64( iterUid->first ); - pSerializer->WriteString( iterUid->second ); + pSerializer->WriteInt64(iterUid->first); + pSerializer->WriteString(iterUid->second); } - + // write GID mapping - pSerializer->WriteInt32( gidToGroupname.size() ); - for( INT64_TO_STRING_MAP::const_iterator iterGid = gidToGroupname.begin(); iterGid != gidToGroupname.end(); iterGid++ ) + pSerializer->WriteInt32(gidToGroupname.size()); + for (INT64_TO_STRING_MAP::const_iterator iterGid = gidToGroupname.begin(); iterGid != gidToGroupname.end(); + ++iterGid) { - pSerializer->WriteInt64( iterGid->first ); - pSerializer->WriteString( iterGid->second ); + pSerializer->WriteInt64(iterGid->first); + pSerializer->WriteString(iterGid->second); } } } @@ -421,92 +424,95 @@ void cFSPropDisplayer::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("Property Displayer Read"))); - - mpvPropsWeDisplay.Read( pSerializer ); + + mpvPropsWeDisplay.Read(pSerializer); int32 iDummy; - pSerializer->ReadInt32( iDummy ); + pSerializer->ReadInt32(iDummy); mbLazy = iDummy == 0 ? false : true; // stuff { - int32 nValues; - int64 key; + int32 nValues; + int64 key; TSTRING val; - int i; + int i; // read UID hashtable - pSerializer->ReadInt32( nValues ); - for( i = 0; i < nValues; i++ ) + pSerializer->ReadInt32(nValues); + for (i = 0; i < nValues; i++) { - pSerializer->ReadInt64( key ); - pSerializer->ReadString( val ); - AddUsernameMapping( key, val ); + pSerializer->ReadInt64(key); + pSerializer->ReadString(val); + AddUsernameMapping(key, val); } - + // read GID hashtable - pSerializer->ReadInt32( nValues ); - for( i = 0; i < nValues; i++ ) + pSerializer->ReadInt32(nValues); + for (i = 0; i < nValues; i++) { - pSerializer->ReadInt64( key ); - pSerializer->ReadString( val ); - AddGroupnameMapping( key, val ); + pSerializer->ReadInt64(key); + pSerializer->ReadString(val); + AddGroupnameMapping(key, val); } } } - - - ////////////////////////////////////////////// // Lookup functions ////////////////////////////////////////////// -bool cFSPropDisplayer::GetUsername( const int64& i64uid, TSTRING& tstrUsername ) const -{ +bool cFSPropDisplayer::GetUsername(const int64& i64uid, TSTRING& tstrUsername) const +{ bool fFound = false; - INT64_TO_STRING_MAP::const_iterator iter = uidToUsername.find( i64uid ); + INT64_TO_STRING_MAP::const_iterator iter = uidToUsername.find(i64uid); - if( iter != uidToUsername.end() ) + if (iter != uidToUsername.end()) { - fFound = true; + fFound = true; tstrUsername = iter->second; } - return( fFound && !tstrUsername.empty() ); + return (fFound && !tstrUsername.empty()); } -bool cFSPropDisplayer::GetGroupname( const int64& i64gid, TSTRING& tstrGroupname ) const -{ +bool cFSPropDisplayer::GetGroupname(const int64& i64gid, TSTRING& tstrGroupname) const +{ bool fFound = false; - INT64_TO_STRING_MAP::const_iterator iter = gidToGroupname.find( i64gid ); + INT64_TO_STRING_MAP::const_iterator iter = gidToGroupname.find(i64gid); - if( iter != gidToGroupname.end() ) + if (iter != gidToGroupname.end()) { - fFound = true; + fFound = true; tstrGroupname = iter->second; } - return( fFound && !tstrGroupname.empty() ); + return (fFound && !tstrGroupname.empty()); } ////////////////////////////////////////////// // Addition functions ////////////////////////////////////////////// -bool cFSPropDisplayer::AddUsernameMapping( const int64& i64uid, const TSTRING& tstrUsername ) +bool cFSPropDisplayer::AddUsernameMapping(const int64& i64uid, const TSTRING& tstrUsername) { - std::pair ret = uidToUsername.insert( INT64_TO_STRING_MAP::value_type( i64uid, tstrUsername ) ); - return( ret.second = false ); // returns true if key didn't exist before + std::pair ret = + uidToUsername.insert(INT64_TO_STRING_MAP::value_type(i64uid, tstrUsername)); + return (ret.second = false); // returns true if key didn't exist before } -bool cFSPropDisplayer::AddGroupnameMapping( const int64& i64gid, const TSTRING& tstrGroupname ) +bool cFSPropDisplayer::AddGroupnameMapping(const int64& i64gid, const TSTRING& tstrGroupname) { - std::pair ret = gidToGroupname.insert( INT64_TO_STRING_MAP::value_type( i64gid, tstrGroupname ) ); - return( ret.second = false ); // returns true if key didn't exist before + std::pair ret = + gidToGroupname.insert(INT64_TO_STRING_MAP::value_type(i64gid, tstrGroupname)); + return (ret.second = false); // returns true if key didn't exist before } - +bool cFSPropDisplayer::operator==(const cFSPropDisplayer& rhs) const +{ + return (mpvPropsWeDisplay == rhs.mpvPropsWeDisplay && uidToUsername == rhs.uidToUsername && + gidToGroupname == rhs.gidToGroupname); +} diff --git a/src/fs/fspropdisplayer.h b/src/fs/fspropdisplayer.h index 03bc8e2..3da823c 100644 --- a/src/fs/fspropdisplayer.h +++ b/src/fs/fspropdisplayer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -101,34 +101,37 @@ class cFSPropDisplayer : public iFCOPropDisplayer virtual iFCOPropDisplayer* Clone() const; - virtual void Merge( const iFCOPropDisplayer* const ppd ); + virtual void Merge(const iFCOPropDisplayer* const ppd); virtual const cFCOPropVector& GetPropsConverted() const; - virtual TSTRING PropAsString(const iFCO* const pFCO, const int propIdx, int iOffset = 0, int iWidth = 0 ) const ; - virtual TSTRING PropAsString( const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0 ); - virtual bool IsMultiLineProp( int propID ) const; - virtual TSTRING& GetDetails( const iFCO* const pfco, TSTRING& strBuf ) const ; - virtual TSTRING& GetDetailsHeader( TSTRING& strBuf, int iMargin ) const; - virtual void InitForProp(const iFCO* const pFCO, const int propIdx); - virtual void InitForFCO( const iFCO* const ifco ); - virtual void SetLazy( const bool bLazy = true ); - virtual bool GetLazy() const; - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) -private: - void AddMapping( const iFCOProp* const pProp, const TSTRING& tstrValue, const int propTypeEnum ); - // pass in a property value and its string representation. for instance: ( FS::PROP_UID --> username ) - - - cFCOPropVector mpvPropsWeDisplay; // if a given prop in this vector is valid, then this class - // can do a PropAsString that's different from iFCOProp::AsString() - bool mbLazy; - - typedef std::map< int64, TSTRING > INT64_TO_STRING_MAP; - - bool GetUsername( const int64& i64uid, TSTRING& tstrUsername ) const; - bool GetGroupname( const int64& i64uid, TSTRING& tstrGroupname ) const; - bool AddUsernameMapping ( const int64& i64ID, const TSTRING& tstrUsername ); - bool AddGroupnameMapping( const int64& i64ID, const TSTRING& tstrGroupname ); + virtual TSTRING PropAsString(const iFCO* const pFCO, const int propIdx, int iOffset = 0, int iWidth = 0) const; + virtual TSTRING PropAsString(const iFCO* const pFCO, int const propIdx, int iOffset = 0, int iWidth = 0); + virtual bool IsMultiLineProp(int propID) const; + virtual TSTRING& GetDetails(const iFCO* const pfco, TSTRING& strBuf) const; + virtual TSTRING& GetDetailsHeader(TSTRING& strBuf, int iMargin) const; + virtual void InitForProp(const iFCO* const pFCO, const int propIdx); + virtual void InitForFCO(const iFCO* const ifco); + virtual void SetLazy(const bool bLazy = true); + virtual bool GetLazy() const; + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + + bool operator==(const cFSPropDisplayer& rhs) const; // for testing + +private: + void AddMapping(const iFCOProp* const pProp, const TSTRING& tstrValue, const int propTypeEnum); + // pass in a property value and its string representation. for instance: ( FS::PROP_UID --> username ) + + + cFCOPropVector mpvPropsWeDisplay; // if a given prop in this vector is valid, then this class + // can do a PropAsString that's different from iFCOProp::AsString() + bool mbLazy; + + typedef std::map INT64_TO_STRING_MAP; + + bool GetUsername(const int64& i64uid, TSTRING& tstrUsername) const; + bool GetGroupname(const int64& i64uid, TSTRING& tstrGroupname) const; + bool AddUsernameMapping(const int64& i64ID, const TSTRING& tstrUsername); + bool AddGroupnameMapping(const int64& i64ID, const TSTRING& tstrGroupname); // storage for conversion stuff INT64_TO_STRING_MAP uidToUsername; @@ -138,13 +141,12 @@ class cFSPropDisplayer : public iFCOPropDisplayer enum Widths { - PROP_MODE_WIDTH = 11, + PROP_MODE_WIDTH = 11, PROP_OWNER_WIDTH = 20, - PROP_SIZE_WIDTH = 10, + PROP_SIZE_WIDTH = 10, PROP_MTIME_WIDTH = 10 }; }; #endif //__FSPROPDISPLAYER_H - diff --git a/src/fs/fspropset.cpp b/src/fs/fspropset.cpp index f734611..4750c8d 100644 --- a/src/fs/fspropset.cpp +++ b/src/fs/fspropset.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,28 +49,26 @@ //############################################################################# TSTRING cFCOPropFileType::AsString() const { - static int fileTypes [] = - { - fs::STR_FT_INVALID, - fs::STR_FT_FILE, - fs::STR_FT_DIR, - fs::STR_FT_BLOCKDEV, - fs::STR_FT_CHARDEV, - fs::STR_FT_SYMLINK, - fs::STR_FT_FIFO, - fs::STR_FT_SOCK, - fs::STR_FT_DOOR, - fs::STR_FT_PORT - }; + static int fileTypes[] = {fs::STR_FT_INVALID, + fs::STR_FT_FILE, + fs::STR_FT_DIR, + fs::STR_FT_BLOCKDEV, + fs::STR_FT_CHARDEV, + fs::STR_FT_SYMLINK, + fs::STR_FT_FIFO, + fs::STR_FT_SOCK, + fs::STR_FT_DOOR, + fs::STR_FT_PORT, + fs::STR_FT_NAMED}; int32 fileType = GetValue(); - if((fileType > cFSPropSet::FT_INVALID) && (fileType < cFSPropSet::FT_NUMITEMS)) - return TSS_GetString( cFS, fileTypes[fileType] ); + if ((fileType > cFSPropSet::FT_INVALID) && (fileType < cFSPropSet::FT_NUMITEMS)) + return TSS_GetString(cFS, fileTypes[fileType]); else - return TSS_GetString( cFS, fileTypes[cFSPropSet::FT_INVALID] ); + return TSS_GetString(cFS, fileTypes[cFSPropSet::FT_INVALID]); } - + //############################################################################# // cFSPropSet //############################################################################# @@ -82,51 +80,33 @@ IMPLEMENT_TYPEDSERIALIZABLE(cFSPropSet, _T("cFSPropSet"), 0, 1); // TODO -- put these in a class-static hash table of something of the like so that // name lookups are constant time -- mdb /////////////////////////////////////////////////////////////////////////////// -static int cFSPropSet_PropNames [] = -{ - fs::STR_PROP_FILETYPE, - fs::STR_PROP_DEV, - fs::STR_PROP_RDEV, - fs::STR_PROP_INODE, - fs::STR_PROP_MODE, - fs::STR_PROP_NLINK, - fs::STR_PROP_UID, - fs::STR_PROP_GID, - fs::STR_PROP_SIZE, - fs::STR_PROP_ATIME, - fs::STR_PROP_MTIME, - fs::STR_PROP_CTIME, - fs::STR_PROP_BLOCK_SIZE, - fs::STR_PROP_BLOCKS, - fs::STR_PROP_GROWING_FILE, - fs::STR_PROP_CRC32, - fs::STR_PROP_MD5, - fs::STR_PROP_SHA, - fs::STR_PROP_HAVAL, - fs::STR_PROP_ACL -}; +static int cFSPropSet_PropNames[] = { + fs::STR_PROP_FILETYPE, fs::STR_PROP_DEV, fs::STR_PROP_RDEV, fs::STR_PROP_INODE, fs::STR_PROP_MODE, + fs::STR_PROP_NLINK, fs::STR_PROP_UID, fs::STR_PROP_GID, fs::STR_PROP_SIZE, fs::STR_PROP_ATIME, + fs::STR_PROP_MTIME, fs::STR_PROP_CTIME, fs::STR_PROP_BLOCK_SIZE, fs::STR_PROP_BLOCKS, fs::STR_PROP_GROWING_FILE, + fs::STR_PROP_CRC32, fs::STR_PROP_MD5, fs::STR_PROP_SHA, fs::STR_PROP_HAVAL, fs::STR_PROP_ACL}; /////////////////////////////////////////////////////////////////////////////// // TraceContents /////////////////////////////////////////////////////////////////////////////// void cFSPropSet::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; cDebug d("cFSPropSet::TraceContents"); TOSTRINGSTREAM ostr; ostr << _T("File Sysytem Prop Set: "); - for(int i=0; iGetValidVector().ContainsItem( i ) ); + ASSERT(pSrc->GetValidVector().ContainsItem(i)); const iFCOProp* pProp = pSrc->GetPropAt(i); if (pProp->GetType() != cFCOUndefinedProp::GetInstance()->GetType()) { - GetPropAt(i)->Copy( pProp ); + GetPropAt(i)->Copy(pProp); mUndefinedProps.RemoveItem(i); } else @@ -172,11 +152,11 @@ void cFSPropSet::InvalidateAll() mValidProps.Clear(); } -void cFSPropSet::InvalidateProps(const cFCOPropVector& propsToInvalidate) +void cFSPropSet::InvalidateProps(const cFCOPropVector& propsToInvalidate) { - cFCOPropVector inBoth = mValidProps; - inBoth &= propsToInvalidate; - mValidProps ^= inBoth; + cFCOPropVector inBoth = mValidProps; + inBoth &= propsToInvalidate; + mValidProps ^= inBoth; } /////////////////////////////////////////////////////////////////////////////// @@ -190,36 +170,31 @@ int cFSPropSet::GetNumFSProps() /////////////////////////////////////////////////////////////////////////////// // ctors. dtor, operator= /////////////////////////////////////////////////////////////////////////////// -cFSPropSet::cFSPropSet() : - iFCOPropSet(), - mValidProps(cFSPropSet::PROP_NUMITEMS), - mUndefinedProps(cFSPropSet::PROP_NUMITEMS) +cFSPropSet::cFSPropSet() + : iFCOPropSet(), mValidProps(cFSPropSet::PROP_NUMITEMS), mUndefinedProps(cFSPropSet::PROP_NUMITEMS) { // TODO: do I want to zero out all the property values here? } cFSPropSet::~cFSPropSet() { - } -cFSPropSet::cFSPropSet(const cFSPropSet& rhs) : - iFCOPropSet(), - mValidProps(cFSPropSet::PROP_NUMITEMS) +cFSPropSet::cFSPropSet(const cFSPropSet& rhs) : iFCOPropSet(), mValidProps(cFSPropSet::PROP_NUMITEMS) { *this = rhs; } const cFSPropSet& cFSPropSet::operator=(const cFSPropSet& rhs) { - mValidProps = rhs.GetValidVector(); + mValidProps = rhs.GetValidVector(); mUndefinedProps = rhs.mUndefinedProps; - for (int i=0; i < PROP_NUMITEMS; i++) + for (int i = 0; i < PROP_NUMITEMS; i++) { - if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) + if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) { - GetPropAt(i)->Copy( ((cFSPropSet&)rhs).GetPropAt(i) ); + GetPropAt(i)->Copy(((cFSPropSet&)rhs).GetPropAt(i)); // call non-const GetPropAt for rhs // don't want it to assert ContainsItem } @@ -228,21 +203,21 @@ const cFSPropSet& cFSPropSet::operator=(const cFSPropSet& rhs) return *this; } -const cFCOPropVector& cFSPropSet::GetValidVector() const +const cFCOPropVector& cFSPropSet::GetValidVector() const { return mValidProps; } -int cFSPropSet::GetNumProps() const +int cFSPropSet::GetNumProps() const { return PROP_NUMITEMS; } int cFSPropSet::GetPropIndex(const TCHAR* name) const { - for(int i=0; i= 0) && (index < GetNumProps())); - return TSS_GetString( cFS, cFSPropSet_PropNames[index]); + return TSS_GetString(cFS, cFSPropSet_PropNames[index]); } const iFCOProp* cFSPropSet::GetPropAt(int index) const { // the specified property had better have a valid value... ASSERT((index >= 0) && (index < GetNumProps())); - ASSERT(mValidProps.ContainsItem(index)); + ASSERT(mValidProps.ContainsItem(index)); if (mUndefinedProps.ContainsItem(index)) { return cFCOUndefinedProp::GetInstance(); } - switch(index) + switch (index) { - case PROP_FILETYPE: - return &mFileType; - case PROP_DEV: - return &mDev; - case PROP_RDEV: - return &mRDev; - case PROP_INODE: - return &mInode; - case PROP_MODE: - return &mMode; - case PROP_NLINK: - return &mNLink; - case PROP_UID: - return &mUID; - case PROP_GID: - return &mGID; - case PROP_SIZE: - return &mSize; - case PROP_ATIME: - return &mAccessTime; - case PROP_MTIME: - return &mModifyTime; - case PROP_CTIME: - return &mCreateTime; - case PROP_BLOCK_SIZE: - return &mBlockSize; - case PROP_BLOCKS: - return &mBlocks; - case PROP_GROWING_FILE: - return &mGrowingFile; - case PROP_CRC32: - return &mCRC32; - case PROP_MD5: - return &mMD5; - case PROP_SHA: - return &mSHA; - case PROP_HAVAL: - return &mHAVAL; - case PROP_ACL: - ASSERT( false ); // unimplemented - return NULL; - default: - { - // bad parameter passed to GetPropAt - ASSERT(false); - } + case PROP_FILETYPE: + return &mFileType; + case PROP_DEV: + return &mDev; + case PROP_RDEV: + return &mRDev; + case PROP_INODE: + return &mInode; + case PROP_MODE: + return &mMode; + case PROP_NLINK: + return &mNLink; + case PROP_UID: + return &mUID; + case PROP_GID: + return &mGID; + case PROP_SIZE: + return &mSize; + case PROP_ATIME: + return &mAccessTime; + case PROP_MTIME: + return &mModifyTime; + case PROP_CTIME: + return &mCreateTime; + case PROP_BLOCK_SIZE: + return &mBlockSize; + case PROP_BLOCKS: + return &mBlocks; + case PROP_GROWING_FILE: + return &mGrowingFile; + case PROP_CRC32: + return &mCRC32; + case PROP_MD5: + return &mMD5; + case PROP_SHA: + return &mSHA; + case PROP_HAVAL: + return &mHAVAL; + case PROP_ACL: + ASSERT(false); // unimplemented + return NULL; + default: + { + // bad parameter passed to GetPropAt + ASSERT(false); + } } return NULL; } @@ -324,64 +299,63 @@ iFCOProp* cFSPropSet::GetPropAt(int index) ASSERT((index >= 0) && (index < GetNumProps())); // don't assert for non-const GetPropAt() because we might want to get a non-valid // property for copying - //ASSERT(mValidProps.ContainsItem(index)); + //ASSERT(mValidProps.ContainsItem(index)); if (mUndefinedProps.ContainsItem(index)) { return cFCOUndefinedProp::GetInstance(); } - switch(index) + switch (index) { - case PROP_FILETYPE: - return &mFileType; - case PROP_DEV: - return &mDev; - case PROP_RDEV: - return &mRDev; - case PROP_INODE: - return &mInode; - case PROP_MODE: - return &mMode; - case PROP_NLINK: - return &mNLink; - case PROP_UID: - return &mUID; - case PROP_GID: - return &mGID; - case PROP_SIZE: - return &mSize; - case PROP_ATIME: - return &mAccessTime; - case PROP_MTIME: - return &mModifyTime; - case PROP_CTIME: - return &mCreateTime; - case PROP_BLOCK_SIZE: - return &mBlockSize; - case PROP_BLOCKS: - return &mBlocks; - case PROP_GROWING_FILE: - return &mGrowingFile; - case PROP_CRC32: - return &mCRC32; - case PROP_MD5: - return &mMD5; - case PROP_SHA: - return &mSHA; - case PROP_HAVAL: - return &mHAVAL; - case PROP_ACL: - ASSERT( false ); // unimplemented - return NULL; - default: - { - // bad parameter passed to GetPropAt - ASSERT(false); - } + case PROP_FILETYPE: + return &mFileType; + case PROP_DEV: + return &mDev; + case PROP_RDEV: + return &mRDev; + case PROP_INODE: + return &mInode; + case PROP_MODE: + return &mMode; + case PROP_NLINK: + return &mNLink; + case PROP_UID: + return &mUID; + case PROP_GID: + return &mGID; + case PROP_SIZE: + return &mSize; + case PROP_ATIME: + return &mAccessTime; + case PROP_MTIME: + return &mModifyTime; + case PROP_CTIME: + return &mCreateTime; + case PROP_BLOCK_SIZE: + return &mBlockSize; + case PROP_BLOCKS: + return &mBlocks; + case PROP_GROWING_FILE: + return &mGrowingFile; + case PROP_CRC32: + return &mCRC32; + case PROP_MD5: + return &mMD5; + case PROP_SHA: + return &mSHA; + case PROP_HAVAL: + return &mHAVAL; + case PROP_ACL: + ASSERT(false); // unimplemented + return NULL; + default: + { + // bad parameter passed to GetPropAt + ASSERT(false); + } } return NULL; - } void cFSPropSet::Read(iSerializer* pSerializer, int32 version) @@ -392,7 +366,7 @@ void cFSPropSet::Read(iSerializer* pSerializer, int32 version) mValidProps.Read(pSerializer); mUndefinedProps.Read(pSerializer); - for (int i=0; i < PROP_NUMITEMS; i++) + for (int i = 0; i < PROP_NUMITEMS; i++) { if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) GetPropAt(i)->Read(pSerializer); @@ -401,13 +375,12 @@ void cFSPropSet::Read(iSerializer* pSerializer, int32 version) void cFSPropSet::Write(iSerializer* pSerializer) const { - mValidProps.Write(pSerializer); - mUndefinedProps.Write(pSerializer); - - for (int i=0; i < PROP_NUMITEMS; i++) - { + mValidProps.Write(pSerializer); + mUndefinedProps.Write(pSerializer); + + for (int i = 0; i < PROP_NUMITEMS; i++) + { if (mValidProps.ContainsItem(i) && !mUndefinedProps.ContainsItem(i)) GetPropAt(i)->Write(pSerializer); - } + } } - diff --git a/src/fs/fspropset.h b/src/fs/fspropset.h index 423e5cc..ac3eae8 100644 --- a/src/fs/fspropset.h +++ b/src/fs/fspropset.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -88,7 +88,7 @@ class cFSPropSet : public iFCOPropSet PROP_CTIME, PROP_BLOCK_SIZE, PROP_BLOCKS, - PROP_GROWING_FILE, // a hack to detect growing files; this holds the same thing as PROP_SIZE + PROP_GROWING_FILE, // a hack to detect growing files; this holds the same thing as PROP_SIZE PROP_CRC32, PROP_MD5, PROP_SHA, @@ -101,16 +101,17 @@ class cFSPropSet : public iFCOPropSet // the type of file this is enum FileType { - FT_INVALID = 0, - FT_FILE, - FT_DIR, - FT_BLOCKDEV, + FT_INVALID = 0, + FT_FILE, + FT_DIR, + FT_BLOCKDEV, FT_CHARDEV, FT_SYMLINK, FT_FIFO, FT_SOCK, FT_DOOR, FT_PORT, + FT_NAMED, FT_NUMITEMS }; @@ -121,58 +122,59 @@ class cFSPropSet : public iFCOPropSet const cFSPropSet& operator=(const cFSPropSet& rhs); - virtual const cFCOPropVector& GetValidVector() const ; - virtual int GetNumProps () const ; - virtual int GetPropIndex(const TCHAR* name) const; - virtual TSTRING GetPropName (int index) const; - virtual const iFCOProp* GetPropAt(int index) const; - virtual iFCOProp* GetPropAt(int index) ; - virtual void InvalidateProp(int index); - virtual void InvalidateProps(const cFCOPropVector& propsToInvalidate) ; - virtual void InvalidateAll(); - virtual void CopyProps(const iFCOPropSet* pSrc, const cFCOPropVector& propsToCopy); + virtual const cFCOPropVector& GetValidVector() const; + virtual int GetNumProps() const; + virtual int GetPropIndex(const TCHAR* name) const; + virtual TSTRING GetPropName(int index) const; + virtual const iFCOProp* GetPropAt(int index) const; + virtual iFCOProp* GetPropAt(int index); + virtual void InvalidateProp(int index); + virtual void InvalidateProps(const cFCOPropVector& propsToInvalidate); + virtual void InvalidateAll(); + virtual void CopyProps(const iFCOPropSet* pSrc, const cFCOPropVector& propsToCopy); static int GetNumFSProps(); - // convenience function that returns the number of properties FSPropSets have without needing - // to create one. This is useful in creating property vectors, since you need to know the size... + // convenience function that returns the number of properties FSPropSets have without needing + // to create one. This is useful in creating property vectors, since you need to know the size... // note that file type and normalized time are redundant properties (that is, they are derived from // the values of other properties) but their values are dependent on the file system the fsobject // came from, so they must be set during property calculation - + // Get/Set functions for all the properties - PROPERTY(cFCOPropFileType, FileType, PROP_FILETYPE) // file type enumeration above - PROPERTY(cFCOPropUint64, Dev, PROP_DEV) //st_dev -- the device number of the disk - PROPERTY(cFCOPropUint64, RDev, PROP_RDEV) //st_rdev -- the device number of character or block file - PROPERTY(cFCOPropUint64, Inode, PROP_INODE) //st_ino -- the indode number - PROPERTY(cFCOPropUint64, Mode, PROP_MODE) //st_mode -- the file's mode; also indicates whether it is a directory or a file - PROPERTY(cFCOPropInt64, NLink, PROP_NLINK) //st_nlink -- number of links to this file - PROPERTY(cFCOPropInt64, UID, PROP_UID) //st_uid -- uid who owns the file - PROPERTY(cFCOPropInt64, GID, PROP_GID) //st_gid -- gid who owns the file - PROPERTY(cFCOPropInt64, Size, PROP_SIZE) //st_size -- the size of the file - PROPERTY(cFCOPropInt64, AccessTime, PROP_ATIME) //st_atime -- last access time - PROPERTY(cFCOPropInt64, ModifyTime, PROP_MTIME) //st_mtime -- last modify time - PROPERTY(cFCOPropInt64, CreateTime, PROP_CTIME) //st_ctime -- create time - PROPERTY(cFCOPropInt64, BlockSize, PROP_BLOCK_SIZE)//st_blksize - PROPERTY(cFCOPropInt64, Blocks, PROP_BLOCKS) //st_blocks - PROPERTY(cFCOPropGrowingFile, GrowingFile, PROP_GROWING_FILE) //growing file property; synonym for Size above. - PROPERTY_OBJ(cCRC32Signature, CRC32, PROP_CRC32) - PROPERTY_OBJ(cMD5Signature, MD5, PROP_MD5) - PROPERTY_OBJ(cSHASignature, SHA, PROP_SHA) - PROPERTY_OBJ(cHAVALSignature, HAVAL, PROP_HAVAL) + PROPERTY(cFCOPropFileType, FileType, PROP_FILETYPE) // file type enumeration above + PROPERTY(cFCOPropUint64, Dev, PROP_DEV) //st_dev -- the device number of the disk + PROPERTY(cFCOPropUint64, RDev, PROP_RDEV) //st_rdev -- the device number of character or block file + PROPERTY(cFCOPropUint64, Inode, PROP_INODE) //st_ino -- the indode number + PROPERTY(cFCOPropUint64, + Mode, + PROP_MODE) //st_mode -- the file's mode; also indicates whether it is a directory or a file + PROPERTY(cFCOPropInt64, NLink, PROP_NLINK) //st_nlink -- number of links to this file + PROPERTY(cFCOPropInt64, UID, PROP_UID) //st_uid -- uid who owns the file + PROPERTY(cFCOPropInt64, GID, PROP_GID) //st_gid -- gid who owns the file + PROPERTY(cFCOPropInt64, Size, PROP_SIZE) //st_size -- the size of the file + PROPERTY(cFCOPropInt64, AccessTime, PROP_ATIME) //st_atime -- last access time + PROPERTY(cFCOPropInt64, ModifyTime, PROP_MTIME) //st_mtime -- last modify time + PROPERTY(cFCOPropInt64, CreateTime, PROP_CTIME) //st_ctime -- create time + PROPERTY(cFCOPropInt64, BlockSize, PROP_BLOCK_SIZE) //st_blksize + PROPERTY(cFCOPropInt64, Blocks, PROP_BLOCKS) //st_blocks + PROPERTY(cFCOPropGrowingFile, GrowingFile, PROP_GROWING_FILE) //growing file property; synonym for Size above. + PROPERTY_OBJ(cCRC32Signature, CRC32, PROP_CRC32) + PROPERTY_OBJ(cMD5Signature, MD5, PROP_MD5) + PROPERTY_OBJ(cSHASignature, SHA, PROP_SHA) + PROPERTY_OBJ(cHAVALSignature, HAVAL, PROP_HAVAL) //PROPERTY_OBJ(cUnixACL, ACL, PROP_ACL) // will eventually be implememented - + // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) // debugging method virtual void TraceContents(int dl = -1) const; private: - cFCOPropVector mValidProps; // all the properties that have been evaluated - cFCOPropVector mUndefinedProps; // properties that have been measured but have undefined values + cFCOPropVector mValidProps; // all the properties that have been evaluated + cFCOPropVector mUndefinedProps; // properties that have been measured but have undefined values }; #endif - diff --git a/src/fs/fsstrings.cpp b/src/fs/fsstrings.cpp index 3eee809..ee115a1 100644 --- a/src/fs/fsstrings.cpp +++ b/src/fs/fsstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,42 +39,32 @@ #include "fs.h" #include "fsstrings.h" -TSS_BeginStringtable( cFS ) - - TSS_StringEntry( fs::STR_FT_INVALID, _T("Invalid") ), - TSS_StringEntry( fs::STR_FT_FILE, _T("Regular File") ), - TSS_StringEntry( fs::STR_FT_DIR, _T("Directory") ), - TSS_StringEntry( fs::STR_FT_BLOCKDEV, _T("Block Device") ), - TSS_StringEntry( fs::STR_FT_CHARDEV, _T("Character Device") ), - TSS_StringEntry( fs::STR_FT_SYMLINK, _T("Symbolic Link") ), - TSS_StringEntry( fs::STR_FT_FIFO, _T("FIFO") ), - TSS_StringEntry( fs::STR_FT_SOCK, _T("Socket") ), - TSS_StringEntry( fs::STR_FT_DOOR, _T("Door") ), - TSS_StringEntry( fs::STR_FT_PORT, _T("Event Port") ), +TSS_BeginStringtable(cFS) + + TSS_StringEntry(fs::STR_FT_INVALID, _T("Invalid")), + TSS_StringEntry(fs::STR_FT_FILE, _T("Regular File")), TSS_StringEntry(fs::STR_FT_DIR, _T("Directory")), + TSS_StringEntry(fs::STR_FT_BLOCKDEV, _T("Block Device")), + TSS_StringEntry(fs::STR_FT_CHARDEV, _T("Character Device")), + TSS_StringEntry(fs::STR_FT_SYMLINK, _T("Symbolic Link")), TSS_StringEntry(fs::STR_FT_FIFO, _T("FIFO")), + TSS_StringEntry(fs::STR_FT_SOCK, _T("Socket")), TSS_StringEntry(fs::STR_FT_DOOR, _T("Door")), + TSS_StringEntry(fs::STR_FT_PORT, _T("Event Port")), TSS_StringEntry(fs::STR_FT_NAMED, _T("Named Special File")), // property names - TSS_StringEntry( fs::STR_PROP_DEV, _T("Device Number") ), - TSS_StringEntry( fs::STR_PROP_RDEV, _T("File Device Number") ), - TSS_StringEntry( fs::STR_PROP_INODE, _T("Inode Number") ), - TSS_StringEntry( fs::STR_PROP_MODE, _T("Mode") ), - TSS_StringEntry( fs::STR_PROP_NLINK, _T("Num Links") ), - TSS_StringEntry( fs::STR_PROP_UID, _T("UID") ), - TSS_StringEntry( fs::STR_PROP_GID, _T("GID") ), - TSS_StringEntry( fs::STR_PROP_SIZE, _T("Size") ), - TSS_StringEntry( fs::STR_PROP_ATIME, _T("Access Time") ), - TSS_StringEntry( fs::STR_PROP_MTIME, _T("Modify Time") ), - TSS_StringEntry( fs::STR_PROP_CTIME, _T("Change Time") ), - TSS_StringEntry( fs::STR_PROP_BLOCK_SIZE, _T("Block Size") ), - TSS_StringEntry( fs::STR_PROP_BLOCKS, _T("Blocks") ), - TSS_StringEntry( fs::STR_PROP_CRC32, _T("CRC32") ), - TSS_StringEntry( fs::STR_PROP_MD5, _T("MD5") ), - TSS_StringEntry( fs::STR_PROP_FILETYPE, _T("Object Type") ), - TSS_StringEntry( fs::STR_PROP_GROWING_FILE, _T("Growing Object Size") ), - TSS_StringEntry( fs::STR_PROP_SHA, _T("SHA") ), - TSS_StringEntry( fs::STR_PROP_HAVAL, _T("HAVAL") ), - TSS_StringEntry( fs::STR_PROP_ACL, _T("ACL Placeholder -- Not Implemented") ), - - // TODO: get actual strings + TSS_StringEntry(fs::STR_PROP_DEV, _T("Device Number")), + TSS_StringEntry(fs::STR_PROP_RDEV, _T("File Device Number")), + TSS_StringEntry(fs::STR_PROP_INODE, _T("Inode Number")), TSS_StringEntry(fs::STR_PROP_MODE, _T("Mode")), + TSS_StringEntry(fs::STR_PROP_NLINK, _T("Num Links")), TSS_StringEntry(fs::STR_PROP_UID, _T("UID")), + TSS_StringEntry(fs::STR_PROP_GID, _T("GID")), TSS_StringEntry(fs::STR_PROP_SIZE, _T("Size")), + TSS_StringEntry(fs::STR_PROP_ATIME, _T("Access Time")), TSS_StringEntry(fs::STR_PROP_MTIME, _T("Modify Time")), + TSS_StringEntry(fs::STR_PROP_CTIME, _T("Change Time")), TSS_StringEntry(fs::STR_PROP_BLOCK_SIZE, _T("Block Size")), + TSS_StringEntry(fs::STR_PROP_BLOCKS, _T("Blocks")), TSS_StringEntry(fs::STR_PROP_CRC32, _T("CRC32")), + TSS_StringEntry(fs::STR_PROP_MD5, _T("MD5")), TSS_StringEntry(fs::STR_PROP_FILETYPE, _T("Object Type")), + TSS_StringEntry(fs::STR_PROP_GROWING_FILE, _T("Growing Object Size")), TSS_StringEntry(fs::STR_PROP_SHA, _T("SHA")), + TSS_StringEntry(fs::STR_PROP_HAVAL, _T("HAVAL")), + TSS_StringEntry(fs::STR_PROP_ACL, _T("ACL Placeholder -- Not Implemented")), + + /* Leaving these here in case we ever implement long property names + TSS_StringEntry( fs::STR_PARSER_PROP_DEV, _T("unimplemented") ), TSS_StringEntry( fs::STR_PARSER_PROP_RDEV, _T("unimplemented") ), TSS_StringEntry( fs::STR_PARSER_PROP_INODE, _T("unimplemented") ), @@ -94,24 +84,20 @@ TSS_BeginStringtable( cFS ) TSS_StringEntry( fs::STR_PARSER_PROP_MD5, _T("unimplemented") ), TSS_StringEntry( fs::STR_PARSER_PROP_SHA, _T("unimplemented") ), TSS_StringEntry( fs::STR_PARSER_PROP_HAVAL, _T("unimplemented") ), +*/ + TSS_StringEntry(fs::STR_PARSER_READONLY, _T("ReadOnly")), TSS_StringEntry(fs::STR_PARSER_DYNAMIC, _T("Dynamic")), + TSS_StringEntry(fs::STR_PARSER_GROWING, _T("Growing")), TSS_StringEntry(fs::STR_PARSER_IGNOREALL, _T("IgnoreAll")), + TSS_StringEntry(fs::STR_PARSER_IGNORENONE, _T("IgnoreNone")), TSS_StringEntry(fs::STR_PARSER_DEVICE, _T("Device")), + TSS_StringEntry(fs::STR_PARSER_HOSTNAME, _T("HOSTNAME")), - TSS_StringEntry( fs::STR_PARSER_READONLY, _T("ReadOnly")), - TSS_StringEntry( fs::STR_PARSER_DYNAMIC, _T("Dynamic")), - TSS_StringEntry( fs::STR_PARSER_GROWING, _T("Growing")), - TSS_StringEntry( fs::STR_PARSER_IGNOREALL, _T("IgnoreAll")), - TSS_StringEntry( fs::STR_PARSER_IGNORENONE, _T("IgnoreNone")), - TSS_StringEntry( fs::STR_PARSER_DEVICE, _T("Device")), - TSS_StringEntry( fs::STR_PARSER_HOSTNAME, _T("HOSTNAME")), - - TSS_StringEntry( fs::STR_FS_PARSER_READONLY_VAL, _T("+pinugsmtdbCM-raclSH" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_DYNAMIC_VAL, _T("+pinugtd-rsacmblCMSH" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_GROWING_VAL, _T("+pinugtdl-rsacmbCMSH" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_IGNOREALL_VAL, _T("-pinusgamctdrblCMSH" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_IGNORENONE_VAL, _T("+pinusgamctdrbCMSH-l" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_DEVICE_VAL, _T("+pugsdr-intlbamcCMSH" ) ), - TSS_StringEntry( fs::STR_FS_PARSER_HOSTNAME_VAL, _T("localhost" ) ), - - TSS_StringEntry( fs::STR_DIFFERENT_FILESYSTEM, _T("The object: \"%s\" is on a different file system...ignoring.\n") ), + TSS_StringEntry(fs::STR_FS_PARSER_READONLY_VAL, _T("+pinugsmtdbCM-raclSH" )), + TSS_StringEntry(fs::STR_FS_PARSER_DYNAMIC_VAL, _T("+pinugtd-rsacmblCMSH" )), + TSS_StringEntry(fs::STR_FS_PARSER_GROWING_VAL, _T("+pinugtdl-rsacmbCMSH" )), + TSS_StringEntry(fs::STR_FS_PARSER_IGNOREALL_VAL, _T("-pinusgamctdrblCMSH" )), + TSS_StringEntry(fs::STR_FS_PARSER_IGNORENONE_VAL, _T("+pinusgamctdrbCMSH-l" )), + TSS_StringEntry(fs::STR_FS_PARSER_DEVICE_VAL, _T("+pugsdr-intlbamcCMSH" )), + TSS_StringEntry(fs::STR_FS_PARSER_HOSTNAME_VAL, _T("localhost" )), -TSS_EndStringtable( cFS ) + TSS_StringEntry(fs::STR_DIFFERENT_FILESYSTEM, _T("The object: \"%s\" is on a different file system...ignoring.\n")), + TSS_EndStringtable(cFS) diff --git a/src/fs/fsstrings.h b/src/fs/fsstrings.h index c61fe70..22850ae 100644 --- a/src/fs/fsstrings.h +++ b/src/fs/fsstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,46 +38,23 @@ #ifndef __FSSTRINGS_H #define __FSSTRINGS_H -#include "fs.h" // for: STRINGTABLE syntax +#include "fs.h" // for: STRINGTABLE syntax //--Message Keys -TSS_BeginStringIds( fs ) - +TSS_BeginStringIds(fs) + // file types STR_FT_INVALID, - STR_FT_FILE, - STR_FT_DIR, - STR_FT_BLOCKDEV, - STR_FT_CHARDEV, - STR_FT_SYMLINK, - STR_FT_FIFO, - STR_FT_SOCK, - STR_FT_DOOR, - STR_FT_PORT, + STR_FT_FILE, STR_FT_DIR, STR_FT_BLOCKDEV, STR_FT_CHARDEV, STR_FT_SYMLINK, STR_FT_FIFO, STR_FT_SOCK, STR_FT_DOOR, + STR_FT_PORT, STR_FT_NAMED, // property names - STR_PROP_DEV, - STR_PROP_RDEV, - STR_PROP_INODE, - STR_PROP_MODE, - STR_PROP_NLINK, - STR_PROP_UID, - STR_PROP_GID, - STR_PROP_SIZE, - STR_PROP_ATIME, - STR_PROP_MTIME, - STR_PROP_CTIME, - STR_PROP_BLOCK_SIZE, - STR_PROP_BLOCKS, - STR_PROP_CRC32, - STR_PROP_MD5, - STR_PROP_FILETYPE, - STR_PROP_GROWING_FILE, - STR_PROP_SHA, - STR_PROP_HAVAL, - STR_PROP_ACL, - + STR_PROP_DEV, STR_PROP_RDEV, STR_PROP_INODE, STR_PROP_MODE, STR_PROP_NLINK, STR_PROP_UID, STR_PROP_GID, + STR_PROP_SIZE, STR_PROP_ATIME, STR_PROP_MTIME, STR_PROP_CTIME, STR_PROP_BLOCK_SIZE, STR_PROP_BLOCKS, STR_PROP_CRC32, + STR_PROP_MD5, STR_PROP_FILETYPE, STR_PROP_GROWING_FILE, STR_PROP_SHA, STR_PROP_HAVAL, STR_PROP_ACL, + + /* Leaving these here in case we ever implement long property names STR_PARSER_PROP_DEV, STR_PARSER_PROP_RDEV, STR_PARSER_PROP_INODE, @@ -97,27 +74,16 @@ TSS_BeginStringIds( fs ) STR_PARSER_PROP_MD5, STR_PARSER_PROP_SHA, STR_PARSER_PROP_HAVAL, - - STR_PARSER_READONLY, - STR_PARSER_DYNAMIC, - STR_PARSER_GROWING, - STR_PARSER_IGNOREALL, - STR_PARSER_IGNORENONE, - STR_PARSER_DEVICE, - STR_PARSER_HOSTNAME, - - STR_FS_PARSER_READONLY_VAL, - STR_FS_PARSER_DYNAMIC_VAL, - STR_FS_PARSER_GROWING_VAL, - STR_FS_PARSER_IGNOREALL_VAL, - STR_FS_PARSER_IGNORENONE_VAL, - STR_FS_PARSER_DEVICE_VAL, - STR_FS_PARSER_HOSTNAME_VAL, - - STR_DIFFERENT_FILESYSTEM +*/ + STR_PARSER_READONLY, STR_PARSER_DYNAMIC, STR_PARSER_GROWING, STR_PARSER_IGNOREALL, STR_PARSER_IGNORENONE, + STR_PARSER_DEVICE, STR_PARSER_HOSTNAME, -TSS_EndStringIds( fs ) + STR_FS_PARSER_READONLY_VAL, STR_FS_PARSER_DYNAMIC_VAL, STR_FS_PARSER_GROWING_VAL, STR_FS_PARSER_IGNOREALL_VAL, + STR_FS_PARSER_IGNORENONE_VAL, STR_FS_PARSER_DEVICE_VAL, STR_FS_PARSER_HOSTNAME_VAL, + + STR_DIFFERENT_FILESYSTEM + TSS_EndStringIds(fs) -#endif//__FSSTRINGS_H +#endif //__FSSTRINGS_H diff --git a/src/fs/fsvisitor.cpp b/src/fs/fsvisitor.cpp index b9a669c..1508b8b 100644 --- a/src/fs/fsvisitor.cpp +++ b/src/fs/fsvisitor.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,4 +38,3 @@ // type information IMPLEMENT_TYPED(iFSVisitor, _T("FSVisitor")); - diff --git a/src/fs/fsvisitor.h b/src/fs/fsvisitor.h index ac9c042..838a567 100644 --- a/src/fs/fsvisitor.h +++ b/src/fs/fsvisitor.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // fsvisitor.h // -// iFCOVisitor -- top-level visitor interface. Right now, this only contains +// iFCOVisitor -- top-level visitor interface. Right now, this only contains // GetGenre(), which returns the visitor's type #ifndef __FSVISITOR_H #define __FSVISITOR_H @@ -52,8 +52,7 @@ class iFSVisitor : public iFCOVisitor virtual void VisitFSObject(cFSObject& obj) = 0; protected: - virtual ~iFSVisitor() {}; + virtual ~iFSVisitor(){}; }; #endif - diff --git a/src/fs/stdfs.cpp b/src/fs/stdfs.cpp index 4a7c176..24a6365 100644 --- a/src/fs/stdfs.cpp +++ b/src/fs/stdfs.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdfs.h" - -// eof: stdfs.cpp diff --git a/src/fs/stdfs.h b/src/fs/stdfs.h index 58712e0..cf1f244 100644 --- a/src/fs/stdfs.h +++ b/src/fs/stdfs.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/parser/lexyacc_header.h b/src/parser/lexyacc_header.h index d2b67ae..c211efa 100644 --- a/src/parser/lexyacc_header.h +++ b/src/parser/lexyacc_header.h @@ -1,50 +1,47 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // #include "stdtwparser.h" #if IS_WIN32 -#pragma warning( disable : 4305 ) +# pragma warning(disable : 4305) // C4305: The specified identifier type was converted to a smaller type. Information was lost in the casting. -#pragma warning( disable : 4309 ) +# pragma warning(disable : 4309) // C4309: 'conversion' : truncation of constant value -#pragma warning( disable : 4129 ) +# pragma warning(disable : 4129) // C4129: 'character' : unrecognized character escape sequence -#pragma warning( disable : 4068 ) +# pragma warning(disable : 4068) // C4086: expected pragma parameter to be '1', '2', '4', '8', or '16' -#pragma warning( disable : 4102 ) +# pragma warning(disable : 4102) // C4102: 'label' : unreferenced label -#pragma warning( disable : 4244 ) - // C4244: '=' : conversion from 'int' to 'short', possible loss of data +# pragma warning(disable : 4244) +// C4244: '=' : conversion from 'int' to 'short', possible loss of data #endif //#if IS_WIN32 - - - diff --git a/src/parser/policy.y b/src/parser/policy.y index 910c79f..f2d255c 100644 --- a/src/parser/policy.y +++ b/src/parser/policy.y @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // diff --git a/src/parser/testfiles.bad/arrow.txt b/src/parser/testfiles.bad/arrow.txt new file mode 100644 index 0000000..e4400a5 --- /dev/null +++ b/src/parser/testfiles.bad/arrow.txt @@ -0,0 +1 @@ +-> diff --git a/src/parser/testfiles.bad/asdf.txt b/src/parser/testfiles.bad/asdf.txt new file mode 100644 index 0000000..e08928b --- /dev/null +++ b/src/parser/testfiles.bad/asdf.txt @@ -0,0 +1,4 @@ +(asdf=fjfj) +{ +/foo -> $(IgnoreNone); +} diff --git a/src/parser/testfiles.bad/atat.txt b/src/parser/testfiles.bad/atat.txt new file mode 100644 index 0000000..0282815 --- /dev/null +++ b/src/parser/testfiles.bad/atat.txt @@ -0,0 +1 @@ +@@ diff --git a/src/parser/testfiles.bad/bad-directive.txt b/src/parser/testfiles.bad/bad-directive.txt new file mode 100644 index 0000000..87e2747 --- /dev/null +++ b/src/parser/testfiles.bad/bad-directive.txt @@ -0,0 +1 @@ +@@unknown fjfjfj diff --git a/src/parser/testfiles.bad/bad-ifhost.txt b/src/parser/testfiles.bad/bad-ifhost.txt new file mode 100644 index 0000000..6672764 --- /dev/null +++ b/src/parser/testfiles.bad/bad-ifhost.txt @@ -0,0 +1 @@ +@@ifhost diff --git a/src/parser/testfiles.bad/error.txt b/src/parser/testfiles.bad/error.txt new file mode 100644 index 0000000..179b4a5 --- /dev/null +++ b/src/parser/testfiles.bad/error.txt @@ -0,0 +1 @@ +@@error This should fail diff --git a/src/parser/testfiles.bad/global-foo.txt b/src/parser/testfiles.bad/global-foo.txt new file mode 100644 index 0000000..81cfcd6 --- /dev/null +++ b/src/parser/testfiles.bad/global-foo.txt @@ -0,0 +1,2 @@ +@@section GLOBAL +/foo -> $(IgnoreNone); diff --git a/src/parser/testfiles.bad/ignore-some.txt b/src/parser/testfiles.bad/ignore-some.txt new file mode 100644 index 0000000..70f3d29 --- /dev/null +++ b/src/parser/testfiles.bad/ignore-some.txt @@ -0,0 +1 @@ +/foo -> $(IgnoreSome); diff --git a/src/parser/testfiles.bad/incomplete-1.txt b/src/parser/testfiles.bad/incomplete-1.txt new file mode 100644 index 0000000..0661686 --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-1.txt @@ -0,0 +1 @@ +/foo diff --git a/src/parser/testfiles.bad/incomplete-2.txt b/src/parser/testfiles.bad/incomplete-2.txt new file mode 100644 index 0000000..cdceccf --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-2.txt @@ -0,0 +1 @@ +/foo -> diff --git a/src/parser/testfiles.bad/incomplete-3.txt b/src/parser/testfiles.bad/incomplete-3.txt new file mode 100644 index 0000000..5b7d008 --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-3.txt @@ -0,0 +1 @@ +/foo -> $(IgnoreNone) diff --git a/src/parser/testfiles.bad/incomplete-4.txt b/src/parser/testfiles.bad/incomplete-4.txt new file mode 100644 index 0000000..7073e76 --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-4.txt @@ -0,0 +1,2 @@ +{ +/foo -> $(IgnoreNone); diff --git a/src/parser/testfiles.bad/incomplete-5.txt b/src/parser/testfiles.bad/incomplete-5.txt new file mode 100644 index 0000000..533ee7f --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-5.txt @@ -0,0 +1,2 @@ +/foo -> $(IgnoreNone); +} diff --git a/src/parser/testfiles.bad/incomplete-6.txt b/src/parser/testfiles.bad/incomplete-6.txt new file mode 100644 index 0000000..ff668ee --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-6.txt @@ -0,0 +1,4 @@ +(emailto="foo@bar +{ +/foo -> $(IgnoreNone); +} diff --git a/src/parser/testfiles.bad/incomplete-7.txt b/src/parser/testfiles.bad/incomplete-7.txt new file mode 100644 index 0000000..82df1f7 --- /dev/null +++ b/src/parser/testfiles.bad/incomplete-7.txt @@ -0,0 +1,4 @@ +(emailto="foo@bar" +{ +/foo -> $(IgnoreNone); +} diff --git a/src/parser/testfiles.bad/relpath.txt b/src/parser/testfiles.bad/relpath.txt new file mode 100644 index 0000000..ac86154 --- /dev/null +++ b/src/parser/testfiles.bad/relpath.txt @@ -0,0 +1 @@ +foo -> $(IgnoreNone); diff --git a/src/parser/testfiles/basic.txt b/src/parser/testfiles/basic.txt new file mode 100644 index 0000000..86c70fe --- /dev/null +++ b/src/parser/testfiles/basic.txt @@ -0,0 +1,3 @@ +/foo -> +S; +/bar -> $(IgnoreNone); +!/baz; diff --git a/src/parser/testfiles/directives.txt b/src/parser/testfiles/directives.txt index 4374975..7e9446a 100644 --- a/src/parser/testfiles/directives.txt +++ b/src/parser/testfiles/directives.txt @@ -1,19 +1,19 @@ -# replace your_host with the name of your host. +# Exercises the ifhost conditional, assuming your host answers to 'localhost'. # parser will echo YES1 through YES9 # there's a problem with the parser if it echoes NO -@@ifhost turd +@@ifhost foo @@error NO1 @@else - @@echo +YES1; + @@print +YES1 @@endif -@@ifhost crap || your_host||poo +@@ifhost bar || localhost||baz - @@ifhost turd + @@ifhost foo - @@ifhost your_host + @@ifhost localhost @@error +NO2; @@else @@error +NO3; @@ -23,31 +23,31 @@ @@else - @@ifhost turd + @@ifhost foo @@error +NO5; @@else - @@echo +YES2; + @@print +YES2; @@endif - @@echo +YES3; + @@print +YES3; @@endif - @@ifhost your_host + @@ifhost localhost - @@ifhost your_host - @@echo +YES4; + @@ifhost localhost + @@print +YES4; @@else @@error +NO6; @@endif - @@echo +YES5; + @@print +YES5; @@else - @@ifhost your_host + @@ifhost localhost @@error +NO7; @@else @@error +NO8; @@ -57,37 +57,37 @@ @@endif - @@ifhost your_host - @@echo +YES6; + @@ifhost localhost + @@print +YES6; @@else @@error +NO10; @@endif - @@ifhost turd + @@ifhost foo @@error +NO11; @@else - @@echo +YES7; + @@print +YES7; @@endif - @@ifhost your_host || poo - @@echo +YES8; + @@ifhost localhost || baz + @@print +YES8; @@endif - @@ifhost poo || your_host - @@echo +YES9; + @@ifhost baz || localhost + @@print +YES9; @@endif - @@ifhost poo + @@ifhost baz @@error +NO12; @@endif @@else - @@ifhost turd + @@ifhost foo - @@ifhost your_host + @@ifhost localhost @@error +NO13; @@else @@error +NO14; @@ -97,7 +97,7 @@ @@else - @@ifhost turd + @@ifhost foo @@error +NO16; @@else @@error +NO17; @@ -107,29 +107,31 @@ @@endif - @@ifhost turd + @@ifhost foo @@error +NO19; @@else @@error +NO20; @@endif - @@ifhost your_host + @@ifhost localhost @@error +NO21; @@else @@error +NO22; @@endif - @@ifhost turd + @@ifhost foo @@error +NO23; @@else @@error +NO24; @@endif - @@ifhost poo + @@ifhost baz @@error +NO25; @@endif @@endif +#A token rule at the end to avoid 'no rules in policy file' errors +/asdf -> +a; diff --git a/lib/.keepme b/src/parser/testfiles/empty.txt similarity index 100% rename from lib/.keepme rename to src/parser/testfiles/empty.txt diff --git a/src/parser/testfiles/ifhost.txt b/src/parser/testfiles/ifhost.txt new file mode 100644 index 0000000..4117d1c --- /dev/null +++ b/src/parser/testfiles/ifhost.txt @@ -0,0 +1,6 @@ +@@ifhost localhost + @@print Hello World + /foo -> $(IgnoreNone); +@@else + @@error Failed +@@endif diff --git a/src/parser/testfiles/pol.txt b/src/parser/testfiles/pol.txt index 2b0accc..d83eadf 100644 --- a/src/parser/testfiles/pol.txt +++ b/src/parser/testfiles/pol.txt @@ -14,34 +14,32 @@ /simple -> +ppp; # variable -$(poo) = pinug; -/simplevar -> $(poo) ; +FOO = pinug; +/simplevar -> $(FOO) ; -$(turd) = /test6; -$(turd) -> $(poo); +BAR = /test6; +$(BAR) -> $(FOO); # named attributes -/namedattr -> +pinug (name /namedattr ) ; +#/namedattr -> +pinug (name /namedattr ) ; # multiple attributes -/namedattr2 -> +pinug (emailreport on, emailsendto genek, name /namedattr2, name4 val4, name5 val5 ); +#/namedattr2 -> +pinug (emailreport on, emailsendto genek, name /namedattr2, name4 val4, name5 val5 ); # test line continuations -/turd \ +/bar \ ->\ +p ; -@@EnD +#@@EnD -/test -> +p; -"/te\x73t2" -> +p-p ; -"/te\163t3" -> +pinugs-am ; -"c:\\te\163t3\\" -> +pinugs-am ; -"c:\\te\"as\163t3\\" -> +pinugs-am ; -"/te\163t3" -> +pinugs-am ; -"/te\163t3" -> +pinugs-am ; -/test4 -> +pinugs---am ; -/test5 -> $(ReadOnly)s-+-am ; +/test7 -> +p; +"/te\x73t8" -> +p-p ; +"/te\163t9" -> +pinugs-am ; +"/te\163t12" -> +pinugs-am ; +"/te\163t13" -> +pinugs-am ; +/test14 -> +pinugs---am ; +/test15 -> $(ReadOnly)s-+-am ; # test weird file names /lost+found -> +p ; @@ -51,50 +49,51 @@ $(turd) -> $(poo); ; # simple default policy -/simple -> +ppp; +/simple2 -> +ppp; # variable -$(poo) = pinug; -/simplevar -> $(poo) ; -$(turd) = /test6; -$(turd) -> $(poo); +FOO = pinug; +/simplevar2 -> $(FOO) ; +BAR = /test16; +$(BAR) -> $(FOO); # omit with space seperation ! /omit ; # omit with no space separation - !/omit ; + !/omit2 ; # named attributes -/namedattr -> +pinug (name1 value1) ; +#/namedattr -> +pinug (name1 value1) ; # multiple attributes -/namedattr2 -> +pinug (emailreport on; emailsendto genek; name3 val3; name4 val4; name5 val5 ) ; +#/namedattr2 -> +pinug (emailreport on; emailsendto genek; name3 val3; name4 val4; name5 val5 ) ; # test line continuations -/turd \ +/bar2 \ ->\ +p ; -@@END +#@@END # the following isn't implemented yet #########################################3 # attributes on specifers -/conditions { - xxx: +pinug (inside1 name1 ;) ; - yyy: +pinug ; - zzz: +pinug ; - default: +pinug ; - }; +#/conditions2 { +# xxx: +pinug (inside1 name1 ;) ; +# yyy: +pinug ; +# zzz: +pinug ; +# default: +pinug ; +# }; # multiple specmasks -/conditions { - xxx: +pinug ; - yyy: +pinug ; - zzz: +pinug ; - default: +pinug ; - }; \ No newline at end of file +#/conditions3 { +# xxx: +pinug ; +# yyy: +pinug ; +# zzz: +pinug ; +# default: +pinug ; +# }; +# diff --git a/src/parser/testfiles/poleasy.txt b/src/parser/testfiles/poleasy.txt index f88a1f6..d9a11da 100644 --- a/src/parser/testfiles/poleasy.txt +++ b/src/parser/testfiles/poleasy.txt @@ -1 +1 @@ -/etc jj ; +/etc -> $(IgnoreNone); diff --git a/src/parser/testfiles/polhard.txt b/src/parser/testfiles/polhard.txt index 1586dc2..6d3f7cd 100644 --- a/src/parser/testfiles/polhard.txt +++ b/src/parser/testfiles/polhard.txt @@ -1,17 +1,16 @@ # test weird file names /lost+found -> +p ; -/l-o_st+fo/und -> +ping (l-o_st+fo/und2 l-o_st+fo/und3) ; +/l-o_st+fo/und -> +ping; # test variables -$(ReadOnly) = ping; -/simplevar -> $(ReadOnly) ; -/var -> $(ReadOnly)-p ; +FOO = ping; +/simplevar -> $(FOO) ; +/var -> $(FOO)-p ; # test line continuations -c:/test -> +p ; -/turd \ +/bar \ ->\ +p ; @@ -20,25 +19,24 @@ c:/test -> +p ; "/qfoo" -> +p ; "/Program Files" -> +p ; " /lots o' spaces " -> +p ; -" colon: semicolon; quote' " -> +p ; +#" colon: semicolon; quote' " -> +p ; # test attributes -/namedattr2 -> +p ( name1 value1; name2 value2; ) ; -/namedattr -> +p (name1 value1; ) ; +#/namedattr2 -> +p ( name1 value1; name2 value2; ) ; +#/namedattr -> +p (name1 value1; ) ; # test propvector -c:/test -> +p ; -/test -> +p ; -/test -> +p-p ; -/test -> +pinugs-am ; -/test -> +pinugs---am ; -/test -> +pinugs-+-am ; +/test1 -> +p ; +/test2 -> +p-p ; +/test3 -> +pinugs-am ; +/test4 -> +pinugs---am ; +/test5 -> +pinugs-+-am ; # attributes and props -/namedattr3 -> +pinug ( name1 value1; name2 value2; ) ; -/namedattr4 -> +pinug (name1 value1; ) ; +#/namedattr3 -> +pinug ( name1 value1; name2 value2; ) ; +#/namedattr4 -> +pinug (name1 value1; ) ; # simple default policy /simple -> +ppp; @@ -48,38 +46,39 @@ c:/test -> +p ; ! /omit ; # omit with no space separation - !/omit ; + !/omit2 ; # multiple attributes -/namedattr -> +pinug (emailreport on; emailsendto genek; name3 val3; name4 val4; name5 val5; ) ; +#/namedattr -> +pinug (emailreport on; emailsendto genek; name3 val3; name4 val4; name5 val5; ) ; -@@END +#@@END # the following isn't implemented yet #########################################3 # multiple specmasks -/conditions -> { - xxx -> +pinug ; - yyy -> +pinug ; - zzz -> +pinug ; - default -> +pinug ; - }; +#/conditions -> { +# xxx -> +pinug ; +# yyy -> +pinug ; +# zzz -> +pinug ; +# default -> +pinug ; +# }; # attributes on specifers -/conditions -> { - xxx -> +pinug (inside1 name1 ;) ; - yyy -> +pinug ; - zzz -> +pinug ; - default -> +pinug ; - }; +#/conditions -> { +# xxx -> +pinug (inside1 name1 ;) ; +# yyy -> +pinug ; +# zzz -> +pinug ; +# default -> +pinug ; +# }; # hard ones -/conditions -> { - xxx -> +pinug (inside1 name1 ;) ; - yyy -> $(poo)+pinug ; - zzz -> +pinug ( inside1 name1 ; outside name2); - default -> $(turd)-p ; - }; \ No newline at end of file +#/conditions -> { +# xxx -> +pinug (inside1 name1 ;) ; +# yyy -> $(baz)+pinug ; +# zzz -> +pinug ( inside1 name1 ; outside name2); +# default -> $(bar)-p ; +# }; + diff --git a/src/parser/testfiles/polruleattr.txt b/src/parser/testfiles/polruleattr.txt index 468fa36..3f5febc 100644 --- a/src/parser/testfiles/polruleattr.txt +++ b/src/parser/testfiles/polruleattr.txt @@ -1,4 +1,4 @@ -( emailreport on ; ) +(emailto=root@localhost) { /foo -> +pinugs ; -} \ No newline at end of file +} diff --git a/src/parser/testfiles/variable.txt b/src/parser/testfiles/variable.txt new file mode 100644 index 0000000..f651b03 --- /dev/null +++ b/src/parser/testfiles/variable.txt @@ -0,0 +1,7 @@ +@@section GLOBAL +FOO =/foo ; +BAR = +pinug ; + +@@section FS +$(FOO) -> $(BAR); + diff --git a/src/parser/tokens.l b/src/parser/tokens.l index 94bc773..708b214 100644 --- a/src/parser/tokens.l +++ b/src/parser/tokens.l @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -311,12 +311,12 @@ END {WS}*{DIRECTIVE}{WS}*end *mpstring = strW; -#ifdef _DEBUG +#ifdef DEBUG TSTRING strDisplay = *mpstring; cDisplayEncoder e; e.Encode( strDisplay ); d.TraceDetail("interpreted as --> <%s>\n", strDisplay.c_str()); -#endif // _DEBUG +#endif // DEBUG // attach to lval yylval.mpString = mpstring; diff --git a/src/siggen/Makefile.am b/src/siggen/Makefile.am index f1e4912..f400881 100644 --- a/src/siggen/Makefile.am +++ b/src/siggen/Makefile.am @@ -1,18 +1,22 @@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. LIBS = -ltripwire -lcryptlib @LIBS@ LDFLAGS = @LDFLAGS@ -L../../lib LN_S = @LN@ sbin_PROGRAMS = siggen +siggendir=. siggen_SOURCES = \ siggen.cpp siggencmdline.cpp siggenmain.cpp \ siggenstrings.cpp stdsiggen.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../bin/siggen +siggen_HEADERS = \ + siggen.h siggencmdline.h siggenstrings.h stdsiggen.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = ../../bin/siggen *.gcno *.gcda all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin diff --git a/src/siggen/Makefile.in b/src/siggen/Makefile.in index f103d23..8db2435 100644 --- a/src/siggen/Makefile.in +++ b/src/siggen/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(siggen_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,43 +87,117 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ sbin_PROGRAMS = siggen$(EXEEXT) subdir = src/siggen -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(siggen_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(siggendir)" PROGRAMS = $(sbin_PROGRAMS) am_siggen_OBJECTS = siggen.$(OBJEXT) siggencmdline.$(OBJEXT) \ siggenmain.$(OBJEXT) siggenstrings.$(OBJEXT) \ stdsiggen.$(OBJEXT) siggen_OBJECTS = $(am_siggen_OBJECTS) siggen_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(siggen_SOURCES) DIST_SOURCES = $(siggen_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +HEADERS = $(siggen_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -88,7 +213,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -96,6 +221,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -107,6 +233,7 @@ LN = @LN@ LN_S = @LN@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -123,21 +250,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -167,20 +297,28 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. +siggendir = . siggen_SOURCES = \ siggen.cpp siggencmdline.cpp siggenmain.cpp \ siggenstrings.cpp stdsiggen.cpp -CLEANFILES = ../../bin/siggen +siggen_HEADERS = \ + siggen.h siggencmdline.h siggenstrings.h stdsiggen.h + +CLEANFILES = ../../bin/siggen *.gcno *.gcda all: all-am .SUFFIXES: @@ -189,15 +327,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/siggen/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/siggen/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/siggen/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/siggen/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -214,32 +351,53 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): install-sbinPROGRAMS: $(sbin_PROGRAMS) @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(mkdir_p) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(sbindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(sbindir)" || exit 1; \ + fi; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p \ + ; then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' \ + -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || exit $$?; \ + } \ + ; done uninstall-sbinPROGRAMS: @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' \ + `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(sbindir)" && rm -f $$files clean-sbinPROGRAMS: -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -siggen$(EXEEXT): $(siggen_OBJECTS) $(siggen_DEPENDENCIES) + +siggen$(EXEEXT): $(siggen_OBJECTS) $(siggen_DEPENDENCIES) $(EXTRA_siggen_DEPENDENCIES) @rm -f siggen$(EXEEXT) - $(CXXLINK) $(siggen_LDFLAGS) $(siggen_OBJECTS) $(siggen_LDADD) $(LIBS) + $(AM_V_CXXLD)$(CXXLINK) $(siggen_OBJECTS) $(siggen_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -248,93 +406,120 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-siggenHEADERS: $(siggen_HEADERS) + @$(NORMAL_INSTALL) + @list='$(siggen_HEADERS)'; test -n "$(siggendir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(siggendir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(siggendir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(siggendir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(siggendir)" || exit $$?; \ + done + +uninstall-siggenHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(siggen_HEADERS)'; test -n "$(siggendir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(siggendir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + for dir in "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(siggendir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -346,17 +531,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -376,18 +567,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-siggenHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: install-sbinPROGRAMS +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -406,22 +617,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-sbinPROGRAMS +uninstall-am: uninstall-sbinPROGRAMS uninstall-siggenHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-sbinPROGRAMS ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-sbinPROGRAMS install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-sbinPROGRAMS cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ + install-siggenHEADERS install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am uninstall-sbinPROGRAMS + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-sbinPROGRAMS uninstall-siggenHEADERS + +.PRECIOUS: Makefile all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/siggen/Script2.aps b/src/siggen/Script2.aps deleted file mode 100644 index 2479766..0000000 Binary files a/src/siggen/Script2.aps and /dev/null differ diff --git a/src/siggen/resource.h b/src/siggen/resource.h deleted file mode 100644 index 5510e67..0000000 --- a/src/siggen/resource.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by Script2.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif - diff --git a/src/siggen/siggen.cpp b/src/siggen/siggen.cpp index 06b63a8..a1ad86d 100644 --- a/src/siggen/siggen.cpp +++ b/src/siggen/siggen.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,19 +53,16 @@ // cSiggen /////////////////////////////////////////////////////////////////////////////// -TSS_ImplementPackage( cSiggen ) +TSS_ImplementPackage(cSiggen) cSiggen::cSiggen() { - TSS_Dependency( cTW ); - TSS_Dependency( cUtil ); - TSS_Dependency( cCore ); - TSS_Dependency( cFCO ); - TSS_Dependency( cFS ); - TSS_Dependency( cDb ); - TSS_Dependency( cTWParser ); - TSS_Dependency( cTWCrypto ); + TSS_Dependency(cTW); + TSS_Dependency(cUtil); + TSS_Dependency(cCore); + TSS_Dependency(cFCO); + TSS_Dependency(cFS); + TSS_Dependency(cDb); + TSS_Dependency(cTWParser); + TSS_Dependency(cTWCrypto); } - -// eof: siggen.cpp - diff --git a/src/siggen/siggen.h b/src/siggen/siggen.h index 666bec9..1844053 100644 --- a/src/siggen/siggen.h +++ b/src/siggen/siggen.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,21 +40,20 @@ #ifndef __SIGGEN_H #define __SIGGEN_H -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #include "core/package.h" -TSS_BeginPackage( cSiggen ) +TSS_BeginPackage(cSiggen) TSS_DECLARE_STRINGTABLE; public: - cSiggen(); - -TSS_EndPackage( cSiggen ) +cSiggen(); +TSS_EndPackage(cSiggen) -#endif//__SIGGEN_H +#endif //__SIGGEN_H diff --git a/src/siggen/siggencmdline.cpp b/src/siggen/siggencmdline.cpp index 27767b1..f0ab1ca 100644 --- a/src/siggen/siggencmdline.cpp +++ b/src/siggen/siggencmdline.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,27 +34,26 @@ #include "siggencmdline.h" #include "core/cmdlineparser.h" -#include "core/archive.h" // cArchive and friends -#include "fco/signature.h" // cSignature -#include "fs/fsstrings.h" // file system related strings -#include "core/usernotify.h" // for notifying the user of events -#include "core/errorbucketimpl.h" // for the error table +#include "core/archive.h" // cArchive and friends +#include "fco/signature.h" // cSignature +#include "fs/fsstrings.h" // file system related strings +#include "core/usernotify.h" // for notifying the user of events +#include "core/errorbucketimpl.h" // for the error table #include "core/fsservices.h" #include "tw/twstrings.h" #include "core/displayencoder.h" #include "siggenstrings.h" -#include // for the FileExists() stuff +#include // for the FileExists() stuff - -#if IS_UNIX #include #include +#if SUPPORTS_TERMIOS #include #include +#endif //#include int _getch(void); -#endif using namespace std; @@ -62,7 +61,7 @@ using namespace std; // Static Functions, Variables -- /////////////////////////////////////////////////////////////////////////////// static void PrintHeader(TSTRING filename); -static bool util_FileExists(const TSTRING &fileName); +static bool util_FileExists(const TSTRING& fileName); //========================================================================= // GLOBALS @@ -72,30 +71,33 @@ const TCHAR* g_szEightyDashes = _T("-------------------------------------------- /////////////////////////////////////////////////////////////////////////////// //Insulated implementation for cSiggenCmdLine -struct cSiggen_i +struct cSiggen_i { - cSiggen_i() : mPrintHex(false), mTerseOutput(false) {} + cSiggen_i() : mPrintHex(false), mTerseOutput(false) + { + } ~cSiggen_i(); //Data Members: - bool mPrintHex; - //If this is true, the signatures will be output in hex rather than Base64 - bool mTerseOutput; - //If this is true, only the signatures will be printed, and the output will only use one line. - - typedef std::list > ListType; - ListType mSignatures; - std::list mFilesToCheck; - //A list of the files that need signatures generated for them. + bool mPrintHex; + //If this is true, the signatures will be output in hex rather than Base64 + bool mTerseOutput; + //If this is true, only the signatures will be printed, and the output will only use one line. + + typedef std::list > ListType; + ListType mSignatures; + std::list mFilesToCheck; + //A list of the files that need signatures generated for them. }; //Dtor: cSiggen_i::~cSiggen_i() -{ +{ cSiggen_i::ListType::iterator i; //Delete all the dynamically allocated signature objects. - for (i = mSignatures.begin(); i != mSignatures.end(); ++i) { - if ( ((*i).first) != NULL) + for (i = mSignatures.begin(); i != mSignatures.end(); ++i) + { + if (((*i).first) != NULL) delete ((*i).first); } } @@ -119,35 +121,35 @@ cSiggenCmdLine::~cSiggenCmdLine() // InitCmdLineParser -- Make the command line cognizant of siggen's arguments /////////////////////////////////////////////////////////////////////////////// void cSiggenCmdLine::InitCmdLineParser(cCmdLineParser& parser) -{ +{ - parser.AddArg(HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE) ; + parser.AddArg(HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); //Signatures: - parser.AddArg(CRC32, TSTRING(_T("C")), TSTRING(_T("CRC32")), cCmdLineParser::PARAM_NONE); - parser.AddArg(MD5, TSTRING(_T("M")), TSTRING(_T("MD5")), cCmdLineParser::PARAM_NONE); - parser.AddArg(SHA, TSTRING(_T("S")), TSTRING(_T("SHA")), cCmdLineParser::PARAM_NONE); - parser.AddArg(HAVAL, TSTRING(_T("H")), TSTRING(_T("HAVAL")), cCmdLineParser::PARAM_NONE); + parser.AddArg(CRC32, TSTRING(_T("C")), TSTRING(_T("CRC32")), cCmdLineParser::PARAM_NONE); + parser.AddArg(MD5, TSTRING(_T("M")), TSTRING(_T("MD5")), cCmdLineParser::PARAM_NONE); + parser.AddArg(SHA, TSTRING(_T("S")), TSTRING(_T("SHA")), cCmdLineParser::PARAM_NONE); + parser.AddArg(HAVAL, TSTRING(_T("H")), TSTRING(_T("HAVAL")), cCmdLineParser::PARAM_NONE); //Output switches - parser.AddArg(ALL, TSTRING(_T("a")), TSTRING(_T("all")), cCmdLineParser::PARAM_NONE); - parser.AddArg(HEX, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); - parser.AddArg(TERSE, TSTRING(_T("t")), TSTRING(_T("terse")), cCmdLineParser::PARAM_NONE); + parser.AddArg(ALL, TSTRING(_T("a")), TSTRING(_T("all")), cCmdLineParser::PARAM_NONE); + parser.AddArg(HEX, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); + parser.AddArg(TERSE, TSTRING(_T("t")), TSTRING(_T("terse")), cCmdLineParser::PARAM_NONE); //file parameters - parser.AddArg(PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + parser.AddArg(PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); } int cSiggenCmdLine::Execute() { cFileArchive arch; - //archive for reading in files - TCOUT.flags( ( TCOUT.flags() & ~std::ios::adjustfield ) | std::ios::left ); - //align all output to the left. + //archive for reading in files + TCOUT.flags((TCOUT.flags() & ~std::ios::adjustfield) | std::ios::left); + //align all output to the left. int rtn = 0; - // return value -- by default, it is set to 0 (OK) - + // return value -- by default, it is set to 0 (OK) + //Check to see if files have been specified. - if(mpData->mFilesToCheck.empty()) + if (mpData->mFilesToCheck.empty()) return 0; //Iterate over file list and generate each signature: @@ -155,15 +157,15 @@ int cSiggenCmdLine::Execute() for (fileIter = mpData->mFilesToCheck.begin(); fileIter != mpData->mFilesToCheck.end(); ++fileIter) { cDisplayEncoder e; - TSTRING displayStr = *fileIter; + TSTRING displayStr = *fileIter; e.Encode(displayStr); - if(!mpData->mTerseOutput) - PrintHeader( displayStr ); + if (!mpData->mTerseOutput) + PrintHeader(displayStr); - if( ! util_FileExists( *fileIter ) ) + if (!util_FileExists(*fileIter)) { - TCOUT << TSS_GetString( cSiggen, siggen::STR_ERR_NO_FILE ) << _T(": ") << displayStr.c_str() <Stat(*fileIter, fileInfo); - if(fileInfo.mFileType != cFSStatArgs::TY_FILE) + if (fileInfo.mFileType != cFSStatArgs::TY_FILE) { // Not a regular file; warn and skip this file. // - TCOUT << displayStr << TSS_GetString( cSiggen, siggen::STR_SIGGEN_NOT_REG_FILE ) << std::endl; + TCOUT << displayStr << TSS_GetString(cSiggen, siggen::STR_SIGGEN_NOT_REG_FILE) << std::endl; rtn = 1; continue; } } - catch(eFSServices& e) + catch (eFSServices& e) { cErrorReporter::PrintErrorMsg(e); rtn = 1; @@ -194,37 +196,37 @@ int cSiggenCmdLine::Execute() //Prepare the archive for reading from current file (in loop). try { - arch.OpenRead( (*fileIter).c_str() ); + arch.OpenRead((*fileIter).c_str()); } catch (eArchive&) { - TCOUT << TSS_GetString( cSiggen, siggen::STR_ERR_OPEN_FAILED ) << _T(": ") << displayStr.c_str() < list and add each signature to the + // Iterate over the list and add each signature to the // sig generator // - cArchiveSigGen asg; - std::list< std::pair >::iterator sigIter; - for ( sigIter = mpData->mSignatures.begin(); sigIter!= mpData->mSignatures.end(); ++sigIter ) - asg.AddSig( (*sigIter).first ); + cArchiveSigGen asg; + std::list >::iterator sigIter; + for (sigIter = mpData->mSignatures.begin(); sigIter != mpData->mSignatures.end(); ++sigIter) + asg.AddSig((*sigIter).first); // // calculate signatures // arch.Seek(0, cBidirArchive::BEGINNING); - asg.CalculateSignatures( arch ); + asg.CalculateSignatures(arch); arch.Close(); - + // // Iterate over the list and output each signature: // - for ( sigIter = mpData->mSignatures.begin(); sigIter != mpData->mSignatures.end(); ++sigIter ) + for (sigIter = mpData->mSignatures.begin(); sigIter != mpData->mSignatures.end(); ++sigIter) { - if(!mpData->mTerseOutput) + if (!mpData->mTerseOutput) TCOUT.width(20); //Set the output string to Hex or Base64, depending on the value of mPrintHex @@ -235,135 +237,135 @@ int cSiggenCmdLine::Execute() sigStringOut = ((*sigIter).first)->AsString(); //Output the signatures, include identifiers and newlines only if mTerseOutput is false. - if(!mpData->mTerseOutput) + if (!mpData->mTerseOutput) TCOUT << (*sigIter).second.c_str(); TCOUT << sigStringOut; - if(!mpData->mTerseOutput) + if (!mpData->mTerseOutput) TCOUT << endl; else TCOUT << _T(" "); //Output finished for iteration - }//end for + } //end for //Seperate lines of signatures (for multiple files) with a newline (if terse output) - if(mpData->mTerseOutput) + if (mpData->mTerseOutput) TCOUT << endl; } - if(!mpData->mTerseOutput) - TCOUT << g_szEightyDashes << _T("\n"); + if (!mpData->mTerseOutput) + TCOUT << g_szEightyDashes << _T("\n"); return rtn; } - + //Interprets the parsed command line and sets the member variables necessary for correct output. //See cSiggen_i. //Returns 0 if no file parameters have been passed, otherwise, returns 1. int cSiggenCmdLine::Init(cCmdLineParser& parser) { - cCmdLineIter iter(parser); //iterator for traversing command line - iter.SeekBegin(); - int i = 0; //loop variable - bool crc_select = false, md5_select = false, sha_select = false, haval_select = false; - //boolean locals for dealing with ALL switch. (temp.?) fix -DA + cCmdLineIter iter(parser); //iterator for traversing command line + iter.SeekBegin(); + int i = 0; //loop variable + bool crc_select = false, md5_select = false, sha_select = false, haval_select = false; + //boolean locals for dealing with ALL switch. (temp.?) fix -DA bool switch_present = false; - int ret = 0; //return value. will be false unless some file is specified. + int ret = 0; //return value. will be false unless some file is specified. - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) + { + case HELP: + { + return 0; + } + case CRC32: { - case HELP: - { - return 0; - break; - } - case CRC32: - { - crc_select = switch_present = true; - break; - } - case MD5: - { - md5_select = switch_present = true; - break; - } - case SHA: - { - sha_select = switch_present = true; - break; - } - case HAVAL: - { - haval_select = switch_present = true; - break; - } - case ALL: - { - crc_select = md5_select = sha_select = haval_select = switch_present = true; - break; - } - case HEX: - { - mpData->mPrintHex = true; - break; - } - case TERSE: - { - mpData->mTerseOutput = true; - break; - } - case PARAMS: - { - ret |= 1; - for (; i < iter.NumParams(); ++i) { - mpData->mFilesToCheck.push_back(TSTRING (iter.ParamAt(i)) ); - } - } - default: - break; + crc_select = switch_present = true; + break; + } + case MD5: + { + md5_select = switch_present = true; + break; + } + case SHA: + { + sha_select = switch_present = true; + break; + } + case HAVAL: + { + haval_select = switch_present = true; + break; + } + case ALL: + { + crc_select = md5_select = sha_select = haval_select = switch_present = true; + break; + } + case HEX: + { + mpData->mPrintHex = true; + break; + } + case TERSE: + { + mpData->mTerseOutput = true; + break; + } + case PARAMS: + { + ret |= 1; + for (; i < iter.NumParams(); ++i) + { + mpData->mFilesToCheck.push_back(TSTRING(iter.ParamAt(i))); + } + } + default: + break; } } //Default behavior is to print all signatures if no switch is specified. - if(!switch_present) + if (!switch_present) crc_select = md5_select = sha_select = haval_select = true; //Push the signatures and their output identifiers onto the mSignature list: - if(crc_select) + if (crc_select) { iSignature* sig_ptr = new cCRC32Signature; - TSTRING str = TSS_GetString( cFS, fs::STR_PROP_CRC32); - mpData->mSignatures.push_back(std::pair< iSignature*, TSTRING>(sig_ptr, str)); + TSTRING str = TSS_GetString(cFS, fs::STR_PROP_CRC32); + mpData->mSignatures.push_back(std::pair(sig_ptr, str)); } - if(md5_select) + if (md5_select) { iSignature* sig_ptr = new cMD5Signature; - TSTRING str = TSS_GetString( cFS, fs::STR_PROP_MD5); - mpData->mSignatures.push_back(std::pair< iSignature*, TSTRING>(sig_ptr, str)); + TSTRING str = TSS_GetString(cFS, fs::STR_PROP_MD5); + mpData->mSignatures.push_back(std::pair(sig_ptr, str)); } - if(sha_select) + if (sha_select) { iSignature* sig_ptr = new cSHASignature; - TSTRING str = TSS_GetString( cFS, fs::STR_PROP_SHA); - mpData->mSignatures.push_back(std::pair< iSignature*, TSTRING>(sig_ptr, str)); + TSTRING str = TSS_GetString(cFS, fs::STR_PROP_SHA); + mpData->mSignatures.push_back(std::pair(sig_ptr, str)); } - if(haval_select) + if (haval_select) { iSignature* sig_ptr = new cHAVALSignature; - TSTRING str = TSS_GetString( cFS, fs::STR_PROP_HAVAL); - mpData->mSignatures.push_back(std::pair< iSignature*, TSTRING>(sig_ptr, str)); + TSTRING str = TSS_GetString(cFS, fs::STR_PROP_HAVAL); + mpData->mSignatures.push_back(std::pair(sig_ptr, str)); } return ret; } //Prints a header for each signature. -void PrintHeader( TSTRING filename) +void PrintHeader(TSTRING filename) { TCOUT << g_szEightyDashes << _T( "\n" ); TCOUT << _T("Signatures for file: ") << filename.c_str() << _T("\n\n"); @@ -371,11 +373,5 @@ void PrintHeader( TSTRING filename) bool util_FileExists(const TSTRING& fileName) { -#if IS_UNIX - // for unix we may be able to use the same logic as above, but - // it is too close to 2.2.1 release to make that change w/o testing. - // I know the above works for windows. return _taccess(fileName.c_str(), F_OK) == 0; -#endif } - diff --git a/src/siggen/siggencmdline.h b/src/siggen/siggencmdline.h index 585eb25..a449e4c 100644 --- a/src/siggen/siggencmdline.h +++ b/src/siggen/siggencmdline.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,21 +42,22 @@ class cArchive; //Struct for storing class data. struct cSiggen_i; -class cSiggenCmdLine { +class cSiggenCmdLine +{ +public: public: - public: cSiggenCmdLine(); ~cSiggenCmdLine(); - void InitCmdLineParser (cCmdLineParser& parser ); - // call this to initialize the command line parser + void InitCmdLineParser(cCmdLineParser& parser); + // call this to initialize the command line parser - int Init ( cCmdLineParser& parser ); - //This function should be called prior to Execute. - //It's purpose is to transfer the information from the - //cmdlineparser class to the member data struct. - int Execute (); - //This is where the actual execution will take place. + int Init(cCmdLineParser& parser); + //This function should be called prior to Execute. + //It's purpose is to transfer the information from the + //cmdlineparser class to the member data struct. + int Execute(); + //This is where the actual execution will take place. // constants for all the command line arguments enum CmdLineArgs @@ -73,15 +74,14 @@ class cSiggenCmdLine { HEX, TERSE, - PARAMS, // the final parameters + PARAMS, // the final parameters NUM_CMDLINEARGS }; - private: +private: cSiggen_i* mpData; - //insulated implementation. + //insulated implementation. }; #endif //__SIGGENCMDLINE_H - diff --git a/src/siggen/siggenmain.cpp b/src/siggen/siggenmain.cpp index c669722..9c3c9fa 100644 --- a/src/siggen/siggenmain.cpp +++ b/src/siggen/siggenmain.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,7 +33,6 @@ #include "stdsiggen.h" - #include "core/types.h" #include "core/tchar.h" #include "core/debug.h" @@ -43,10 +42,10 @@ #include "core/cmdlineparser.h" #include "core/errorbucketimpl.h" #include "core/usernotifystdout.h" -#include "core/timebomb.h" +#include "core/epoch.h" #include "fs/fsstrings.h" #include "tw/twstrings.h" -#include "tw/twutil.h" // for cTWUtil::PrintErrorMsg +#include "tw/twutil.h" // for cTWUtil::PrintErrorMsg #include "siggenstrings.h" #include "siggen.h" @@ -55,10 +54,8 @@ #include #include -#if IS_UNIX #include "core/unixfsservices.h" #include -#endif /////////////////////////////////////////////////////////////////////////////// // terminate and unexpected handlers @@ -78,40 +75,38 @@ void tw_unexpected_handler() static void SiggenInit() { - TSS_Dependency( cSiggen ); - - static cUserNotifyStdout unStdout; - static cErrorTracer et; - static cErrorReporter er; + TSS_Dependency(cSiggen); + + static cUserNotifyStdout unStdout; + static cErrorTracer et; + static cErrorReporter er; // // initialize iUserNotify // - iUserNotify::SetInstance( &unStdout ); + iUserNotify::SetInstance(&unStdout); iUserNotify::GetInstance()->SetVerboseLevel(iUserNotify::V_NORMAL); // - // set up the file system services + // set up the file system services // -#if IS_UNIX - static cUnixFSServices fss; -#endif - iFSServices::SetInstance( &fss ); + static cUnixFSServices fss; + iFSServices::SetInstance(&fss); // // set up an error bucket that will spit things to stderr // - et.SetChild( &er ); + et.SetChild(&er); } int __cdecl _tmain(int argc, const TCHAR** argv) { int ret = 0; - if (TimeBombExploded()) + if (CheckEpoch()) return 1; - try + try { // set unexpected and terminate handlers // Note: we do this before Init() in case it attempts to call these handlers @@ -128,10 +123,10 @@ int __cdecl _tmain(int argc, const TCHAR** argv) // first, process the command line if (argc < 2) { - TCOUT << TSS_GetString( cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - + TCOUT << TSS_GetString(cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + ret = 1; goto exit; } @@ -141,9 +136,9 @@ int __cdecl _tmain(int argc, const TCHAR** argv) // this is quick and dirty ... just the way I like it :-) -- mdb // if (_tcscmp(argv[1], _T("--version")) == 0) - { - TCOUT << TSS_GetString( cTW, tw::STR_VERSION_LONG) << std::endl; - ret=0; + { + TCOUT << TSS_GetString(cTW, tw::STR_VERSION_LONG) << std::endl; + ret = 0; goto exit; } @@ -154,11 +149,11 @@ int __cdecl _tmain(int argc, const TCHAR** argv) { cmdLine.Parse(argc, argv); } - catch( eError& e ) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); - TCERR << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - + TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + ret = 1; goto exit; } @@ -166,22 +161,22 @@ int __cdecl _tmain(int argc, const TCHAR** argv) cCmdLineIter iter(cmdLine); if (iter.SeekToArg(cSiggenCmdLine::HELP)) { - TCOUT << TSS_GetString( cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - TCOUT << TSS_GetString( cSiggen, siggen::STR_SIGGEN_USAGE) << std::endl; + TCOUT << TSS_GetString(cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cSiggen, siggen::STR_SIGGEN_USAGE) << std::endl; ret = 1; goto exit; } - if(! siggen.Init(cmdLine)) + if (!siggen.Init(cmdLine)) { - TCOUT << TSS_GetString( cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - TCOUT << TSS_GetString( cSiggen, siggen::STR_SIGGEN_USAGE) << std::endl; + TCOUT << TSS_GetString(cSiggen, siggen::STR_SIGGEN_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cSiggen, siggen::STR_SIGGEN_USAGE) << std::endl; ret = 1; goto exit; } - ret = siggen.Execute(); + ret = siggen.Execute(); } //end try block catch (eError& error) @@ -193,5 +188,4 @@ int __cdecl _tmain(int argc, const TCHAR** argv) exit: return ret; -}//end MAIN - +} //end MAIN diff --git a/src/siggen/siggenstrings.cpp b/src/siggen/siggenstrings.cpp index 621ad4a..a89f6a7 100644 --- a/src/siggen/siggenstrings.cpp +++ b/src/siggen/siggenstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,31 +42,34 @@ #include "stdsiggen.h" #include "siggenstrings.h" +#if IS_AROS +# define VERSION_PREFIX "$VER: " +#else +# define VERSION_PREFIX "@(#)" +#endif + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // String Table //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -TSS_BeginStringtable( cSiggen ) - - TSS_StringEntry( siggen::STR_SIGGEN_USAGE, - _T("Usage: siggen [options] file1 [file2...]\n") - _T("\n") - _T(" -t --terse\n") - _T(" -h --hexadecimal\n") - _T(" -a --all\n") - _T(" -C --CRC32\n") - _T(" -M --MD5\n") - _T(" -S --SHA\n") - _T(" -H --HAVAL\n") - _T("file1 [file 2 ...]\n") - _T("\n") - ), - TSS_StringEntry( siggen::STR_SIGGEN_VERSION, _T("siggen: Display signature function values. \n")), - TSS_StringEntry( siggen::STR_ERR_OPEN_FAILED, _T("File could not be opened") ), - TSS_StringEntry( siggen::STR_ERR_NO_FILE, _T("File does not exist") ), - TSS_StringEntry( siggen::STR_SIGGEN_NOT_REG_FILE, _T(" is not a regular file; ignoring.") ) - -TSS_EndStringtable( cSiggen ) +TSS_BeginStringtable(cSiggen) -// eof: siggenstrings.cpp + TSS_StringEntry(siggen::STR_SIGGEN_USAGE, + _T("Usage: siggen [options] file1 [file2...]\n") + _T("\n") + _T(" -t --terse\n") + _T(" -h --hexadecimal\n") + _T(" -a --all\n") + _T(" -C --CRC32\n") + _T(" -M --MD5\n") + _T(" -S --SHA\n") + _T(" -H --HAVAL\n") + _T("file1 [file 2 ...]\n") + _T("\n")), + TSS_StringEntry(siggen::STR_SIGGEN_VERSION, _T("siggen: Display signature function values. \n")), + TSS_StringEntry(siggen::STR_EMBEDDED_VERSION, _T(VERSION_PREFIX "siggen " PACKAGE_VERSION)), + TSS_StringEntry(siggen::STR_ERR_OPEN_FAILED, _T("File could not be opened")), + TSS_StringEntry(siggen::STR_ERR_NO_FILE, _T("File does not exist")), + TSS_StringEntry(siggen::STR_SIGGEN_NOT_REG_FILE, _T(" is not a regular file; ignoring.")) + TSS_EndStringtable(cSiggen) diff --git a/src/siggen/siggenstrings.h b/src/siggen/siggenstrings.h index cac8b73..8f349ac 100644 --- a/src/siggen/siggenstrings.h +++ b/src/siggen/siggenstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,15 +42,12 @@ #include "siggen.h" -TSS_BeginStringIds( siggen ) +TSS_BeginStringIds(siggen) STR_SIGGEN_USAGE, - STR_SIGGEN_VERSION, - STR_SIGGEN_NOT_REG_FILE, - STR_ERR_NO_FILE, + STR_SIGGEN_VERSION, STR_EMBEDDED_VERSION, STR_SIGGEN_NOT_REG_FILE, STR_ERR_NO_FILE, STR_ERR_OPEN_FAILED -TSS_EndStringIds( siggen ) + TSS_EndStringIds(siggen) #endif // __SIGGENSTRINGS_H - diff --git a/src/siggen/stdsiggen.cpp b/src/siggen/stdsiggen.cpp index 54e47e1..504ca4e 100644 --- a/src/siggen/stdsiggen.cpp +++ b/src/siggen/stdsiggen.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // // #include "stdsiggen.h" - -// eof: stdsiggen.cpp diff --git a/src/siggen/stdsiggen.h b/src/siggen/stdsiggen.h index 874dc91..c8a6418 100644 --- a/src/siggen/stdsiggen.h +++ b/src/siggen/stdsiggen.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/test-harness/tests/chpass.pm b/src/test-harness/tests/chpass.pm new file mode 100644 index 0000000..3e201f2 --- /dev/null +++ b/src/test-harness/tests/chpass.pm @@ -0,0 +1,84 @@ + +use twtools; + +package chpass; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "change passphrases test"; +} + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + my $newpass = "password"; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases -S $twtools::twrootdir/$twtools::twsitekeyloc --site-passphrase $newpass --site-passphrase-old $twtools::twsitepass`); + if ( $? != 0 ) { + twtools::logStatus("first change site passphrase failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases -S $twtools::twrootdir/$twtools::twsitekeyloc --site-passphrase $twtools::twsitepass --site-passphrase-old $newpass`); + if ( $? != 0 ) { + twtools::logStatus("second change site passphrase failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases -L $twtools::twrootdir/$twtools::twlocalkeyloc --local-passphrase $newpass --local-passphrase-old $twtools::twlocalpass`); + if ( $? != 0 ) { + twtools::logStatus("first change local passphrase failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases -L $twtools::twrootdir/$twtools::twlocalkeyloc --local-passphrase $twtools::twlocalpass --local-passphrase-old $newpass`); + if ( $? != 0 ) { + twtools::logStatus("second change local passphrase failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + return 0; + } +} + + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/complex.pm b/src/test-harness/tests/complex.pm index 201f9f0..15ad9b9 100644 --- a/src/test-harness/tests/complex.pm +++ b/src/test-harness/tests/complex.pm @@ -119,8 +119,8 @@ EOT # sub initialize() { - my $twstr = getPolicyFileString(); - twtools::GeneratePolicyFile($twstr); + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); } @@ -131,29 +131,36 @@ sub initialize() { # sub run() { - my $twpassed = 1; + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); - twtools::logStatus("*** Beginning $description\n"); - printf("%-30s", "-- $description"); + if ($^O eq "skyos" || $^O eq "gnu") { + ++$twtools::twskippedtests; + print "SKIPPED; TODO: OS has fewer expected changes here; refactor so we can test for correct values\n"; + return; + } - ######################################################### - # - # Run the tests describe above in the %TESTS structure. - # - $twpassed = twtools::RunIntegrityTests(%TESTS); + my $twpassed = 1; + ######################################################### + # + # Run the tests describe above in the %TESTS structure. + # + $twpassed = twtools::RunIntegrityTests(%TESTS); - ######################################################### - # - # See if the tests all succeeded... - # - if ($twpassed) { + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { print "PASSED\n"; - } - else { + ++$twtools::twpassedtests; + } + else { ++$twtools::twfailedtests; print "*FAILED*\n"; - } + } } diff --git a/src/test-harness/tests/crc32.pm b/src/test-harness/tests/crc32.pm index 28a071a..764eccf 100644 --- a/src/test-harness/tests/crc32.pm +++ b/src/test-harness/tests/crc32.pm @@ -28,39 +28,48 @@ sub initialize() { # sub run() { - my $twpassed = 1; + my $twpassed = 1; - twtools::logStatus("*** Beginning $description\n"); - printf("%-30s", "-- $description"); + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + # lets see if the system 'cksum' agree's with siggen's crc32 value + # Doing split with ' ' instead of / / because some flavors of cksum + # like to separate fields with tabs, as seen on Solaris 10. + # + my ($crc32, undef) = split(' ', `cksum $twtools::twrootdir/test`); - # lets see if the system 'cksum' agree's with siggen's md5 hash - # - my ($crc32, undef) = split(/ /, `cksum $twtools::twrootdir/test`); - my $siggen = `$twtools::twrootdir/bin/siggen -h -t -C $twtools::twrootdir/test`; + if ($crc32 eq "") { + ++$twtools::twskippedtests; + print "SKIPPED\n"; + return; + } - chomp $md5sum; - chomp $siggen; + my $siggen = `$twtools::twrootdir/bin/siggen -h -t -C $twtools::twrootdir/test`; - # cksum issues results in decimal, so get siggen's result in base10. - $siggen = hex($siggen); + chomp $crc32; + chomp $siggen; - twtools::logStatus(" cksum reports: $crc32\n"); - twtools::logStatus("siggen reports: $siggen\n"); + # cksum issues results in decimal, so get siggen's result in base10. + $siggen = hex($siggen); - $twpassed = $crc32 == $siggen; + twtools::logStatus(" cksum reports: $crc32\n"); + twtools::logStatus("siggen reports: $siggen\n"); - ######################################################### - # - # See if the tests all succeeded... - # - if ($twpassed) { + $twpassed = ($crc32 eq $siggen); + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { print "PASSED\n"; - } - else { + ++$twtools::twpassedtests; + } + else { ++$twtools::twfailedtests; print "*FAILED*\n"; - } + } } diff --git a/src/test-harness/tests/createpolicy.pm b/src/test-harness/tests/createpolicy.pm new file mode 100644 index 0000000..7aac8cb --- /dev/null +++ b/src/test-harness/tests/createpolicy.pm @@ -0,0 +1,121 @@ + +use twtools; + +package createpolicy; + + +###################################################################### +# One time module initialization goes in here... +# +BEGIN +{ + $description = "policy creation test"; + $testpolicydir = "$twtools::twrootdir/../../parser/testfiles"; + $badpolicydir = "$twtools::twrootdir/../../parser/testfiles.bad"; + $twpassed = 1; +} + + +###################################################################### +# Try all policy files in specified directory, & verify each returns expected value +# +sub test_policy_dir +{ + my ($policydir, $expected) = @_; + # my $twpassed = 1; + + opendir my $dir, $policydir or return 0; + my @files = readdir $dir; + closedir $dir; + + foreach my $current_file (@files) { + + if ($current_file eq "." || $current_file eq ".." ) { + next; + } + + twtools::logStatus "Trying policy text $policydir/$current_file\n"; + + twtools::CreatePolicy({policy_text => "$policydir/$current_file"}); + if ( $? != $expected ) { + twtools::logStatus ("*** create-polfile with $policydir/$current_file failed, error = $?\n"); + $twpassed = 0; + } + } + + twtools::logStatus("Done with policy dir $policydir, result = $twpassed\n"); + return $twpassed; +} + + +###################################################################### +# +# Run the test. +# +sub run +{ + my $out = 1; + + + # First try a bunch of policies that are supposed to succeed + # + twtools::logStatus("*** Beginning policy creation test\n"); + printf("%-30s", "-- policy creation test"); + + test_policy_dir( "$testpolicydir", 0 ); + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + $out = 0; + } + + + # Now try some bad policies + # + twtools::logStatus("*** Beginning bad policy rejection test\n"); + printf("%-30s", "-- bad policy rejection test"); + + $twpassed = 1; + ++$twtools::twtotaltests; + + test_policy_dir( "$badpolicydir", 256 ); + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + $out = 0; + } + + + return $out; +} + + + +###################################################################### +# +# Initialize the test +# + +sub initialize +{ + return 1; +} + + +###################################################################### +# One time module cleanup goes in here... +# +END +{ +} + +1; + diff --git a/src/test-harness/tests/crypto.pm b/src/test-harness/tests/crypto.pm new file mode 100644 index 0000000..795f078 --- /dev/null +++ b/src/test-harness/tests/crypto.pm @@ -0,0 +1,108 @@ + +use twtools; + +package crypto; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "file crypto test"; +} + + +###################################################################### +# PolicyFileString -- return the policy text as a string +# +sub PolicyFileString +{ + return < +M; #read only plus MD5 + +POLICY_END + +} + + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + + my $twstr = PolicyFileString(); + twtools::GeneratePolicyFile($twstr); + +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + my $testpath = "$twtools::twrootdir/$twtools::twpolfileloc"; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + if ( ! twtools::ExamineEncryption("$testpath")) + { + twtools::logStatus("first examine encryption failed\n"); + $twpassed = 0; + } + + twtools::logStatus("testing file crypto removal...\n"); + if ( !twtools::RemoveEncryption("$testpath")) + { + twtools::logStatus("remove encryption failed\n"); + $twpassed = 0; + } + + if ( ! twtools::ExamineEncryption("$testpath")) + { + twtools::logStatus("second examine encryption failed\n"); + $twpassed = 0; + } + + twtools::logStatus("testing file crypto...\n"); + if ( ! twtools::AddEncryption("$testpath")) + { + twtools::logStatus("add encryption failed\n"); + $twpassed = 0; + } + + if ( ! twtools::ExamineEncryption("$testpath")) + { + twtools::logStatus("third examine encryption failed\n"); + $twpassed = 0; + } + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + return 0; + } +} + + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/dbupdate.pm b/src/test-harness/tests/dbupdate.pm index 9b0c448..befbe9f 100644 --- a/src/test-harness/tests/dbupdate.pm +++ b/src/test-harness/tests/dbupdate.pm @@ -9,7 +9,6 @@ package dbupdate; # BEGIN { - # This is the root directory we will be integrity checking # $root = "$twtools::twcwd/$twtools::twrootdir/dbupdate-test"; @@ -135,7 +134,7 @@ sub PrepareForTest # Initialize the database # - twtools::initializeDatabase(); + twtools::InitializeDatabase(); } ###################################################################### @@ -143,128 +142,144 @@ sub PrepareForTest # sub RunBasicTest { - PrepareForTest(); - - printf("%-30s", "-- dbupdate.basic test"); - - # make some violations... - # - MoveFile ( "meow.txt", "cat.txt" ); - CreateFile( "dog/bark.txt", "bark bark bark" ); - - # run the integrity check... - # - twtools::runIntegrityCheck(); - - # Make sure we got 4 violations: 2 mod, 1 add, 1 rm. - # - my ($n, $a, $r, $c) = - twtools::analyzeReport( twtools::runReport() ); - - if( ($n != 4) || ($a != 1) || ($r != 1) || ($c != 2) ) - { - print "FAILED -- initial integrity check was wack!"; - return 0; - } - - # do the database update... - # - twtools::updateDatabase(); - - # do another IC and make sure there are no violations - # - twtools::runIntegrityCheck(); - - ($n, $a, $r, $c) = - twtools::analyzeReport( twtools::runReport() ); - - if( $n != 0 ) - { - print "FAILED -- violations after update!"; - return 0; - } - - print "PASSED!!!\n"; - return 1; + twtools::logStatus("*** Beginning dbupdate.basic test\n"); + printf("%-30s", "-- dbupdate.basic test"); + + PrepareForTest(); + + # make some violations... + # + MoveFile ( "meow.txt", "cat.txt" ); + CreateFile( "dog/bark.txt", "bark bark bark" ); + + # run the integrity check... + # + twtools::RunIntegrityCheck(); + + # Make sure we got 4 violations: 2 mod, 1 add, 1 rm. + # + my $dir_mods = (($^O eq "skyos") || ($^O eq "dragonfly")) ? 0 : 1; + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 4 : 3; + my $c_expected = $dir_mods ? 2 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 1) || ($c != $c_expected) ) { + + twtools::logStatus("FAILED -- initial integrity check had unexpected results\n"); + return 0; + } + + # do the database update... + # + if (0 != twtools::UpdateDatabase()) + { + twtools::logStatus("FAILED -- db update did not succeed\n"); + return 0; + } + + # do another IC and make sure there are no violations + # + twtools::RunIntegrityCheck(); + + ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + if( $n != 0 ) + { + twtools::logStatus("FAILED -- violations after update\n"); + return 0; + } + + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; } ###################################################################### -# RunSecureModeTest -- test that secure-mode high and low are working +# RunSecureModeTest -- test that secure_mode high and low are working # sub RunSecureModeTest { - PrepareForTest(); - - printf("%-30s", "-- dbupdate.secure-mode test"); - - # make a violation and generate a report - # - CreateFile( "dog/bark.txt", "bark bark bark" ); - twtools::runIntegrityCheck( { report => $report1 } ); - - # change the same file in a slightly different way and generate - # another report - # - CreateFile( "dog/bark.txt", "bark bark bark woof" ); - twtools::runIntegrityCheck( { report => $report2 } ); - - # Remove a file and generate a third report - # - RemoveFile( "dog/bark.txt" ); - twtools::runIntegrityCheck( { report => $report3 } ); - - # Add a file and generate the fourth report - # - CreateFile( "dog/cow.txt", "moo moo" ); - twtools::runIntegrityCheck( { report => $report4 } ); - - - # Update the database with report 1. - # - twtools::updateDatabase( { report => $report1 } ); - - # Try to update the database with report 2 ... this should fail - # in secure-mode == high because the "old" values don't match. - # - if( twtools::updateDatabase( - { report => $report2, secure-mode => "high" } ) ) - { - print "FAILED ... Secure-mode high didn't catch a bad update!"; - return 0; - } - - # do a high severity update with report3 -- this should - # succeed - # - if( ! twtools::updateDatabase( - { report => $report3, secure-mode => "high" } ) ) - { - print "FAILED ... Update with report 3 failed!"; - return 0; - } - - # Try 2 again ... now we are trying to update an object that - # doesn't exist in the database at all. This should - # succeed in low but fail in high. - # - if( twtools::updateDatabase( - { report => $report2, secure-mode => "high" } ) ) - { - print "FAILED ... Update with report 2 after 3 succeeded in high mode!"; - return 0; - } - - if( ! twtools::updateDatabase( - { report => $report2, secure-mode => "low" } ) ) - { - print "FAILED ... Update with report 2 after 3 failed in low mode!"; - return 0; - } - - - - print "PASSED!!!\n"; - return 1; + twtools::logStatus("*** Beginning dbupdate.secure_mode test\n"); + printf("%-30s", "-- dbupdate.secure_mode test"); + + PrepareForTest(); + + # make a violation and generate a report + # + CreateFile( "dog/bark.txt", "bark bark bark" ); + twtools::RunIntegrityCheck( { report => $report1 } ); + + # change the same file in a slightly different way and generate + # another report + # + CreateFile( "dog/bark.txt", "bark bark bark woof" ); + twtools::RunIntegrityCheck( { report => $report2 } ); + + # Remove a file and generate a third report + # + RemoveFile( "dog/bark.txt" ); + twtools::RunIntegrityCheck( { report => $report3 } ); + + # Add a file and generate the fourth report + # + CreateFile( "dog/cow.txt", "moo moo" ); + twtools::RunIntegrityCheck( { report => $report4 } ); + + # Update the database with report 1. + # + twtools::UpdateDatabase( { report => $report1 } ); + + # Try to update the database with report 1 again ... this should fail + # in secure_mode == high because the db can't accept same changes again. + # + if( 0 == twtools::UpdateDatabase( + { report => $report1, secure_mode => "high" } ) ) + { + twtools::logStatus("FAILED ... secure_mode high didn't catch a bad update\n"); + return 0; + } + + # Try to update the database with report 2 ... this should fail + # in secure_mode == high because the "old" values don't match. + # + if( 0 == twtools::UpdateDatabase( + { report => $report2, secure_mode => "high" } ) ) + { + twtools::logStatus("FAILED ... secure_mode high didn't catch a bad update\n"); + return 0; + } + + # do a high severity update with report3 -- this should + # succeed + # + if( 0 != twtools::UpdateDatabase( + { report => $report3, secure_mode => "high" } ) ) + { + twtools::logStatus("FAILED ... Update with report 3 failed\n"); + return 0; + } + + # Try 2 again ... now we are trying to update an object that + # doesn't exist in the database at all. This should + # succeed in low but fail in high. + # + if( 0 == twtools::UpdateDatabase( + { report => $report2, secure_mode => "high" } ) ) + { + twtools::logStatus("FAILED ... Update with report 2 after 3 succeeded in high mode\n"); + return 0; + } + + if( 0 != twtools::UpdateDatabase( + { report => $report2, secure_mode => "low" } ) ) + { + twtools::logStatus("FAILED ... Update with report 2 after 3 failed in low mode\n"); + return 0; + } + + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; } @@ -275,9 +290,10 @@ sub RunSecureModeTest sub initialize { - # Make the policy file - # - twtools::generatePolicyFile( PolicyFileString() ); + # Make the policy file + # + twtools::GeneratePolicyFile( PolicyFileString() ); + return 1; } @@ -287,8 +303,26 @@ sub initialize # sub run { - RunBasicTest() || return; - RunSecureModeTest() || return; + eval { + RunBasicTest(); + } or do { + my $e = $@; + twtools::logStatus("Exception in DBUpdate RunBasicTest: $e\n"); + ++$twtools::twfailedtests; + print "*FAILED*\n"; + }; + + # bump the total test count since this file's a twofer + ++$twtools::twtotaltests; + + eval { + RunSecureModeTest(); + } or do { + my $e = $@; + twtools::logStatus("Exception in DBUpdate RunSecureModeTest: $e\n"); + ++$twtools::twfailedtests; + print "*FAILED*\n"; + }; } sub cleanup diff --git a/src/test-harness/tests/dirs.pm b/src/test-harness/tests/dirs.pm index b714b7d..dfbb37a 100644 --- a/src/test-harness/tests/dirs.pm +++ b/src/test-harness/tests/dirs.pm @@ -105,12 +105,12 @@ EOT # sub initialize() { - my $twstr = getPolicyFileString(); - twtools::GeneratePolicyFile($twstr); + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); - # this test requires a clean start of it's tree - # - system("rm -rf $twtools::twrootdir/" . $TESTS{"0-createTempDir"}{dir}); + # this test requires a clean start of it's tree + # + system("rm -rf $twtools::twrootdir/" . $TESTS{"0-createTempDir"}{dir}); } @@ -120,29 +120,37 @@ sub initialize() { # sub run() { - my $twpassed = 1; + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); - twtools::logStatus("*** Beginning $description\n"); - printf("%-30s", "-- $description"); + if (($^O eq "skyos") || ($^O eq "dragonfly")) { + ++$twtools::twskippedtests; + print "SKIPPED; TODO: OS has fewer expected changes here; refactor so we can test for correct values\n"; + return; + } - ######################################################### - # - # Run the tests describe above in the %TESTS structure. - # - $twpassed = twtools::RunIntegrityTests(%TESTS); + my $twpassed = 1; - ######################################################### - # - # See if the tests all succeeded... - # - if ($twpassed) { + ######################################################### + # + # Run the tests describe above in the %TESTS structure. + # + $twpassed = twtools::RunIntegrityTests(%TESTS); + + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; - } - else { + } + else { ++$twtools::twfailedtests; print "*FAILED*\n"; - } + } } diff --git a/src/test-harness/tests/email.pm b/src/test-harness/tests/email.pm new file mode 100644 index 0000000..f03eb09 --- /dev/null +++ b/src/test-harness/tests/email.pm @@ -0,0 +1,85 @@ + +use twtools; + +package email; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "email test"; +} + + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + my($sending, undef, undef, $mailfrom, $mailto, $subject, undef, undef, undef, $body) = twtools::RunEmailTest(); + + # Verify that various lines in the test email output look right, + # including the RFC 2822-required CRLFs that should be in everything + # except $sending, which isn't part of the actual email. + # + if ( !($sending =~ "Sending a test message to: elvis\@mars")) { + twtools::logStatus("Unexpected sending line: $sending\n"); + $twpassed = 0; + } + + if ( !($mailfrom =~ "taz\@cat")) { + twtools::logStatus("Unexpected From: field: $mailfrom\n"); + $twpassed = 0; + } + + if ( !($mailto =~ "To: elvis\@mars\r")) { + twtools::logStatus("Unexpected To: field: $mailto\n"); + $twpassed = 0; + } + + if ( !($subject =~ "Subject: Test email message from Tripwire\r")) { + twtools::logStatus("Unexpected Subject field: $subject\n"); + $twpassed = 0; + } + + if ( !($body =~ "If you receive this message, email notification from tripwire is working correctly.\r")) { + twtools::logStatus("Unexpected message body: $body\n"); + $twpassed = 0; + } + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + print "PASSED\n"; + ++$twtools::twpassedtests; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + } +} + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/hashes.pm b/src/test-harness/tests/hashes.pm index e9741bc..0cab2f7 100644 --- a/src/test-harness/tests/hashes.pm +++ b/src/test-harness/tests/hashes.pm @@ -125,6 +125,7 @@ sub run() { # See if the tests all succeeded... # if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; } else { diff --git a/src/test-harness/tests/inoderef.pm b/src/test-harness/tests/inoderef.pm index 8711179..50117d1 100644 --- a/src/test-harness/tests/inoderef.pm +++ b/src/test-harness/tests/inoderef.pm @@ -77,8 +77,8 @@ EOT # sub initialize() { - my $twstr = getPolicyFileString(); - twtools::GeneratePolicyFile($twstr); + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); } @@ -89,29 +89,36 @@ sub initialize() { # sub run() { - my $twpassed = 1; + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); - twtools::logStatus("*** Beginning $description\n"); - printf("%-30s", "-- $description"); + if ($^O eq "skyos" || $^O eq "haiku" || $^O eq "syllable") { + ++$twtools::twskippedtests; + print "SKIPPED; OS doesn't support hardlinks.\n"; + return; + } - ######################################################### - # - # Run the tests describe above in the %TESTS structure. - # - $twpassed = twtools::RunIntegrityTests(%TESTS); + my $twpassed = 1; + ######################################################### + # + # Run the tests describe above in the %TESTS structure. + # + $twpassed = twtools::RunIntegrityTests(%TESTS); - ######################################################### - # - # See if the tests all succeeded... - # - if ($twpassed) { + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; - } - else { + } + else { ++$twtools::twfailedtests; print "*FAILED*\n"; - } + } } diff --git a/src/test-harness/tests/integritycheck.pm b/src/test-harness/tests/integritycheck.pm new file mode 100644 index 0000000..c95d98d --- /dev/null +++ b/src/test-harness/tests/integritycheck.pm @@ -0,0 +1,439 @@ + +use twtools; + +package integritycheck; + + +###################################################################### +# One time module initialization goes in here... +# +BEGIN +{ + $description = "integrity check test"; + + # This is the root directory we will be integrity checking + # + $root = "$twtools::twcwd/$twtools::twrootdir/ic-test-a"; + $root2 = "$twtools::twcwd/$twtools::twrootdir/ic-test-b"; + + # Here are the names of the report files this test will create + # + $report1 = "$twtools::twcwd/$twtools::twrootdir/report/ic-1.twr"; + + $report2 = "$twtools::twcwd/$twtools::twrootdir/report/dbupdate-2.twr"; + $report3 = "$twtools::twcwd/$twtools::twrootdir/report/dbupdate-3.twr"; + $report4 = "$twtools::twcwd/$twtools::twrootdir/report/dbupdate-4.twr"; +} + +###################################################################### +# PolicyFileString -- return the policy text as a string +# +sub PolicyFileString +{ + return < \$(ReadOnly) +S -ab; #read only plus SHA-1 minus atime & blocks + } + + (rulename="RuleB", severity=200, emailto="elvis@mars") + { + $root2 -> \$(ReadOnly) +S -ab; #read only plus SHA-1 minus atime & blocks + } + +POLICY_END + +} + +###################################################################### +# CreateFile -- create a file with the specified contents +# +# input: path -- path to the file; relative to $root +# contents -- string to put in the file +# +sub CreateFile +{ + my ($path, $contents) = @_; + + system( "echo $contents > $path" ); + + $? && die "Create file failed for $path\n"; +} + +###################################################################### +# RemoveFile -- removes the named file +# +sub RemoveFile +{ + my ($path) = @_; + + if( -e "$path" ) + { + system( "rm -f $path" ); + } + + $? && die "Remove file failed for $root/$path\n"; +} + + +###################################################################### +# CreateDir -- create a directory +# +sub CreateDir +{ + my($dir) = @_; + + # NOTE: mkdir fails if it is already a directory! + # + if( ! -d "$dir" ) + { + system( "rm -f $dir" ); + system( "mkdir -p $dir" ); + + $? && die "Mkdir failed for $root/$dir\n"; + } +} + +###################################################################### +# MoveFile -- move a file from one place to another +# NOTE: file names are relative to $root +# +# input: old_name -- name of file to move +# new_name -- where it should be moved to +# +sub MoveFile +{ + my($old, $new) = @_; + + system( "mv $old $new" ); + $? && die "mv $old $new failed!\n"; +} + +###################################################################### +# PrintDatabase +# +sub PrintDatabase +{ + system( "$twtools::twrootdir/bin/twprint -m d -c $twtools::twrootdir/tw.cfg" ); +} + +###################################################################### +# PrintReport +# +sub PrintReport +{ + my ($report) = @_; + system( "$twtools::twrootdir/bin/twprint -m r -c $twtools::twrootdir/tw.cfg -r $report" ); +} + +###################################################################### +# PrepareForTest -- creates the files that each test will be +# integrity checking and initializes the database. +# +sub PrepareForTest +{ + # make sure we are cleaned up... + # + cleanup(); + + # Make the files we will be using... + # + CreateDir ( "$root"); + CreateDir ( "$root/subdir" ); + CreateFile( "$root/subdir/modify.txt", "hello world" ); + CreateFile( "$root/copy-src.txt", "asdf" ); + + CreateDir ( "$root2"); + CreateFile( "$root2/deleteme.txt", "goodbye cruel world" ); + + # Initialize the database + # + twtools::InitializeDatabase(); +} + + +###################################################################### +# +# Run the test. +# +sub run +{ + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + if ($^O eq "dragonfly") { + ++$twtools::twskippedtests; + print "SKIPPED; TODO: DragonflyBSD has fewer expected changes here; refactor so we can test for correct values\n"; + return; + } + + my $twpassed = 1; + my $dir_mods = ($^O eq "skyos") ? 0 : 1; + + PrepareForTest(); + + # make some violations... + # + MoveFile ( "$root/copy-src.txt", "$root/copy-dest.txt" ); + CreateFile( "$root/subdir/modify.txt", "bark bark bark" ); + RemoveFile( "$root2/deleteme.txt"); + + ####################################################### + # First run a full IC + # + twtools::RunIntegrityCheck(); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 6 : 4; + my $c_expected = $dir_mods ? 3 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 2) || ($c != $c_expected) ) + { + twtools::logStatus("Full IC failed: $n $a $r $c\n"); + $twpassed = 0; + } + + # TODO: Make RunReport+AnalyzeReport play nice with signed report files + ####################################################### + # Do it again, but sign it this time. + # + #twtools::RunIntegrityCheck({trailing_opts => "-E -P $twtools::twlocalpass"}); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + #my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + #if( ($n != 6) || ($a != 1) || ($r != 2) || ($c != 3) ) + #{ + # twtools::logStatus("Full IC with signing failed: $n $a $r $c\n"); + # $twpassed = 0; + #} + + ####################################################### + # Now run 'just' the FS section, aka the whole policy + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck(trailing_opts => "-x FS"); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 6 : 4; + my $c_expected = $dir_mods ? 3 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 2) || ($c != $c_expected) ) + { + twtools::logStatus("IC with FS section failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Now run a check ignoring the SHA attribute, should still return same changes + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck(trailing_opts => "-i S"); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 6 : 4; + my $c_expected = $dir_mods ? 3 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 2) || ($c != $c_expected) ) + { + twtools::logStatus("IC with FS section failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Now just run RuleA + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-R RuleA"}); + + # Make sure we got 4 violations this time: 2 mod, 1 add, 1 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 4 : 3; + my $c_expected = $dir_mods ? 2 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 1) || ($c != $c_expected) ) + { + twtools::logStatus("IC of Rule A failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Now run severity level 200, meaning RuleB + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-l 200"}); + + # Make sure we got 2 violations this time: 1 mod, 0 add, 1 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 2 : 1; + my $c_expected = $dir_mods ? 1 : 0; + + if( ($n != $n_expected) || ($a != 0) || ($r != 1) || ($c != $c_expected) ) + { + twtools::logStatus("IC of severity 200+ failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Now run severity level "high", also meaning RuleB + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-l high"}); + + # Make sure we got 2 violations this time: 1 mod, 0 add, 1 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 2 : 1; + my $c_expected = $dir_mods ? 1 : 0; + + if( ($n != $n_expected) || ($a != 0) || ($r != 1) || ($c != $c_expected) ) + { + twtools::logStatus("IC of severity 'high' failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Now run against one object, modify.txt + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "$root/subdir/modify.txt"}); + + # Make sure we got 1 violation this time: 1 mod, 0 add, 0 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + if( ($n != 1) || ($a != 0) || ($r != 0) || ($c != 1) ) + { + twtools::logStatus("IC of single object modify.txt failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Run a few full check w/ email reporting, all the valid levels + # (we're configured to pipe to cat as a fake mailprogram) + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-M -t 0"}); + twtools::RunIntegrityCheck({trailing_opts => "-M -t 1"}); + twtools::RunIntegrityCheck({trailing_opts => "-M -t 2"}); + twtools::RunIntegrityCheck({trailing_opts => "-M -t 3"}); + twtools::RunIntegrityCheck({trailing_opts => "-M -t 4"}); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 6 : 4; + my $c_expected = $dir_mods ? 3 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 2) || ($c != $c_expected) ) + { + twtools::logStatus("Full IC failed: $n $a $r $c\n"); + $twpassed = 0; + } + + + ####################################################### + # Now run an interactive IC with cat as a fake editor, so DB gets auto updated. + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-I -V cat -P $twtools::twlocalpass"}); + + # Make sure we got 6 violations: 3 mod, 1 add, 2 rm. + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + my $n_expected = $dir_mods ? 6 : 4; + my $c_expected = $dir_mods ? 3 : 1; + + if( ($n != $n_expected) || ($a != 1) || ($r != 2) || ($c != $c_expected) ) + { + twtools::logStatus("Interactive IC failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ####################################################### + # Finally run another full IC to verify db was updated + # + also exercise the verbose & hex output options since we don't elsewhere. + # + RemoveFile("$reportloc"); + twtools::RunIntegrityCheck({trailing_opts => "-v -h"}); + + # Make sure we got no violations this time + # + my ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + if( ($n != 0) || ($a != 0) || ($r != 0) || ($c != 0) ) + { + twtools::logStatus("IC after interactive IC failed: $n $a $r $c\n"); + $twpassed = 0; + } + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + return 0; + } +} + + + +###################################################################### +# +# Initialize the test +# + +sub initialize +{ + # Make the policy file + # + twtools::GeneratePolicyFile( PolicyFileString() ); + return 1; +} + + +sub cleanup +{ + # remove all of the files we were integrity checking... + # + system( "rm -rf $root/*" ); + system( "rm -rf $root2/*" ); + $? && print "WARNING: IC cleanup failed.\n"; + + # remove the report files we created... + # + system( "rm -f $report1" ) if (-e $report1); + system( "rm -r $report2" ) if (-e $report2); + system( "rm -r $report3" ) if (-e $report3); + system( "rm -r $report4" ) if (-e $report4); + +} + + +###################################################################### +# One time module cleanup goes in here... +# +END +{ +} + +1; + diff --git a/src/test-harness/tests/md5sum.pm b/src/test-harness/tests/md5sum.pm index 0a37a00..09e612f 100644 --- a/src/test-harness/tests/md5sum.pm +++ b/src/test-harness/tests/md5sum.pm @@ -37,21 +37,34 @@ sub run() { # lets see if the system 'md5sum' agree's with siggen's md5 hash # my ($md5sum, undef) = split(/ /, `md5sum $twtools::twrootdir/test`); + if ($mf5sum eq "") { + twtools::logStatus("md5sum not found, trying openssl instead\n"); + (undef, $md5sum) = split(/=/, `openssl md5 $twtools::twrootdir/test`); + } + if ($md5sum eq "") { + ++$twtools::twskippedtests; + print "SKIPPED\n"; + return; + } + my $siggen = `$twtools::twrootdir/bin/siggen -h -t -M $twtools::twrootdir/test`; chomp $md5sum; chomp $siggen; + $md5sum =~ s/^\s+|\s+$//g; + $siggen =~ s/^\s+|\s+$//g; twtools::logStatus("md5sum reports: $md5sum\n"); twtools::logStatus("siggen reports: $siggen\n"); - $twpassed = $md5sum == $siggen; + $twpassed = ($md5sum eq $siggen); ######################################################### # # See if the tests all succeeded... # if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; } else { diff --git a/src/test-harness/tests/polupdate.pm b/src/test-harness/tests/polupdate.pm new file mode 100644 index 0000000..3721d68 --- /dev/null +++ b/src/test-harness/tests/polupdate.pm @@ -0,0 +1,301 @@ + +use twtools; + +package polupdate; + + +###################################################################### +# One time module initialization goes in here... +# +BEGIN +{ + # This is the root directory we will be integrity checking + # + $root1 = "$twtools::twcwd/$twtools::twrootdir/polupdate-test-1"; + $root2 = "$twtools::twcwd/$twtools::twrootdir/polupdate-test-2"; + $root3 = "$twtools::twcwd/$twtools::twrootdir/polupdate-test-3"; + + # Here are the names of the report files this test will create + # + $report1 = "$twtools::twcwd/$twtools::twrootdir/report/polupdate-1.twr"; + $report2 = "$twtools::twcwd/$twtools::twrootdir/report/polupdate-2.twr"; + $report3 = "$twtools::twcwd/$twtools::twrootdir/report/polupdate-3.twr"; + $report4 = "$twtools::twcwd/$twtools::twrootdir/report/polupdate-4.twr"; +} + +###################################################################### +# PolicyFileString -- return the policy text as a string +# +sub PolicyFileString +{ + return < \$(ReadOnly) +M -ab; #read only plus MD5 minus atime & blocks + $root2 -> \$(ReadOnly) +M -ab; #read only plus MD5 minus atime & blocks + +POLICY_END + +} + +###################################################################### +# PolicyFileStringNew -- return the policy text as a string +# +sub PolicyFileStringNew +{ + return < \$(ReadOnly) +S -ab; #read only plus SHA1 minus atime & blocks + $root3 -> \$(ReadOnly) +S -ab; #read only plus SHA1 minus atime & blocks + +POLICY_END + +} + +###################################################################### +# CreateFile -- create a file with the specified contents +# +# input: path -- *absolute* path to the file +# contents -- string to put in the file +# +sub CreateFile +{ + my ($path, $contents) = @_; + + system( "echo $contents > $path" ); + + $? && die "Create file failed for $path\n"; +} + +###################################################################### +# RemoveFile -- removes the named file by absolute path +# +sub RemoveFile +{ + my ($path) = @_; + + if( -e $path ) + { + system( "rm -f $path" ); + } + + $? && die "Remove file failed for $path\n"; +} + + +###################################################################### +# CreateDir -- create a directory +# +sub CreateDir +{ + my($dir) = @_; + + # NOTE: mkdir fails if it is already a directory! + # + if( ! -d "$dir" ) + { + system( "rm -f $dir" ); + system( "mkdir -p $dir" ); + + $? && die "Mkdir failed for $dir\n"; + } +} + +###################################################################### +# MoveFile -- move a file from one place to another +# NOTE: file names are relative to $root +# +# input: old_name -- name of file to move +# new_name -- where it should be moved to +# +sub MoveFile +{ + my($old, $new) = @_; + + system( "mv $old $new" ); + $? && die "mv $old $new failed!\n"; +} + +###################################################################### +# PrintDatabase +# +sub PrintDatabase +{ + system( "$twtools::twrootdir/bin/twprint -m d -c $twtools::twrootdir/tw.cfg" ); +} + +###################################################################### +# PrintReport +# +sub PrintReport +{ + my ($report) = @_; + system( "$twtools::twrootdir/bin/twprint -m r -c $twtools::twrootdir/tw.cfg -r $report" ); +} + +###################################################################### +# PrepareForTest -- creates the files that each test will be +# integrity checking and initializes the database. +# +sub PrepareForTest +{ + # make sure we are cleaned up... + # + cleanup(); + + # Make the files we will be using... + # + CreateDir ( "$root1/sub" ); + CreateFile( "$root1/sub/hello.txt", "hello world one" ); + + CreateDir ( "$root2/sub" ); + CreateFile( "$root2/sub/hello.txt", "hello world two" ); + + CreateDir ( "$root3/sub" ); + CreateFile( "$root3/sub/hello.txt", "hello world three" ); + + # Initialize the database + # + twtools::InitializeDatabase(); +} + +###################################################################### +# RunBasicTest -- performs a rudimentary UpdateDatabase test +# +sub RunBasicTest +{ + twtools::logStatus("*** Beginning polupdate.basic test\n"); + printf("%-30s", "-- polupdate.basic test"); + + PrepareForTest(); + + twtools::WritePolicyFile( PolicyFileStringNew() ); + if( ! twtools::UpdatePolicy() ) + { + twtools::logStatus("FAILED -- update policy returned nonzero\n"); + return 0; + } + + # do another IC and make sure there are no violations + # + twtools::RunIntegrityCheck(); + + ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + if( $n != 0 ) + { + twtools::logStatus("FAILED -- violations after update\n"); + return 0; + } + + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; +} + +###################################################################### +# RunSecureModeTest -- performs a rudimentary UpdateDatabase test +# +sub RunSecureModeTest +{ + twtools::logStatus("*** Beginning polupdate.secure_mode test\n"); + printf("%-30s", "-- polupdate.secure_mode test"); + + PrepareForTest(); + + twtools::WritePolicyFile( PolicyFileStringNew() ); + if( ! twtools::UpdatePolicy({ secure_mode => "high" } )) + { + twtools::logStatus("FAILED -- update policy returned nonzero\n"); + return 0; + } + + # do another IC and make sure there are no violations + # + twtools::RunIntegrityCheck(); + + ($n, $a, $r, $c) = twtools::AnalyzeReport( twtools::RunReport() ); + + if( $n != 0 ) + { + twtools::logStatus("FAILED -- violations after update\n"); + return 0; + } + + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; +} + + +###################################################################### +# +# Initialize the test +# + +sub initialize +{ + # Make the policy file + # + twtools::GeneratePolicyFile( PolicyFileString() ); + return 1; +} + + +###################################################################### +# +# Run the test. +# +sub run +{ + eval { + RunBasicTest(); + } or do { + my $e = $@; + twtools::logStatus("Exception in Polupdate RunBasicTest: $e\n"); + ++$twtools::twfailedtests; + print "*FAILED*\n"; + }; + + # bump the total test count since this file's a twofer + ++$twtools::twtotaltests; + + eval { + RunSecureModeTest(); + } or do { + my $e = $@; + twtools::logStatus("Exception in Polupdate RunSecureModeTest: $e\n"); + ++$twtools::twfailedtests; + print "*FAILED*\n"; + }; +} + +sub cleanup +{ + # remove all of the files we were integrity checking... + # + system( "rm -rf $root1/*" ); + system( "rm -rf $root2/*" ); + system( "rm -rf $root3/*" ); + $? && print "WARNING: polupdate cleanup failed.\n"; + + # remove the report files we created... + # + system( "rm -f $report1" ) if (-e $report1); + system( "rm -r $report2" ) if (-e $report2); + system( "rm -r $report3" ) if (-e $report3); + system( "rm -r $report4" ) if (-e $report4); + +} + + +###################################################################### +# One time module cleanup goes in here... +# +END +{ +} + +1; + diff --git a/src/test-harness/tests/readonly.pm b/src/test-harness/tests/readonly.pm index 230e462..811b293 100644 --- a/src/test-harness/tests/readonly.pm +++ b/src/test-harness/tests/readonly.pm @@ -55,9 +55,9 @@ sub getPolicyFileString { return < \$(ReadOnly); -$twtools::twcwd/$twtools::twrootdir/$TESTS{"1-accessed"}{file} -> \$(ReadOnly); -$twtools::twcwd/$twtools::twrootdir/$TESTS{"2-removed"}{file} -> \$(ReadOnly); +$twtools::twcwd/$twtools::twrootdir/$TESTS{"0-permsChange"}{file} -> \$(ReadOnly) -a; +$twtools::twcwd/$twtools::twrootdir/$TESTS{"1-accessed"}{file} -> \$(ReadOnly) -a; +$twtools::twcwd/$twtools::twrootdir/$TESTS{"2-removed"}{file} -> \$(ReadOnly) -a; EOT @@ -71,8 +71,8 @@ EOT sub initialize() { - my $twstr = getPolicyFileString(); - twtools::GeneratePolicyFile($twstr); + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); } @@ -83,31 +83,42 @@ sub initialize() { # sub run() { - my $twpassed = 1; + twtools::logStatus("\n\n*** Beginning $description\n"); + printf("%-30s", "-- $description"); - twtools::logStatus("\n\n*** Beginning $description\n"); + if ($^O eq "skyos") { + ++$twtools::twskippedtests; + print "SKIPPED; SkyOS doesn't support readonly files.\n"; + return; + } elsif ($^O eq "gnu") { + ++$twtools::twskippedtests; + print "SKIPPED; TODO: Hurd has fewer expected changes here; refactor so we can test for correct values\n"; + return; + } - printf("%-30s", "-- $description"); - ######################################################### - # - # Run the tests describe above in the %TESTS structure. - # - $twpassed = twtools::RunIntegrityTests(%TESTS); + my $twpassed = 1; + ######################################################### + # + # Run the tests describe above in the %TESTS structure. + # + $twpassed = twtools::RunIntegrityTests(%TESTS); - ######################################################### - # - # See if the tests all succeeded... - # - if ($twpassed) { + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; return 0; - } - else { + } + else { print "*FAILED*\n"; ++$twtools::twfailedtests; - } + } } diff --git a/src/test-harness/tests/sha1sum.pm b/src/test-harness/tests/sha1sum.pm new file mode 100644 index 0000000..145a6a5 --- /dev/null +++ b/src/test-harness/tests/sha1sum.pm @@ -0,0 +1,83 @@ + +use twtools; + +package sha1sum; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + + $description = "sha1 hash check"; +} + + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + + twtools::CreateFile( { file => "test", contents => "deadbeef"x5000} ); +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + + # lets see if the system 'sha1sum' agree's with siggen's sha1 hash + # + my ($sha1sum, undef) = split(/ /, `sha1sum $twtools::twrootdir/test`); + if ($sha1sum eq "") { + twtools::logStatus("sha1sum not found, trying openssl instead\n"); + (undef, $sha1sum) = split(/=/, `openssl sha1 $twtools::twrootdir/test`); + } + if ($sha1sum eq "") { + ++$twtools::twskippedtests; + print "SKIPPED\n"; + return; + } + + my $siggen = `$twtools::twrootdir/bin/siggen -h -t -S $twtools::twrootdir/test`; + + chomp $sha1sum; + chomp $siggen; + $sha1sum =~ s/^\s+|\s+$//g; + $siggen =~ s/^\s+|\s+$//g; + + twtools::logStatus("sha1sum reports: $sha1sum\n"); + twtools::logStatus("siggen reports: $siggen\n"); + + $twpassed = ($sha1sum eq $siggen); + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + } +} + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/siggen.pm b/src/test-harness/tests/siggen.pm new file mode 100644 index 0000000..f73ae90 --- /dev/null +++ b/src/test-harness/tests/siggen.pm @@ -0,0 +1,146 @@ + +use twtools; + +package siggen; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "siggen test"; +} + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + + twtools::logStatus(`ps > $twtools::twrootdir/hashme.txt`); + if ( $? != 0 ) { + twtools::logStatus("test file creation failed\n"); + $twpassed = 0; + } + + # SkyOS doesn't have FIFOs, so this won't work + if ( $^O ne "skyos") { + twtools::logStatus(`mkfifo $twtools::twrootdir/donthashme.fifo`); + if ( $? != 0 ) { + twtools::logStatus("test fifo creation failed\n"); + $twpassed = 0; + } + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen`); + if ( $? != 256 ) { + twtools::logStatus("no-args siggen failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -h -t -a`); + if ( $? != 256 ) { + twtools::logStatus("no-args siggen failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen --help`); + if ( $? != 256 ) { + twtools::logStatus("siggen --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen --version`); + if ( $? != 0 ) { + twtools::logStatus("siggen --version failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("siggen --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen $twtools::twrootdir/hashme.txt`); + if ( $? != 0 ) { + twtools::logStatus("siggen hashme.txt failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -a $twtools::twrootdir/hashme.txt`); + if ( $? != 0 ) { + twtools::logStatus("siggen -a hashme.txt failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -h -t -a $twtools::twrootdir/hashme.txt`); + if ( $? != 0 ) { + twtools::logStatus("siggen -h -t -a hashme.txt failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -a $twtools::twrootdir/donthashme.fifo`); + if ( $? != 256 ) { + twtools::logStatus("siggen -a donthashme.fifo failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -h -t -a $twtools::twrootdir/donthashme.fifo`); + if ( $? != 256 ) { + twtools::logStatus("siggen -h -t -a donthashme.fifo failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -a $twtools::twrootdir/no-existe.txt`); + if ( $? != 256 ) { + twtools::logStatus("siggen -a no-existe.txt failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/siggen -h -t -a $twtools::twrootdir/no-existe.txt`); + if ( $? != 256 ) { + twtools::logStatus("siggen -h -t -a no-existe.txt failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + return 0; + } +} + + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/sizes.pm b/src/test-harness/tests/sizes.pm index dac2594..b880bfe 100644 --- a/src/test-harness/tests/sizes.pm +++ b/src/test-harness/tests/sizes.pm @@ -97,6 +97,7 @@ sub run() { # See if the tests all succeeded... # if ($twpassed) { + ++$twtools::twpassedtests; print "PASSED\n"; } else { diff --git a/src/test-harness/tests/tripwire.pm b/src/test-harness/tests/tripwire.pm new file mode 100644 index 0000000..af7810c --- /dev/null +++ b/src/test-harness/tests/tripwire.pm @@ -0,0 +1,124 @@ + +use twtools; + +package tripwire; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "tripwire options test"; +} + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire`); + if ( $? != 2048 ) { + twtools::logStatus("no-args tripwire failed, error = $?\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --version`); + if ( $? != 0 ) { + twtools::logStatus("tripwire --version failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --help`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --help all`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire --help all failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --help i c`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire --help i c failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --asdf 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire --asdf --help 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire --asdf --help\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire -m 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire -m\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire -m Z 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire -m Z failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire -m -m 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire -m -m failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/tripwire -m i -c nope.cfg 2>&1`); + if ( $? != 2048 ) { + twtools::logStatus("tripwire -m -i -c nope.cfg\n"); + $twpassed = 0; + } + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + return 1; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + return 0; + } +} + + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/twadmin.pm b/src/test-harness/tests/twadmin.pm new file mode 100644 index 0000000..6fe6050 --- /dev/null +++ b/src/test-harness/tests/twadmin.pm @@ -0,0 +1,413 @@ + +use twtools; + +package twadmin; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + $description = "twadmin test"; +} + + +###################################################################### +# Return the policy file text for this test... +# +sub getPolicyFileString { + + return < +S; + + +EOT + +} + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); + +} + +sub runTests() { + + +} + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + + ######################################################### + # + # print-policy & print-config variants + # + + twtools::PrintConfig(); + if ( $? != 0 ) { + twtools::logStatus("base print-cfgfile failed, error = $?\n"); + $twpassed = 0; + } + + twtools::PrintConfig(opts => "--verbose"); + if ( $? != 0 ) { + twtools::logStatus("print-cfgfile --verbose failed, error = $?\n"); + $twpassed = 0; + } + + twtools::PrintConfig(opts => "--silent"); + if ( $? != 0 ) { + twtools::logStatus("print-cfgfile --silent failed\, error = $?n"); + $twpassed = 0; + } + + twtools::PrintPolicy(); + if ( $? != 0 ) { + twtools::logStatus("base print-polfile failed, error = $?\n"); + $twpassed = 0; + } + + twtools::PrintPolicy(opts => "--verbose"); + if ( $? != 0 ) { + twtools::logStatus("print-polfile --verbose failed, error = $?\n"); + $twpassed = 0; + } + + twtools::PrintPolicy(opts => "--silent"); + if ( $? != 0 ) { + twtools::logStatus("print-polfile --silent failed, error = $?\n"); + $twpassed = 0; + } + + ######################################################### + # + # Now try misc help & version options + # + twtools::logStatus(`$twtools::twrootdir/bin/twadmin 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin, no args failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -?`); + if ( $? != 256 ) { + twtools::logStatus("twadmin -? failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --help all`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help all failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --help f p`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help d r failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --help asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --asdf --help 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin -m failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m Z 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin -m Z failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m -m 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin -m -m failed\n"); + $twpassed = 0; + } + + ######################################################### + # + # Various missing files + # + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m P 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m P nope.txt 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m P -c nope.cfg nope.txt 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin -m P -S site.nope nope.txt 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --help failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # Per-mode help & errors + # + + # create-polfile + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-polfile --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-polfile --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --help --create-polfile --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-polfile --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-polfile --asdf failed\n"); + $twpassed = 0; + } + + + # create-cfgfile + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-cfgfile --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-cfgfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-cfgfile --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-cfgfile --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --create-cfgfile --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --create-cfgfile --asdf failed\n"); + $twpassed = 0; + } + + + # print-polfile + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-polfile --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-polfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-polfile --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-polfile --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-polfile --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-polfile --asdf failed\n"); + $twpassed = 0; + } + + + # print-cfgfile + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-cfgfile --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-cfgfile --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-cfgfile --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-cfgfile --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --print-cfgfile --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --print-cfgfile --asdf failed\n"); + $twpassed = 0; + } + + + # encrypt + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --encrypt --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --encrypt --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --encrypt --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --encrypt --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --encrypt --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --encrypt --asdf failed\n"); + $twpassed = 0; + } + + + # remove-encryption + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --remove-encryption --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --remove-encryption --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --remove-encryption --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --remove-encryption --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --remove-encryption --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --remove-encryption --asdf failed\n"); + $twpassed = 0; + } + + + # examine + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --examine --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --examine --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --examine --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --examine --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --examine --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --examine --asdf failed\n"); + $twpassed = 0; + } + + + # generate-keys + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --generate-keys --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --generate-keys --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --generate-keys --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --generate-keys --verbose --silent failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --generate-keys--asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --generate-keys--asdf failed\n"); + $twpassed = 0; + } + + # change-passphrases + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases --help`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --change-passphrases --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases --verbose --silent 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --change-passphrases --verbose --silent` failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --change-passphrases --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twadmin --change-passphrases --asdf failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # Version + # + twtools::logStatus(`$twtools::twrootdir/bin/twadmin --version`); + if ( $? != 0 ) { + twtools::logStatus("twadmin --version failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + } +} + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/tests/twprint.pm b/src/test-harness/tests/twprint.pm new file mode 100644 index 0000000..e49b913 --- /dev/null +++ b/src/test-harness/tests/twprint.pm @@ -0,0 +1,308 @@ + +use twtools; + +package twprint; + +###################################################################### +# One time module initialization goes in here... +# +BEGIN { + + %TESTS = ( + + "twprintInit" => { + + changeFunc => \&twtools::MakeBigger, + createFunc => \&twtools::CreateFile, + file => "printme.txt", + perms => "a+w", + contents => "testing", + violations => "V:1 S:0 A:0 R:0 C:1" + }, + ); + + + $description = "twprint test"; +} + + +###################################################################### +# Return the policy file text for this test... +# +sub getPolicyFileString { + + return < +S; + + +EOT + +} + +###################################################################### +# +# Initialize, get ready to run this test... +# +sub initialize() { + + my $twstr = getPolicyFileString(); + twtools::GeneratePolicyFile($twstr); + +} + + +###################################################################### +# +# Run the test. +# +sub run() { + + my $twpassed = 1; + + twtools::logStatus("*** Beginning $description\n"); + printf("%-30s", "-- $description"); + + ######################################################### + # + # Run a check first, to set up for twprint exercises + # + $twpassed = twtools::RunIntegrityTests(%TESTS); + + + + ######################################################### + # + # Now run thru the valid report levels & verify return codes + # TODO: look for expected result in various report levels + + twtools::RunReport({ report_level => 0 }); + if ( $? != 0 ) { + twtools::logStatus("level 0 report failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => 1 }); + if ( $? != 0 ) { + twtools::logStatus("level 1 report failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => 2 }); + if ( $? != 0 ) { + twtools::logStatus("level 2 report failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => 3 }); + if ( $? != 0 ) { + twtools::logStatus("level 3 report failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => 4 }); + if ( $? != 0 ) { + twtools::logStatus("level 4 report failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => "4 --verbose --hexadecimal" }); + if ( $? != 0 ) { + twtools::logStatus("level 4 report (verbose, hex) failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => "4 --silent" }); + if ( $? != 0 ) { + twtools::logStatus("level 4 report (silent) failed\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_object_list => "$twtools::twrootdir/printme.txt" }); + if ( $? != 0 ) { + twtools::logStatus("print-report with an object list failedn"); + $twpassed = 0; + } + + + ######################################################### + # + # Now some failure cases, to verify they fail + # + twtools::RunReport({ report_level => 5 }); + if ( $? != 256 ) { + twtools::logStatus("nonexistent level 5 report failed, result = $?\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => "asdf" }); + if ( $? != 256 ) { + twtools::logStatus("nonexistent level 'asdf' report failed, result = $?\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => "0 --help" }); + if ( $? != 256 ) { + twtools::logStatus("print-report help mode failed, result = $?\n"); + $twpassed = 0; + } + + twtools::RunReport({ report_level => "4 --verbose --silent" }); + if ( $? != 256 ) { + twtools::logStatus("print-report verbose vs silent failed, result = $?\n"); + $twpassed = 0; + } + + ######################################################### + # + # Now try db printing + # + twtools::RunDbPrint(); + if ( $? != 0 ) { + twtools::logStatus("db print failed\n"); + $twpassed = 0; + } + + twtools::RunDbPrint({ db_object_list => "$twtools::twrootdir/printme.txt" }); + if ( $? != 0 ) { + twtools::logStatus("db print with an object failed\n"); + $twpassed = 0; + } + + twtools::RunDbPrint({ db_object_list => "$twtools::twrootdir/nonexistent.vbs" }); + if ( $? != 0 ) { + twtools::logStatus("db print with nonexistent object failed\n"); + $twpassed = 0; + } + + twtools::RunDbPrint({ db_print_level => 0 }); + if ( $? != 0 ) { + twtools::logStatus("db print level 0 failed\n"); + $twpassed = 0; + } + + twtools::RunDbPrint({ db_print_level => 1 }); + if ( $? != 0 ) { + twtools::logStatus("db print level 1 failed\n"); + $twpassed = 0; + } + + twtools::RunDbPrint({ db_print_level => 2 }); + if ( $? != 0 ) { + twtools::logStatus("db print level 2 failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # Now try misc help & version options + # + twtools::logStatus(`$twtools::twrootdir/bin/twprint 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint, no args failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --help`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint -?`); + if ( $? != 256 ) { + twtools::logStatus("twprint -? failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --help all`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help all failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --help d r`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help d r failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --help asdf 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --asdf --help 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help --asdf failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --print-dbfile --help`); + if ( $? != 256 ) { + twtools::logStatus("twprint --help --print-dbfile failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --print-report --help `); + if ( $? != 256 ) { + twtools::logStatus("twprint --help --print-reportfile failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint -m Z 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint -m Z failed\n"); + $twpassed = 0; + } + + + twtools::logStatus(`$twtools::twrootdir/bin/twprint -m 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint -m failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint -m -m 2>&1`); + if ( $? != 256 ) { + twtools::logStatus("twprint -m -m failed\n"); + $twpassed = 0; + } + + twtools::logStatus(`$twtools::twrootdir/bin/twprint --version`); + if ( $? != 0 ) { + twtools::logStatus("twprint --version failed\n"); + $twpassed = 0; + } + + + ######################################################### + # + # See if the tests all succeeded... + # + if ($twpassed) { + ++$twtools::twpassedtests; + print "PASSED\n"; + } + else { + ++$twtools::twfailedtests; + print "*FAILED*\n"; + } +} + + +###################################################################### +# One time module cleanup goes in here... +# +END { +} + +1; diff --git a/src/test-harness/twtest.pl b/src/test-harness/twtest.pl index 1f7ea53..1611811 100755 --- a/src/test-harness/twtest.pl +++ b/src/test-harness/twtest.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl use strict; - +use lib '.'; use twtools; my @twtests = (); @@ -94,6 +94,8 @@ sub runTests { for $module (@twtests) { + ++$twtools::twtotaltests; + # use the module # eval qq{use tests::$module}; @@ -135,8 +137,9 @@ sub runTests { prepareListOfTests() if scalar(@twtests) == 0; # only if none were on the cmdline print "\n"; -print "initializing for tests...\n\n"; +print "initializing for tests on $^O...\n\n"; +print "logging to $ENV{'PWD'}/$twtools::twrootdir/status.log\n\n"; # all tests can assume a base configuration, i.e. default tw.cfg, site and local keys # @@ -151,7 +154,13 @@ sub runTests { # runTests(); -print "\n\n$twtools::twfailedtests test(s) failed...\n\n"; +# Any test that didn't report a status gets counted as skipped. +$twtools::twskippedtests += ($twtools::twtotaltests - ($twtools::twpassedtests + $twtools::twfailedtests + $twtools::twskippedtests)); + +print "\n\n$twtools::twtotaltests test(s) run\n"; +print "$twtools::twpassedtests test(s) passed\n"; +print "$twtools::twfailedtests test(s) failed\n"; +print "$twtools::twskippedtests test(s) skipped\n\n"; exit($twtools::twfailedtests); diff --git a/src/test-harness/twtools.pm b/src/test-harness/twtools.pm index 894a161..505f0d1 100644 --- a/src/test-harness/twtools.pm +++ b/src/test-harness/twtools.pm @@ -1,4 +1,3 @@ - package twtools; ###################################################################### @@ -17,13 +16,18 @@ BEGIN { $twsitekeyloc = "key/site.key"; $twlocalkeyloc = "key/local.key"; $twpolicyloc = "policy/twpol.txt"; + $twpolfileloc = "policy/tw.pol"; $twcfgloc = "tw.cfg"; + $twsitepass = "testing"; $twlocalpass = "testing"; $twbinaries = "../../../../bin"; + $twtotaltests = 0; $twfailedtests = 0; + $twpassedtests = 0; + $twskippedtests = 0; # get's setup in twtest... # @@ -32,7 +36,7 @@ BEGIN { %twcfgdirs = ( ROOT => '', - POLFILE => 'policy/tw.pol', + POLFILE => $twpolfileloc, DBFILE => 'db/$(HOSTNAME).twd', REPORTFILE => 'report/$(HOSTNAME)-$(DATE).twr', SITEKEYFILE => $twsitekeyloc, @@ -49,9 +53,9 @@ BEGIN { EMAILREPORTLEVEL => '3', REPORTLEVEL => '3', MAILMETHOD => 'SENDMAIL', - SYSLOGREPORTING => 'false', - MAILPROGRAM => '/usr/lib/sendmail -oi -t' - + SYSLOGREPORTING => 'true', + MAILPROGRAM => 'cat', + MAILFROMADDRESS => 'taz@cat' ); } @@ -155,9 +159,9 @@ sub GenerateKeys { # sub SignConfigFile { - if (!-e "$twrootdir/tw.cfg") { + if (!-e "$twrootdir/$twcfgloc") { print "signing configuration file...\n" if $verbose; - logStatus(`$twrootdir/bin/twadmin -m F -Q $twsitepass -c $twrootdir/tw.cfg -S $twrootdir/$twsitekeyloc $twrootdir/twcfg.txt`); + logStatus(`$twrootdir/bin/twadmin -m F -Q $twsitepass -c $twrootdir/$twcfgloc -S $twrootdir/$twsitekeyloc $twrootdir/twcfg.txt`); } return ($? == 0); @@ -165,22 +169,138 @@ sub SignConfigFile { ###################################################################### -# Generate and sign the policy file... Note the contents +# Examine encryption +# +sub ExamineEncryption { + + my ($filename) = @_; + + logStatus(`$twrootdir/bin/twadmin -m e -c $twrootdir/$twcfgloc $filename`); + + return ($? == 0); +} + + +###################################################################### +# Add encryption +# +sub AddEncryption { + + my ($filename) = @_; + logStatus "addding crypt to file...\n"; + logStatus(`$twrootdir/bin/twadmin -m E -c $twrootdir/$twcfgloc -P $twlocalpass -Q $twsitepass $filename 2>&1`); + + return ($? == 0); +} + + +###################################################################### +# Remove encryption +# + +sub RemoveEncryption { + + my ($filename) = @_; + + logStatus "removing crypto from file...\n"; + logStatus(`$twrootdir/bin/twadmin -m R -c $twrootdir/$twcfgloc -P $twlocalpass -Q $twsitepass $filename 2>&1`); + + return ($? == 0); +} + + +###################################################################### +# Print polfile +# + +sub PrintPolicy { + + my (%params) = %{$_[0]}; + logStatus "printing policy file...\n"; + + my (@out) = `$twrootdir/bin/twadmin -m p -c $twrootdir/$twcfgloc -p $twrootdir/$twpolfileloc -S $twrootdir/$twsitekeyloc $params{opts} 2>&1`; + + my ($result) = $?; + + logStatus(@out); + + return $result; +} + +###################################################################### +# Print polfile +# + +sub PrintConfig { + + my (%params) = %{$_[0]}; + + logStatus "printing config file...\n"; + my (@out) = `$twrootdir/bin/twadmin -m f -c $twrootdir/$twcfgloc $params{opts} 2>&1`; + + my ($result) = $?; + + logStatus(@out); + + return $result; +} + + +###################################################################### +# Write policy text to disk... Note the contents # of the policy file are passed in as '$twstr'. # -sub GeneratePolicyFile { +sub WritePolicyFile { my ($twstr) = @_; open(FH, ">$twrootdir/$twpolicyloc") || warn $!; print FH $twstr; close(FH); +} + + +###################################################################### +# Generate and sign the policy file... Note the contents +# of the policy file are passed in as '$twstr'. +# +sub GeneratePolicyFile { + + my ($twstr) = @_; + + WritePolicyFile($twstr); print "generating policy file...\n" if $verbose; - logStatus(`$twrootdir/bin/twadmin -m P -c $twrootdir/tw.cfg -Q $twsitepass -p $twrootdir/policy/tw.pol $twrootdir/policy/twpol.txt`); + my (@out) = `$twrootdir/bin/twadmin -m P -c $twrootdir/$twcfgloc -Q $twsitepass -p $twrootdir/$twpolfileloc $twrootdir/$twpolicyloc 2>&1`; - return ($? == 0); + my ($result) = $?; + + logStatus(@out); + + return $result; +} + + +###################################################################### +# Generate and sign the policy file... Note the contents +# of the policy file are passed in as '$twstr'. +# +sub CreatePolicy { + + my (%params) = %{$_[0]}; + + $params{policy_text} = "$twrootdir/$twpolicyloc" if( ! defined($params{policy_text}) ); + + print "generating policy file...\n" if $verbose; + + my (@out) = `$twrootdir/bin/twadmin -m P -c $twrootdir/$twcfgloc -Q $twsitepass -p $twrootdir/$twpolfileloc $params{policy_text} 2>&1`; + + my ($result) = $?; + + logStatus(@out); + + return $result; } @@ -192,43 +312,100 @@ sub InitializeDatabase { my ($twmsg) = @_; print "initializing database for '$twmsg' test...\n" if $verbose; - logStatus(`$twrootdir/bin/tripwire -m i -P $twsitepass -p $twrootdir/policy/tw.pol -c $twrootdir/tw.cfg`); + my (@out) = `$twrootdir/bin/tripwire -m i -P $twsitepass -p $twrootdir/$twpolfileloc -c $twrootdir/$twcfgloc 2>&1`; - return ($? == 0); + my ($result) = $?; + + logStatus(@out); + + return $result; } ###################################################################### -# Run tripwire to initialize the database... +# Run tripwire to update the database... # sub UpdateDatabase { my (%params) = %{$_[0]}; - $params{'report'} = $reportloc if( ! defined($params{'report'}) ); - $params{'secure-mode'} = "low" if( ! defined($params{'secure-mode'}) ); + $params{report} = $reportloc if( ! defined($params{report}) ); + $params{secure_mode} = "low" if( ! defined($params{secure_mode}) ); print "updating database for '$twmsg' test...\n" if $verbose; - logStatus(`$twrootdir/bin/tripwire -m u -a -P $twsitepass -Z $params{'secure-mode'} -p $twrootdir/policy/tw.pol -c $twrootdir/tw.cfg -r $params{'report'}`); - + my (@out) = `$twrootdir/bin/tripwire -m u -a -P $twsitepass -Z $params{secure_mode} -p $twrootdir/$twpolfileloc -c $twrootdir/$twcfgloc -r $params{report} 2>&1`; + + my ($result) = $?; + + logStatus(@out); + + return $result; +} + +###################################################################### +# Run tripwire to update the policy... +# +sub UpdatePolicy { + + my (%params) = %{$_[0]}; + $params{secure_mode} = "low" if( ! defined($params{secure_mode}) ); + + print "updating policy for '$twmsg' test...\n" if $verbose; + logStatus(`$twrootdir/bin/tripwire -m p -P $twsitepass -Q $twlocalpass -Z $params{secure_mode} -p $twrootdir/$twpolfileloc -c $twrootdir/$twcfgloc $twrootdir/$twpolicyloc 2>&1`); + return ($? == 0); } +###################################################################### +# Use twprint to get a report of specified level (default 0) and return +# that. +# +sub RunReport { + + my (%params) = %{$_[0]}; + my ($reportobjects); + + $params{report} = $reportloc if( ! defined($params{report}) ); + $params{report_level} = 0 if( ! defined($params{report_level}) ); + $params{report_object_list} = "" if( ! defined($params{report_object_list}) ); + + my (@out) = `$twrootdir/bin/twprint -m r -c $twrootdir/$twcfgloc -t $params{report_level} -r $params{report} $params{report_object_list} 2>&1`; + + logStatus(@out); + + return @out; + +} + ###################################################################### # Use twprint to get a report level 0 report and return # that. # -sub RunReport(%) { +sub RunDbPrint { - my (%params) = %{$_[0]}; - $params{report} = $reportloc if( ! defined($params{report}) ); + my (%params) = %{$_[0]}; + + $params{db_object_list} = "" if( ! defined($params{db_object_list}) ); + $params{db_print_level} = "2" if( ! defined($params{db_print_level}) ); - my (@out) = `$twrootdir/bin/twprint -m r -c $twrootdir/tw.cfg -t 0 -r $params{report}`; + my (@out) = `$twrootdir/bin/twprint -m d -c $twrootdir/$twcfgloc -t $params{db_print_level} $params{db_object_list} 2>&1`; - logStatus(@out); + logStatus(@out); + + return @out; +} - return @out; +###################################################################### +# Run an email test (configured with mailmethod=sendmail) & capture output +# +sub RunEmailTest { + + my (@out) = `$twrootdir/bin/tripwire --test -c $twrootdir/$twcfgloc --email elvis\@mars`; + + logStatus(@out); + + return @out; } @@ -240,9 +417,10 @@ sub RunIntegrityCheck { my (%params) = %{$_[0]}; $params{report} = $reportloc if( ! defined($params{report}) ); + $params{trailing_opts} = "" if( ! defined($params{trailing_opts}) ); print("running integrity check for test '$twmsg'...\n") if $verbose; - logStatus(`$twrootdir/bin/tripwire -m c -r $params{report} -p $twrootdir/policy/tw.pol -c $twrootdir/tw.cfg 2>&1`); + logStatus(`$twrootdir/bin/tripwire -m c -r $params{report} -p $twrootdir/$twpolfileloc -c $twrootdir/$twcfgloc $params{trailing_opts} 2>&1`); return ($? & 8); } @@ -260,14 +438,11 @@ sub AnalyzeReport { # my (undef, $twstatus) = @_; -# print "*** $twstatus\n"; - # split the report summary line into it's fields # my (undef, undef, undef, $violations, $severity, $added, $removed, $changed) = split(/ /, $twstatus); - # Split out the count for each type of # violation. # diff --git a/src/tripwire/Makefile.am b/src/tripwire/Makefile.am index fa7f790..2ec808a 100644 --- a/src/tripwire/Makefile.am +++ b/src/tripwire/Makefile.am @@ -1,20 +1,26 @@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. LIBS = -ltripwire -lcryptlib @LIBS@ LDFLAGS = @LDFLAGS@ -L../../lib LN_S = @LN@ sbin_PROGRAMS = tripwire +tripwiredir=. tripwire_SOURCES = \ generatedb.cpp integritycheck.cpp mailmessage.cpp pipedmailmessage.cpp \ policyupdate.cpp smtpmailmessage.cpp stdtripwire.cpp syslog_trip.cpp \ tripwire.cpp tripwireerrors.cpp tripwiremain.cpp tripwirestrings.cpp \ tripwireutil.cpp twcmdline.cpp twcmdlineutil.cpp updatedb.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../bin/tripwire ../../lib/libtripwire.a +tripwire_HEADERS = \ + generatedb.h integritycheck.h mailmessage.h policyupdate.h resource.h \ + stdtripwire.h syslog_trip.h tripwire.h tripwireerrors.h tripwiremsg.h \ + tripwirestrings.h tripwireutil.h twcmdline.h twcmdlineutil.h updatedb.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = ../../bin/tripwire ../../lib/libtripwire.a *.gcno *.gcda all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin diff --git a/src/tripwire/Makefile.in b/src/tripwire/Makefile.in index 8884b58..df8e69c 100644 --- a/src/tripwire/Makefile.in +++ b/src/tripwire/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(tripwire_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,23 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ sbin_PROGRAMS = tripwire$(EXEEXT) subdir = src/tripwire -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(tripwire_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(tripwiredir)" PROGRAMS = $(sbin_PROGRAMS) am_tripwire_OBJECTS = generatedb.$(OBJEXT) integritycheck.$(OBJEXT) \ mailmessage.$(OBJEXT) pipedmailmessage.$(OBJEXT) \ @@ -60,23 +114,94 @@ am_tripwire_OBJECTS = generatedb.$(OBJEXT) integritycheck.$(OBJEXT) \ twcmdline.$(OBJEXT) twcmdlineutil.$(OBJEXT) updatedb.$(OBJEXT) tripwire_OBJECTS = $(am_tripwire_OBJECTS) tripwire_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(tripwire_SOURCES) DIST_SOURCES = $(tripwire_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +HEADERS = $(tripwire_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -92,7 +217,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -100,6 +225,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -111,6 +237,7 @@ LN = @LN@ LN_S = @LN@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -127,21 +254,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -171,22 +301,32 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. +tripwiredir = . tripwire_SOURCES = \ generatedb.cpp integritycheck.cpp mailmessage.cpp pipedmailmessage.cpp \ policyupdate.cpp smtpmailmessage.cpp stdtripwire.cpp syslog_trip.cpp \ tripwire.cpp tripwireerrors.cpp tripwiremain.cpp tripwirestrings.cpp \ tripwireutil.cpp twcmdline.cpp twcmdlineutil.cpp updatedb.cpp -CLEANFILES = ../../bin/tripwire ../../lib/libtripwire.a +tripwire_HEADERS = \ + generatedb.h integritycheck.h mailmessage.h policyupdate.h resource.h \ + stdtripwire.h syslog_trip.h tripwire.h tripwireerrors.h tripwiremsg.h \ + tripwirestrings.h tripwireutil.h twcmdline.h twcmdlineutil.h updatedb.h + +CLEANFILES = ../../bin/tripwire ../../lib/libtripwire.a *.gcno *.gcda all: all-am .SUFFIXES: @@ -195,15 +335,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/tripwire/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/tripwire/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/tripwire/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/tripwire/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -220,32 +359,53 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): install-sbinPROGRAMS: $(sbin_PROGRAMS) @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(mkdir_p) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(sbindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(sbindir)" || exit 1; \ + fi; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p \ + ; then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' \ + -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || exit $$?; \ + } \ + ; done uninstall-sbinPROGRAMS: @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' \ + `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(sbindir)" && rm -f $$files clean-sbinPROGRAMS: -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -tripwire$(EXEEXT): $(tripwire_OBJECTS) $(tripwire_DEPENDENCIES) + +tripwire$(EXEEXT): $(tripwire_OBJECTS) $(tripwire_DEPENDENCIES) $(EXTRA_tripwire_DEPENDENCIES) @rm -f tripwire$(EXEEXT) - $(CXXLINK) $(tripwire_LDFLAGS) $(tripwire_OBJECTS) $(tripwire_LDADD) $(LIBS) + $(AM_V_CXXLD)$(CXXLINK) $(tripwire_OBJECTS) $(tripwire_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -254,93 +414,120 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-tripwireHEADERS: $(tripwire_HEADERS) + @$(NORMAL_INSTALL) + @list='$(tripwire_HEADERS)'; test -n "$(tripwiredir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(tripwiredir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(tripwiredir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(tripwiredir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(tripwiredir)" || exit $$?; \ + done + +uninstall-tripwireHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(tripwire_HEADERS)'; test -n "$(tripwiredir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(tripwiredir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + for dir in "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(tripwiredir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -352,17 +539,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -382,18 +575,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-tripwireHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: install-sbinPROGRAMS +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -412,22 +625,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-sbinPROGRAMS +uninstall-am: uninstall-sbinPROGRAMS uninstall-tripwireHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-sbinPROGRAMS ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-sbinPROGRAMS install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-sbinPROGRAMS cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ + install-strip install-tripwireHEADERS installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am uninstall-sbinPROGRAMS + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-sbinPROGRAMS uninstall-tripwireHEADERS + +.PRECIOUS: Makefile all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/tripwire/generatedb.cpp b/src/tripwire/generatedb.cpp index dbb4ba4..5923d69 100644 --- a/src/tripwire/generatedb.cpp +++ b/src/tripwire/generatedb.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -56,13 +56,14 @@ // // this returns true if at least one object was added to the directory. /////////////////////////////////////////////////////////////////////////////// -static void util_ProcessDir( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, iFCOSpec* pSpec, iFCOPropCalc* pPC, iFCOPropDisplayer* pPD ) +static void util_ProcessDir( + cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, iFCOSpec* pSpec, iFCOPropCalc* pPC, iFCOPropDisplayer* pPD) { - ASSERT( ! dbIter.Done() ); - ASSERT( ! pIter->Done() ); - ASSERT( pIter->CanDescend() ); - ASSERT( dbIter.CanDescend() ); - if( ! pIter->CanDescend() ) + ASSERT(!dbIter.Done()); + ASSERT(!pIter->Done()); + ASSERT(pIter->CanDescend()); + ASSERT(dbIter.CanDescend()); + if (!pIter->CanDescend()) return; // // first, descend into the directory @@ -72,64 +73,64 @@ static void util_ProcessDir( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter // // now, iterate through the data source, adding entries to the database ... // - for( pIter->SeekBegin(); ! pIter->Done(); pIter->Next() ) + for (pIter->SeekBegin(); !pIter->Done(); pIter->Next()) { // // don't continue if the spec says we shouldn't // - if( pSpec->ShouldStopDescent( pIter->GetName() ) ) + if (pSpec->ShouldStopDescent(pIter->GetName())) { continue; } // TODO -- do I need to check the db iter to see if the given item already exists? // this should never really happen unless the data source iter is screwed up. - // TODO -- use a smart reference counted object pointer here to release the object when it + // TODO -- use a smart reference counted object pointer here to release the object when it // goes out of scope. iFCO* pFCO = pIter->CreateFCO(); - if( pFCO ) + if (pFCO) { - cTripwireUtil::CalcProps( pFCO, pSpec, pPC, pPD ); - dbIter.AddFCO( pIter->GetShortName(), pFCO ); + cTripwireUtil::CalcProps(pFCO, pSpec, pPC, pPD); + dbIter.AddFCO(pIter->GetShortName(), pFCO); pFCO->Release(); // // descend into this directory if we can... // - if( pIter->CanDescend() ) + if (pIter->CanDescend()) { - if( ! dbIter.CanDescend() ) + if (!dbIter.CanDescend()) { dbIter.AddChildArray(); } - std::auto_ptr pCopy( pIter->CreateCopy() ); - util_ProcessDir( dbIter, pCopy.get(), pSpec, pPC, pPD ); + TW_UNIQUE_PTR pCopy(pIter->CreateCopy()); + util_ProcessDir(dbIter, pCopy.get(), pSpec, pPC, pPD); // // if no files were added, remove the child array... // - if( dbIter.CanRemoveChildArray() ) + if (dbIter.CanRemoveChildArray()) { dbIter.RemoveChildArray(); } } } } - } /////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// -void cGenerateDb::Execute( const cFCOSpecList& specList, cHierDatabase& db, iFCOPropDisplayer* pPD, cErrorBucket* pBucket, uint32 flags ) +void cGenerateDb::Execute( + const cFCOSpecList& specList, cHierDatabase& db, iFCOPropDisplayer* pPD, cErrorBucket* pBucket, uint32 flags) { // TODO -- assert the db is empty or clear it out myself! - std::auto_ptr pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); + TW_UNIQUE_PTR pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); // // set up the database's iterator... // I assume the current genre is correct... // - cDbDataSourceIter dbIter( &db ); - + cDbDataSourceIter dbIter(&db); + // // set the iterators' error bucket... // @@ -139,68 +140,71 @@ void cGenerateDb::Execute( const cFCOSpecList& specList, cHierDatabase& db, iFCO // // this is the object that will calculate all of the properties of the fcos. // - std::auto_ptr pPC(iTWFactory::GetInstance()->CreatePropCalc()); - pPC->SetErrorBucket( pBucket ); - if( flags & FLAG_ERASE_FOOTPRINTS_GD ) + TW_UNIQUE_PTR pPC(iTWFactory::GetInstance()->CreatePropCalc()); + pPC->SetErrorBucket(pBucket); + if (flags & FLAG_ERASE_FOOTPRINTS_GD) + { + pPC->SetCalcFlags(iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES); + dbIter.SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + pDSIter->SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + } + + if (flags & FLAG_DIRECT_IO) { - pPC->SetCalcFlags( iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES ); - dbIter.SetIterFlags( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); - pDSIter->SetIterFlags( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); + pPC->SetCalcFlags(pPC->GetCalcFlags() | iFCOPropCalc::DIRECT_IO); } // // iterate over all of the specs... // cFCOSpecListCanonicalIter specIter(specList); - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { // verbose output - TW_NOTIFY_VERBOSE( _T("%s %s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_PROCESSING ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( specIter.Spec()->GetStartPoint() ).c_str() ); + TW_NOTIFY_VERBOSE( + _T("%s %s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_PROCESSING).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(specIter.Spec()->GetStartPoint()).c_str()); // // have the iterators seek to the appropriate starting point // - pDSIter->SeekToFCO ( specIter.Spec()->GetStartPoint(), false ); // false means don't generate my peers... - if( ! pDSIter->Done() ) + pDSIter->SeekToFCO(specIter.Spec()->GetStartPoint(), false); // false means don't generate my peers... + if (!pDSIter->Done()) { iFCO* pFCO = pDSIter->CreateFCO(); - if( pFCO ) + if (pFCO) { - dbIter.CreatePath( specIter.Spec()->GetStartPoint() ); + dbIter.CreatePath(specIter.Spec()->GetStartPoint()); // // ok, now process this directory // we need to add the start point here, since the first thing the ProcessDir function does is // Descend(). // - cTripwireUtil::CalcProps( pFCO, specIter.Spec(), pPC.get(), pPD ); - dbIter.SetFCOData( pFCO ); + cTripwireUtil::CalcProps(pFCO, specIter.Spec(), pPC.get(), pPD); + dbIter.SetFCOData(pFCO); pFCO->Release(); // // if this is a directory, process its children... // - if( pDSIter->CanDescend() && (! specIter.Spec()->ShouldStopDescent( pDSIter->GetName() )) ) + if (pDSIter->CanDescend() && (!specIter.Spec()->ShouldStopDescent(pDSIter->GetName()))) { // make the child array, if it doesn't exist... // - if( ! dbIter.CanDescend() ) + if (!dbIter.CanDescend()) { dbIter.AddChildArray(); } - std::auto_ptr pCopy( pDSIter->CreateCopy() ); - util_ProcessDir( dbIter, pCopy.get(), specIter.Spec(), pPC.get(), pPD ); + TW_UNIQUE_PTR pCopy(pDSIter->CreateCopy()); + util_ProcessDir(dbIter, pCopy.get(), specIter.Spec(), pPC.get(), pPD); // // if no files were added, remove the child array... // - if( dbIter.CanRemoveChildArray() ) + if (dbIter.CanRemoveChildArray()) { dbIter.RemoveChildArray(); } } } } - } } - diff --git a/src/tripwire/generatedb.h b/src/tripwire/generatedb.h index c894b4b..54383e9 100644 --- a/src/tripwire/generatedb.h +++ b/src/tripwire/generatedb.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,17 +49,22 @@ class iFCOPropDisplayer; class cGenerateDb { public: - static void Execute( const cFCOSpecList& specList, cHierDatabase& db, iFCOPropDisplayer* pPD, cErrorBucket* pBucket, uint32 flags = 0 ); - // generates a tripwire database; this asserts that the database is open - + static void Execute(const cFCOSpecList& specList, + cHierDatabase& db, + iFCOPropDisplayer* pPD, + cErrorBucket* pBucket, + uint32 flags = 0); + // generates a tripwire database; this asserts that the database is open + enum Flags { - FLAG_ERASE_FOOTPRINTS_GD = 0x00000001 - // when this flag is set, cGenerateDb will attempt to leave no footprints when - // creating the database for instance, cGenerateDb will tell the property calculator - // to reset access times. + FLAG_ERASE_FOOTPRINTS_GD = 0x00000001, + // when this flag is set, cGenerateDb will attempt to leave no footprints when + // creating the database for instance, cGenerateDb will tell the property calculator + // to reset access times. + FLAG_DIRECT_IO = 0x00000002 + // Use direct i/o when scanning files }; }; #endif //__GENERATEDB_H - diff --git a/src/tripwire/generatedb_t.cpp b/src/tripwire/generatedb_t.cpp index bfc31c4..b847cdb 100644 --- a/src/tripwire/generatedb_t.cpp +++ b/src/tripwire/generatedb_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,43 +53,42 @@ void TestGenerateDb() try { - iFCONameInfo* pInfo = iTWFactory::GetInstance()->GetNameInfo(); - cErrorTracer et; - cHierDatabase db( pInfo->IsCaseSensitive(), pInfo->GetDelimitingChar() ); - db.Open( _T("c:/tmp/tw.db"), 5, true ); - cHierDatabase::iterator iter( &db ); + iFCONameInfo* pInfo = iTWFactory::GetInstance()->GetNameInfo(); + cErrorTracer et; + cHierDatabase db(pInfo->IsCaseSensitive(), pInfo->GetDelimitingChar()); + db.Open(_T("c:/tmp/tw.db"), 5, true); + cHierDatabase::iterator iter(&db); // // make some specs... // cGenreSpecListVector slv; - std::ifstream in; - in.open("c:/tmp/pol.pol"); - if(in.fail()) + std::ifstream in; + in.open("c:/tmp/pol.pol"); + if (in.fail()) { - d.TraceError( "Unable to open policy file!\n" ); - TEST( false ); + d.TraceError("Unable to open policy file!\n"); + TEST(false); return; } cPolicyParser parser(in); parser.Execute(slv, &et); - - + + // // ok, time to integrity check! // cGenreSpecListVector::iterator at; - for( at = slv.begin(); at != slv.end(); at++ ) + for (at = slv.begin(); at != slv.end(); ++at) { - cGenerateDb::Execute( - at->GetSpecList(), - db, - cGenreSwitcher::GetInstance()->GetFactoryForGenre( at->GetGenre() )->CreatePropDisplayer(), - &et - ); - } + cGenerateDb::Execute( + at->GetSpecList(), + db, + cGenreSwitcher::GetInstance()->GetFactoryForGenre(at->GetGenre())->CreatePropDisplayer(), + &et); + } } - catch( eError& e ) + catch (eError& e) { - d.TraceError( "*** Caught Exception: %d %s\n", e.GetID(), e.GetMsg().c_str() ); + d.TraceError("*** Caught Exception: %d %s\n", e.GetID(), e.GetMsg().c_str()); } } diff --git a/src/tripwire/integritycheck.cpp b/src/tripwire/integritycheck.cpp index 39009a9..6796cc2 100644 --- a/src/tripwire/integritycheck.cpp +++ b/src/tripwire/integritycheck.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,7 +51,7 @@ #include "fco/fconametranslator.h" // -// TODO -- change the report interface so that it takes an error bucket instead of an error queue and then +// TODO -- change the report interface so that it takes an error bucket instead of an error queue and then // pass our error bucket to it. // // TODO -- we need to pass in the prop displayer and do ??? with it at the appropriate times... @@ -60,38 +60,40 @@ /////////////////////////////////////////////////////////////////////////////// // ProcessAddedFCO /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::ProcessAddedFCO( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse ) +void cIntegrityCheck::ProcessAddedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse) { - ASSERT( pIter && (! pIter->Done()) ); + ASSERT(pIter && (!pIter->Done())); // // don't do anything if this FCO is not a part of the spec... // - if( mpCurSpec->ShouldStopDescent( pIter->GetName() ) ) + if (mpCurSpec->ShouldStopDescent(pIter->GetName())) return; // // note that pIter points to the added fco // iFCO* pFCO = pIter->CreateFCO(); mnObjectsScanned++; - mReportIter.SetObjectsScanned( mReportIter.GetObjectsScanned() + 1 ); - if( pFCO ) + mReportIter.SetObjectsScanned(mReportIter.GetObjectsScanned() + 1); + if (pFCO) { - cTripwireUtil::CalcProps( pFCO, mpCurSpec, mpPropCalc, 0 ); //TODO -- a property displayer should be passed in here. - mReportIter.GetAddedSet()->Insert( pFCO ); + cTripwireUtil::CalcProps( + pFCO, mpCurSpec, mpPropCalc, 0); //TODO -- a property displayer should be passed in here. + mReportIter.GetAddedSet()->Insert(pFCO); pFCO->Release(); // // descend here, if we can... // - if( bRecurse ) + if (bRecurse) { - if( pIter->CanDescend() ) + if (pIter->CanDescend()) { // note that we don't want to descend into the dbIter, so we will seek it // to done... // - while( ! dbIter.Done() ) dbIter.Next(); - std::auto_ptr pCopy( pIter->CreateCopy() ); - ProcessDir( dbIter, pCopy.get() ); + while (!dbIter.Done()) + dbIter.Next(); + TW_UNIQUE_PTR pCopy(pIter->CreateCopy()); + ProcessDir(dbIter, pCopy.get()); } } } @@ -100,34 +102,34 @@ void cIntegrityCheck::ProcessAddedFCO( cDbDataSourceIter dbIter, iFCODataSourceI /////////////////////////////////////////////////////////////////////////////// // ProcessRemovedFCO /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::ProcessRemovedFCO( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse ) +void cIntegrityCheck::ProcessRemovedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse) { - ASSERT( ! dbIter.Done() ); + ASSERT(!dbIter.Done()); // // don't do anything if this FCO is not a part of the spec... // - if( mpCurSpec->ShouldStopDescent( dbIter.GetName() ) ) + if (mpCurSpec->ShouldStopDescent(dbIter.GetName())) return; // // we have to be careful here, since not all db nodes are guarenteed to have fco data associated with them. // - if( dbIter.HasFCOData() ) + if (dbIter.HasFCOData()) { // add this to the "removed" set // iFCO* pFCO = dbIter.CreateFCO(); - mReportIter.GetRemovedSet()->Insert( pFCO ); + mReportIter.GetRemovedSet()->Insert(pFCO); pFCO->Release(); } // descend if we can... // - if( bRecurse ) + if (bRecurse) { - if( dbIter.CanDescend() ) + if (dbIter.CanDescend()) { // we don't want pIter to be descended into, so we will pass null as the second param... // - ProcessDir( dbIter, 0 ); + ProcessDir(dbIter, 0); } } } @@ -135,49 +137,48 @@ void cIntegrityCheck::ProcessRemovedFCO( cDbDataSourceIter dbIter, iFCODataSourc /////////////////////////////////////////////////////////////////////////////// // ProcessChangedFCO /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::ProcessChangedFCO( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse ) +void cIntegrityCheck::ProcessChangedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse) { - ASSERT( pIter && (! pIter->Done()) ); - ASSERT( ! dbIter.Done() ); + ASSERT(pIter && (!pIter->Done())); + ASSERT(!dbIter.Done()); cDebug d("cIntegrityCheck::ProcessChangedFCO"); // // don't do anything if this FCO is not a part of the spec... // - if( mpCurSpec->ShouldStopDescent( pIter->GetName() ) ) + if (mpCurSpec->ShouldStopDescent(pIter->GetName())) return; // if the database doesn't have this data, then process this as an add // - if( ! dbIter.HasFCOData() ) + if (!dbIter.HasFCOData()) { - ProcessAddedFCO( dbIter, pIter, false ); // false means not to recurse + ProcessAddedFCO(dbIter, pIter, false); // false means not to recurse } else { // here we will actually compare the two FCOs // - TW_NOTIFY_VERBOSE( _T("--- %s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHECKING ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( pIter->GetName() ).c_str() ); + TW_NOTIFY_VERBOSE(_T("--- %s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_CHECKING).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(pIter->GetName()).c_str()); iFCO* pNewFCO = pIter->CreateFCO(); iFCO* pOldFCO = dbIter.CreateFCO(); - + mnObjectsScanned++; - mReportIter.SetObjectsScanned( mReportIter.GetObjectsScanned() + 1 ); + mReportIter.SetObjectsScanned(mReportIter.GetObjectsScanned() + 1); // // if we can't create the operating system object, treat this as a removal; we will // increment the os iterator... // - if( ! pNewFCO ) + if (!pNewFCO) { pIter->Next(); - ProcessRemovedFCO( dbIter, pIter, bRecurse ); + ProcessRemovedFCO(dbIter, pIter, bRecurse); return; } - CompareFCOs( pOldFCO, pNewFCO ); + CompareFCOs(pOldFCO, pNewFCO); //------------------------------------------------------------------------- // Begin functionality necessary for policy update @@ -185,37 +186,38 @@ void cIntegrityCheck::ProcessChangedFCO( cDbDataSourceIter dbIter, iFCODataSourc bool bDbFCODirty = false; // change the valid vector for the db's fco, if the appropriate flag is set // - if( mFlags & FLAG_INVALIDATE_EXTRA_DB_PROPS ) + if (mFlags & FLAG_INVALIDATE_EXTRA_DB_PROPS) { - cFCOPropVector propsToInvalidate = pOldFCO->GetPropSet()->GetValidVector() & mpCurSpec->GetPropVector( pOldFCO ); - propsToInvalidate ^= pOldFCO->GetPropSet()->GetValidVector(); - pOldFCO->GetPropSet()->InvalidateProps( propsToInvalidate ); + cFCOPropVector propsToInvalidate = + pOldFCO->GetPropSet()->GetValidVector() & mpCurSpec->GetPropVector(pOldFCO); + propsToInvalidate ^= pOldFCO->GetPropSet()->GetValidVector(); + pOldFCO->GetPropSet()->InvalidateProps(propsToInvalidate); bDbFCODirty = true; } // update the old fco with the new properties... // - if( mFlags & FLAG_SET_NEW_PROPS ) + if (mFlags & FLAG_SET_NEW_PROPS) { - cFCOPropVector propsToCopy = pOldFCO->GetPropSet()->GetValidVector() & pNewFCO->GetPropSet()->GetValidVector(); - propsToCopy ^= pNewFCO->GetPropSet()->GetValidVector(); + cFCOPropVector propsToCopy = + pOldFCO->GetPropSet()->GetValidVector() & pNewFCO->GetPropSet()->GetValidVector(); + propsToCopy ^= pNewFCO->GetPropSet()->GetValidVector(); - pOldFCO->GetPropSet()->CopyProps( pNewFCO->GetPropSet(), propsToCopy ); + pOldFCO->GetPropSet()->CopyProps(pNewFCO->GetPropSet(), propsToCopy); bDbFCODirty = true; } // rewrite the fco to the database, if necessary // - if( bDbFCODirty ) + if (bDbFCODirty) { dbIter.RemoveFCOData(); - dbIter.SetFCOData( pOldFCO ); - - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_DB_CHANGING ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( pOldFCO->GetName() ).c_str() ); + dbIter.SetFCOData(pOldFCO); + TW_NOTIFY_VERBOSE( + _T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_DB_CHANGING).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(pOldFCO->GetName()).c_str()); } // // end policy update specific code @@ -227,12 +229,12 @@ void cIntegrityCheck::ProcessChangedFCO( cDbDataSourceIter dbIter, iFCODataSourc // // finally, we need to recurse into our child directories... // - if( bRecurse ) + if (bRecurse) { - if( pIter->CanDescend() || dbIter.CanDescend() ) + if (pIter->CanDescend() || dbIter.CanDescend()) { - std::auto_ptr pCopy( pIter->CreateCopy() ); - ProcessDir( dbIter, pCopy.get() ); + TW_UNIQUE_PTR pCopy(pIter->CreateCopy()); + ProcessDir(dbIter, pCopy.get()); } } } @@ -240,63 +242,62 @@ void cIntegrityCheck::ProcessChangedFCO( cDbDataSourceIter dbIter, iFCODataSourc /////////////////////////////////////////////////////////////////////////////// // CompareFCOs /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::CompareFCOs( iFCO* pOldFCO, iFCO* pNewFCO ) +void cIntegrityCheck::CompareFCOs(iFCO* pOldFCO, iFCO* pNewFCO) { - cTripwireUtil::CalcProps( pNewFCO, mpCurSpec, mpPropCalc, 0 ); //TODO -- a property displayer should be passed in here. + cTripwireUtil::CalcProps( + pNewFCO, mpCurSpec, mpPropCalc, 0); //TODO -- a property displayer should be passed in here. // // figure out what properties we are comparing...for an explanation of the propsToCheck derivation, see tripwire.cpp line 250. // cFCOPropVector propsToCheck; - if( mFlags & FLAG_COMPARE_VALID_PROPS_ONLY ) + if (mFlags & FLAG_COMPARE_VALID_PROPS_ONLY) { - propsToCheck = pOldFCO->GetPropSet()->GetValidVector() & - pNewFCO->GetPropSet()->GetValidVector(); + propsToCheck = pOldFCO->GetPropSet()->GetValidVector() & pNewFCO->GetPropSet()->GetValidVector(); } else { - propsToCheck = pOldFCO->GetPropSet()->GetValidVector() | - pNewFCO->GetPropSet()->GetValidVector(); + propsToCheck = pOldFCO->GetPropSet()->GetValidVector() | pNewFCO->GetPropSet()->GetValidVector(); } - propsToCheck &= mpCurSpec->GetPropVector( pNewFCO ); + propsToCheck &= mpCurSpec->GetPropVector(pNewFCO); // // trim off the loose dir stuff... // - if( (pOldFCO->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN) && - (pNewFCO->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN) ) + if ((pOldFCO->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN) && (pNewFCO->GetCaps() & iFCO::CAP_CAN_HAVE_CHILDREN)) { - cFCOPropVector tmp = (propsToCheck ^ mLooseDirProps); - propsToCheck &= tmp; + cFCOPropVector tmp = (propsToCheck ^ mLooseDirProps); + propsToCheck &= tmp; } // // construct the compare object and actually do the compare // - cFCOCompare compareObj( propsToCheck ); - uint32 result = compareObj.Compare(pOldFCO, pNewFCO); + cFCOCompare compareObj(propsToCheck); + uint32 result = compareObj.Compare(pOldFCO, pNewFCO); - if( (result & cFCOCompare::PROPS_UNEQUAL) || (result & cFCOCompare::PROPS_NOT_ALL_VALID) ) + if ((result & cFCOCompare::PROPS_UNEQUAL) || (result & cFCOCompare::PROPS_NOT_ALL_VALID)) { // this is a violation... // - mReport.AddChangedFCO(mReportIter, pOldFCO, pNewFCO, compareObj.GetUnequalProps() | compareObj.GetInvalidProps()); + mReport.AddChangedFCO( + mReportIter, pOldFCO, pNewFCO, compareObj.GetUnequalProps() | compareObj.GetInvalidProps()); } } /////////////////////////////////////////////////////////////////////////////// // ProcessDir /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::ProcessDir( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter ) +void cIntegrityCheck::ProcessDir(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter) { cDebug d("cIntegrityCheck::ProcessDir"); - // if either iterator is done, or if the data source iter is NULL, that indicates that the tree + // if either iterator is done, or if the data source iter is NULL, that indicates that the tree // has stopped for that iterator, and all FCOs encountered by the other iter are all adds or removals, // as appropriate. // // the first thing we will do is descend, if possible, and if not possible, set them to done(). // - if( pIter ) + if (pIter) { - if( pIter->CanDescend() ) + if (pIter->CanDescend()) { pIter->Descend(); } @@ -305,131 +306,136 @@ void cIntegrityCheck::ProcessDir( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter = 0; } } - if( ! dbIter.Done() ) + if (!dbIter.Done()) { - if( dbIter.CanDescend() ) + if (dbIter.CanDescend()) { dbIter.Descend(); } else { - while( ! dbIter.Done() ) dbIter.Next(); + while (!dbIter.Done()) + dbIter.Next(); } } // if they are both done, then we are done dealin'! // - if( ((! pIter) || (pIter->Done())) && ( dbIter.Done() ) ) + if (((!pIter) || (pIter->Done())) && (dbIter.Done())) { //TODO -- what else do I need to do here? return; } -#ifdef _DEBUG - if( dbIter.Done() ) +#ifdef DEBUG + if (dbIter.Done()) { - d.TraceDebug( "Processing directory %s\n", pIter->GetParentName().AsString().c_str() ); + d.TraceDebug("Processing directory %s\n", pIter->GetParentName().AsString().c_str()); } else { - d.TraceDebug( "Processing directory %s\n", dbIter.GetParentName().AsString().c_str() ); + d.TraceDebug("Processing directory %s\n", dbIter.GetParentName().AsString().c_str()); } #endif // // now, process the entries in this directory... // - while( true ) + while (true) { // this just cleans up some logic statements below... // - if( pIter && pIter->Done() ) + if (pIter && pIter->Done()) pIter = NULL; // if they are both done, then we are finished... // - if( dbIter.Done() && (! pIter ) ) + if (dbIter.Done() && (!pIter)) break; - if( dbIter.Done() ) + if (dbIter.Done()) { - ASSERT( pIter != 0); - d.TraceDetail( "Examining and %s\n", pIter->GetName().AsString().c_str() ); - // - // these are all new entries, add them to the "Added" set... - // - ProcessAddedFCO( dbIter, pIter ); - pIter->Next(); + ASSERT(pIter != 0); + if (pIter) + { + d.TraceDetail("Examining and %s\n", pIter->GetName().AsString().c_str()); + // + // these are all new entries, add them to the "Added" set... + // + ProcessAddedFCO(dbIter, pIter); + pIter->Next(); + } } - else if( ! pIter ) + else if (!pIter) { - ASSERT( ! dbIter.Done() ); - d.TraceDetail( _T("--Examining %s and \n"), dbIter.GetName().AsString().c_str() ); + ASSERT(!dbIter.Done()); + d.TraceDetail(_T("--Examining %s and \n"), dbIter.GetName().AsString().c_str()); // - // these are all removed objects. + // these are all removed objects. // - ProcessRemovedFCO( dbIter, pIter ); + ProcessRemovedFCO(dbIter, pIter); dbIter.Next(); } else { - d.TraceDetail( _T("--Examining %s and %s\n"), dbIter.GetName().AsString().c_str(), pIter->GetName().AsString().c_str() ); + d.TraceDetail(_T("--Examining %s and %s\n"), + dbIter.GetName().AsString().c_str(), + pIter->GetName().AsString().c_str()); - ASSERT( pIter->GetParentName() == dbIter.GetParentName() ); + ASSERT(pIter->GetParentName() == dbIter.GetParentName()); // // get the relationship between the current nodes of the two iterators... // - iFCODataSourceIter::Relationship rel = dbIter.GetRelationship( *pIter ); + iFCODataSourceIter::Relationship rel = dbIter.GetRelationship(*pIter); // // if rel == LT, then the old has something the new doesn't (ie -- a removal!) // if rel == GT, then there is an addition // - if( rel == iFCODataSourceIter::REL_LT ) + if (rel == iFCODataSourceIter::REL_LT) { - ProcessRemovedFCO( dbIter, pIter ); + ProcessRemovedFCO(dbIter, pIter); dbIter.Next(); } - else if( rel == iFCODataSourceIter::REL_GT ) + else if (rel == iFCODataSourceIter::REL_GT) { - ProcessAddedFCO( dbIter, pIter ); + ProcessAddedFCO(dbIter, pIter); pIter->Next(); - } else { // we actually have to compare the FCOs at this point... // NOTE -- if the db iter has no data, then this is an add again. - // - ProcessChangedFCO( dbIter, pIter ); + // + ProcessChangedFCO(dbIter, pIter); dbIter.Next(); pIter->Next(); } - ASSERT( pIter->GetParentName() == dbIter.GetParentName() ); + ASSERT(pIter->GetParentName() == dbIter.GetParentName()); } } - d.TraceDebug( "Done Processing Directory\n"); + d.TraceDebug("Done Processing Directory\n"); } /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cIntegrityCheck::cIntegrityCheck(cGenre::Genre genreNum, const cFCOSpecList& specList, cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket ) -: - mGenre ( genreNum ), - mSpecList ( specList ), - mDb ( db ), - mReport ( report ), - mpPropCalc ( iTWFactory::GetInstance()->CreatePropCalc() ), - mpCurSpec ( 0 ), - mReportIter ( report, genreNum ), - mFlags ( 0 ), - mnObjectsScanned( 0 ) +cIntegrityCheck::cIntegrityCheck( + cGenre::Genre genreNum, const cFCOSpecList& specList, cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket) + : mGenre(genreNum), + mSpecList(specList), + mDb(db), + mReport(report), + mpPropCalc(iTWFactory::GetInstance()->CreatePropCalc()), + mpCurSpec(0), + mReportIter(report, genreNum), + mFlags(0), + mnObjectsScanned(0) { // mBucket is a pass-thru bucket; its only job is to pass the errors onto its child. // - mBucket.SetChild ( pBucket ); - mpPropCalc->SetErrorBucket ( &mBucket ); + mBucket.SetChild(pBucket); + mpPropCalc->SetErrorBucket(&mBucket); } @@ -445,17 +451,17 @@ cIntegrityCheck::~cIntegrityCheck() /////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::Execute( uint32 flags ) +void cIntegrityCheck::Execute(uint32 flags) { mFlags = flags; // create the data source iterator // - std::auto_ptr pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); + TW_UNIQUE_PTR pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); // // set up the database's iterator... // I assume the current genre is correct... // - cDbDataSourceIter dbIter( &mDb ); + cDbDataSourceIter dbIter(&mDb); // // set the iterator's error bucket... @@ -468,98 +474,103 @@ void cIntegrityCheck::Execute( uint32 flags ) // be removed from the ones used to compare, so if loose dirs is not specified, we can set this // to the empty vector. // - if( flags & FLAG_LOOSE_DIR ) + if (flags & FLAG_LOOSE_DIR) { mLooseDirProps = iTWFactory::GetInstance()->GetLooseDirMask(); } // // set up flags for the property calculator and iterators - // - if( flags & FLAG_ERASE_FOOTPRINTS_IC ) + // + if (flags & FLAG_ERASE_FOOTPRINTS_IC) + { + mpPropCalc->SetCalcFlags(iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES); + dbIter.SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + pDSIter->SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + } + + if (flags & FLAG_DIRECT_IO) { - mpPropCalc->SetCalcFlags( iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES ); - dbIter.SetIterFlags ( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); - pDSIter->SetIterFlags ( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); + mpPropCalc->SetCalcFlags(mpPropCalc->GetCalcFlags() | iFCOPropCalc::DIRECT_IO); } - + // // iterate over all of the specs... // - cFCOSpecListCanonicalIter specIter(mSpecList); - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) + cFCOSpecListCanonicalIter specIter(mSpecList); + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { mpCurSpec = specIter.Spec(); - + // verbose output - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHECKING_RULE ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( mpCurSpec->GetStartPoint() ).c_str() ); - // + TW_NOTIFY_VERBOSE( + _T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_CHECKING_RULE).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(mpCurSpec->GetStartPoint()).c_str()); + // // add the spec to the report... // mReport.AddSpec(mGenre, mpCurSpec, specIter.Attr(), &mReportIter); - ASSERT(! mReportIter.Done()); + ASSERT(!mReportIter.Done()); // // associate the error bucket to this current spec in the report // - mReportIter.GetErrorQueue()->SetChild( mBucket.GetChild() ); - mBucket.SetChild( mReportIter.GetErrorQueue() ); + mReportIter.GetErrorQueue()->SetChild(mBucket.GetChild()); + mBucket.SetChild(mReportIter.GetErrorQueue()); // // seek each iterator to the appropriate starting point... // - dbIter.SeekToFCO ( mpCurSpec->GetStartPoint(), false ); // false means not to create my peers - pDSIter->SeekToFCO ( mpCurSpec->GetStartPoint(), false ); + dbIter.SeekToFCO(mpCurSpec->GetStartPoint(), false); // false means not to create my peers + pDSIter->SeekToFCO(mpCurSpec->GetStartPoint(), false); // // integrity check the start point; note that the ProcessXXX functions will // handle recursing into the subdirectories and stopping when the spec says to // - if( dbIter.Done() && pDSIter->Done() ) + if (dbIter.Done() && pDSIter->Done()) { - // nothing to do here... + // nothing to do here... ; } - else if( pDSIter->Done() ) + else if (pDSIter->Done()) { // removed object... - ProcessRemovedFCO( dbIter, pDSIter.get() ); + ProcessRemovedFCO(dbIter, pDSIter.get()); } - else if( dbIter.Done() ) + else if (dbIter.Done()) { // added object... - ProcessAddedFCO( dbIter, pDSIter.get() ); + ProcessAddedFCO(dbIter, pDSIter.get()); } else { // possible changed fco - ProcessChangedFCO( dbIter, pDSIter.get() ); + ProcessChangedFCO(dbIter, pDSIter.get()); } // dissociate the report error bucket and mine... // - mBucket.SetChild( mReportIter.GetErrorQueue()->GetChild() ); - mReportIter.GetErrorQueue()->SetChild( 0 ); + mBucket.SetChild(mReportIter.GetErrorQueue()->GetChild()); + mReportIter.GetErrorQueue()->SetChild(0); } } /////////////////////////////////////////////////////////////////////////////// // ExecuteOnObjectList /////////////////////////////////////////////////////////////////////////////// -void cIntegrityCheck::ExecuteOnObjectList( const std::list& fcoNames, uint32 flags ) +void cIntegrityCheck::ExecuteOnObjectList(const std::list& fcoNames, uint32 flags) { iFCONameTranslator* pTrans = iTWFactory::GetInstance()->GetNameTranslator(); // // create the data source iterator // - std::auto_ptr pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); + TW_UNIQUE_PTR pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); // // set up the database's iterator... // I assume the current genre is correct... // - cDbDataSourceIter dbIter ( &mDb ); - cFCOSpecListCanonicalIter specIter(mSpecList); - + cDbDataSourceIter dbIter(&mDb); + cFCOSpecListCanonicalIter specIter(mSpecList); + // // set the iterators' error bucket... // @@ -568,37 +579,42 @@ void cIntegrityCheck::ExecuteOnObjectList( const std::list& fcoNames, // // set up flags for the property calculator and iterators - // - if( flags & FLAG_ERASE_FOOTPRINTS_IC ) + // + if (flags & FLAG_ERASE_FOOTPRINTS_IC) + { + mpPropCalc->SetCalcFlags(iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES); + dbIter.SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + pDSIter->SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); + } + + if (flags & FLAG_DIRECT_IO) { - mpPropCalc->SetCalcFlags( iFCOPropCalc::DO_NOT_MODIFY_PROPERTIES ); - dbIter.SetIterFlags ( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); - pDSIter->SetIterFlags ( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); + mpPropCalc->SetCalcFlags(mpPropCalc->GetCalcFlags() | iFCOPropCalc::DIRECT_IO); } // // iterate over all the objects to integrity check.. // std::list::const_iterator it; - for( it = fcoNames.begin(); it != fcoNames.end(); it++ ) + for (it = fcoNames.begin(); it != fcoNames.end(); ++it) { - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHECKING ).c_str(), - pTrans->ToStringDisplay( *it ).c_str() ); + TW_NOTIFY_VERBOSE(_T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_CHECKING).c_str(), + pTrans->ToStringDisplay(*it).c_str()); // // figure out which spec this fco belongs in... // - for( specIter.SeekBegin(); ! specIter.Done(); specIter.Next() ) + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { - if( specIter.Spec()->SpecContainsFCO( *it ) ) + if (specIter.Spec()->SpecContainsFCO(*it)) break; } // error if we found no spec. // - if( specIter.Done() ) + if (specIter.Done()) { - mBucket.AddError ( eICFCONotInSpec( pTrans->ToStringDisplay( *it ) ) ); - mReport.GetErrorQueue()->cErrorBucket::AddError ( eICFCONotInSpec( pTrans->ToStringDisplay( *it ) ) ); + mBucket.AddError(eICFCONotInSpec(pTrans->ToStringDisplay(*it))); + mReport.GetErrorQueue()->cErrorBucket::AddError(eICFCONotInSpec(pTrans->ToStringDisplay(*it))); continue; } mpCurSpec = specIter.Spec(); @@ -606,23 +622,23 @@ void cIntegrityCheck::ExecuteOnObjectList( const std::list& fcoNames, // add this spec to the report if it is not there // and seek to the spec // - if( ! mReportIter.SeekToSpec( mpCurSpec ) ) + if (!mReportIter.SeekToSpec(mpCurSpec)) { mReport.AddSpec(mGenre, mpCurSpec, specIter.Attr(), &mReportIter); } // insert the report error bucket between mpErrorBucket and its children... // - mReportIter.GetErrorQueue()->SetChild( mBucket.GetChild() ); - mBucket.SetChild( mReportIter.GetErrorQueue() ); + mReportIter.GetErrorQueue()->SetChild(mBucket.GetChild()); + mBucket.SetChild(mReportIter.GetErrorQueue()); // // create the fco in the database... // - dbIter.SeekToFCO( *it, false ); - if( dbIter.Done() || (! dbIter.HasFCOData()) ) + dbIter.SeekToFCO(*it, false); + if (dbIter.Done() || (!dbIter.HasFCOData())) { // fco not found in the db! // - mBucket.AddError( eICFCONotInDb( pTrans->ToStringDisplay( *it ) ) ); + mBucket.AddError(eICFCONotInDb(pTrans->ToStringDisplay(*it))); } else { @@ -630,30 +646,28 @@ void cIntegrityCheck::ExecuteOnObjectList( const std::list& fcoNames, // // create the fco from the data source // - pDSIter->SeekToFCO ( *it, false ); - if( ! pDSIter->Done() ) + pDSIter->SeekToFCO(*it, false); + if (!pDSIter->Done()) { iFCO* pNewFCO = pDSIter->CreateFCO(); - mnObjectsScanned++; - mReportIter.SetObjectsScanned( mReportIter.GetObjectsScanned() + 1 ); - - if( pNewFCO ) + mnObjectsScanned++; + mReportIter.SetObjectsScanned(mReportIter.GetObjectsScanned() + 1); + + if (pNewFCO) { - CompareFCOs( pOldFCO, pNewFCO ); + CompareFCOs(pOldFCO, pNewFCO); pNewFCO->Release(); } else { - mBucket.AddError( eICFCOCreate( pTrans->ToStringDisplay( *it ) ) ); + mBucket.AddError(eICFCOCreate(pTrans->ToStringDisplay(*it))); } } pOldFCO->Release(); } // dissociate the report error bucket and mine... // - mBucket.SetChild( mReportIter.GetErrorQueue()->GetChild() ); - mReportIter.GetErrorQueue()->SetChild( 0 ); + mBucket.SetChild(mReportIter.GetErrorQueue()->GetChild()); + mReportIter.GetErrorQueue()->SetChild(0); } - } - diff --git a/src/tripwire/integritycheck.h b/src/tripwire/integritycheck.h index da5dae4..a06eef2 100644 --- a/src/tripwire/integritycheck.h +++ b/src/tripwire/integritycheck.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,82 +60,89 @@ class iFCOSpec; class cFCOReportSpecIter; class iFCOPropCalc; -TSS_EXCEPTION( eIC, eError ); -TSS_EXCEPTION( eICFCONotInSpec, eIC ); -TSS_EXCEPTION( eICFCONotInDb, eIC ); -TSS_EXCEPTION( eICFCOCreate, eIC ); -TSS_EXCEPTION( eICBadPol, eIC ); -TSS_EXCEPTION( eICUnknownGenre, eIC ); -TSS_EXCEPTION( eICBadSevVal, eIC ); -TSS_EXCEPTION( eICInappropriateGenre, eIC ); -TSS_EXCEPTION( eICDifferentUsers, eIC ); -TSS_EXCEPTION( eICMismatchingParams, eIC ); +TSS_EXCEPTION(eIC, eError); +TSS_EXCEPTION(eICFCONotInSpec, eIC); +TSS_EXCEPTION(eICFCONotInDb, eIC); +TSS_EXCEPTION(eICFCOCreate, eIC); +TSS_EXCEPTION(eICBadPol, eIC); +TSS_EXCEPTION(eICUnknownGenre, eIC); +TSS_EXCEPTION(eICBadSevVal, eIC); +TSS_EXCEPTION(eICInappropriateGenre, eIC); +TSS_EXCEPTION(eICDifferentUsers, eIC); +TSS_EXCEPTION(eICMismatchingParams, eIC); class cIntegrityCheck { public: - cIntegrityCheck( cGenre::Genre genreNum, const cFCOSpecList& specList, - cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket ); - // if this is an integrity check of a set of files (instead of a policy file based check) - // then specList refers to the db's spec list. Otherwise, it represents the spec list being - // checked. NOTE -- this class has no way to decide if the specList is appropriate for the database - // or not, so it is the client's responsibility to do this. + cIntegrityCheck(cGenre::Genre genreNum, + const cFCOSpecList& specList, + cHierDatabase& db, + cFCOReport& report, + cErrorBucket* pBucket); + // if this is an integrity check of a set of files (instead of a policy file based check) + // then specList refers to the db's spec list. Otherwise, it represents the spec list being + // checked. NOTE -- this class has no way to decide if the specList is appropriate for the database + // or not, so it is the client's responsibility to do this. ~cIntegrityCheck(); - void Execute( uint32 flags = 0 ); - // flags should be 0, or some combination of the below enumeration - // TODO -- specify what kinds of exception can come up from here.... - void ExecuteOnObjectList( const std::list& fcoNames, uint32 flags = 0 ); - // executes an integrity check on the objects named in the list. The specList passed in - // as the first parameter to the ctor is interprited as the db's spec list. - int ObjectsScanned() { return mnObjectsScanned; }; + void Execute(uint32 flags = 0); + // flags should be 0, or some combination of the below enumeration + // TODO -- specify what kinds of exception can come up from here.... + void ExecuteOnObjectList(const std::list& fcoNames, uint32 flags = 0); + // executes an integrity check on the objects named in the list. The specList passed in + // as the first parameter to the ctor is interprited as the db's spec list. + int ObjectsScanned() + { + return mnObjectsScanned; + }; enum Flags { - FLAG_LOOSE_DIR = 0x00000001, - // when this is set, fcos whose caps return CAP_CAN_HAVE_CHILDREN will not - // compare any properties that are returned from iTWFactory::GetLooseDirMask() - FLAG_COMPARE_VALID_PROPS_ONLY = 0x00000002, - // when this is set, only the properties that are valid in both FCOs being - // compared are compared. - FLAG_INVALIDATE_EXTRA_DB_PROPS = 0x00000004, - // used by policy update; this flag indicates that we should invalidate properties - // of objects in the database that are not a part of the spec used to compare the object. - // Note: it is kind of a hack that this is here; in a perfect design, integrity check - // would never modify the database -- 8 feb 99 mdb - FLAG_SET_NEW_PROPS = 0x00000008, - // also used exclusively in policy update, this is an even bigger and even sicker hack than the - // previous enumeration. This flag indicates that any valid properties in the new FCO during - // an integrity check that are not valid in the database FCO should be copied to the db's fco. - // Yuck! - FLAG_ERASE_FOOTPRINTS_IC = 0x00000010 - // when this flag is set, IC will attempt to leave no footprints when doing an integrity check. - // for instance, IC will tell the property calculator to reset access times. + FLAG_LOOSE_DIR = 0x00000001, + // when this is set, fcos whose caps return CAP_CAN_HAVE_CHILDREN will not + // compare any properties that are returned from iTWFactory::GetLooseDirMask() + FLAG_COMPARE_VALID_PROPS_ONLY = 0x00000002, + // when this is set, only the properties that are valid in both FCOs being + // compared are compared. + FLAG_INVALIDATE_EXTRA_DB_PROPS = 0x00000004, + // used by policy update; this flag indicates that we should invalidate properties + // of objects in the database that are not a part of the spec used to compare the object. + // Note: it is kind of a hack that this is here; in a perfect design, integrity check + // would never modify the database -- 8 feb 99 mdb + FLAG_SET_NEW_PROPS = 0x00000008, + // also used exclusively in policy update, this is an even bigger and even sicker hack than the + // previous enumeration. This flag indicates that any valid properties in the new FCO during + // an integrity check that are not valid in the database FCO should be copied to the db's fco. + // Yuck! + FLAG_ERASE_FOOTPRINTS_IC = 0x00000010, + // when this flag is set, IC will attempt to leave no footprints when doing an integrity check. + // for instance, IC will tell the property calculator to reset access times. + FLAG_DIRECT_IO = 0x00000020 + // Use direct i/o when scanning files }; private: - cGenre::Genre mGenre; - const cFCOSpecList& mSpecList; - cHierDatabase& mDb; - cFCOReport& mReport; - cErrorBucketPassThru mBucket; - iFCOPropCalc* mpPropCalc; - iFCOSpec* mpCurSpec; // the spec we are currently operating on - cFCOReportSpecIter mReportIter; // the current iterator into the report - cFCOPropVector mLooseDirProps; // properties that should be ignored in loose directories - uint32 mFlags; // flags passed in to execute() - int mnObjectsScanned; // number of objects scanned in system ( scanning includes - // discovering that an FCO does not exist ) + cGenre::Genre mGenre; + const cFCOSpecList& mSpecList; + cHierDatabase& mDb; + cFCOReport& mReport; + cErrorBucketPassThru mBucket; + iFCOPropCalc* mpPropCalc; + iFCOSpec* mpCurSpec; // the spec we are currently operating on + cFCOReportSpecIter mReportIter; // the current iterator into the report + cFCOPropVector mLooseDirProps; // properties that should be ignored in loose directories + uint32 mFlags; // flags passed in to execute() + int mnObjectsScanned; // number of objects scanned in system ( scanning includes + // discovering that an FCO does not exist ) - void ProcessDir ( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter ); - void ProcessAddedFCO ( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true ); - void ProcessRemovedFCO ( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true ); - void ProcessChangedFCO ( cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true ); - void CompareFCOs ( iFCO* pOldFCO, iFCO* pNewFCO ); + void ProcessDir(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter); + void ProcessAddedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true); + void ProcessRemovedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true); + void ProcessChangedFCO(cDbDataSourceIter dbIter, iFCODataSourceIter* pIter, bool bRecurse = true); + void CompareFCOs(iFCO* pOldFCO, iFCO* pNewFCO); }; #endif //__INTEGRITYCHECK_H - diff --git a/src/tripwire/integritycheck_t.cpp b/src/tripwire/integritycheck_t.cpp index a28f519..d211462 100644 --- a/src/tripwire/integritycheck_t.cpp +++ b/src/tripwire/integritycheck_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -56,33 +56,33 @@ void TestIntegrityCheck() try { - cFCOReport report; + cFCOReport report; cGenreSpecListVector slv; - cErrorTracer et; - iFCONameInfo* pInfo = iTWFactory::GetInstance()->GetNameInfo(); - cHierDatabase db( pInfo->IsCaseSensitive(), pInfo->GetDelimitingChar() ); - db.Open( _T("c:/tmp/tw.db"), 5, false ); + cErrorTracer et; + iFCONameInfo* pInfo = iTWFactory::GetInstance()->GetNameInfo(); + cHierDatabase db(pInfo->IsCaseSensitive(), pInfo->GetDelimitingChar()); + db.Open(_T("c:/tmp/tw.db"), 5, false); // // make some specs... // std::ifstream in; - in.open("c:/tmp/pol.pol"); - if(in.fail()) + in.open("c:/tmp/pol.pol"); + if (in.fail()) { - d.TraceError( "Unable to open policy file!\n" ); - TEST( false ); + d.TraceError("Unable to open policy file!\n"); + TEST(false); return; } cPolicyParser parser(in); parser.Execute(slv, &et); - + // // ok, time to integrity check! // cGenreSpecListVector::iterator at; - for( at = slv.begin(); at != slv.end(); at++ ) + for (at = slv.begin(); at != slv.end(); ++at) { - cIntegrityCheck ic( at->GetGenre(), at->GetSpecList(), db, report, &et ); + cIntegrityCheck ic(at->GetGenre(), at->GetSpecList(), db, report, &et); ic.Execute(); } @@ -90,10 +90,9 @@ void TestIntegrityCheck() // finally, let's print out the report... // report.TraceContents(); - } - catch( eError& e ) + catch (eError& e) { - d.TraceError( "*** Caught Exception: %d %s\n", e.GetID(), e.GetMsg().c_str() ); + d.TraceError("*** Caught Exception: %d %s\n", e.GetID(), e.GetMsg().c_str()); } } diff --git a/src/tripwire/mailmessage.cpp b/src/tripwire/mailmessage.cpp index 94b59f6..72a5168 100644 --- a/src/tripwire/mailmessage.cpp +++ b/src/tripwire/mailmessage.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -69,7 +69,7 @@ void cMailMessage::SetFrom(const TSTRING& strFrom) /////////////////////////////////////////////////////////////////////////////// void cMailMessage::SetFromName(const TSTRING& strFromName) { - mstrFromName = strFromName; + mstrFromName = strFromName; } @@ -98,7 +98,7 @@ void cMailMessage::AttachFile(const TSTRING& strFullPath) bool cMailMessage::Send() { // this is a pure virtual method. You should never end up here. - ASSERT(false); + ASSERT(false); return false; } @@ -110,13 +110,13 @@ bool cMailMessage::Send() bool cMailMessage::Ready() { // You must specify 'from', 'to', the subject - if( mstrFrom.length() == 0 || mvstrRecipients.size() == 0 || mstrSubject.length() == 0 ) + if (mstrFrom.length() == 0 || mvstrRecipients.size() == 0 || mstrSubject.length() == 0) { return false; } // make sure we can at least send something... - if( mstrBody.empty() ) + if (mstrBody.empty()) { mstrBody = _T("\r\n"); } @@ -124,20 +124,18 @@ bool cMailMessage::Ready() return true; } -bool cMailMessage::GetAttachmentsAsString( std::string& s ) +bool cMailMessage::GetAttachmentsAsString(std::string& s) { s.erase(); bool allOK = true; - for( std::vector::const_iterator at = mvstrAttachments.begin(); - at != mvstrAttachments.end(); - at++ ) + for (std::vector::const_iterator at = mvstrAttachments.begin(); at != mvstrAttachments.end(); ++at) { s += "\r\n"; cFile file; - try + try { - file.Open( at->c_str(), cFile::OPEN_READ); + file.Open(at->c_str(), cFile::OPEN_READ); // Simply stream the file into the socket. @@ -148,17 +146,17 @@ bool cMailMessage::GetAttachmentsAsString( std::string& s ) while ((bytes = file.Read(buf, cBufSize)) != 0) { - ASSERT( bytes > 0 && bytes <= cBufSize ); // ensures typecast below - ASSERT( (std::string::size_type)bytes < std::string().max_size() ); + ASSERT(bytes > 0 && bytes <= cBufSize); // ensures typecast below + ASSERT((std::string::size_type)bytes < std::string().max_size()); - s += std::string( buf, (size_t)bytes ); + s += std::string(buf, (size_t)bytes); } file.Close(); } catch (eFile&) { - // TODO: There is no method of reporting detailed information on + // TODO: There is no method of reporting detailed information on // errors if they occur. Perhaps someday there will be. At the moment // it does not seem necessary as the only attached files that will // be sent are temporary files that tripwire has just created. Thus @@ -179,27 +177,25 @@ bool cMailMessage::GetAttachmentsAsString( std::string& s ) std::string cMailMessage::Create822Header() { std::ostringstream ss; - std::string strToList; - for( std::vector< TSTRING >::size_type i = 0; - i < mvstrRecipients.size(); - i++ ) + std::string strToList; + for (std::vector::size_type i = 0; i < mvstrRecipients.size(); i++) { - if( strToList.length() > 0 ) + if (strToList.length() > 0) strToList += ", "; - strToList += cStringUtil::TstrToStr( mvstrRecipients[i] ); + strToList += cStringUtil::TstrToStr(mvstrRecipients[i]); } - ss << cMailMessageUtil::FormatAddressHeader( "MIME-Version", "1.0" ); + ss << cMailMessageUtil::FormatAddressHeader("MIME-Version", "1.0"); TSTRING strDate; - if( cMailMessageUtil::ReadDate( strDate ) ) - ss << cMailMessageUtil::FormatAddressHeader( "Date", cStringUtil::TstrToStr( strDate ) ); + if (cMailMessageUtil::ReadDate(strDate)) + ss << cMailMessageUtil::FormatAddressHeader("Date", cStringUtil::TstrToStr(strDate)); std::string fromAddress; - if( ! mstrFromName.empty() ) + if (!mstrFromName.empty()) { - fromAddress = "\""; + fromAddress = "\""; fromAddress += cStringUtil::TstrToStr(mstrFromName); fromAddress += "\" <"; fromAddress += cStringUtil::TstrToStr(mstrFrom); @@ -210,10 +206,10 @@ std::string cMailMessage::Create822Header() fromAddress = cStringUtil::TstrToStr(mstrFrom); } - ss << cMailMessageUtil::FormatAddressHeader( "From", fromAddress); - ss << cMailMessageUtil::FormatAddressHeader( "To", strToList ); - ss << cMailMessageUtil::FormatNonAddressHeader( "Subject", cStringUtil::TstrToStr(mstrSubject) ); - ss << cMailMessageUtil::FormatAddressHeader( "Content-Type", "text/plain" ); + ss << cMailMessageUtil::FormatAddressHeader("From", fromAddress); + ss << cMailMessageUtil::FormatAddressHeader("To", strToList); + ss << cMailMessageUtil::FormatNonAddressHeader("Subject", cStringUtil::TstrToStr(mstrSubject)); + ss << cMailMessageUtil::FormatAddressHeader("Content-Type", "text/plain"); return ss.str(); } @@ -224,33 +220,31 @@ std::string cMailMessage::Create822Header() // gets the date in the RFC822 compliant form "Tue, 16 Mar 1999 10:53:17 -0800 (PST)" // TODO:BAM -- make windows and unix use same function -bool cMailMessageUtil::ReadDate( TSTRING& strDateBuf ) +bool cMailMessageUtil::ReadDate(TSTRING& strDateBuf) { bool fGotDate = false; #if HAVE_STRFTIME - TCHAR szDate[1024]; - struct tm *tm = NULL; - - time_t current_time = time(NULL); - tm = localtime ( ¤t_time ); - + TCHAR szDate[1024]; + time_t current_time = time(NULL); + struct tm* tm = localtime(¤t_time); + const TCHAR* szFormat = _T("%a, %d %b %Y %H:%M:%S %z"); - - size_t numChars = _tcsftime( szDate, countof( szDate ), szFormat, tm ); - - if ( numChars != 0 ) + + size_t numChars = _tcsftime(szDate, countof(szDate), szFormat, tm); + + if (numChars != 0) { strDateBuf = szDate; - fGotDate = true; + fGotDate = true; } #else - int64 now = cSystemInfo::GetExeStartTime(); + int64 now = cSystemInfo::GetExeStartTime(); strDateBuf = cTimeUtil::GetRFC822Date(cTimeUtil::TimeToDateGMT(now)); - fGotDate = true; + fGotDate = true; #endif // HAVE_STRFTIME @@ -260,16 +254,15 @@ bool cMailMessageUtil::ReadDate( TSTRING& strDateBuf ) static const char* util_Get_IANA_CharSet() { - const char* pCP = setlocale( LC_CTYPE, NULL ); + const char* pCP = setlocale(LC_CTYPE, NULL); - if( pCP && pCP[0] ) + if (pCP && pCP[0]) { std::string s = pCP; // TODO:BAM -- change this to ctype::tolower when all compilers // have a proper locale impl. or better yet move to core/twlocale.cpp - std::transform( s.begin(), s.end(), s.begin(), tolower ); - if( std::string::npos != s.find( "jp" ) || - std::string::npos != s.find( "jap" ) ) + std::transform(s.begin(), s.end(), s.begin(), tolower); + if (std::string::npos != s.find("jp") || std::string::npos != s.find("jap")) { return "ISO-2022-JP"; } @@ -277,37 +270,30 @@ static const char* util_Get_IANA_CharSet() // default return "US-ASCII"; - } -static -bool -NeedsEncoding( char ch ) +static bool NeedsEncoding(char ch) { - return( ( ch < 33 ) || - ( ch > 60 && ch < 62 ) || - ( ch > 126 ) ); + return ((ch < 33) || (ch > 60 && ch < 62) || (ch > 126)); } -static -std::string -EncodeChar( char ch ) +static std::string EncodeChar(char ch) { std::ostringstream ss; - ss.imbue( std::locale::classic() ); - ss.fill( '0' ); - ss.setf( std::ios_base::hex, std::ios_base::basefield ); - ss.width( 2 ); + ss.imbue(std::locale::classic()); + ss.fill('0'); + ss.setf(std::ios_base::hex, std::ios_base::basefield); + ss.width(2); ss << (unsigned int)(unsigned char)ch; - ASSERT( ss.str().length() == 2 ); + ASSERT(ss.str().length() == 2); // Make sure the hex is uppercase std::string s = ss.str(); - std::transform( s.begin(), s.end(), s.begin(), toupper ); + std::transform(s.begin(), s.end(), s.begin(), toupper); return s; } @@ -318,50 +304,45 @@ iMimeEncoding* iMimeEncoding::GetInstance() { #define TSS_USE_QUOTED_PRINTABLE_MIME - static iMimeEncoding* pME= + static iMimeEncoding* pME = - #if defined( TSS_USE_BASE64_MIME ) +#if defined(TSS_USE_BASE64_MIME) new cBase64Encoding; - #elif defined( TSS_USE_QUOTED_PRINTABLE_MIME ) +#elif defined(TSS_USE_QUOTED_PRINTABLE_MIME) new cQuotedPrintableEncoding; - #else - #error what is iMimeEncoding? - #endif +#else +# error what is iMimeEncoding? +#endif return pME; } // TODO:BAM -- line breaks // TODO:BAM -- ToEncoding( const std::string& sIn, int maxLineLen = -1, int maxLen = -1 ) -std::string -cQuotedPrintableEncoding::Encode( const std::string& sIn, - int maxLineLen, - int maxLen ) +std::string cQuotedPrintableEncoding::Encode(const std::string& sIn, int maxLineLen, int maxLen) { - static const size_t _CHAR_AS_HEX_LEN = 2; - static const size_t _ENCODED_CHAR_LEN = _CHAR_AS_HEX_LEN + sizeof( '=' ); + static const size_t _CHAR_AS_HEX_LEN = 2; + static const size_t _ENCODED_CHAR_LEN = _CHAR_AS_HEX_LEN + sizeof('='); std::string sOut; - sOut.resize( sIn.size() * _ENCODED_CHAR_LEN ); // optimize. one char can turn into 3 + sOut.resize(sIn.size() * _ENCODED_CHAR_LEN); // optimize. one char can turn into 3 std::string::const_iterator at; - std::string::size_type i = 0; - std::string::size_type lineLen = 0; - for( at = sIn.begin(); - at != sIn.end(); - at++, lineLen += _ENCODED_CHAR_LEN ) + std::string::size_type i = 0; + std::string::size_type lineLen = 0; + for (at = sIn.begin(); at != sIn.end(); ++at, lineLen += _ENCODED_CHAR_LEN) { - if( NeedsEncoding( *at ) ) + if (NeedsEncoding(*at)) { - ASSERT( (unsigned char)*at <= 0xFF ); + ASSERT((unsigned char)*at <= 0xFF); - std::string sTmp = EncodeChar( *at ); - ASSERT( sTmp.length() == _CHAR_AS_HEX_LEN ); + std::string sTmp = EncodeChar(*at); + ASSERT(sTmp.length() == _CHAR_AS_HEX_LEN); sOut[i++] = '='; - std::copy( &sTmp[0], &sTmp[_CHAR_AS_HEX_LEN], &sOut[i] ); - ASSERT( _CHAR_AS_HEX_LEN > 0 ); + std::copy(&sTmp[0], &sTmp[_CHAR_AS_HEX_LEN], &sOut[i]); + ASSERT(_CHAR_AS_HEX_LEN > 0); i += _CHAR_AS_HEX_LEN; } else @@ -372,7 +353,7 @@ cQuotedPrintableEncoding::Encode( const std::string& sIn, // // if string is too long, just quit // - if( maxLen != -1 && i >= maxLen - _ENCODED_CHAR_LEN ) + if (maxLen != -1 && i >= maxLen - _ENCODED_CHAR_LEN) { break; } @@ -380,26 +361,26 @@ cQuotedPrintableEncoding::Encode( const std::string& sIn, // // check line len // - if( maxLineLen != -1 && lineLen >= maxLineLen - _ENCODED_CHAR_LEN ) + if (maxLineLen != -1 && lineLen >= maxLineLen - _ENCODED_CHAR_LEN) { // append EOL sOut[i++] = '='; sOut[i++] = '\r'; sOut[i++] = '\n'; - lineLen = 0; + lineLen = 0; } } - sOut.resize( i ); + sOut.resize(i); return sOut; } -std::string cMailMessageUtil::CreateEncodedText( const std::string& text ) +std::string cMailMessageUtil::CreateEncodedText(const std::string& text) { cDebug d("cMailMessageUtil::CreateEncodedText"); - d.TraceDebug( "came in as: %s\n", text.c_str() ); + d.TraceDebug("came in as: %s\n", text.c_str()); std::string s; @@ -410,80 +391,77 @@ std::string cMailMessageUtil::CreateEncodedText( const std::string& text ) s += "?"; s += iMimeEncoding::GetInstance()->GetEncodedWordIdentifier(); s += "?"; - s += iMimeEncoding::GetInstance()->Encode( text, -1, _MAX_RFC822_HEADER_LEN ); + s += iMimeEncoding::GetInstance()->Encode(text, -1, _MAX_RFC822_HEADER_LEN); s += "?="; - ASSERT( s.length() < _MAX_RFC822_LINE_LEN - _EOL_LEN ); + ASSERT(s.length() < _MAX_RFC822_LINE_LEN - _EOL_LEN); - d.TraceDebug( "came out as: %s\n", s.c_str() ); + d.TraceDebug("came out as: %s\n", s.c_str()); return s; } // TODO:BAM -- note that address headers can only have usascii chars // TODO:BAM -- lines can only be 76 chars long -- enforce that! -std::string cMailMessageUtil::FormatAddressHeader( const std::string& name, const std::string& addr ) +std::string cMailMessageUtil::FormatAddressHeader(const std::string& name, const std::string& addr) { cDebug d("cMailMessageUtil::FormatAddressHeader"); - d.TraceDebug( "name: %s, value: %s\n", name.c_str(), addr.c_str() ); + d.TraceDebug("name: %s, value: %s\n", name.c_str(), addr.c_str()); std::string s; - + s += name; s += ": "; s += addr; s += "\r\n"; - - d.TraceDebug( "came out as: %s\n", s.c_str() ); + + d.TraceDebug("came out as: %s\n", s.c_str()); return s; } // TODO:BAM -- lines can only be 76 chars long -- enforce that! -std::string cMailMessageUtil::FormatNonAddressHeader( const std::string& name, const std::string& valC ) +std::string cMailMessageUtil::FormatNonAddressHeader(const std::string& name, const std::string& valC) { cDebug d("cMailMessageUtil::FormatNonAddressHeader"); - d.TraceDebug( "name: %s, value: %s\n", name.c_str(), valC.c_str() ); + d.TraceDebug("name: %s, value: %s\n", name.c_str(), valC.c_str()); std::string val = valC; - ASSERT( val != "To" ); - ASSERT( val != "From" ); - ASSERT( val != "Sender" ); - ASSERT( val != "cc" ); - ASSERT( val != "bcc" ); - // ... + ASSERT(val != "To"); + ASSERT(val != "From"); + ASSERT(val != "Sender"); + ASSERT(val != "cc"); + ASSERT(val != "bcc"); + // ... std::string s; - + s += name; s += ": "; - if( HasNonAsciiChars( val ) ) - s += CreateEncodedText( val ); + if (HasNonAsciiChars(val)) + s += CreateEncodedText(val); else s += val; - + s += "\r\n"; - - d.TraceDebug( "came out as: %s\n", s.c_str() ); - ASSERT( s.length() < _MAX_RFC822_LINE_LEN - _EOL_LEN ); - + d.TraceDebug("came out as: %s\n", s.c_str()); + + ASSERT(s.length() < _MAX_RFC822_LINE_LEN - _EOL_LEN); + return s; } -bool -cMailMessageUtil::HasNonAsciiChars( const std::string& s ) +bool cMailMessageUtil::HasNonAsciiChars(const std::string& s) { - for( std::string::const_iterator at = s.begin(); - at != s.end(); - at ++ ) + for (std::string::const_iterator at = s.begin(); at != s.end(); ++at) { - if( (unsigned char)*at > (unsigned char)0x7F ) + if ((unsigned char)*at > (unsigned char)0x7F) return true; } @@ -491,41 +469,40 @@ cMailMessageUtil::HasNonAsciiChars( const std::string& s ) } // converts lone \n's to \r\n -std::string& cMailMessageUtil::LFToCRLF( std::string& sIn ) +std::string& cMailMessageUtil::LFToCRLF(std::string& sIn) { cDebug d("cMailMessageUtil::LFToCRLF"); - if( sIn.empty() ) + if (sIn.empty()) return sIn; std::string sOut; - // worst case: could be just '\n's + // worst case: could be just '\n's // in which case we'd double the length - sOut.resize( sIn.size() * 2 ); + sOut.resize(sIn.size() * 2); bool lastCharCR = false; - std::string::size_type stringSize = 0; - std::string::const_iterator at; + std::string::size_type stringSize = 0; + std::string::const_iterator at; std::string::difference_type charSize; - for( at = sIn.begin(), charSize = ( (*at ? at+1 : at) - at ); - at != sIn.end(); - at += charSize, charSize = ( (*at ? at+1 : at) - at ) ) + for (at = sIn.begin(), charSize = ((*at ? at + 1 : at) - at); at != sIn.end(); + at += charSize, charSize = ((*at ? at + 1 : at) - at)) { - ASSERT( charSize > 0 ); + ASSERT(charSize > 0); - if( *at == '\n' ) + if (*at == '\n') { - if( ! lastCharCR ) + if (!lastCharCR) { - d.TraceDebug( "Adding LF\n"); + d.TraceDebug("Adding LF\n"); sOut[stringSize++] = '\r'; } lastCharCR = false; } - else if( *at == '\r') + else if (*at == '\r') { lastCharCR = true; } @@ -534,11 +511,11 @@ std::string& cMailMessageUtil::LFToCRLF( std::string& sIn ) lastCharCR = false; } - std::copy( at, at + charSize, &sOut[stringSize] ); + std::copy(at, at + charSize, &sOut[stringSize]); stringSize += charSize; } - sOut.resize( stringSize ); + sOut.resize(stringSize); sIn = sOut; return sIn; } @@ -667,8 +644,8 @@ cMailMessageUtil::ToBase64( const byte* p, size_t size ) return s; } */ -#else//RDIFALCO_BASE64_IMPLEMENTATION - +#else //RDIFALCO_BASE64_IMPLEMENTATION + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // RAD:10311999 -- A Different Try @@ -676,211 +653,193 @@ cMailMessageUtil::ToBase64( const byte* p, size_t size ) namespace /*Unique*/ { - typedef byte byte_t; +typedef byte byte_t; -#ifdef TSS_MAKE_EOL_CRLF - const byte _aszEoL[] = "\r\n"; - size_t _EOL_LEN = 2; +# ifdef TSS_MAKE_EOL_CRLF +const byte _aszEoL[] = "\r\n"; +size_t _EOL_LEN = 2; -#else - const byte _aszEoL[] = "\n"; - size_t _EOL_LEN = 1; +# else +const byte _aszEoL[] = "\n"; +size_t _EOL_LEN = 1; -#endif +# endif - const byte_t _abBase64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; +const byte_t _abBase64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; - inline - size_t - tss_base64_amplitude() // TODO: Make a Constant - { - /* +inline size_t tss_base64_amplitude() // TODO: Make a Constant +{ + /* * NOTE:RAD -- Calculate Max Incoming Bytes: * * eol_bytes = ( UINT_MAX / _MAX_RFC822_LINE_LEN ) * _EOL_LEN; * max_bytes = UINT_MAX - eol_bytes; * cvt_bytes = max_bytes / 4 * 3; */ - return (((UINT_MAX - (UINT_MAX / _MAX_RFC822_LINE_LEN * _EOL_LEN)) / 4) * 3) + 1; - } + return (((UINT_MAX - (UINT_MAX / _MAX_RFC822_LINE_LEN * _EOL_LEN)) / 4) * 3) + 1; +} - inline - size_t - tss_encode_base64_size( size_t nchSource ) - { - ASSERT( nchSource < tss_base64_amplitude() ); // NOTE: +inline size_t tss_encode_base64_size(size_t nchSource) +{ + ASSERT(nchSource < tss_base64_amplitude()); // NOTE: - /* NOTE: The formula is -- + /* NOTE: The formula is -- + bring source bytes to an even divisible of 3 (the padding bytes) + number of source bytes to converted (3:4 conversion ratio) + ( number of lines ) * ( size of end of line string ) */ - size_t nchPadding = nchSource % 3; - size_t nchOut = ((nchSource + nchPadding) / 3) * 4; - size_t nchEol = (nchOut / (_MAX_RFC822_LINE_LEN - _EOL_LEN)) * _EOL_LEN; - - return nchOut + nchEol + 2; + size_t nchPadding = nchSource % 3; + size_t nchOut = ((nchSource + nchPadding) / 3) * 4; + size_t nchEol = (nchOut / (_MAX_RFC822_LINE_LEN - _EOL_LEN)) * _EOL_LEN; + + return nchOut + nchEol + 2; +} + +void tss_encode_digit_base64(const byte_t*& pchSrc, size_t& nchSrcLeft, byte_t*& pchBuf, size_t& nchBufLeft) +{ + // NOTE:RAD -- Redundant and ugly but very fast!! + + ASSERT(nchBufLeft > 4); // One for NULL + + switch (nchSrcLeft) + { + case 0: + { + ASSERTMSG(false, "Invalid call to encode_base64_digit!"); + break; } + case 1: + { + int ch1 = int(*pchSrc++ & 0xFF); - void - tss_encode_digit_base64( - const byte_t*& pchSrc, size_t& nchSrcLeft, - byte_t*& pchBuf, size_t& nchBufLeft ) + *pchBuf++ = _abBase64[(ch1 & 0xFC) >> 2]; + *pchBuf++ = _abBase64[(ch1 & 0x03) << 4]; + *pchBuf++ = '='; + *pchBuf++ = '='; + + nchSrcLeft = 0; // NOTE: + break; + } + case 2: { - // NOTE:RAD -- Redundant and ugly but very fast!! + int ch1 = int(*pchSrc++ & 0xFF); + int ch2 = int(*pchSrc++ & 0xFF); - ASSERT( nchBufLeft > 4 ); // One for NULL + *pchBuf++ = _abBase64[((ch1 & 0xFC) >> 2)]; + *pchBuf++ = _abBase64[((ch1 & 0x03) << 4) | ((ch2 & 0xF0) >> 4)]; + *pchBuf++ = _abBase64[((ch2 & 0x0F) << 2)]; + *pchBuf++ = '='; - switch ( nchSrcLeft ) - { - case 0: - { - ASSERTMSG( false, "Invalid call to encode_base64_digit!" ); - break; - } - case 1: - { - int ch1 = int( *pchSrc++ & 0xFF ); + nchSrcLeft = 0; // NOTE: + break; + } + default: + { - *pchBuf++ = _abBase64[ (ch1 & 0xFC) >> 2 ]; - *pchBuf++ = _abBase64[ (ch1 & 0x03) << 4 ]; - *pchBuf++ = '='; - *pchBuf++ = '='; + int ch1 = int(*pchSrc++ & 0xFF); + int ch2 = int(*pchSrc++ & 0xFF); + int ch3 = int(*pchSrc++ & 0xFF); - nchSrcLeft = 0; // NOTE: - break; - } - case 2: - { - int ch1 = int( *pchSrc++ & 0xFF ); - int ch2 = int( *pchSrc++ & 0xFF ); + *pchBuf++ = _abBase64[((ch1 & 0xFC) >> 2)]; + *pchBuf++ = _abBase64[((ch1 & 0x03) << 4) | ((ch2 & 0xF0) >> 4)]; + *pchBuf++ = _abBase64[((ch2 & 0x0F) << 2) | ((ch3 & 0xC0) >> 6)]; + *pchBuf++ = _abBase64[(ch3 & 0x3F)]; - *pchBuf++ = _abBase64[ ( (ch1 & 0xFC) >> 2 ) ]; - *pchBuf++ = _abBase64[ ( (ch1 & 0x03) << 4 ) | ( (ch2 & 0xF0) >> 4 ) ]; - *pchBuf++ = _abBase64[ ( (ch2 & 0x0F) << 2 ) ]; - *pchBuf++ = '='; + nchSrcLeft -= 3; // NOTE: Probably greater than 3 + break; + } + } - nchSrcLeft = 0; // NOTE: - break; - } - default: - { + nchBufLeft -= 4; // Always the same due to padding! +}; - int ch1 = int( *pchSrc++ & 0xFF ); - int ch2 = int( *pchSrc++ & 0xFF ); - int ch3 = int( *pchSrc++ & 0xFF ); - *pchBuf++ = _abBase64[ ( (ch1 & 0xFC) >> 2 ) ]; - *pchBuf++ = _abBase64[ ( (ch1 & 0x03) << 4 ) | ( (ch2 & 0xF0) >> 4 ) ]; - *pchBuf++ = _abBase64[ ( (ch2 & 0x0F) << 2 ) | ( (ch3 & 0xC0) >> 6 ) ]; - *pchBuf++ = _abBase64[ ( ch3 & 0x3F ) ]; +size_t tss_encode_base64(const byte_t* pchSource, size_t nchSource, byte_t* pchBuffer, size_t nchBuffer) +{ + const size_t _ERROR = std::string::npos; // -1; - nchSrcLeft -= 3; // NOTE: Probably greater than 3 - break; - } - } - nchBufLeft -= 4; // Always the same due to padding! - }; + //--Assert Preconditions + if (pchSource == 0 || nchSource == 0) + return _ERROR; - size_t - tss_encode_base64( - const byte_t* pchSource, size_t nchSource, - byte_t* pchBuffer, size_t nchBuffer ) - { - const size_t _ERROR = std::string::npos; // -1; - - //--Assert Preconditions + //--If pchBuffer == 0, User is requesting Size - if ( pchSource == 0 || nchSource == 0 ) - return _ERROR; - - - //--If pchBuffer == 0, User is requesting Size - - size_t nchBuf = tss_encode_base64_size( nchSource ); + size_t nchBuf = tss_encode_base64_size(nchSource); - if ( pchBuffer == 0 ) // Requesting Size - return nchBuf; + if (pchBuffer == 0) // Requesting Size + return nchBuf; - if ( nchBuf > nchBuffer ) // DOH!! - return _ERROR; - + if (nchBuf > nchBuffer) // DOH!! + return _ERROR; - //--Get three characters at a time and encode them (watching linelen) - byte_t* pchBuf = ( pchBuffer + 0 ); - const byte_t* pchSrc = ( pchSource + 0 ); - + //--Get three characters at a time and encode them (watching linelen) - const size_t _max_linelen = ( _MAX_RFC822_LINE_LEN - _EOL_LEN ); - size_t nLineLen = 0; - - for ( ; nchSource; ) - { - // Like iconv: Increment pointers and decrement sizes - tss_encode_digit_base64( pchSrc, nchSource, pchBuf, nchBuf ); + byte_t* pchBuf = (pchBuffer + 0); + const byte_t* pchSrc = (pchSource + 0); - nLineLen += 4; - if ( nchSource == 0 || nLineLen > _max_linelen ) - { - nLineLen = 0; // RESET: + const size_t _max_linelen = (_MAX_RFC822_LINE_LEN - _EOL_LEN); + size_t nLineLen = 0; - const byte_t* pchEol = &_aszEoL[0]; - while ( *pchEol ) - *pchBuf++ = *pchEol++; - } - } + for (; nchSource;) + { + // Like iconv: Increment pointers and decrement sizes + tss_encode_digit_base64(pchSrc, nchSource, pchBuf, nchBuf); + + nLineLen += 4; - *pchBuf = 0x00; // CAUTION: Null Terminate!!! + if (nchSource == 0 || nLineLen > _max_linelen) + { + nLineLen = 0; // RESET: - return ( pchBuf - pchBuffer ); + const byte_t* pchEol = &_aszEoL[0]; + while (*pchEol) + *pchBuf++ = *pchEol++; + } } -}//Unique:: + + *pchBuf = 0x00; // CAUTION: Null Terminate!!! + + return (pchBuf - pchBuffer); +} +} // namespace const std::string::value_type* -cMailMessageUtil::ConvertBase64( - std::string& sEncode, - const byte_t* pchSrc, - size_t nchSrc ) +cMailMessageUtil::ConvertBase64(std::string& sEncode, const byte_t* pchSrc, size_t nchSrc) { - size_t nch = tss_encode_base64( pchSrc, nchSrc, 0, 0 ); // Like mbstowcs + size_t nch = tss_encode_base64(pchSrc, nchSrc, 0, 0); // Like mbstowcs - sEncode.reserve( nch ); // Make it big enough but don't resize - sEncode.resize( 0 ); // String must be clean in case of exception! - - const char* - pch = sEncode.c_str(); // Get Pointer (won't change) + sEncode.reserve(nch); // Make it big enough but don't resize + sEncode.resize(0); // String must be clean in case of exception! - size_t nLength = // Action - tss_encode_base64( - pchSrc, nchSrc, (byte_t*)pch, nch ); + const char* pch = sEncode.c_str(); // Get Pointer (won't change) - if ( nLength == std::string::npos ) + size_t nLength = // Action + tss_encode_base64(pchSrc, nchSrc, (byte_t*)pch, nch); + + if (nLength == std::string::npos) throw std::bad_alloc(); - sEncode.resize( nLength ); // Now it's okay to resize - - return pch; // So user can do stuff like "out << ConvertBase64()"; + sEncode.resize(nLength); // Now it's okay to resize + + return pch; // So user can do stuff like "out << ConvertBase64()"; } -std::string -cMailMessageUtil::ToBase64( const byte_t* pchSrc, size_t nchSrc ) +std::string cMailMessageUtil::ToBase64(const byte_t* pchSrc, size_t nchSrc) { // NOTE: It sucks to use std::string this way! Should be // passed in by reference. std::string sucks; - cMailMessageUtil::ConvertBase64( sucks, pchSrc, nchSrc ); + cMailMessageUtil::ConvertBase64(sucks, pchSrc, nchSrc); return sucks; } -#endif//RDIFALCO_BASE64_IMPLEMENTATION - +#endif //RDIFALCO_BASE64_IMPLEMENTATION diff --git a/src/tripwire/mailmessage.h b/src/tripwire/mailmessage.h index 866d389..871dcd0 100644 --- a/src/tripwire/mailmessage.h +++ b/src/tripwire/mailmessage.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,38 +36,37 @@ #include "core/error.h" #endif +#if IS_REDOX +# define restrict __restrict__ +#endif -#if IS_UNIX +#if SUPPORTS_NETWORKING && HAVE_SYS_SOCKET_H #include -#define SOCKET int #endif +#define SOCKET int /////////////////////////////////////////////////////////////////////////////// // // This error class is thrown by cMailMessage and its derivatives. // -TSS_EXCEPTION( eMailMessageError, eError ); +TSS_EXCEPTION(eMailMessageError, eError); // SMTP -TSS_EXCEPTION( eMailSMTPWinsockDidNotStart, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPWinsockUnloadable, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPWinsockCleanup, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPIPUnresolvable, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPSocket, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPOpenConnection, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPCloseConnection, eMailMessageError ); -TSS_EXCEPTION( eMailSMTPServer, eMailMessageError ); - -// MAPI -TSS_EXCEPTION( eMailMAPINotAvailable, eMailMessageError ); -TSS_EXCEPTION( eMailMAPIUnload, eMailMessageError ); -TSS_EXCEPTION( eMailMAPISend, eMailMessageError ); +TSS_EXCEPTION(eMailSMTPWinsockDidNotStart, eMailMessageError); +TSS_EXCEPTION(eMailSMTPWinsockUnloadable, eMailMessageError); +TSS_EXCEPTION(eMailSMTPWinsockCleanup, eMailMessageError); +TSS_EXCEPTION(eMailSMTPIPUnresolvable, eMailMessageError); +TSS_EXCEPTION(eMailSMTPSocket, eMailMessageError); +TSS_EXCEPTION(eMailSMTPOpenConnection, eMailMessageError); +TSS_EXCEPTION(eMailSMTPCloseConnection, eMailMessageError); +TSS_EXCEPTION(eMailSMTPServer, eMailMessageError); +TSS_EXCEPTION(eMailSMTPNotSupported, eMailMessageError); // piped -TSS_EXCEPTION( eMailPipedOpen, eMailMessageError ); -TSS_EXCEPTION( eMailPipedWrite, eMailMessageError ); -TSS_EXCEPTION( eMailPipedCmdFailed, eMailMessageError ); +TSS_EXCEPTION(eMailPipedOpen, eMailMessageError); +TSS_EXCEPTION(eMailPipedWrite, eMailMessageError); +TSS_EXCEPTION(eMailPipedCmdFailed, eMailMessageError); /////////////////////////////////////////////////////////////////////////////// // @@ -82,11 +81,11 @@ class cMailMessage virtual ~cMailMessage(); void AddRecipient(const TSTRING& strRecipient); - void SetFrom (const TSTRING& strFrom); - void SetFromName (const TSTRING& strFromName); - void SetSubject (const TSTRING& strSubject); - void SetBody (const TSTRING& strBody); - void AttachFile (const TSTRING& strFullPath); + void SetFrom(const TSTRING& strFrom); + void SetFromName(const TSTRING& strFromName); + void SetSubject(const TSTRING& strSubject); + void SetBody(const TSTRING& strBody); + void AttachFile(const TSTRING& strFullPath); virtual bool Send() = 0; //throw(eMailMessageError) // returns true upon success @@ -98,27 +97,24 @@ class cMailMessage INVALID_METHOD, MAIL_BY_SMTP, MAIL_BY_PIPE, - MAIL_BY_MAPI, MAIL_NUM_ITEMS }; -protected: - - - TSTRING mstrFrom; - TSTRING mstrFromName; - TSTRING mstrSubject; - TSTRING mstrBody; - std::vector mvstrRecipients; - std::vector mvstrAttachments; +protected: + TSTRING mstrFrom; + TSTRING mstrFromName; + TSTRING mstrSubject; + TSTRING mstrBody; + std::vector mvstrRecipients; + std::vector mvstrAttachments; - // Returns true if enough things have been set so that a useful + // Returns true if enough things have been set so that a useful // email message can be sent - bool Ready(); - std::string Create822Header(); - // creates 822 header with info from the class - bool GetAttachmentsAsString( std::string& s ); + bool Ready(); + std::string Create822Header(); + // creates 822 header with info from the class + bool GetAttachmentsAsString(std::string& s); }; class cMailMessageUtil @@ -126,94 +122,89 @@ class cMailMessageUtil public: enum - { - _MAX_RFC822_LINE_LEN = 76, + { + _MAX_RFC822_LINE_LEN = 76, _MAX_RFC822_HEADER_LEN = 76, - _EOL_LEN = 2 + _EOL_LEN = 2 }; - static - const std::string::value_type* - ConvertBase64( std::string&, const byte*, size_t ); + static const std::string::value_type* ConvertBase64(std::string&, const byte*, size_t); - static bool HasNonAsciiChars( const std::string& s ); - static std::string CreateEncodedText( const std::string& text ); - - static std::string FormatAddressHeader( const std::string& name, const std::string& addr ); - static std::string FormatNonAddressHeader( const std::string& name, const std::string& val ); + static bool HasNonAsciiChars(const std::string& s); + static std::string CreateEncodedText(const std::string& text); - static bool ReadDate( TSTRING& strDateBuf ); - static std::string& LFToCRLF( std::string& s ); - // converts lone \n's to \r\n + static std::string FormatAddressHeader(const std::string& name, const std::string& addr); + static std::string FormatNonAddressHeader(const std::string& name, const std::string& val); + static bool ReadDate(TSTRING& strDateBuf); + static std::string& LFToCRLF(std::string& s); + // converts lone \n's to \r\n }; class iMimeEncoding { public: - virtual ~iMimeEncoding() {} - - virtual - std::string - Encode( const std::string& sIn, - int maxLineLen = -1, - int maxLen = -1 ) = 0; - // -1 means no limit - - virtual - std::string - GetEncodedWordIdentifier() = 0; - - virtual - std::string - GetContentTypeIdentifier() = 0; - - static iMimeEncoding* GetInstance(); + virtual ~iMimeEncoding() + { + } + + virtual std::string Encode(const std::string& sIn, int maxLineLen = -1, int maxLen = -1) = 0; + // -1 means no limit + + virtual std::string GetEncodedWordIdentifier() = 0; + + virtual std::string GetContentTypeIdentifier() = 0; + + static iMimeEncoding* GetInstance(); }; // TODO:BAM -- convert ToBase64 to Encode class cBase64Encoding : public iMimeEncoding { public: - virtual ~cBase64Encoding() {} - - virtual - std::string - Encode( const std::string& sIn, - int maxLineLen = -1, - int maxLen = -1 ) { ASSERT( false ); return ""; }; - - virtual - std::string - GetEncodedWordIdentifier() { return "B"; }; - - virtual - std::string - GetContentTypeIdentifier() { return "base64"; }; + virtual ~cBase64Encoding() + { + } + + virtual std::string Encode(const std::string& sIn, int maxLineLen = -1, int maxLen = -1) + { + ASSERT(false); + return ""; + }; + + virtual std::string GetEncodedWordIdentifier() + { + return "B"; + }; + + virtual std::string GetContentTypeIdentifier() + { + return "base64"; + }; }; class cQuotedPrintableEncoding : public iMimeEncoding { public: - virtual ~cQuotedPrintableEncoding() {} - - virtual - std::string - Encode( const std::string& sIn, - int maxLineLen = -1, - int maxLen = -1 ); - - virtual - std::string - GetEncodedWordIdentifier() { return "Q"; }; - - virtual - std::string - GetContentTypeIdentifier() { return "quoted-printable"; }; -}; + virtual ~cQuotedPrintableEncoding() + { + } + virtual std::string Encode(const std::string& sIn, int maxLineLen = -1, int maxLen = -1); + + virtual std::string GetEncodedWordIdentifier() + { + return "Q"; + }; + virtual std::string GetContentTypeIdentifier() + { + return "quoted-printable"; + }; +}; + +#if SUPPORTS_NETWORKING /////////////////////////////////////////////////////////////////////////////// // // This class implements sending a message via SMTP @@ -221,72 +212,16 @@ class cQuotedPrintableEncoding : public iMimeEncoding class cSMTPMailMessage : public cMailMessage { public: - cSMTPMailMessage(TSTRING strServerName, unsigned short portNumber); virtual ~cSMTPMailMessage(); virtual bool Send(); //throw(eMailMessageError) - // returns true upon success + // returns true upon success private: - // socket related member variables - SOCKET mSocket; - -#if USES_WINSOCK - // - // Types for the functions in winsock.dll - // - // These function prototypes and the pointers that use them allow us to use - // winsock without requiring the DLL to be on the end system for the application - // to run. It seems unacceptable for tripwire to fail to run at all if wsock32.dll - // is not present on the system. - // - HINSTANCE mHlibWinsock; - typedef int (PASCAL * WSASTARTUPPROC) (WORD wVersionRequired, LPWSADATA lpWSAData); - typedef SOCKET (PASCAL * SOCKETPROC) (int af, int type, int protocol); - typedef unsigned long (PASCAL * INETADDRPROC) (const char FAR * cp); - typedef int (PASCAL FAR * GETHOSTNAMEPROC) (char FAR * name, int namelen); - typedef struct hostent FAR * (PASCAL * GETHOSTBYNAMEPROC)(const char FAR * name); - typedef int (PASCAL * CONNECTPROC) (SOCKET s, const struct sockaddr FAR *name, int namelen); - typedef int (PASCAL * CLOSESOCKETPROC) (SOCKET s); - typedef int (PASCAL * SENDPROC) (SOCKET s, const char FAR * buf, int len, int flags); - typedef int (PASCAL * RECVPROC) (SOCKET s, char FAR * buf, int len, int flags); - typedef int (PASCAL * SELECTPROC) (int nfds, fd_set FAR * readfds, fd_set FAR * writefds, fd_set FAR * exceptfds, const struct timeval FAR * timeout); - typedef u_long (PASCAL * LONGPROC) (u_long netlong); - typedef u_short (PASCAL * SHORTPROC) (u_short netlong); - - // pointers to the functions in wsock32.dll - - // Berkeley functions - SOCKETPROC mPfnSocket; - INETADDRPROC mPfnInetAddr; - GETHOSTNAMEPROC mPfnGethostname; - GETHOSTBYNAMEPROC mPfnGethostbyname; - CONNECTPROC mPfnConnect; - CLOSESOCKETPROC mPfnCloseSocket; - SENDPROC mPfnSend; - RECVPROC mPfnRecv; - SELECTPROC mPfnSelect; - - // winsock functions - FARPROC mPfnWSAGetLastError; - WSASTARTUPPROC mPfnWSAStartup; - FARPROC mPfnWSACleanup; - - // Endian convertion functions - LONGPROC mPfnNtohl; - LONGPROC mPfnHtonl; - SHORTPROC mPfnNtohs; - SHORTPROC mPfnHtons; - - // Methods to set the pointers to functions. - bool LoadDll(); - bool UnloadDll(); - -#endif - - void SendString( const std::string& str ); + SOCKET mSocket; + void SendString(const std::string& str); // methods common to windows and unix: bool OpenConnection(); @@ -302,76 +237,38 @@ class cSMTPMailMessage : public cMailMessage void DecodeError(); // the settings necessary for an SMTP connection: - TSTRING mstrServerName; + TSTRING mstrServerName; unsigned short mPortNumber; }; - - -#if SUPPORTS_MAPI - - -/////////////////////////////////////////////////////////////////////////////// -// -// This class implements sending a message via MAPI under Win32 -// -class cMAPIMailMessage : public cMailMessage -{ -public: - - cMAPIMailMessage(); - virtual ~cMAPIMailMessage(); - - virtual bool Send(); //throw(eMailMessageError) - //returns true upon success - -private: - - bool InitMAPI(); - bool FinitMAPI(); - - HINSTANCE hlibMAPI; - - bool DoSendMessage(); - void PrintMAPIErrorMessage(ULONG errorMessage); -}; - #endif - -//#ifdef IS_UNIX - /////////////////////////////////////////////////////////////////////////////// // -// This class implements sending a message through a unix pipe to a program +// This class implements sending a message through a unix pipe to a program // like 'sendmail' // class cPipedMailMessage : public cMailMessage { public: - cPipedMailMessage(TSTRING strSendMailExePath); + explicit cPipedMailMessage(const TSTRING& strSendMailExePath); virtual ~cPipedMailMessage(); virtual bool Send(); //throw(eMailMessageError) - // returns true upon success + // returns true upon success private: + TSTRING& CreateHeader(TSTRING& strHeaderBuf) const; - TSTRING& CreateHeader( TSTRING& strHeaderBuf ) const; - - void SendInit();// throw (eMailMessageError) + void SendInit(); // throw (eMailMessageError) // opens a pipe to sendmail and writes the header. - - FILE* GetFilePointer() const; - // returns a pointer to the current file pointer. Only valid between - // SendInit() and SendFinit() - - void SendFinit(); //throw (eMailMessageError) + + void SendFinit(); //throw (eMailMessageError) // closes the file descriptor, sending the rest of the message - bool SendAttachments(); - // called between SendInit and SendFinit to send the attachments + bool SendAttachments(); + // called between SendInit and SendFinit to send the attachments - void SendString( const TSTRING& s ); + void SendString(const TSTRING& s); TSTRING mstrSendMailExePath; FILE* mpFile; // only valid with Init/Finit and Send @@ -380,4 +277,3 @@ class cPipedMailMessage : public cMailMessage //#endif #endif // __MAILMESSAGE_H - diff --git a/src/tripwire/pipedmailmessage.cpp b/src/tripwire/pipedmailmessage.cpp index 9fbb753..eddc1ce 100644 --- a/src/tripwire/pipedmailmessage.cpp +++ b/src/tripwire/pipedmailmessage.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,10 +49,10 @@ // // Constructor. Not much to do beside initialize the handle to the DLL // -cPipedMailMessage::cPipedMailMessage(TSTRING strSendMailExePath) +cPipedMailMessage::cPipedMailMessage(const TSTRING& strSendMailExePath) { mstrSendMailExePath = strSendMailExePath; - mpFile = NULL; + mpFile = NULL; } @@ -72,38 +72,37 @@ cPipedMailMessage::~cPipedMailMessage() bool cPipedMailMessage::Send() { // Be sure that everything that needs to be set has been set - if (!Ready()) + if (!Ready()) { // the message has not been adequately defined and cannot be sent. return false; } SendInit(); - - FILE* sendPipe = GetFilePointer(); - ASSERT( sendPipe != 0 ); - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + ASSERT(mpFile != 0); + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Get Body and Attachments //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // get body - std::string sNBody = cStringUtil::TstrToStr( mstrBody ); + std::string sNBody = cStringUtil::TstrToStr(mstrBody); // get attachments std::string sAttachments; - if( ! GetAttachmentsAsString( sAttachments ) ) + if (!GetAttachmentsAsString(sAttachments)) { sAttachments.erase(); } - + std::string sSend = sNBody + sAttachments; - + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Make sure that there's no lone LFs //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cMailMessageUtil::LFToCRLF( sSend ); + cMailMessageUtil::LFToCRLF(sSend); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Determine encoding needed for body or attachments @@ -111,18 +110,17 @@ bool cPipedMailMessage::Send() std::string sContentType = "Content-Transfer-Encoding: "; - if( cMailMessageUtil::HasNonAsciiChars( sSend ) ) + if (cMailMessageUtil::HasNonAsciiChars(sSend)) { // encode text - sSend = iMimeEncoding::GetInstance()->Encode( sSend, - cMailMessageUtil::_MAX_RFC822_LINE_LEN ); + sSend = iMimeEncoding::GetInstance()->Encode(sSend, cMailMessageUtil::_MAX_RFC822_LINE_LEN); // identify content type sContentType += iMimeEncoding::GetInstance()->GetContentTypeIdentifier(); } else { - // do no encoding + // do no encoding // identify content type sContentType += "7bit"; @@ -130,14 +128,14 @@ bool cPipedMailMessage::Send() // send content type sContentType += "\r\n"; - SendString( cStringUtil::StrToTstr( sContentType ) ); + SendString(cStringUtil::StrToTstr(sContentType)); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Send Body and Attachments //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SendString( _T("\r\n") ); - SendString( cStringUtil::StrToTstr( sSend ) ); + SendString(_T("\r\n")); + SendString(cStringUtil::StrToTstr(sSend)); SendFinit(); @@ -148,42 +146,38 @@ bool cPipedMailMessage::Send() /////////////////////////////////////////////////////////////////////////////// // SendInit /////////////////////////////////////////////////////////////////////////////// -void cPipedMailMessage::SendInit()// throw( eMailMessageError ) +void cPipedMailMessage::SendInit() // throw( eMailMessageError ) { ASSERT(mpFile == 0); TSTRING strHeader; - strHeader += cStringUtil::StrToTstr( cMailMessage::Create822Header() ); + strHeader += cStringUtil::StrToTstr(cMailMessage::Create822Header()); #if !USES_MPOPEN - // Call _wpopen under NT - // TODO access the risk of _wpopen under NT - mpFile = _wpopen(mstrSendMailExePath.c_str(), _T("w")); + mpFile = popen(mstrSendMailExePath.c_str(), _T("w")); #else // call mpopen, our safe version popen - mpFile = mpopen( (char*) mstrSendMailExePath.c_str(), _T("w") ); + mpFile = mpopen((char*)mstrSendMailExePath.c_str(), _T("w")); #endif - if(! mpFile) + if (!mpFile) { TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND ) - << mstrSendMailExePath; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND) << mstrSendMailExePath; - throw eMailPipedOpen( estr.str() ); + throw eMailPipedOpen(estr.str()); } - SendString( strHeader ); + SendString(strHeader); } -void cPipedMailMessage::SendString( const TSTRING& s ) +void cPipedMailMessage::SendString(const TSTRING& s) { - if( _ftprintf( mpFile, "%s", s.c_str() ) < 0 ) + if (_ftprintf(mpFile, "%s", s.c_str()) < 0) { TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND ) - << mstrSendMailExePath; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND) << mstrSendMailExePath; - throw eMailPipedOpen( estr.str() ); + throw eMailPipedOpen(estr.str()); } } @@ -192,29 +186,21 @@ void cPipedMailMessage::SendString( const TSTRING& s ) /////////////////////////////////////////////////////////////////////////////// void cPipedMailMessage::SendFinit() //throw ( eMailMessageError ) { - if(mpFile) + if (mpFile) { #if !USES_MPOPEN - int result = fclose( mpFile ); + int result = fclose(mpFile); #else - int result = mpclose( mpFile ); + int result = mpclose(mpFile); #endif - if( result != 0 ) + if (result != 0) { TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND ) - << mstrSendMailExePath; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND) << mstrSendMailExePath; // uh oh! something bad has happened! - throw eMailPipedCmdFailed( estr.str() ); - } + throw eMailPipedCmdFailed(estr.str()); + } } mpFile = 0; } - - -FILE* cPipedMailMessage::GetFilePointer() const -{ - return mpFile; -} - diff --git a/src/tripwire/policyupdate.cpp b/src/tripwire/policyupdate.cpp index 8d5dab2..d4c9d69 100644 --- a/src/tripwire/policyupdate.cpp +++ b/src/tripwire/policyupdate.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,15 +46,15 @@ #include "fco/genreswitcher.h" /////////////////////////////////////////////////////////////////////////////// -// util_FCOInSpecList -- given a spec list and an fco name, return true if the +// util_FCOInSpecList -- given a spec list and an fco name, return true if the // name belongs in one of the specs /////////////////////////////////////////////////////////////////////////////// -static bool util_FCOInSpecList( const cFCOSpecList& specList, const cFCOName& name ) +static bool util_FCOInSpecList(const cFCOSpecList& specList, const cFCOName& name) { - cFCOSpecListCanonicalIter iter( specList ); - for( iter.SeekBegin(); ! iter.Done(); iter.Next() ) + cFCOSpecListCanonicalIter iter(specList); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - if( iter.Spec()->SpecContainsFCO( name ) ) + if (iter.Spec()->SpecContainsFCO(name)) return true; } return false; @@ -65,33 +65,32 @@ static bool util_FCOInSpecList( const cFCOSpecList& specList, const cFCOName& na // util_PruneExtraObjects -- checks every object in the database against the // provided spec set and adds them to the vector if they don't fall under any specs. /////////////////////////////////////////////////////////////////////////////// -static void util_PruneExtraObjects( cDbDataSourceIter iter, cFCOSpecListCanonicalIter specIter, - bool bFirst = true ) +static void util_PruneExtraObjects(cDbDataSourceIter iter, cFCOSpecListCanonicalIter specIter, bool bFirst = true) { - if( ! bFirst ) + if (!bFirst) { iter.Descend(); } - for( iter.SeekBegin(); ! iter.Done(); /*iter.Next()*/ ) + for (iter.SeekBegin(); !iter.Done(); /*iter.Next()*/) { // process our children first... // - if( iter.CanDescend() ) + if (iter.CanDescend()) { - util_PruneExtraObjects( iter, specIter, false ); + util_PruneExtraObjects(iter, specIter, false); } - - if( iter.HasFCOData() ) + + if (iter.HasFCOData()) { // figure out if this fco fits in the new policy // bool bFoundSpec = false; - for( specIter.SeekBegin(); ! specIter.Done(); specIter.Next() ) + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { - if( specIter.Spec()->SpecContainsFCO( iter.GetName() ) ) + if (specIter.Spec()->SpecContainsFCO(iter.GetName())) { // this doesn't belong in the new db; remove it! // @@ -99,25 +98,25 @@ static void util_PruneExtraObjects( cDbDataSourceIter iter, cFCOSpecListCanonica break; } } - if( ! bFoundSpec ) + if (!bFoundSpec) { - TW_NOTIFY_VERBOSE( _T("--- %s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_DB_REMOVING ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( iter.GetName() ).c_str() ); + TW_NOTIFY_VERBOSE( + _T("--- %s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_DB_REMOVING).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(iter.GetName()).c_str()); iter.RemoveFCOData(); } } // // remove the infrastructure, if appropriate... - // this is also where the iterator incrementing occurs, so we need to + // this is also where the iterator incrementing occurs, so we need to // be careful with the Next()s // - if( ! iter.HasFCOData() ) + if (!iter.HasFCOData()) { - if( iter.CanDescend() && iter.CanRemoveChildArray() ) + if (iter.CanDescend() && iter.CanRemoveChildArray()) iter.RemoveChildArray(); - if( ! iter.CanDescend() ) + if (!iter.CanDescend()) iter.RemoveFCO(); else iter.Next(); @@ -131,88 +130,90 @@ static void util_PruneExtraObjects( cDbDataSourceIter iter, cFCOSpecListCanonica /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cPolicyUpdate::cPolicyUpdate( cGenre::Genre genreNum, const cFCOSpecList& oldPolicy, const cFCOSpecList& newPolicy, - cHierDatabase& db, cErrorBucket* pBucket ) -: mOldPolicy ( oldPolicy ), - mNewPolicy ( newPolicy ), - mDb ( db ), - mGenre ( genreNum ), - mpBucket ( pBucket ) +cPolicyUpdate::cPolicyUpdate(cGenre::Genre genreNum, + const cFCOSpecList& oldPolicy, + const cFCOSpecList& newPolicy, + cHierDatabase& db, + cErrorBucket* pBucket) + : mOldPolicy(oldPolicy), mNewPolicy(newPolicy), mDb(db), mGenre(genreNum), mpBucket(pBucket) { - } /////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// -bool cPolicyUpdate::Execute( uint32 flags ) // throw (eError) +bool cPolicyUpdate::Execute(uint32 flags) // throw (eError) { // here is my current idea for the algorithm: first, do an integrity check with the new policy on the database and // a special flag passed to Execute() to modify what properties are checked. Then, take the resulting // report print to the user its contents, minus any violations that don't make sense to report (see my EPS for - // details on what doesn't get displayed) Finally, do a database update with the full report, making sure that - // properties that were from the policy are also removed from existing FCOs in the database ( I might need to + // details on what doesn't get displayed) Finally, do a database update with the full report, making sure that + // properties that were from the policy are also removed from existing FCOs in the database ( I might need to // add a parameter to DbUpdate to accomodate that). // // first, do the integrity check with the new database... // - TW_NOTIFY_NORMAL( TSS_GetString( cTripwire, tripwire::STR_PU_PROCESSING_GENRE ).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( cGenreSwitcher::GetInstance()->CurrentGenre(), true ) ); - TW_NOTIFY_NORMAL( TSS_GetString( cTripwire, tripwire::STR_PU_INTEGRITY_CHECK ).c_str() ); + TW_NOTIFY_NORMAL(TSS_GetString(cTripwire, tripwire::STR_PU_PROCESSING_GENRE).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(cGenreSwitcher::GetInstance()->CurrentGenre(), true)); + TW_NOTIFY_NORMAL(TSS_GetString(cTripwire, tripwire::STR_PU_INTEGRITY_CHECK).c_str()); // - iFCONameTranslator* pTrans = iTWFactory::GetInstance()->GetNameTranslator(); - bool bResult = true; // begin by assuming success - cFCOReport report; - cIntegrityCheck ic( mGenre, mNewPolicy, mDb, report, mpBucket ); - + iFCONameTranslator* pTrans = iTWFactory::GetInstance()->GetNameTranslator(); + bool bResult = true; // begin by assuming success + cFCOReport report; + cIntegrityCheck ic(mGenre, mNewPolicy, mDb, report, mpBucket); + // // set up flags for the property calculator and iterators - // - uint32 icFlags = cIntegrityCheck::FLAG_COMPARE_VALID_PROPS_ONLY | - cIntegrityCheck::FLAG_INVALIDATE_EXTRA_DB_PROPS | + // + uint32 icFlags = cIntegrityCheck::FLAG_COMPARE_VALID_PROPS_ONLY | cIntegrityCheck::FLAG_INVALIDATE_EXTRA_DB_PROPS | cIntegrityCheck::FLAG_SET_NEW_PROPS; - if( flags & FLAG_ERASE_FOOTPRINTS_PU ) + if (flags & FLAG_ERASE_FOOTPRINTS_PU) { icFlags |= cIntegrityCheck::FLAG_ERASE_FOOTPRINTS_IC; } - ic.Execute( icFlags ); - //TODO-- the second flag I just added probably makes the flag to cUpdateDb::Execute() unnecessary; - // I should probably remove it. + if (flags & FLAG_DIRECT_IO) + { + icFlags |= cIntegrityCheck::FLAG_DIRECT_IO; + } + + ic.Execute(icFlags); + //TODO-- the second flag I just added probably makes the flag to cUpdateDb::Execute() unnecessary; + // I should probably remove it. // - // Note that I will probably end up making two passes through the report (one for reporting to the user and one for - // the db update). I don't think there is a clean way to do this in a single report pass, other than rewriting + // Note that I will probably end up making two passes through the report (one for reporting to the user and one for + // the db update). I don't think there is a clean way to do this in a single report pass, other than rewriting // db update, which I am not going to do. // - cFCOReportSpecIter specIter( report, mGenre ); - for( specIter.SeekBegin(); ! specIter.Done(); specIter.Next() ) + cFCOReportSpecIter specIter(report, mGenre); + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { // notify the user of what we are doing... - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_PROCESSING ).c_str(), - pTrans->ToStringDisplay( specIter.GetSpec()->GetStartPoint() ).c_str() ); + TW_NOTIFY_VERBOSE(_T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_PROCESSING).c_str(), + pTrans->ToStringDisplay(specIter.GetSpec()->GetStartPoint()).c_str()); // // report objects in the added set should only be reported if they fall in a spec // in the old policy // - iFCOSet* pAddSet = specIter.GetAddedSet(); - const cIterProxy pIter = pAddSet->GetIter(); - for( pIter->SeekBegin(); ! pIter->Done(); pIter->Next() ) + iFCOSet* pAddSet = specIter.GetAddedSet(); + const cIterProxy pIter = pAddSet->GetIter(); + for (pIter->SeekBegin(); !pIter->Done(); pIter->Next()) { - if( util_FCOInSpecList( mOldPolicy, pIter->FCO()->GetName() ) ) + if (util_FCOInSpecList(mOldPolicy, pIter->FCO()->GetName())) { // this is an error that should be reported to the user. - ePolicyUpdateAddedFCO e( pTrans->ToStringDisplay( pIter->FCO()->GetName() ) ); - if( (flags & ANAL) == 0 ) - e.SetFlags( eError::NON_FATAL ); + ePolicyUpdateAddedFCO e(pTrans->ToStringDisplay(pIter->FCO()->GetName())); + if ((flags & FLAG_SECURE_MODE) == 0) + e.SetFlags(eError::NON_FATAL); else - e.SetFlags( eError::SUPRESS_THIRD_MSG ); - mpBucket->AddError( e ); + e.SetFlags(eError::SUPRESS_THIRD_MSG); + mpBucket->AddError(e); bResult = false; } } @@ -220,72 +221,72 @@ bool cPolicyUpdate::Execute( uint32 flags ) // throw (eError) // objects in the removed set should only be reported if they fall in a spec in the // new policy.. // - iFCOSet* pRmSet = specIter.GetRemovedSet(); - const cIterProxy pRmIter = pRmSet->GetIter(); - for( pRmIter->SeekBegin(); ! pRmIter->Done(); pRmIter->Next() ) + iFCOSet* pRmSet = specIter.GetRemovedSet(); + const cIterProxy pRmIter = pRmSet->GetIter(); + for (pRmIter->SeekBegin(); !pRmIter->Done(); pRmIter->Next()) { - if( util_FCOInSpecList( mNewPolicy, pRmIter->FCO()->GetName() ) ) + if (util_FCOInSpecList(mNewPolicy, pRmIter->FCO()->GetName())) { // this is an error that should be reported to the user. - ePolicyUpdateRemovedFCO e( pTrans->ToStringDisplay( pRmIter->FCO()->GetName() ) ); + ePolicyUpdateRemovedFCO e(pTrans->ToStringDisplay(pRmIter->FCO()->GetName())); - if( (flags & ANAL) == 0 ) - e.SetFlags( eError::NON_FATAL ); + if ((flags & FLAG_SECURE_MODE) == 0) + e.SetFlags(eError::NON_FATAL); else - e.SetFlags( eError::SUPRESS_THIRD_MSG ); - mpBucket->AddError( e ); + e.SetFlags(eError::SUPRESS_THIRD_MSG); + mpBucket->AddError(e); bResult = false; } } // // every object in the changed set should be document.... // - cFCOReportChangeIter changeIter( specIter ); - for( changeIter.SeekBegin(); ! changeIter.Done(); changeIter.Next() ) + cFCOReportChangeIter changeIter(specIter); + for (changeIter.SeekBegin(); !changeIter.Done(); changeIter.Next()) { //---------------------------------------------------------------- - // I need to construct a string that contains all of the - // property names that have changed. + // I need to construct a string that contains all of the + // property names that have changed. //---------------------------------------------------------------- - TSTRING badPropStr = TSS_GetString( cTripwire, tripwire::STR_PU_BAD_PROPS ); - - badPropStr += pTrans->ToStringDisplay( changeIter.GetOld()->GetName() ); + TSTRING badPropStr = TSS_GetString(cTripwire, tripwire::STR_PU_BAD_PROPS); + + badPropStr += pTrans->ToStringDisplay(changeIter.GetOld()->GetName()); const cFCOPropVector& changeVector = changeIter.GetChangeVector(); - for(int i=0; i < changeVector.GetSize(); i++) + for (int i = 0; i < changeVector.GetSize(); i++) { - if(changeVector.ContainsItem(i)) + if (changeVector.ContainsItem(i)) { - badPropStr += _T("\n> "); + badPropStr += _T("\n> "); badPropStr += changeIter.GetOld()->GetPropSet()->GetPropName(i); } } // add this to the error bucket - ePolicyUpdateChangedFCO e( badPropStr ); - if( (flags & ANAL) == 0 ) - e.SetFlags( eError::NON_FATAL ); + ePolicyUpdateChangedFCO e(badPropStr); + if ((flags & FLAG_SECURE_MODE) == 0) + e.SetFlags(eError::NON_FATAL); else - e.SetFlags( eError::SUPRESS_THIRD_MSG ); - mpBucket->AddError( e ); + e.SetFlags(eError::SUPRESS_THIRD_MSG); + mpBucket->AddError(e); bResult = false; } } // // now, we will update the database with everything in the report... - // TODO -- don't do this if the anal flag was passed in + // TODO -- don't do this if the secure mode flag was passed in // - TW_NOTIFY_NORMAL( TSS_GetString( cTripwire, tripwire::STR_PU_UPDATE_DB ).c_str() ); + TW_NOTIFY_NORMAL(TSS_GetString(cTripwire, tripwire::STR_PU_UPDATE_DB).c_str()); // - cUpdateDb update( mDb, report, mpBucket ); - + cUpdateDb update(mDb, report, mpBucket); + uint32 updateDBFlags = cUpdateDb::FLAG_REPLACE_PROPS; - if( flags & FLAG_ERASE_FOOTPRINTS_PU ) + if (flags & FLAG_ERASE_FOOTPRINTS_PU) { updateDBFlags |= cUpdateDb::FLAG_ERASE_FOOTPRINTS_UD; } - update.Execute( updateDBFlags ); - + update.Execute(updateDBFlags); + // the last thing that we have to do is to remove everything that is still // in the database that does not belong in the new database (ie -- does not fall under any // new rules) @@ -294,18 +295,18 @@ bool cPolicyUpdate::Execute( uint32 flags ) // throw (eError) // TODO -- I should probably write a general-purpose database iterator class to do this... // - TW_NOTIFY_NORMAL( TSS_GetString( cTripwire, tripwire::STR_PU_PRUNING ).c_str() ); + TW_NOTIFY_NORMAL(TSS_GetString(cTripwire, tripwire::STR_PU_PRUNING).c_str()); // - cDbDataSourceIter i( &mDb ); + cDbDataSourceIter i(&mDb); i.SetErrorBucket(mpBucket); - - if( flags & FLAG_ERASE_FOOTPRINTS_PU ) + + if (flags & FLAG_ERASE_FOOTPRINTS_PU) { - i.SetIterFlags( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); + i.SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); } - const cFCOSpecListCanonicalIter newPolIter( mNewPolicy ); - util_PruneExtraObjects( i, newPolIter ); + + const cFCOSpecListCanonicalIter newPolIter(mNewPolicy); + util_PruneExtraObjects(i, newPolIter); return bResult; } - diff --git a/src/tripwire/policyupdate.h b/src/tripwire/policyupdate.h index 4611b3d..1c6b2e1 100644 --- a/src/tripwire/policyupdate.h +++ b/src/tripwire/policyupdate.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,28 +51,34 @@ class cErrorBucket; //////////////////////////////////////////////////////////// // Policy Update Exceptions //////////////////////////////////////////////////////////// -TSS_EXCEPTION( ePolicyUpdate, eError ); -TSS_EXCEPTION( ePolicyUpdateAddedFCO, ePolicyUpdate ); -TSS_EXCEPTION( ePolicyUpdateRemovedFCO, ePolicyUpdate ); -TSS_EXCEPTION( ePolicyUpdateChangedFCO, ePolicyUpdate ); +TSS_EXCEPTION(ePolicyUpdate, eError); +TSS_EXCEPTION(ePolicyUpdateAddedFCO, ePolicyUpdate); +TSS_EXCEPTION(ePolicyUpdateRemovedFCO, ePolicyUpdate); +TSS_EXCEPTION(ePolicyUpdateChangedFCO, ePolicyUpdate); class cPolicyUpdate { public: - cPolicyUpdate( cGenre::Genre genreNum, const cFCOSpecList& oldPolicy, const cFCOSpecList& newPolicy, - cHierDatabase& db, cErrorBucket* pBucket ); + cPolicyUpdate(cGenre::Genre genreNum, + const cFCOSpecList& oldPolicy, + const cFCOSpecList& newPolicy, + cHierDatabase& db, + cErrorBucket* pBucket); - bool Execute( uint32 flags = 0 ) ; // throw (eError) + bool Execute(uint32 flags = 0); // throw (eError) // if false is returned, then there was at least one conflict that came up during the policy - // update, and if tripwire was run in anal mode then the policy update should fail. + // update, and if tripwire was run in secure mode then the policy update should fail. enum Flags { - ANAL = 0x00000001, // if this is set, then we are in anal mode. This affects whether error - // messages appear as "Error" or "Warning" - FLAG_ERASE_FOOTPRINTS_PU= 0x00000002 - // when this flag is set, cPolicyUpdate will attempt undo any inadvertant modifications - // it may make when executing. + FLAG_SECURE_MODE = 0x00000001, // if this is set, then we're in pedantic mode. This affects whether error + // messages appear as "Error" or "Warning" + FLAG_ERASE_FOOTPRINTS_PU = 0x00000002, + // when this flag is set, cPolicyUpdate will attempt undo any inadvertant modifications + // it may make when executing. + + FLAG_DIRECT_IO = 0x00000004 + // Use direct i/o when scanning files }; private: @@ -84,4 +90,3 @@ class cPolicyUpdate }; #endif //__POLICYUPDATE_H - diff --git a/src/tripwire/resource.h b/src/tripwire/resource.h index fbe9e46..f68b707 100644 --- a/src/tripwire/resource.h +++ b/src/tripwire/resource.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,13 +35,12 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 +# ifndef APSTUDIO_READONLY_SYMBOLS +# define _APS_NEXT_RESOURCE_VALUE 102 +# define _APS_NEXT_COMMAND_VALUE 40001 +# define _APS_NEXT_CONTROL_VALUE 1000 +# define _APS_NEXT_SYMED_VALUE 101 +# endif #endif -#endif - diff --git a/src/tripwire/smtpmailmessage.cpp b/src/tripwire/smtpmailmessage.cpp index ea01129..d51ae7e 100644 --- a/src/tripwire/smtpmailmessage.cpp +++ b/src/tripwire/smtpmailmessage.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,87 +37,95 @@ #include "tripwirestrings.h" #include "core/stringutil.h" #include -#include "core/msystem.h" #include "core/file.h" -#if IS_UNIX - #include +#if SUPPORTS_NETWORKING + //All the spleck that it takes to run sockets in Unix... #include -#include +# if HAVE_SYS_SOCKET_H +# include +# include +# include +# include +# endif #include #include -#include -#include -#include -#include -#ifdef _SORTIX_SOURCE -# include -#endif +# if HAVE_SYS_UTSNAME_H +# include +# endif + +# if HAVE_SYS_SELECT_H +# include +# endif /* Some systems like Solaris and AIX don't define * INADDR_NONE, but it's pretty standard. If not, * then the OS _should_ define it for us. */ -#ifndef INADDR_NONE -#define INADDR_NONE 0xffffffff -#endif +# ifndef INADDR_NONE +# define INADDR_NONE 0xffffffff +# endif #include -#define INVALID_SOCKET -1 +# define INVALID_SOCKET -1 -#ifdef __AROS__ - #ifndef HAVE_GETHOSTNAME - #define HAVE_GETHOSTNAME 1 - #endif -#endif +# if IS_AROS +# ifndef HAVE_GETHOSTNAME +# define HAVE_GETHOSTNAME 1 +# endif +# endif -#ifndef HAVE_GETHOSTNAME -static int gethostname( char* name, int namelen ) +# ifndef HAVE_GETHOSTNAME +static int gethostname(char* name, int namelen) { name[0] = '\0'; - + +# if HAVE_SYS_UTSNAME_H struct utsname myname; - uname( & myname ); - - if ( strlen( myname.nodename ) < (unsigned int)namelen ) + uname(&myname); + + if (strlen(myname.nodename) < (unsigned int)namelen) { - strcpy( name, myname.nodename ); + strncpy(name, myname.nodename, namelen); return 0; } else { //Not enough room in the buffer for the nodename return -1; - // equivalent of SOCKET_ERROR + // equivalent of SOCKET_ERROR } +# else + strncpy(name, "localhost", namelen); +# endif } -#endif - // Unix does not require us to go though any silly DLL hoops, so we'll - // just #define the pointers to functions needed by Windows to be the - // berkely functions. - #define mPfnSocket socket - #define mPfnInetAddr inet_addr - #define mPfnGethostname gethostname - #define mPfnGethostbyname gethostbyname - #define mPfnConnect connect - #define mPfnCloseSocket close - #define mPfnSend send - #define mPfnRecv recv - #define mPfnSelect select - #define mPfnNtohl ntohl - #define mPfnHtonl htonl - #define mPfnNtohs ntohs - #define mPfnHtons htons -#endif +# endif //HAVE_GETHOSTNAME + +// Unix does not require us to go though any silly DLL hoops, so we'll +// just #define the pointers to functions needed by Windows to be the +// berkely functions. +# define mPfnSocket socket +# define mPfnInetAddr inet_addr +# define mPfnGethostname gethostname +# define mPfnGethostbyname gethostbyname +# define mPfnConnect connect +# define mPfnCloseSocket close +# define mPfnSend send +# define mPfnRecv recv +# define mPfnSelect select +# define mPfnNtohl ntohl +# define mPfnHtonl htonl +# define mPfnNtohs ntohs +# define mPfnHtons htons // // TODO - maybe convert this SMTP code to non-blocking socket calls, or use -// another thread, or make it fail gracefully when the server fails to +// another thread, or make it fail gracefully when the server fails to // respond at all. // @@ -127,32 +135,9 @@ static int gethostname( char* name, int namelen ) // cSMTPMailMessage::cSMTPMailMessage(TSTRING strServerName, unsigned short portNumber) { - mstrServerName = strServerName; - mPortNumber = portNumber; - mSocket = INVALID_SOCKET; - -#if USES_WINSOCK - mHlibWinsock = NULL; - - mPfnSocket = NULL; - mPfnInetAddr = NULL; - mPfnGethostname = NULL; - mPfnGethostbyname = NULL; - mPfnConnect = NULL; - mPfnCloseSocket = NULL; - mPfnSend = NULL; - mPfnRecv = NULL; - mPfnSelect = NULL; - - mPfnWSAStartup = NULL; - mPfnWSACleanup = NULL; - mPfnWSAGetLastError = NULL; - - mPfnNtohl = NULL; - mPfnHtonl = NULL; - mPfnNtohs = NULL; - mPfnHtons = NULL; -#endif // USES_WINSOCK + mstrServerName = strServerName; + mPortNumber = portNumber; + mSocket = INVALID_SOCKET; } @@ -165,12 +150,10 @@ cSMTPMailMessage::~cSMTPMailMessage() } - - /////////////////////////////////////////////////////////////////////////////// // -// Get the IP address from the the server string. It's OK to have -// this function look up a string like "192.34.64.23" or one like +// Get the IP address from the the server string. It's OK to have +// this function look up a string like "192.34.64.23" or one like // "mail.stinkycheese.com" // long cSMTPMailMessage::GetServerAddress() @@ -179,9 +162,9 @@ long cSMTPMailMessage::GetServerAddress() // Decide if the string is in the form "127.0.0.1" or "mail.domain.com" // by looking for an character that is not a digit or a period. - for (std::vector::size_type i=0; i < mstrServerName.length(); i++) + for (std::vector::size_type i = 0; i < mstrServerName.length(); i++) { - if (mstrServerName[i] != '.' && (mstrServerName[i]<'0' || mstrServerName[i]>'9')) + if (mstrServerName[i] != '.' && (mstrServerName[i] < '0' || mstrServerName[i] > '9')) { bIsNumeric = false; } @@ -191,21 +174,25 @@ long cSMTPMailMessage::GetServerAddress() if (bIsNumeric) { +# ifndef HAVE_SYS_SOCKET_H + return 0; +# else // convert the numberic address to a long return mPfnInetAddr(sNarrowString.c_str()); +# endif } else { -#ifdef _SORTIX_SOURCE +# if IS_SORTIX || !defined(HAVE_SYS_SOCKET_H) return INADDR_NONE; -#else +# else // do a DNS lookup of the hostname and get the long - hostent *ent = mPfnGethostbyname(sNarrowString.c_str()); + hostent* ent = mPfnGethostbyname(sNarrowString.c_str()); if (!ent) return INADDR_NONE; else - return *(long *)ent->h_addr_list[0]; -#endif + return *(long*)ent->h_addr_list[0]; +# endif } } @@ -216,31 +203,32 @@ long cSMTPMailMessage::GetServerAddress() // bool cSMTPMailMessage::OpenConnection() { +# ifndef HAVE_SYS_SOCKET_H + return false; +# else // Initialize the socket structure sockaddr_in sockAddrIn; memset(&sockAddrIn, 0, sizeof(sockaddr)); - sockAddrIn.sin_family = AF_INET; - sockAddrIn.sin_port = mPfnHtons(mPortNumber); + sockAddrIn.sin_family = AF_INET; + sockAddrIn.sin_port = mPfnHtons(mPortNumber); uint32 iServerAddress = GetServerAddress(); -#if IS_UNIX sockAddrIn.sin_addr.s_addr = iServerAddress; -#endif - if ( iServerAddress == INADDR_NONE ) + + if (iServerAddress == INADDR_NONE) { DecodeError(); TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER ) - << mstrServerName; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER) << mstrServerName; throw eMailSMTPIPUnresolvable(estr.str()); return false; } - + // Create the socket mSocket = mPfnSocket(AF_INET, SOCK_STREAM, 0); - if (mSocket == INVALID_SOCKET) + if (mSocket == INVALID_SOCKET) { DecodeError(); throw eMailSMTPSocket(); @@ -248,20 +236,20 @@ bool cSMTPMailMessage::OpenConnection() } // Make the connection - int connectVal = mPfnConnect(mSocket, (struct sockaddr *)&sockAddrIn, sizeof(sockAddrIn)); - if (connectVal < 0) + int connectVal = mPfnConnect(mSocket, (struct sockaddr*)&sockAddrIn, sizeof(sockAddrIn)); + if (connectVal < 0) { DecodeError(); TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER ) - << mstrServerName; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER) << mstrServerName; throw eMailSMTPOpenConnection(estr.str()); return false; } return true; +# endif } @@ -271,11 +259,11 @@ bool cSMTPMailMessage::OpenConnection() // bool cSMTPMailMessage::CloseConnection() { - if ( INVALID_SOCKET != mSocket ) + if (INVALID_SOCKET != mSocket) { // close the connection int closeVal = mPfnCloseSocket(mSocket); - if (closeVal != 0) + if (closeVal != 0) { DecodeError(); throw eMailSMTPCloseConnection(); @@ -298,7 +286,7 @@ bool cSMTPMailMessage::CloseConnection() bool cSMTPMailMessage::Send() { // Be sure that everything that needs to be set has been set - if (!Ready()) + if (!Ready()) { // the message has not been adequately defined and cannot be sent. return false; @@ -319,36 +307,37 @@ bool cSMTPMailMessage::Send() /////////////////////////////////////////////////////////////////////////////// -// -// Once the connection is set, this function conducts the SMTP protocol +// +// Once the connection is set, this function conducts the SMTP protocol // to actually send the message. // bool cSMTPMailMessage::MailMessage() { - cDebug d("cSMTPMailMessage::MailMessage()"); + cDebug d("cSMTPMailMessage::MailMessage()"); std::string sNarrowString; // Get the greeting message from the SMTP server if (!GetAcknowledgement()) return false; - char sLocalHost[256]; // It's alright for this to be a fixed buffer, since - // we will be explicitely passing it's length to - // mpfnGethostname (see below). It won't be used - // after that. + char sLocalHost[256]; // It's alright for this to be a fixed buffer, since + // we will be explicitely passing it's length to + // mpfnGethostname (see below). It won't be used + // after that. std::ostringstream strmSend; - // This should be a stream object, so we don't have - // to use nasty calls to sprintf that might overflow - // the buffer. Before, we used a fixed buffer of 512 - // characters, and there's really no guarantee that any - // of the string objects (that we are printing to the buffer - // from) will be below this limit. + // This should be a stream object, so we don't have + // to use nasty calls to sprintf that might overflow + // the buffer. Before, we used a fixed buffer of 512 + // characters, and there's really no guarantee that any + // of the string objects (that we are printing to the buffer + // from) will be below this limit. - ASSERT( strmSend.str().length() == 0 ); // This bad boy better be empty. + ASSERT(strmSend.str().length() == 0); // This bad boy better be empty. // get our hostname for the HELO message - if (mPfnGethostname(sLocalHost, 256) < 0 ) { + if (mPfnGethostname(sLocalHost, 256) < 0) + { DecodeError(); return false; } @@ -358,31 +347,27 @@ bool cSMTPMailMessage::MailMessage() //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Say hello - strmSend.str(""); //Clear the stream buffer. - strmSend << "HELO " << sLocalHost << "\r\n"; //Fill the stream buffer. - SendString( strmSend.str() ); + strmSend.str(""); //Clear the stream buffer. + strmSend << "HELO " << sLocalHost << "\r\n"; //Fill the stream buffer. + SendString(strmSend.str()); if (!GetAcknowledgement()) return false; - strmSend.str(""); //Clear the stream buffer. - strmSend << "MAIL FROM:<" - << cStringUtil::TstrToStr(mstrFrom) - << ">\r\n"; - SendString( strmSend.str() ); + strmSend.str(""); //Clear the stream buffer. + strmSend << "MAIL FROM:<" << cStringUtil::TstrToStr(mstrFrom) << ">\r\n"; + SendString(strmSend.str()); if (!GetAcknowledgement()) return false; // Say who all we're sending to - strmSend.str(""); //Clear the stream buffer. - for (std::vector::size_type i=0; i::size_type i = 0; i < mvstrRecipients.size(); i++) { sNarrowString = cStringUtil::TstrToStr(mvstrRecipients[i]); - strmSend << "RCPT TO:<" - << cStringUtil::TstrToStr(mvstrRecipients[i]) - << ">\r\n"; + strmSend << "RCPT TO:<" << cStringUtil::TstrToStr(mvstrRecipients[i]) << ">\r\n"; - SendString( strmSend.str() ); + SendString(strmSend.str()); if (!GetAcknowledgement()) return false; @@ -393,10 +378,10 @@ bool cSMTPMailMessage::MailMessage() //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Send start the message process - SendString( "DATA\r\n" ); + SendString("DATA\r\n"); if (!GetAcknowledgement()) return false; - + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Send Header //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -404,7 +389,7 @@ bool cSMTPMailMessage::MailMessage() // set up header strmSend.str(""); strmSend << cMailMessage::Create822Header(); - SendString( strmSend.str() ); + SendString(strmSend.str()); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Get Body and Attachments @@ -414,23 +399,23 @@ bool cSMTPMailMessage::MailMessage() // get body - std::string sNBody = cStringUtil::TstrToStr( mstrBody ); + std::string sNBody = cStringUtil::TstrToStr(mstrBody); std::string sAttachments; - if( ! GetAttachmentsAsString( sAttachments ) ) + if (!GetAttachmentsAsString(sAttachments)) { sAttachments.erase(); allOK = false; } - + std::string sSend = sNBody + sAttachments; - + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Make sure that there's no lone LFs //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cMailMessageUtil::LFToCRLF( sSend ); + cMailMessageUtil::LFToCRLF(sSend); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Determine encoding needed for body or attachments @@ -438,18 +423,17 @@ bool cSMTPMailMessage::MailMessage() std::string sContentType = "Content-Transfer-Encoding: "; - if( cMailMessageUtil::HasNonAsciiChars( sSend ) ) + if (cMailMessageUtil::HasNonAsciiChars(sSend)) { // encode text - sSend = iMimeEncoding::GetInstance()->Encode( sSend, - cMailMessageUtil::_MAX_RFC822_LINE_LEN ); + sSend = iMimeEncoding::GetInstance()->Encode(sSend, cMailMessageUtil::_MAX_RFC822_LINE_LEN); // identify content type sContentType += iMimeEncoding::GetInstance()->GetContentTypeIdentifier(); } else { - // do no encoding + // do no encoding // identify content type sContentType += "7bit"; @@ -457,22 +441,22 @@ bool cSMTPMailMessage::MailMessage() // send content type sContentType += "\r\n"; - SendString( sContentType ); + SendString(sContentType); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Send Body and Attachments //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SendString( "\r\n" ); - SendString( sSend ); + SendString("\r\n"); + SendString(sSend); // send the end of message line - SendString( "\r\n.\r\n" ); + SendString("\r\n.\r\n"); if (!GetAcknowledgement()) return false; // send the quit message - SendString( "QUIT" ); + SendString("QUIT"); return allOK; } @@ -485,54 +469,51 @@ bool cSMTPMailMessage::MailMessage() // bool cSMTPMailMessage::GetAcknowledgement() { - cDebug d( "cSMTPMailMessage::GetAcknowledgement" ); +# ifndef HAVE_SYS_SOCKET_H + return false; +# else + cDebug d("cSMTPMailMessage::GetAcknowledgement"); const int bufsize = 512; - TCHAR sRecvString[bufsize+1]; // This string is and should be unicode - char sTempString[bufsize+1]; // This string is not, and should not be unicode + TCHAR sRecvString[bufsize + 1]; // This string is and should be unicode + char sTempString[bufsize + 1]; // This string is not, and should not be unicode int bytes; - int i=0; + int i = 0; // make socket array for the call to select fd_set socketSet; // need comment timeval tv; - -#if IS_UNIX - FD_ZERO( &socketSet ); - FD_SET( mSocket, &socketSet ); -#else - socketSet.fd_count = 1; - socketSet.fd_array[0] = mSocket; -#endif + FD_ZERO(&socketSet); + FD_SET(mSocket, &socketSet); // set the timeout time to sixty seconds - tv.tv_sec = 60; + tv.tv_sec = 60; tv.tv_usec = 0; // Wait up to sixty seconds fot data to show up on the socket to be read - if (mPfnSelect(mSocket+1, &socketSet, NULL, NULL, &tv) == 1) + if (mPfnSelect(mSocket + 1, &socketSet, NULL, NULL, &tv) == 1) { // Get the reply message bytes = mPfnRecv(mSocket, sTempString, 512, 0); - + // TODO:BAM -- this should be changed to use 'cStringUtil' - for (int j=0; j= 200 && code < 400) + if (code >= 200 && code < 400) { // Error codes in the range of 200-399 indicate success. See RFC 821 return true; @@ -541,125 +522,38 @@ bool cSMTPMailMessage::GetAcknowledgement() { // Error codes other than 200-399 indicate an error or a failure. See RFC 821 TOSTRINGSTREAM estr; - estr << TSS_GetString( cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR ) - << sRecvString; + estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR) << sRecvString; throw eMailSMTPServer(estr.str()); return false; } +# endif } -void cSMTPMailMessage::SendString( const std::string& str ) +void cSMTPMailMessage::SendString(const std::string& str) { cDebug d("util_SendString()"); - - if( str.length() < 800 ) - d.TraceDebug( "Sending \"%s\"\n", str.c_str() ); +# if HAVE_SYS_SOCKET_H + if (str.length() < 800) + d.TraceDebug("Sending \"%s\"\n", str.c_str()); else - d.TraceDebug( "Sending (truncated in this debug output)\"%s\"\n", std::string( str.c_str(), 800 ).c_str() ); - mPfnSend( mSocket, str.c_str(), str.length(), 0 ); + d.TraceDebug("Sending (truncated in this debug output)\"%s\"\n", std::string(str.c_str(), 800).c_str()); + mPfnSend(mSocket, str.c_str(), str.length(), 0); +# endif } - /////////////////////////////////////////////////////////////////////////////// // // Get debug info when a error is encountered. // void cSMTPMailMessage::DecodeError() { -#if defined(_DEBUG) - -#if USES_WINSOCK - // - // decode an error condition encountered by Windows sockets. - // TODO - write something less technical to explain what when wrong. Windows - // message names are not good error strings for a shipping product. - // - int error = mPfnWSAGetLastError(); - fprintf(stderr, "Encountered winsock error message %d", error); - struct ErrorStruct - { - const char *msg; - int error; - } - static const errors[52] = - { - { "WSAEINTR", (WSABASEERR+4) }, - { "WSAEBADF", (WSABASEERR+9) }, - { "WSAEACCES", (WSABASEERR+13) }, - { "WSAEFAULT", (WSABASEERR+14) }, - { "WSAEINVAL", (WSABASEERR+22) }, - { "WSAEMFILE", (WSABASEERR+24) }, - { "WSAEWOULDBLOCK", (WSABASEERR+35) }, - { "WSAEINPROGRESS", (WSABASEERR+36) }, - { "WSAEALREADY", (WSABASEERR+37) }, - { "WSAENOTSOCK", (WSABASEERR+38) }, - { "WSAEDESTADDRREQ", (WSABASEERR+39) }, - { "WSAEMSGSIZE", (WSABASEERR+40) }, - { "WSAEPROTOTYPE", (WSABASEERR+41) }, - { "WSAENOPROTOOPT", (WSABASEERR+42) }, - { "WSAEPROTONOSUPPORT", (WSABASEERR+43) }, - { "WSAESOCKTNOSUPPORT", (WSABASEERR+44) }, - { "WSAEOPNOTSUPP", (WSABASEERR+45) }, - { "WSAEPFNOSUPPORT", (WSABASEERR+46) }, - { "WSAEAFNOSUPPORT", (WSABASEERR+47) }, - { "WSAEADDRINUSE", (WSABASEERR+48) }, - { "WSAEADDRNOTAVAIL", (WSABASEERR+49) }, - { "WSAENETDOWN", (WSABASEERR+50) }, - { "WSAENETUNREACH", (WSABASEERR+51) }, - { "WSAENETRESET", (WSABASEERR+52) }, - { "WSAECONNABORTED", (WSABASEERR+53) }, - { "WSAECONNRESET", (WSABASEERR+54) }, - { "WSAENOBUFS", (WSABASEERR+55) }, - { "WSAEISCONN", (WSABASEERR+56) }, - { "WSAENOTCONN", (WSABASEERR+57) }, - { "WSAESHUTDOWN", (WSABASEERR+58) }, - { "WSAETOOMANYREFS", (WSABASEERR+59) }, - { "WSAETIMEDOUT", (WSABASEERR+60) }, - { "WSAECONNREFUSED", (WSABASEERR+61) }, - { "WSAELOOP", (WSABASEERR+62) }, - { "WSAENAMETOOLONG", (WSABASEERR+63) }, - { "WSAEHOSTDOWN", (WSABASEERR+64) }, - { "WSAEHOSTUNREACH", (WSABASEERR+65) }, - { "WSAENOTEMPTY", (WSABASEERR+66) }, - { "WSAEPROCLIM", (WSABASEERR+67) }, - { "WSAEUSERS", (WSABASEERR+68) }, - { "WSAEDQUOT", (WSABASEERR+69) }, - { "WSAESTALE", (WSABASEERR+70) }, - { "WSAEREMOTE", (WSABASEERR+71) }, - { "WSAEDISCON", (WSABASEERR+101) }, - { "WSASYSNOTREADY", (WSABASEERR+91) }, - { "WSAVERNOTSUPPORTED", (WSABASEERR+92) }, - { "WSANOTINITIALISED", (WSABASEERR+93) }, - { "WSAHOST_NOT_FOUND", (WSABASEERR+1001) }, - { "WSATRY_AGAIN", (WSABASEERR+1002) }, - { "WSANO_RECOVERY", (WSABASEERR+1003) }, - { "WSANO_DATA", (WSABASEERR+1004) }, - { NULL, 0 } - }; - - int i = 0; - while (errors[i].msg) - { - if (errors[i].error == error) - { - fprintf(stderr, ": %s", errors[i].msg); - break; - } - i++; - } - fprintf(stderr, "\n"); -#endif // USES_WINSOCK - -#if IS_UNIX - +# if defined(_DEBUG) // // TODO - Write what ever error reporting will be needed under unix. // - -#endif // IS_UNIX - -#endif // defined(_DEBUG) +# endif // defined(_DEBUG) } +#endif // SUPPORTS_NETWORKING diff --git a/src/tripwire/stdtripwire.cpp b/src/tripwire/stdtripwire.cpp index 76e5c8c..bd81c10 100644 --- a/src/tripwire/stdtripwire.cpp +++ b/src/tripwire/stdtripwire.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // // #include "stdtripwire.h" - -// eof: stdtripwire.cpp diff --git a/src/tripwire/stdtripwire.h b/src/tripwire/stdtripwire.h index e62786d..606ad50 100644 --- a/src/tripwire/stdtripwire.h +++ b/src/tripwire/stdtripwire.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/tripwire/syslog_trip.cpp b/src/tripwire/syslog_trip.cpp index 1beec9e..95d44a3 100644 --- a/src/tripwire/syslog_trip.cpp +++ b/src/tripwire/syslog_trip.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,7 +34,7 @@ // #include "stdtripwire.h" -#include "syslog_trip.h" +#include "syslog_trip.h" #if HAVE_SYSLOG_H #include @@ -44,213 +44,33 @@ #include #endif -#if SUPPORTS_EVENTLOG -#include "tripwiremsg.h" -#include "tw/systeminfo.h" -#endif - // next three includes are for error reporting #include "tw/twutil.h" #include "tw/twerrors.h" #include "tw/twstrings.h" -#ifdef __AROS__ - #include - #define openlog(a,b,c) - #define closelog() +#if IS_AROS +#include +# define openlog(a, b, c) +# define closelog() #endif /////////////////////////////////////////////////////////////////////////////// // Syslog /////////////////////////////////////////////////////////////////////////////// - -#if SUPPORTS_EVENTLOG -static void InitEventLog(); -#endif - void cSyslog::Log(const TCHAR* programName, cSyslog::LogType logType, const TCHAR* message) { -#if HAVE_SYSLOG_H +// SkyOS has syslog.h but doesn't actually implement the calls. +#if SUPPORTS_SYSLOG (void)logType; // logType is not used for Unix syslog -#ifdef _UNICODE - std::basic_string identString; - std::basic_string msgString; - int count; - - count = sizeof(char) * MB_CUR_MAX * _tcslen(programName); // note we use sizeof(char) * 2 because mb chars can be two bytes long - identString.resize(count); - count = wcstombs((char*)identString.data(), programName, count); - identString.resize(count); // count will be set to number of bytes written - - count = sizeof(char) * MB_CUR_MAX * _tcslen(message); - msgString.resize(count); - count = wcstombs((char*)msgString.data(), message, count); - msgString.resize(count); - - const char* ident = programName.data(); - const char* msg = message.data(); -#else ASSERT(sizeof(TCHAR) == sizeof(char)); const char* ident = programName; - const char* msg = message; -#endif + const char* msg = message; -#ifndef SKYOS // Handle an oddball OS that has syslog.h but doesn't implement the calls. openlog(ident, LOG_PID, LOG_USER); syslog(LOG_NOTICE, "%s", msg); closelog(); #endif - -#elif SUPPORTS_EVENTLOG - - static bool eventLogInitialized = false; - if (!eventLogInitialized) - { - InitEventLog(); - eventLogInitialized = true; - } - - HANDLE h = RegisterEventSource(NULL, _T("Tripwire")); - if (h != NULL) - { - LPCTSTR stringArray[1]; - stringArray[0] = message; - - WORD type; - DWORD id; - - switch (logType) - { - default: - ASSERT(false); - case LOG_SUCCESS: - type = EVENTLOG_INFORMATION_TYPE; - id = MSG_TRIPWIRE_GENERIC_SUCCESS; - break; - case LOG_INFORMATION: - type = EVENTLOG_INFORMATION_TYPE; - id = MSG_TRIPWIRE_GENERIC_INFO; - break; - case LOG_WARNING: - type = EVENTLOG_WARNING_TYPE; - id = MSG_TRIPWIRE_GENERIC_WARNING; - break; - case LOG_ERROR: - type = EVENTLOG_ERROR_TYPE; - id = MSG_TRIPWIRE_GENERIC_ERROR; - break; - } - - BOOL ret = ReportEvent( - h, - type, // event type - 0, // catagory - id, // event id - 0, // user sid - 1, // num strings - 0, // raw binary data size - stringArray, // array of strings - 0 // raw binrary data - ); - - if (!ret) - { - eTWSyslog e( TSS_GetString(cTW, tw::STR_REPORTEVENT_FAILED).c_str(), eError::NON_FATAL ); - cTWUtil::PrintErrorMsg(e); - } - - DeregisterEventSource(h); - } - -#else - // No support for syslog like functionality - //ASSERT(false); -#endif -} - - -#if SUPPORTS_EVENTLOG -static void InitEventLog() -{ - // To initialize the event log, we need to verify that Tripwire - // is a valid event source. - // To do this we look up the value for the Tripwire event source. If it - // exists, the the dest is a file called "tripwire.exe" (or this executable) and the - // file exists, then we assume that the event source is set correctly. - - HKEY hKey; - DWORD disposition; - - if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\Tripwire"), 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disposition) == ERROR_SUCCESS && - disposition == REG_OPENED_EXISTING_KEY) - { - DWORD type, count; - - // We need to insure we have back slashes in our exepath - TSTRING exepath = cSystemInfo::GetExePath(); - TSTRING::iterator i; - for (i = exepath.begin(); i != exepath.end(); ++i) - if (*i == _T('/')) - *i = _T('\\'); - - if (RegQueryValueEx(hKey, _T("TypesSupported"), 0, &type, 0, &count) == ERROR_SUCCESS && - type == REG_DWORD && - RegQueryValueEx(hKey, _T("EventMessageFile"), 0, &type, 0, &count) == ERROR_SUCCESS && - type == REG_EXPAND_SZ) - { - TSTRING data; - data.resize(count); - if (RegQueryValueEx(hKey, _T("EventMessageFile"), 0, &type, (LPBYTE)data.data(), &count) == ERROR_SUCCESS && - type == REG_EXPAND_SZ) - { - TSTRING::size_type lastDelimitor; - lastDelimitor = data.find_last_of(_T('\\')); - if (lastDelimitor == TSTRING::npos) - lastDelimitor = (TSTRING::size_type)-1; - - if (_tcscmp(exepath.c_str(), data.c_str()) == 0) - { - RegCloseKey(hKey); - return; - } - - if (_tcsicmp(_T("tripwire.exe"), data.substr(lastDelimitor + 1).c_str()) == 0) - { - HINSTANCE hInst = LoadLibraryEx(data.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES|LOAD_LIBRARY_AS_DATAFILE); - if (hInst != NULL) - { - FreeLibrary(hInst); - RegCloseKey(hKey); - return; - } - } - } - } - - // If we got here then the event source is not set up correctly - - // Add the name to the EventMessageFile subkey. - RegSetValueEx(hKey, // subkey handle - _T("EventMessageFile"), // value name - 0, // must be zero - REG_EXPAND_SZ, // value type - (LPBYTE) exepath.c_str(), // pointer to value data - sizeof(TCHAR)*(exepath.length() + 1)); // length of value data - - // Set the supported event types in the TypesSupported subkey. - DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; - - RegSetValueEx(hKey, // subkey handle - _T("TypesSupported"), // value name - 0, // must be zero - REG_DWORD, // value type - (LPBYTE) &dwData, // pointer to value data - sizeof(DWORD)); // length of value data - - RegCloseKey(hKey); - } } -#endif - diff --git a/src/tripwire/syslog_trip.h b/src/tripwire/syslog_trip.h index 9c8de99..899db41 100644 --- a/src/tripwire/syslog_trip.h +++ b/src/tripwire/syslog_trip.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // syslog.h // -// cSyslog class. Abstracts logging to Unix syslog or NT Event Log +// cSyslog class. Abstracts logging to Unix syslog or NT Event Log // #ifndef __SYSLOG_H @@ -50,11 +50,10 @@ class cSyslog }; static void Log(const TCHAR* programName, cSyslog::LogType logType, const TCHAR* message); - // logs message the syslog mechanism on Unix. - // currently a NOOP on Windows (but asserts in debug mode) - // TODO: Should this be a fsservices function? + // logs message the syslog mechanism on Unix. + // currently a NOOP on Windows (but asserts in debug mode) + // TODO: Should this be a fsservices function? }; #endif - diff --git a/src/tripwire/tripwire.cpp b/src/tripwire/tripwire.cpp index bcdfd30..b74080a 100644 --- a/src/tripwire/tripwire.cpp +++ b/src/tripwire/tripwire.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,21 +53,18 @@ /////////////////////////////////////////////////////////////////////////////// // cTripwire /////////////////////////////////////////////////////////////////////////////// -TSS_ImplementPackage( cTripwire ) +TSS_ImplementPackage(cTripwire) cTripwire::cTripwire() { - TSS_Dependency( cCore ); - TSS_Dependency( cDb ); - TSS_Dependency( cTWCrypto ); - TSS_Dependency( cTWParser ); - TSS_Dependency( cTW ); - TSS_Dependency( cFCO ); - TSS_Dependency( cFS ); - TSS_Dependency( cUtil ); - - TSS_REGISTER_PKG_ERRORS( tripwire ) -} - -// eof: tripwire.cpp + TSS_Dependency(cCore); + TSS_Dependency(cDb); + TSS_Dependency(cTWCrypto); + TSS_Dependency(cTWParser); + TSS_Dependency(cTW); + TSS_Dependency(cFCO); + TSS_Dependency(cFS); + TSS_Dependency(cUtil); + TSS_REGISTER_PKG_ERRORS(tripwire) +} diff --git a/src/tripwire/tripwire.h b/src/tripwire/tripwire.h index b725e76..f13f9b2 100644 --- a/src/tripwire/tripwire.h +++ b/src/tripwire/tripwire.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,21 +40,20 @@ #ifndef __TRIPWIRE_H #define __TRIPWIRE_H -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #include "core/package.h" -TSS_BeginPackage( cTripwire ) +TSS_BeginPackage(cTripwire) TSS_DECLARE_STRINGTABLE; public: - cTripwire(); +cTripwire(); -TSS_EndPackage( cTripwire ) +TSS_EndPackage(cTripwire) #endif - diff --git a/src/tripwire/tripwireerrors.cpp b/src/tripwire/tripwireerrors.cpp index 553734e..a78a827 100644 --- a/src/tripwire/tripwireerrors.cpp +++ b/src/tripwire/tripwireerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,69 +45,78 @@ #include "twcmdline.h" #include "twcmdlineutil.h" -TSS_BEGIN_ERROR_REGISTRATION( tripwire ) +TSS_BEGIN_ERROR_REGISTRATION(tripwire) // MailMessage -TSS_REGISTER_ERROR( eMailMessageError(), _T("Mail message error.") ); +TSS_REGISTER_ERROR(eMailMessageError(), _T("Mail message error.")); // SMTP -TSS_REGISTER_ERROR( eMailSMTPWinsockDidNotStart(), _T("An internet connection could not be found.") ); -TSS_REGISTER_ERROR( eMailSMTPWinsockUnloadable(), _T("WSOCK32.DLL could not be loaded.") ); -TSS_REGISTER_ERROR( eMailSMTPWinsockCleanup(), _T("The internet connection could not be terminated properly.") ); -TSS_REGISTER_ERROR( eMailSMTPIPUnresolvable(), _T("The IP address could not be resolved: ") ); -TSS_REGISTER_ERROR( eMailSMTPSocket(), _T("Socket for an SMTP connection could not be created.") ); -TSS_REGISTER_ERROR( eMailSMTPOpenConnection(), _T("The SMTP connection could not be established.") ); -TSS_REGISTER_ERROR( eMailSMTPCloseConnection(), _T("The SMTP connection could not be properly closed.") ); -TSS_REGISTER_ERROR( eMailSMTPServer(), _T("The SMTP server returned an error.") ); - -// MAPI -TSS_REGISTER_ERROR( eMailMAPINotAvailable(), _T("MAPI is not available.") ); -TSS_REGISTER_ERROR( eMailMAPIUnload(), _T("MAPI32.DLL could not be loaded.") ); -TSS_REGISTER_ERROR( eMailMAPISend(), _T("Sending message via MAPI failed.") ); - +TSS_REGISTER_ERROR(eMailSMTPWinsockDidNotStart(), _T("An internet connection could not be found.")); +TSS_REGISTER_ERROR(eMailSMTPWinsockUnloadable(), _T("WSOCK32.DLL could not be loaded.")); +TSS_REGISTER_ERROR(eMailSMTPWinsockCleanup(), _T("The internet connection could not be terminated properly.")); +TSS_REGISTER_ERROR(eMailSMTPIPUnresolvable(), _T("The IP address could not be resolved: ")); +TSS_REGISTER_ERROR(eMailSMTPSocket(), _T("Socket for an SMTP connection could not be created.")); +TSS_REGISTER_ERROR(eMailSMTPOpenConnection(), _T("The SMTP connection could not be established.")); +TSS_REGISTER_ERROR(eMailSMTPCloseConnection(), _T("The SMTP connection could not be properly closed.")); +TSS_REGISTER_ERROR(eMailSMTPServer(), _T("The SMTP server returned an error.")); +TSS_REGISTER_ERROR(eMailSMTPNotSupported(), _T("SMTP email is not supported on this platform")); // Piped -TSS_REGISTER_ERROR( eMailPipedOpen(), _T("Problem opening mail pipe.") ); -TSS_REGISTER_ERROR( eMailPipedWrite(), _T("Problem writing to mail pipe.") ); -TSS_REGISTER_ERROR( eMailPipedCmdFailed(), _T("Execution of mail program failed.") ); +TSS_REGISTER_ERROR(eMailPipedOpen(), _T("Problem opening mail pipe.")); +TSS_REGISTER_ERROR(eMailPipedWrite(), _T("Problem writing to mail pipe.")); +TSS_REGISTER_ERROR(eMailPipedCmdFailed(), _T("Execution of mail program failed.")); // Policy Update -TSS_REGISTER_ERROR( ePolicyUpdate(), _T("Policy Update") ); -TSS_REGISTER_ERROR( ePolicyUpdateAddedFCO(), _T("Policy Update Added Object.\nAn object has been added since the database was last updated.\nObject name: ") ); -TSS_REGISTER_ERROR( ePolicyUpdateRemovedFCO(), _T("Policy Update Removed Object.\nAn object has been removed since the database was last updated.\nObject name: ") ); -TSS_REGISTER_ERROR( ePolicyUpdateChangedFCO(), _T("Policy Update Changed Object.\nAn object has been changed since the database was last updated.\nObject name: ") ); +TSS_REGISTER_ERROR(ePolicyUpdate(), _T("Policy Update")); +TSS_REGISTER_ERROR( + ePolicyUpdateAddedFCO(), + _T("Policy Update Added Object.\nAn object has been added since the database was last updated.\nObject name: ")); +TSS_REGISTER_ERROR(ePolicyUpdateRemovedFCO(), + _T("Policy Update Removed Object.\nAn object has been removed since the database was last ") + _T("updated.\nObject name: ")); +TSS_REGISTER_ERROR(ePolicyUpdateChangedFCO(), + _T("Policy Update Changed Object.\nAn object has been changed since the database was last ") + _T("updated.\nObject name: ")); // Update Db -TSS_REGISTER_ERROR( eUpdateDb(), _T("Database Update") ); -TSS_REGISTER_ERROR( eUpdateDbAddedFCO(), _T("Database Update Addition.\nThe report may be out of sync with current database.\nThe report indicates an object has been added but the object is already in the database.\nObject name: ") ); -TSS_REGISTER_ERROR( eUpdateDbRemovedFCO(), _T("Database Update Object Not Found.\nThe report may be out of sync with current database.\nThe report indicates that an object has been removed but the object is not in the database.\nObject name: ") ); -TSS_REGISTER_ERROR( eUpdateDbChangedFCO(), _T("Database Update Old Property Mismatch.\nThe report may be out of sync with current database.\nThe old properties for an object do not match the properites stored in the database.\nObject name: ") ); +TSS_REGISTER_ERROR(eUpdateDb(), _T("Database Update")); +TSS_REGISTER_ERROR(eUpdateDbAddedFCO(), + _T("Database Update Addition.\nThe report may be out of sync with current database.\nThe report ") + _T("indicates an object has been added but the object is already in the database.\nObject name: ")); +TSS_REGISTER_ERROR( + eUpdateDbRemovedFCO(), + _T("Database Update Object Not Found.\nThe report may be out of sync with current database.\nThe report indicates ") + _T("that an object has been removed but the object is not in the database.\nObject name: ")); +TSS_REGISTER_ERROR( + eUpdateDbChangedFCO(), + _T("Database Update Old Property Mismatch.\nThe report may be out of sync with current database.\nThe old ") + _T("properties for an object do not match the properites stored in the database.\nObject name: ")); // IC -TSS_REGISTER_ERROR( eIC(), _T("Integrity Check") ); -TSS_REGISTER_ERROR( eICFCONotInSpec(), _T("Integrity Check Internal Error.\nObject to be checked is not in any database rules.\n") ); -TSS_REGISTER_ERROR( eICFCONotInDb(), _T("Integrity Check Internal Error.\nObject to be checked is not in database.\n") ); -TSS_REGISTER_ERROR( eICFCOCreate(), _T("Integrity Check Internal Error.\nObject to be checked could not be created in the database.\n") ); -TSS_REGISTER_ERROR( eICBadPol(), _T("Policy file does not match policy used to create database.") ); -TSS_REGISTER_ERROR( eICUnknownGenre(), _T("Invalid section specified on the command line.") ); -TSS_REGISTER_ERROR( eICBadSevVal(), _T("Invalid severity level specified on the command line.") ); -TSS_REGISTER_ERROR( eICInappropriateGenre(), _T("Inappropriate section specified on the command line.") ); -TSS_REGISTER_ERROR( eICDifferentUsers(), _T("Current user differs from one who created database.") ); -TSS_REGISTER_ERROR( eICMismatchingParams(), _T("Mismatch in specified command line parameters: ") ); -TSS_REGISTER_ERROR( eTWInvalidConfigFileKey(), _T("Configuration file contains an invalid variable.") ); -TSS_REGISTER_ERROR( eTWPassForUnencryptedDb(), _T("Passphrase specified for an unencrypted database file.") ); +TSS_REGISTER_ERROR(eIC(), _T("Integrity Check")); +TSS_REGISTER_ERROR(eICFCONotInSpec(), + _T("Integrity Check Internal Error.\nObject to be checked is not in any database rules.\n")); +TSS_REGISTER_ERROR(eICFCONotInDb(), _T("Integrity Check Internal Error.\nObject to be checked is not in database.\n")); +TSS_REGISTER_ERROR(eICFCOCreate(), + _T("Integrity Check Internal Error.\nObject to be checked could not be created in the database.\n")); +TSS_REGISTER_ERROR(eICBadPol(), _T("Policy file does not match policy used to create database.")); +TSS_REGISTER_ERROR(eICUnknownGenre(), _T("Invalid section specified on the command line.")); +TSS_REGISTER_ERROR(eICBadSevVal(), _T("Invalid severity level specified on the command line.")); +TSS_REGISTER_ERROR(eICInappropriateGenre(), _T("Inappropriate section specified on the command line.")); +TSS_REGISTER_ERROR(eICDifferentUsers(), _T("Current user differs from one who created database.")); +TSS_REGISTER_ERROR(eICMismatchingParams(), _T("Mismatch in specified command line parameters: ")); +TSS_REGISTER_ERROR(eTWInvalidConfigFileKey(), _T("Configuration file contains an invalid variable.")); +TSS_REGISTER_ERROR(eTWPassForUnencryptedDb(), _T("Passphrase specified for an unencrypted database file.")); // General TW -TSS_REGISTER_ERROR( eTWHelpInvalidModeSwitch(), _T("Invalid mode parameter to help: ") ); -TSS_REGISTER_ERROR( eTWInitialization(), _T("Tripwire initialization error.") ); -TSS_REGISTER_ERROR( eTWInvalidReportLevel(), _T("Invalid reporting level specified.\nValid levels: [0-4]\n") ); -TSS_REGISTER_ERROR( eTWInvalidReportLevelCfg(), _T("Invalid reporting level in configuration file\nValid levels: [0-4]\n") ); -TSS_REGISTER_ERROR( eTWInvalidPortNumber(), _T("Invalid SMTP port number.\nValid ports: [0-65535]\n") ); -TSS_REGISTER_ERROR( eTWInvalidTempDirectory(), _T("Cannot access temp directory.") ); +TSS_REGISTER_ERROR(eTWHelpInvalidModeSwitch(), _T("Invalid mode parameter to help: ")); +TSS_REGISTER_ERROR(eTWInitialization(), _T("Tripwire initialization error.")); +TSS_REGISTER_ERROR(eTWInvalidReportLevel(), _T("Invalid reporting level specified.\nValid levels: [0-4]\n")); +TSS_REGISTER_ERROR(eTWInvalidReportLevelCfg(), + _T("Invalid reporting level in configuration file\nValid levels: [0-4]\n")); +TSS_REGISTER_ERROR(eTWInvalidPortNumber(), _T("Invalid SMTP port number.\nValid ports: [0-65535]\n")); +TSS_REGISTER_ERROR(eTWInvalidTempDirectory(), _T("Cannot access temp directory.")); -// GMMS -TSS_REGISTER_ERROR( eGmmsError(), _T("GMMS error.") ); -TSS_REGISTER_ERROR( eGmmsCouldntOpenPipe(), _T("GMMS executable not found: ") ); -TSS_REGISTER_ERROR( eGmmsCouldntWritePipe(), _T("There was a problem writing to gmms: ") ); -TSS_REGISTER_ERROR( eGmmsCmdFailed(), _T("GMMS exited with non-zero status: ") ); +TSS_REGISTER_ERROR(eTWSyslogNotSupported(), _T("Syslog reporting is not supported on this platform.")); +TSS_REGISTER_ERROR(eTWDirectIONotSupported(), _T("Direct I/O hashing is not supported on this platform.")); TSS_END_ERROR_REGISTRATION() diff --git a/src/tripwire/tripwireerrors.h b/src/tripwire/tripwireerrors.h index d3be484..734b027 100644 --- a/src/tripwire/tripwireerrors.h +++ b/src/tripwire/tripwireerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( tripwire ) - -#endif//__TRIPWIREERRORS_H +TSS_DECLARE_ERROR_REGISTRATION(tripwire) +#endif //__TRIPWIREERRORS_H diff --git a/src/tripwire/tripwiremain.cpp b/src/tripwire/tripwiremain.cpp index f93d4f1..4c251ec 100644 --- a/src/tripwire/tripwiremain.cpp +++ b/src/tripwire/tripwiremain.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,32 +43,28 @@ #include "tw/configfile.h" #include "core/errorbucketimpl.h" #include "core/usernotifystdout.h" -#include "core/timebomb.h" -#include // for auto_ptr +#include "core/epoch.h" +#include // for auto_ptr / unique_ptr #include #include #include "tw/twstrings.h" #include "tripwirestrings.h" -#include "tripwire.h" // package initialization +#include "tripwire.h" // package initialization #include "fco/fcogenre.h" #include "fco/genreswitcher.h" -#if IS_UNIX #include "core/unixfsservices.h" #include -#else -#error Who the hell am I? -#endif -static TSTRING util_GetWholeCmdLine( int argc, const TCHAR *argv[] ); +static TSTRING util_GetWholeCmdLine(int argc, const TCHAR* argv[]); /////////////////////////////////////////////////////////////////////////////// // global new() and delete() overrides -- this is done to do performance testing /////////////////////////////////////////////////////////////////////////////// /* -#ifdef _DEBUG +#ifdef DEBUG #if defined(HAVE_MALLOC_H) #include #endif @@ -108,18 +104,18 @@ void tw_unexpected_handler() /////////////////////////////////////////////////////////////////////////////// // main /////////////////////////////////////////////////////////////////////////////// -int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) +int __cdecl _tmain(int argc, const TCHAR* argv[], const TCHAR* envp[]) { - if (TimeBombExploded()) + if (CheckEpoch()) return 8; int ret = 0; cTWInit twInit; - - try + + try { // set unexpected and terminate handlers // Note: we do this before Init() in case it attempts to call these handlers @@ -129,16 +125,16 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) // Initialization // - twInit.Init( argv[0] ); - TSS_Dependency( cTripwire ); + twInit.Init(argv[0]); + TSS_Dependency(cTripwire); // set up the debug output - cDebug::SetDebugLevel( cDebug::D_DEBUG/*D_DETAIL*//*D_NEVER*/ ); - + cDebug::SetDebugLevel(cDebug::D_DEBUG /*D_DETAIL*/ /*D_NEVER*/); + // first, get the right mode... - std::auto_ptr pMode(cTWCmdLine::GetMode(argc, argv)); - if(! pMode.get()) + TW_UNIQUE_PTR pMode(cTWCmdLine::GetMode(argc, argv)); + if (!pMode.get()) { // no valid mode passed; GetMode will display an appropriate string (include usage statement) ret = 8; @@ -148,11 +144,11 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) // if version was requested, output version string and exit if (pMode.get()->GetModeID() == cTWCmdLine::MODE_VERSION) { - TCOUT << TSS_GetString( cTW, tw::STR_VERSION_LONG) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION_LONG) << std::endl; ret = 0; goto exit; } - + // process the command line cCmdLineParser cmdLine; pMode->InitCmdLineParser(cmdLine); @@ -160,30 +156,28 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) { cmdLine.Parse(argc, argv); } - catch( eError& e ) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); - TCERR << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - + TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + ret = 8; goto exit; } - TSTRING commandLine = util_GetWholeCmdLine( argc, argv ); + TSTRING commandLine = util_GetWholeCmdLine(argc, argv); - #if IS_UNIX // erase the command line // TODO: it might be a good idea to move this to cTWUtil int i; for (i = 1; i < argc; ++i) - memset((char*)argv[i], 0, strlen(argv[i])*sizeof(TCHAR)); - #endif + memset((char*)argv[i], 0, strlen(argv[i]) * sizeof(TCHAR)); cCmdLineIter iter(cmdLine); if (iter.SeekToArg(cTWCmdLine::HELP)) { - TCOUT << TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; // //Since --help was passed, exit after emitting a mode-specific usage statement. TCOUT << pMode->GetModeUsage(); @@ -193,15 +187,15 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) if (iter.SeekToArg(cTWCmdLine::VERBOSE)) { - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; } // open up the config file, possibly using the passed in path - cConfigFile config; - TSTRING strConfigFile; + cConfigFile config; + TSTRING strConfigFile; cErrorReporter errorReporter; - if( pMode->GetModeID() != cTWCmdLine::MODE_HELP ) + if (pMode->GetModeID() != cTWCmdLine::MODE_HELP) { try { @@ -211,30 +205,30 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) catch (eError& error) { TSTRING extra; - extra += TSS_GetString( cTW, tw::STR_NEWLINE); - extra += TSS_GetString( cTW, tw::STR_ERR_TWCFG_CANT_READ); + extra += TSS_GetString(cTW, tw::STR_NEWLINE); + extra += TSS_GetString(cTW, tw::STR_ERR_TWCFG_CANT_READ); - cTWUtil::PrintErrorMsg( error, extra ); + cTWUtil::PrintErrorMsg(error, extra); ret = 8; goto exit; } } // ok, now we can initialize the mode object and have it execute - pMode->SetCmdLine( commandLine ); + pMode->SetCmdLine(commandLine); - pMode->SetConfigFile( strConfigFile ); + pMode->SetConfigFile(strConfigFile); - if(! pMode->Init(config, cmdLine)) + if (!pMode->Init(config, cmdLine)) { - TCERR << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; + TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; ret = 8; goto exit; } ret = pMode->Execute(&twInit.errorQueue); - }//end try block + } //end try block catch (eError& error) { @@ -243,7 +237,7 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) ret = 8; } - catch (std::bad_alloc e) + catch (std::bad_alloc& e) { // Note: We use fputs rather than TCERR as it will probably require the // least amount of memory to do its thing. If we ran out of memory we @@ -253,45 +247,42 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) ret = 8; } - catch (std::exception e) + catch (std::exception& e) { TCERR << _T("*** Fatal exception: "); std::cerr << e.what() << std::endl; TCERR << _T("*** Exiting...\n"); ret = 8; } - - /* catch (...) { TCERR << _T("*** Fatal exception occurred.\n"); TCERR << _T("*** Exiting...\n"); ret = 8; } - */ exit: // print out the max memory usage... -/* -#ifdef _DEBUG + /* +#ifdef DEBUG TCOUT << _T("Maximum memory footprint = ") << gMaxAlloc << std::endl; #endif */ - + return ret; } //end MAIN -static TSTRING util_GetWholeCmdLine( int argc, const TCHAR *argv[] ) +static TSTRING util_GetWholeCmdLine(int argc, const TCHAR* argv[]) { TSTRING tstrRet; bool wipeNextItem = false; - for( int i = 0; i < argc; i++ ) + for (int i = 0; i < argc; i++) { if (wipeNextItem) { @@ -304,16 +295,13 @@ static TSTRING util_GetWholeCmdLine( int argc, const TCHAR *argv[] ) tstrRet += _T(" "); // Passwords passed on the command line are not saved - if (_tcsncmp(argv[i], _T("-P"), 2) == 0 || - _tcsncmp(argv[i], _T("-Q"), 2) == 0 || - _tcscmp(argv[i], _T("--local-passphrase")) == 0 || - _tcscmp(argv[i], _T("--site-passphrase")) == 0) + if (_tcsncmp(argv[i], _T("-P"), 2) == 0 || _tcsncmp(argv[i], _T("-Q"), 2) == 0 || + _tcscmp(argv[i], _T("--local-passphrase")) == 0 || _tcscmp(argv[i], _T("--site-passphrase")) == 0) { wipeNextItem = true; } } } - return( tstrRet ); + return (tstrRet); } - diff --git a/src/tripwire/tripwiremsg.h b/src/tripwire/tripwiremsg.h index f6dbb95..4438b51 100644 --- a/src/tripwire/tripwiremsg.h +++ b/src/tripwire/tripwiremsg.h @@ -1,64 +1,64 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // tripwiremsg.mc -// +// // This file (tripwiremsg.mc) is the source for tripwire.exe messages. You // may be reading these comments in tripwiremsg.h, in which case you are reading // an output file from mc.exe. -// +// // This is compiled by the dev studio utility mc.exe to produce the following files: -// +// // tripwiremsg.h // tripwiremsg.rc // MSG00001.bin -// +// // The tripwiremsg.rc file is included in the tripwire resource script "Script1.rc". // This causes the file MSG00001.bin to be included as a binary resrouce in the final // executable. -// +// // All of this is done to support using Tripwire as an event source for Event Logging. -// In general .mc files such as this are used to support custom strings for the +// In general .mc files such as this are used to support custom strings for the // FormatMessage() WinAPI. The event viewer requires this mechanism for event strings. -// +// // We are sort of cheating here. By having each string be "%1", we can have any string // we pass to ReportEvent() be the entire Event Log message. Microsoft discourages this -// as it makes localization difficult (you can't just provide a new rc file with +// as it makes localization difficult (you can't just provide a new rc file with // all of the localized versions of the strings). However, we have chosen to handle the // localization issues by localizing the strings in the various tripwirestrings files. -// +// // To recompile this files into the files listed above run: -// +// // mc tripwiremsg.mc -// +// // // Values are 32 bit values layed out as follows: // @@ -102,7 +102,7 @@ // // %1 // -#define MSG_TRIPWIRE_GENERIC_SUCCESS 0x00000001L +#define MSG_TRIPWIRE_GENERIC_SUCCESS 0x00000001L // // MessageId: MSG_TRIPWIRE_GENERIC_INFO @@ -111,7 +111,7 @@ // // %1 // -#define MSG_TRIPWIRE_GENERIC_INFO 0x40000001L +#define MSG_TRIPWIRE_GENERIC_INFO 0x40000001L // // MessageId: MSG_TRIPWIRE_GENERIC_WARNING @@ -120,7 +120,7 @@ // // %1 // -#define MSG_TRIPWIRE_GENERIC_WARNING 0x80000001L +#define MSG_TRIPWIRE_GENERIC_WARNING 0x80000001L // // MessageId: MSG_TRIPWIRE_GENERIC_ERROR @@ -129,6 +129,4 @@ // // %1 // -#define MSG_TRIPWIRE_GENERIC_ERROR 0xC0000001L - - +#define MSG_TRIPWIRE_GENERIC_ERROR 0xC0000001L diff --git a/src/tripwire/tripwirestrings.cpp b/src/tripwire/tripwirestrings.cpp index bb86ae4..eabe99a 100644 --- a/src/tripwire/tripwirestrings.cpp +++ b/src/tripwire/tripwirestrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,268 +34,226 @@ #include "stdtripwire.h" #include "tripwirestrings.h" - -#ifdef GMMS -#define GMMS_OPTION _T(" -g --gmms\n") -#define GMMS_VERBOSITY_OPTION _T(" -b 1|2 --gmms-verbosity 1|2\n") +#if IS_AROS +# define VERSION_PREFIX "$VER: " #else -#define GMMS_OPTION -#define GMMS_VERBOSITY_OPTION +# define VERSION_PREFIX "@(#)" #endif -#if IS_UNIX -#define MAPI_OPTION -#endif -TSS_BeginStringtable( cTripwire ) +TSS_BeginStringtable(cTripwire) - TSS_StringEntry( tripwire::STR_TRIPWIRE_VERSION, _T("tripwire: File integrity assessment application.\n")), - - TSS_StringEntry( tripwire::STR_TRIPWIRE_USAGE_SUMMARY, - _T("Usage:\n") - _T("\n") - _T("Database Initialization: tripwire [-m i|--init] [options]\n") - _T("Integrity Checking: tripwire [-m c|--check] [object1 [object2...]]\n") - _T("Database Update: tripwire [-m u|--update]\n") - _T("Policy Update: tripwire [-m p|--update-policy] policyfile.txt\n") - _T("Test: tripwire [-m t|--test] --email address\n") - _T("\n") - _T("Type 'tripwire [mode] --help' OR\n") - _T("'tripwire --help mode [mode...]' OR\n") - _T("'tripwire --help all' for extended help\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_VERSION, _T("tripwire: File integrity assessment application.\n")), + TSS_StringEntry(tripwire::STR_EMBEDDED_VERSION, _T(VERSION_PREFIX "tripwire " PACKAGE_VERSION)), - TSS_StringEntry( tripwire::STR_TRIPWIRE_HELP_INIT, - _T("Database Initialization mode:\n") - _T(" -m i --init\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -d database --dbfile database\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -e --no-encryption\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("The -L and -e options are mutually exclusive.\n") - _T("The -P and -e options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_USAGE_SUMMARY, + _T("Usage:\n") + _T("\n") + _T("Database Initialization: tripwire [-m i|--init] [options]\n") + _T("Integrity Checking: tripwire [-m c|--check] [object1 [object2...]]\n") + _T("Database Update: tripwire [-m u|--update]\n") + _T("Policy Update: tripwire [-m p|--update-policy] policyfile.txt\n") + _T("Test: tripwire [-m t|--test] --email address\n") + _T("\n") + _T("Type 'tripwire [mode] --help' OR\n") + _T("'tripwire --help mode [mode...]' OR\n") + _T("'tripwire --help all' for extended help\n")), - TSS_StringEntry( tripwire::STR_TRIPWIRE_HELP_CHECK, - _T("Integrity Check mode:\n") - _T(" -m c --check\n") - _T(" -I --interactive\n") - _T(" -v --verbose\n") - _T(" -h --hexadecimal\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -d database --dbfile database\n") - _T(" -r report --twrfile report\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -n --no-tty-output\n") - _T(" -V editor --visual editor\n") - _T(" -E --signed-report\n") - _T(" -R rule --rule-name rule\n") - _T(" -l {level | name} --severity {level | name}\n") - _T(" -x section --section section\n") - _T(" -i list --ignore list\n") - _T(" -M --email-report\n") - _T(" -t { 0|1|2|3|4 } --email-report-level { 0|1|2|3|4 }\n") - - // Only insert the description of these two options if GMMS is defined. - // Otherwise these two lines will be blank. You cannot have #ifdef in - // the middle of this big concatenated string. - GMMS_OPTION - GMMS_VERBOSITY_OPTION + TSS_StringEntry(tripwire::STR_TRIPWIRE_HELP_INIT, + _T("Database Initialization mode:\n") + _T(" -m i --init\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -d database --dbfile database\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -e --no-encryption\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("The -L and -e options are mutually exclusive.\n") + _T("The -P and -e options are mutually exclusive.\n") + _T("\n")), - _T("[object1 [object2...]]\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("The -l and -R options are mutually exclusive.\n") - _T("The -P option is only valid with -E or -I.\n") - _T("The -V option is only valid with -I.\n") - _T("The -t option is only valid with -M.\n") - _T("Specifying objects overrides the -l and -R options.\n") - _T("\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_HELP_CHECK, + _T("Integrity Check mode:\n") + _T(" -m c --check\n") + _T(" -I --interactive\n") + _T(" -v --verbose\n") + _T(" -h --hexadecimal\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -d database --dbfile database\n") + _T(" -r report --twrfile report\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -n --no-tty-output\n") + _T(" -V editor --visual editor\n") + _T(" -E --signed-report\n") + _T(" -R rule --rule-name rule\n") + _T(" -l {level | name} --severity {level | name}\n") + _T(" -x section --section section\n") + _T(" -i list --ignore list\n") + _T(" -M --email-report\n") + _T(" -t { 0|1|2|3|4 } --email-report-level { 0|1|2|3|4 }\n") + _T("[object1 [object2...]]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("The -l and -R options are mutually exclusive.\n") + _T("The -P option is only valid with -E or -I.\n") + _T("The -V option is only valid with -I.\n") + _T("The -t option is only valid with -M.\n") + _T("Specifying objects overrides the -l and -R options.\n") + _T("\n")), - TSS_StringEntry( tripwire::STR_TRIPWIRE_HELP_UPDATE, - _T("Database Update mode:\n") - _T(" -m u --update\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -d database --dbfile database\n") - _T(" -r report --twrfile report\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -V editor --visual editor\n") - _T(" -a --accept-all\n") - _T(" -Z {low | high} --secure-mode {low | high}\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("The -a and -V options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_HELP_UPDATE, + _T("Database Update mode:\n") + _T(" -m u --update\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -d database --dbfile database\n") + _T(" -r report --twrfile report\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -V editor --visual editor\n") + _T(" -a --accept-all\n") + _T(" -Z {low | high} --secure-mode {low | high}\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("The -a and -V options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY, - _T("Policy Update mode:\n") - _T(" -m p --update-policy\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -d database --dbfile database\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T(" -Z {low | high} --secure-mode {low | high}\n") - _T("policyfile.txt\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY, + _T("Policy Update mode:\n") + _T(" -m p --update-policy\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -d database --dbfile database\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T(" -Z {low | high} --secure-mode {low | high}\n") + _T("policyfile.txt\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( tripwire::STR_TRIPWIRE_HELP_TEST, - _T("Test mode:\n") - _T(" -m t --test\n") - _T(" -e user@domain.com --email user@domain.com\n") - _T("\n") - // Only insert the MAPI option under NT. - MAPI_OPTION - _T("Only one address may be entered.\n") - _T("\n") - ), + TSS_StringEntry(tripwire::STR_TRIPWIRE_HELP_TEST, + _T("Test mode:\n") + _T(" -m t --test\n") + _T(" -e user@domain.com --email user@domain.com\n") + _T("\n") + _T("Only one address may be entered.\n") + _T("\n")), - TSS_StringEntry( tripwire::STR_INTEGRITY_CHECK, _T("Performing integrity check...\n")), - TSS_StringEntry( tripwire::STR_IC_SUCCESS, _T("Integrity check complete.\n")), - TSS_StringEntry( tripwire::STR_IC_FILES, _T("Integrity checking objects specified on command line...\n")), - TSS_StringEntry( tripwire::STR_CHECKING_SPECS_NAMED, _T("Checking rules named: ")), - TSS_StringEntry( tripwire::STR_CHECKING_GENRE, _T("Checking section %s only.\n")), - TSS_StringEntry( tripwire::STR_IC_SEVERITY_LEVEL, _T("Checking rules at or above severity level: ")), - TSS_StringEntry( tripwire::STR_IC_IGNORING_SEVERITY, _T("Ignoring rule %s (severity %d)\n")), - TSS_StringEntry( tripwire::STR_IC_IGNORING_SEV_NUM, _T("Warning: Severity number specified on command line will be ignored.\n")), - TSS_StringEntry( tripwire::STR_IC_IGNORING_SEV_NAME, _T("Warning: Severity name specified on command line will be ignored.\n")), - TSS_StringEntry( tripwire::STR_IC_IGNORING_RULE_NAME, _T("Warning: Rule name specified on command line will be ignored.\n")), - TSS_StringEntry( tripwire::STR_IC_IGNORING_GENRE_NAME, _T("Warning: Section name specified on command line will be ignored.\n")), - TSS_StringEntry( tripwire::STR_IC_NOEMAIL_SENT, _T("Nothing to report, no email sent.\n")), - TSS_StringEntry( tripwire::STR_NO_EMAIL_RECIPIENTS, _T("No email recipients specified, no email sent.\n")), + TSS_StringEntry(tripwire::STR_INTEGRITY_CHECK, _T("Performing integrity check...\n")), + TSS_StringEntry(tripwire::STR_IC_SUCCESS, _T("Integrity check complete.\n")), + TSS_StringEntry(tripwire::STR_IC_FILES, _T("Integrity checking objects specified on command line...\n")), + TSS_StringEntry(tripwire::STR_CHECKING_SPECS_NAMED, _T("Checking rules named: ")), + TSS_StringEntry(tripwire::STR_CHECKING_GENRE, _T("Checking section %s only.\n")), + TSS_StringEntry(tripwire::STR_IC_SEVERITY_LEVEL, _T("Checking rules at or above severity level: ")), + TSS_StringEntry(tripwire::STR_IC_IGNORING_SEVERITY, _T("Ignoring rule %s (severity %d)\n")), + TSS_StringEntry(tripwire::STR_IC_IGNORING_SEV_NUM, + _T("Warning: Severity number specified on command line will be ignored.\n")), + TSS_StringEntry(tripwire::STR_IC_IGNORING_SEV_NAME, + _T("Warning: Severity name specified on command line will be ignored.\n")), + TSS_StringEntry(tripwire::STR_IC_IGNORING_RULE_NAME, + _T("Warning: Rule name specified on command line will be ignored.\n")), + TSS_StringEntry(tripwire::STR_IC_IGNORING_GENRE_NAME, + _T("Warning: Section name specified on command line will be ignored.\n")), + TSS_StringEntry(tripwire::STR_IC_NOEMAIL_SENT, _T("Nothing to report, no email sent.\n")), + TSS_StringEntry(tripwire::STR_NO_EMAIL_RECIPIENTS, _T("No email recipients specified, no email sent.\n")), - TSS_StringEntry( tripwire::STR_PU_PROCESSING_GENRE, _T("======== Policy Update: Processing section %s.\n") ), - TSS_StringEntry( tripwire::STR_PU_INTEGRITY_CHECK, _T("======== Step 1: Gathering information for the new policy.\n") ), - TSS_StringEntry( tripwire::STR_PU_UPDATE_DB, _T("======== Step 2: Updating the database with new objects.\n") ), - TSS_StringEntry( tripwire::STR_PU_PRUNING, _T("======== Step 3: Pruning unneeded objects from the database.\n") ), - TSS_StringEntry( tripwire::STR_PU_ADDING_GENRE, _T("======== Policy Update: Adding section %s.\n") ), - TSS_StringEntry( tripwire::STR_PU_BAD_PROPS, _T("Conflicting properties for object ") ), - TSS_StringEntry( tripwire::STR_PROCESSING_GENRE, _T("*** Processing %s ***\n") ), + TSS_StringEntry(tripwire::STR_PU_PROCESSING_GENRE, _T("======== Policy Update: Processing section %s.\n")), + TSS_StringEntry(tripwire::STR_PU_INTEGRITY_CHECK, + _T("======== Step 1: Gathering information for the new policy.\n")), + TSS_StringEntry(tripwire::STR_PU_UPDATE_DB, _T("======== Step 2: Updating the database with new objects.\n")), + TSS_StringEntry(tripwire::STR_PU_PRUNING, _T("======== Step 3: Pruning unneeded objects from the database.\n")), + TSS_StringEntry(tripwire::STR_PU_ADDING_GENRE, _T("======== Policy Update: Adding section %s.\n")), + TSS_StringEntry(tripwire::STR_PU_BAD_PROPS, _T("Conflicting properties for object ")), + TSS_StringEntry(tripwire::STR_PROCESSING_GENRE, _T("*** Processing %s ***\n")), - // gmms reporting, these strings are for the gmms command line - TSS_StringEntry( tripwire::STR_GMMS_START, _T("alert Tripwire: ")), - TSS_StringEntry( tripwire::STR_GMMS_END, _T(")")), - TSS_StringEntry( tripwire::STR_GMMS_VERBOSITY1A, _T(", Violations found (")), - TSS_StringEntry( tripwire::STR_GMMS_VERBOSITY1B, _T("), Max severity (")), - TSS_StringEntry( tripwire::STR_GMMS_VERBOSITY2A, _T(", Rule Violated (")), - TSS_StringEntry( tripwire::STR_GMMS_VERBOSITY2B, _T("), File (")), - TSS_StringEntry( tripwire::STR_GMMS_VERBOSITY2C, _T("), Severity (")), - - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR1, _T("A recipient matched more than one of the recipient descriptor structures. No message was sent.\n(MAPI error: MAPI_E_AMBIGUOUS_RECIPIENT)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR2, _T("The specified attachment was not found. No message was sent.\n(MAPI error: MAPI_E_ATTACHMENT_NOT_FOUND)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR3, _T("The specified attachment could not be opened. No message was sent.\n(MAPI error: MAPI_E_ATTACHMENT_OPEN_FAILURE)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR4, _T("The type of a recipient was not MAPI_TO, MAPI_CC, or MAPI_BCC. No message was sent.\n(MAPI error: MAPI_E_BAD_RECIPTYPE)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR5, _T("One or more unspecified errors occurred. No message was sent.\n(MAPI error: MAPI_E_FAILURE)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR6, _T("There was insufficient memory to proceed. No message was sent.\n(MAPI error: MAPI_E_INSUFFICIENT_MEMORY)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR7, _T("One or more recipients were invalid or did not resolve to any address.\n(MAPI error: MAPI_E_INVALID_RECIPS)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR8, _T("There was no default logon, and the user failed to log on successfully when the logon dialog box was displayed. No message was sent.\n(MAPI error: MAPI_E_LOGIN_FAILURE)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR9, _T("The text in the message was too large. No message was sent.\n(MAPI error: MAPI_E_TEXT_TOO_LARGE)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR10, _T("There were too many file attachments. No message was sent.\n(MAPI error: MAPI_E_TOO_MANY_FILES)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR11, _T("There were too many recipients. No message was sent.\n(MAPI error: MAPI_E_TOO_MANY_RECIPIENTS)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR12, _T("A recipient did not appear in the address list. No message was sent.\n(MAPI error: MAPI_E_UNKNOWN_RECIPIENT)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR13, _T("The user canceled one of the dialog boxes. No message was sent.\n(MAPI error: MAPI_E_USER_ABORT)")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR14, _T("MAPI returned a unrecognized error (")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR14_1, _T(").")), - - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_SERVER, _T("Server: ")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR, _T("Error Number:")), - TSS_StringEntry( tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND, _T("Command: ")), + TSS_StringEntry(tripwire::STR_ERR2_MAIL_MESSAGE_SERVER, _T("Server: ")), + TSS_StringEntry(tripwire::STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR, _T("Error Number:")), + TSS_StringEntry(tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND, _T("Command: ")), // // Tripwire Command Line // - TSS_StringEntry( tripwire::STR_ERR_IC_EMAIL_AND_FILES, _T("Email reporting cannot be specified when checking a list of objects.")), - TSS_StringEntry( tripwire::STR_ERR_NO_MAIL_METHOD, _T("No mail method specified in configuration file.")), - TSS_StringEntry( tripwire::STR_ERR_INVALID_MAIL_METHOD, _T("Invalid mail method in configuration file.")), - TSS_StringEntry( tripwire::STR_ERR_MAPI_NOT_SUPPORTED, _T("Configuration option MAILMETHOD=MAPI is not supported on this platform.")), - TSS_StringEntry( tripwire::STR_ERR_MISSING_MAILPROGRAM, _T("Mail method is set to SENDMAIL but MAILPROGRAM was not defined in configuration file")), - TSS_StringEntry( tripwire::STR_ERR_NO_TEST_MODE, _T("No test area specified.")), - TSS_StringEntry( tripwire::STR_GENERATING_DB, _T("Generating the database...\n")), - TSS_StringEntry( tripwire::STR_INIT_SUCCESS, _T("The database was successfully generated.\n")), - TSS_StringEntry( tripwire::STR_ERR2_DIFFERENT_USERS1, _T("Created by: ")), - TSS_StringEntry( tripwire::STR_ERR2_DIFFERENT_USERS2, _T("\nCurrent user: ")), - TSS_StringEntry( tripwire::STR_ERR_IC_NO_SPECS_LEFT, _T("No rules to check for section %s.\n")), - TSS_StringEntry( tripwire::STR_ERR_BAD_PARAM, _T("Invalid parameter.")), - TSS_StringEntry( tripwire::STR_ERR_UPDATE_ED_LAUNCH, _T("Interactive Update failed.")), - TSS_StringEntry( tripwire::STR_REPORT_EMPTY, _T("The report contains no new data, the database will not be updated.\n")), - TSS_StringEntry( tripwire::STR_DB_NOT_UPDATED, _T("The database was not updated. ")), - TSS_StringEntry( tripwire::STR_ERR_POL_UPDATE, _T("Policy update failed; policy and database files were not altered.")), - TSS_StringEntry( tripwire::STR_IGNORE_PROPS, _T("Ignoring properties: ")), - TSS_StringEntry( tripwire::STR_ERR_ILLEGAL_MODE_HELP, _T("Error, mode does not exist: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_IDENT, _T("tripwire")), - TSS_StringEntry( tripwire::STR_SYSLOG_INIT_MSG, _T("Database initialized: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_IC_MSG, _T("Integrity Check Complete: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_UP_MSG, _T("Database Update Complete: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_POLUP_MSG, _T("Policy Update Complete: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_INIT_FAIL_MSG, _T("Database initialization Failed: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_IC_FAIL_MSG, _T("Integrity Check Failed: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_UP_FAIL_MSG, _T("Database Update Failed: ")), - TSS_StringEntry( tripwire::STR_SYSLOG_POLUP_FAIL_MSG, _T("Policy Update Failed: ")), + TSS_StringEntry(tripwire::STR_ERR_IC_EMAIL_AND_FILES, + _T("Email reporting cannot be specified when checking a list of objects.")), + TSS_StringEntry(tripwire::STR_ERR_NO_MAIL_METHOD, _T("No mail method specified in configuration file.")), + TSS_StringEntry(tripwire::STR_ERR_INVALID_MAIL_METHOD, _T("Invalid mail method in configuration file.")), + TSS_StringEntry(tripwire::STR_ERR_MISSING_MAILPROGRAM, + _T("Mail method is set to SENDMAIL but MAILPROGRAM was not defined in configuration file")), + TSS_StringEntry(tripwire::STR_ERR_NO_TEST_MODE, _T("No test area specified.")), + TSS_StringEntry(tripwire::STR_GENERATING_DB, _T("Generating the database...\n")), + TSS_StringEntry(tripwire::STR_INIT_SUCCESS, _T("The database was successfully generated.\n")), + TSS_StringEntry(tripwire::STR_ERR2_DIFFERENT_USERS1, _T("Created by: ")), + TSS_StringEntry(tripwire::STR_ERR2_DIFFERENT_USERS2, _T("\nCurrent user: ")), + TSS_StringEntry(tripwire::STR_ERR_IC_NO_SPECS_LEFT, _T("No rules to check for section %s.\n")), + TSS_StringEntry(tripwire::STR_ERR_BAD_PARAM, _T("Invalid parameter.")), + TSS_StringEntry(tripwire::STR_ERR_UPDATE_ED_LAUNCH, _T("Interactive Update failed.")), + TSS_StringEntry(tripwire::STR_REPORT_EMPTY, + _T("The report contains no new data, the database will not be updated.\n")), + TSS_StringEntry(tripwire::STR_DB_NOT_UPDATED, _T("The database was not updated. ")), + TSS_StringEntry(tripwire::STR_ERR_POL_UPDATE, + _T("Policy update failed; policy and database files were not altered.")), + TSS_StringEntry(tripwire::STR_IGNORE_PROPS, _T("Ignoring properties: ")), + TSS_StringEntry(tripwire::STR_ERR_ILLEGAL_MODE_HELP, _T("Error, mode does not exist: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_IDENT, _T("tripwire")), + TSS_StringEntry(tripwire::STR_SYSLOG_INIT_MSG, _T("Database initialized: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_IC_MSG, _T("Integrity Check Complete: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_UP_MSG, _T("Database Update Complete: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_POLUP_MSG, _T("Policy Update Complete: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_INIT_FAIL_MSG, _T("Database initialization Failed: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_IC_FAIL_MSG, _T("Integrity Check Failed: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_UP_FAIL_MSG, _T("Database Update Failed: ")), + TSS_StringEntry(tripwire::STR_SYSLOG_POLUP_FAIL_MSG, _T("Policy Update Failed: ")), // // email testing // - TSS_StringEntry( tripwire::STR_TEST_EMAIL_TO, _T("Sending a test message to:")), - TSS_StringEntry( tripwire::STR_TEST_EMAIL_SUBJECT, _T("Test email message from Tripwire")), - TSS_StringEntry( tripwire::STR_TEST_EMAIL_BODY, _T("If you receive this message, email notification from tripwire is working correctly.")), + TSS_StringEntry(tripwire::STR_TEST_EMAIL_TO, _T("Sending a test message to:")), + TSS_StringEntry(tripwire::STR_TEST_EMAIL_SUBJECT, _T("Test email message from Tripwire")), + TSS_StringEntry(tripwire::STR_TEST_EMAIL_BODY, + _T("If you receive this message, email notification from tripwire is working correctly.")), // // email reporting // - TSS_StringEntry( tripwire::STR_EMAIL_SUBJECT_REPORT_1, _T("Tripwire report (violation count ")), - TSS_StringEntry( tripwire::STR_EMAIL_SUBJECT_REPORT_2, _T(") (max severity ")), - TSS_StringEntry( tripwire::STR_EMAIL_SUBJECT_REPORT_3, _T(")")), - TSS_StringEntry( tripwire::STR_EMAIL_REPORT_TO, _T("Emailing the report to:")), - TSS_StringEntry( tripwire::STR_EMAIL_FROM, _T("tripwire@")), - TSS_StringEntry( tripwire::STR_EMAIL_BEGIN, _T("Beginning email reporting...")), - TSS_StringEntry( tripwire::STR_EMAIL_OK_BODY, _T("Rules with no violations or errors:")), - TSS_StringEntry( tripwire::STR_EMAIL_NO_RECIPIENTS, _T("No email recipients specified in policy file; no email sent.")), - TSS_StringEntry( tripwire::STR_EMAIL_OK_TO, _T("Emailing \"no violations\" message to:")), - TSS_StringEntry( tripwire::STR_EMAIL_SUBJECT_OK, _T("Tripwire found no violations")), - TSS_StringEntry( tripwire::STR_ERR_EMAIL_REPORT, _T("Email reporting failed.")), - TSS_StringEntry( tripwire::STR_ERR_EMAIL_TEST, _T("Email test failed.")), - // - // Gmms errors - // - TSS_StringEntry( tripwire::STR_ERR_BAD_GMMS_VERBOSITY, _T("Error: gmms verbosity must be 1 or 2. ")), - TSS_StringEntry( tripwire::STR_ERR_GMMS_VERBOSITY_ONLY, _T("Error: --gmms-verbosity specified without --gmms. ")), - - - TSS_StringEntry( tripwire::STR_NOTIFY_PROCESSING, _T("Processing: ")), - TSS_StringEntry( tripwire::STR_NOTIFY_CHECKING, _T("Checking: ")), - TSS_StringEntry( tripwire::STR_NOTIFY_CHECKING_RULE, _T("Checking rule: ")), - TSS_StringEntry( tripwire::STR_NOTIFY_DB_CHANGING, _T("Database update: Modifying record ")), - TSS_StringEntry( tripwire::STR_NOTIFY_DB_ADDING, _T("Database update: Adding record ")), - TSS_StringEntry( tripwire::STR_NOTIFY_DB_REMOVING, _T("Database update: Removing record ")), - TSS_StringEntry( tripwire::STR_NOTIFY_GEN_SIG, _T("Generating information for: ")), + TSS_StringEntry(tripwire::STR_EMAIL_SUBJECT_REPORT_1, _T("Tripwire report (violation count ")), + TSS_StringEntry(tripwire::STR_EMAIL_SUBJECT_REPORT_2, _T(") (max severity ")), + TSS_StringEntry(tripwire::STR_EMAIL_SUBJECT_REPORT_3, _T(")")), + TSS_StringEntry(tripwire::STR_EMAIL_REPORT_TO, _T("Emailing the report to:")), + TSS_StringEntry(tripwire::STR_EMAIL_FROM, _T("tripwire@")), + TSS_StringEntry(tripwire::STR_EMAIL_BEGIN, _T("Beginning email reporting...")), + TSS_StringEntry(tripwire::STR_EMAIL_OK_BODY, _T("Rules with no violations or errors:")), + TSS_StringEntry(tripwire::STR_EMAIL_NO_RECIPIENTS, + _T("No email recipients specified in policy file; no email sent.")), + TSS_StringEntry(tripwire::STR_EMAIL_OK_TO, _T("Emailing \"no violations\" message to:")), + TSS_StringEntry(tripwire::STR_EMAIL_SUBJECT_OK, _T("Tripwire found no violations")), + TSS_StringEntry(tripwire::STR_ERR_EMAIL_REPORT, _T("Email reporting failed.")), + TSS_StringEntry(tripwire::STR_ERR_EMAIL_TEST, _T("Email test failed.")), -TSS_EndStringtable( cTripwire ) + TSS_StringEntry(tripwire::STR_NOTIFY_PROCESSING, _T("Processing: ")), + TSS_StringEntry(tripwire::STR_NOTIFY_CHECKING, _T("Checking: ")), + TSS_StringEntry(tripwire::STR_NOTIFY_CHECKING_RULE, _T("Checking rule: ")), + TSS_StringEntry(tripwire::STR_NOTIFY_DB_CHANGING, _T("Database update: Modifying record ")), + TSS_StringEntry(tripwire::STR_NOTIFY_DB_ADDING, _T("Database update: Adding record ")), + TSS_StringEntry(tripwire::STR_NOTIFY_DB_REMOVING, _T("Database update: Removing record ")), + TSS_StringEntry(tripwire::STR_NOTIFY_GEN_SIG, _T("Generating information for: ")), + TSS_EndStringtable(cTripwire) diff --git a/src/tripwire/tripwirestrings.h b/src/tripwire/tripwirestrings.h index 587df82..53ce03a 100644 --- a/src/tripwire/tripwirestrings.h +++ b/src/tripwire/tripwirestrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,141 +37,45 @@ #include "tripwire.h" -TSS_BeginStringIds( tripwire ) +TSS_BeginStringIds(tripwire) STR_TRIPWIRE_VERSION, - STR_TRIPWIRE_HELP_INIT, - STR_TRIPWIRE_HELP_CHECK, - STR_TRIPWIRE_HELP_UPDATE, - STR_TRIPWIRE_HELP_UPDATE_POLICY, - STR_TRIPWIRE_HELP_TEST, - STR_TRIPWIRE_USAGE_SUMMARY, - STR_INTEGRITY_CHECK, - STR_IC_SUCCESS, - STR_IC_FILES, - STR_CHECKING_SPECS_NAMED, - STR_CHECKING_GENRE, - STR_IC_SEVERITY_LEVEL, - STR_IC_IGNORING_SEVERITY, - STR_IC_IGNORING_SEV_NUM, - STR_IC_IGNORING_SEV_NAME, - STR_IC_IGNORING_RULE_NAME, - STR_IC_IGNORING_GENRE_NAME, - STR_IC_NOEMAIL_SENT, - STR_NO_EMAIL_RECIPIENTS, - STR_PU_PROCESSING_GENRE, - STR_PU_INTEGRITY_CHECK, - STR_PU_UPDATE_DB, - STR_PU_PRUNING, - STR_PU_ADDING_GENRE, - STR_PU_BAD_PROPS, + STR_EMBEDDED_VERSION, STR_TRIPWIRE_HELP_INIT, STR_TRIPWIRE_HELP_CHECK, STR_TRIPWIRE_HELP_UPDATE, + STR_TRIPWIRE_HELP_UPDATE_POLICY, STR_TRIPWIRE_HELP_TEST, STR_TRIPWIRE_USAGE_SUMMARY, STR_INTEGRITY_CHECK, + STR_IC_SUCCESS, STR_IC_FILES, STR_CHECKING_SPECS_NAMED, STR_CHECKING_GENRE, STR_IC_SEVERITY_LEVEL, + STR_IC_IGNORING_SEVERITY, STR_IC_IGNORING_SEV_NUM, STR_IC_IGNORING_SEV_NAME, STR_IC_IGNORING_RULE_NAME, + STR_IC_IGNORING_GENRE_NAME, STR_IC_NOEMAIL_SENT, STR_NO_EMAIL_RECIPIENTS, STR_PU_PROCESSING_GENRE, + STR_PU_INTEGRITY_CHECK, STR_PU_UPDATE_DB, STR_PU_PRUNING, STR_PU_ADDING_GENRE, STR_PU_BAD_PROPS, STR_PROCESSING_GENRE, - - // - // GMMS specific - // - STR_GMMS_START, - STR_GMMS_END, - STR_GMMS_VERBOSITY1A, - STR_GMMS_VERBOSITY1B, - STR_GMMS_VERBOSITY2A, - STR_GMMS_VERBOSITY2B, - STR_GMMS_VERBOSITY2C, - - // - // MAPI error messages - // - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR1, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR2, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR3, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR4, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR5, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR6, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR7, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR8, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR9, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR10, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR11, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR12, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR13, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR14, - STR_ERR2_MAIL_MESSAGE_MAPI_SEND_ERRROR14_1, - STR_ERR2_MAIL_MESSAGE_SERVER, - STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR, - STR_ERR2_MAIL_MESSAGE_COMMAND, + STR_ERR2_MAIL_MESSAGE_SERVER, STR_ERR2_MAIL_MESSAGE_SERVER_RETURNED_ERROR, STR_ERR2_MAIL_MESSAGE_COMMAND, // // Tripwire Command Line // - STR_ERR_IC_EMAIL_AND_FILES, - STR_ERR_NO_MAIL_METHOD, - STR_ERR_INVALID_MAIL_METHOD, - STR_ERR_MAPI_NOT_SUPPORTED, - STR_ERR_MISSING_MAILPROGRAM, - STR_ERR_NO_TEST_MODE, - STR_GENERATING_DB, - STR_INIT_SUCCESS, - STR_ERR2_DIFFERENT_USERS1, - STR_ERR2_DIFFERENT_USERS2, - STR_ERR_IC_NO_SPECS_LEFT, - STR_ERR_BAD_PARAM, - STR_ERR_UPDATE_ED_LAUNCH, - STR_REPORT_EMPTY, - STR_DB_NOT_UPDATED, - STR_ERR_POL_UPDATE, - STR_IGNORE_PROPS, - STR_ERR_ILLEGAL_MODE_HELP, - STR_SYSLOG_IDENT, - STR_SYSLOG_INIT_MSG, - STR_SYSLOG_IC_MSG, - STR_SYSLOG_UP_MSG, - STR_SYSLOG_POLUP_MSG, - STR_SYSLOG_INIT_FAIL_MSG, - STR_SYSLOG_IC_FAIL_MSG, - STR_SYSLOG_UP_FAIL_MSG, - STR_SYSLOG_POLUP_FAIL_MSG, + STR_ERR_IC_EMAIL_AND_FILES, STR_ERR_NO_MAIL_METHOD, STR_ERR_INVALID_MAIL_METHOD, STR_ERR_MISSING_MAILPROGRAM, + STR_ERR_NO_TEST_MODE, STR_GENERATING_DB, STR_INIT_SUCCESS, STR_ERR2_DIFFERENT_USERS1, STR_ERR2_DIFFERENT_USERS2, + STR_ERR_IC_NO_SPECS_LEFT, STR_ERR_BAD_PARAM, STR_ERR_UPDATE_ED_LAUNCH, STR_REPORT_EMPTY, STR_DB_NOT_UPDATED, + STR_ERR_POL_UPDATE, STR_IGNORE_PROPS, STR_ERR_ILLEGAL_MODE_HELP, STR_SYSLOG_IDENT, STR_SYSLOG_INIT_MSG, + STR_SYSLOG_IC_MSG, STR_SYSLOG_UP_MSG, STR_SYSLOG_POLUP_MSG, STR_SYSLOG_INIT_FAIL_MSG, STR_SYSLOG_IC_FAIL_MSG, + STR_SYSLOG_UP_FAIL_MSG, STR_SYSLOG_POLUP_FAIL_MSG, // // email testing // - STR_TEST_EMAIL_TO, - STR_TEST_EMAIL_SUBJECT, - STR_TEST_EMAIL_BODY, + STR_TEST_EMAIL_TO, STR_TEST_EMAIL_SUBJECT, STR_TEST_EMAIL_BODY, // // email reporting // - STR_EMAIL_SUBJECT_REPORT_1, - STR_EMAIL_SUBJECT_REPORT_2, - STR_EMAIL_SUBJECT_REPORT_3, - STR_EMAIL_REPORT_TO, - STR_EMAIL_FROM, - STR_EMAIL_BEGIN, - STR_EMAIL_OK_BODY, - STR_EMAIL_NO_RECIPIENTS, - STR_EMAIL_OK_TO, - STR_EMAIL_SUBJECT_OK, - STR_ERR_EMAIL_REPORT, - STR_ERR_EMAIL_TEST, - - - // - // Gmms errors - // - STR_ERR_BAD_GMMS_VERBOSITY, - STR_ERR_GMMS_VERBOSITY_ONLY, + STR_EMAIL_SUBJECT_REPORT_1, STR_EMAIL_SUBJECT_REPORT_2, STR_EMAIL_SUBJECT_REPORT_3, STR_EMAIL_REPORT_TO, + STR_EMAIL_FROM, STR_EMAIL_BEGIN, STR_EMAIL_OK_BODY, STR_EMAIL_NO_RECIPIENTS, STR_EMAIL_OK_TO, STR_EMAIL_SUBJECT_OK, + STR_ERR_EMAIL_REPORT, STR_ERR_EMAIL_TEST, - - STR_NOTIFY_PROCESSING, - STR_NOTIFY_CHECKING, - STR_NOTIFY_CHECKING_RULE, - STR_NOTIFY_DB_CHANGING, - STR_NOTIFY_DB_ADDING, + STR_NOTIFY_PROCESSING, STR_NOTIFY_CHECKING, STR_NOTIFY_CHECKING_RULE, STR_NOTIFY_DB_CHANGING, STR_NOTIFY_DB_ADDING, STR_NOTIFY_DB_REMOVING, STR_NOTIFY_GEN_SIG -TSS_EndStringIds( tripwire ) + TSS_EndStringIds(tripwire) #endif - diff --git a/src/tripwire/tripwireutil.cpp b/src/tripwire/tripwireutil.cpp index 69a5e32..a2864ee 100644 --- a/src/tripwire/tripwireutil.cpp +++ b/src/tripwire/tripwireutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,50 +52,49 @@ /////////////////////////////////////////////////////////////////////////////// // CalcProps /////////////////////////////////////////////////////////////////////////////// -void cTripwireUtil::CalcProps( iFCO* pFCO, const iFCOSpec* pSpec, iFCOPropCalc* pCalc, iFCOPropDisplayer* pPD ) +void cTripwireUtil::CalcProps(iFCO* pFCO, const iFCOSpec* pSpec, iFCOPropCalc* pCalc, iFCOPropDisplayer* pPD) { // verbose output... - TW_NOTIFY_VERBOSE( _T("--- %s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_GEN_SIG ).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( pFCO->GetName() ).c_str() ); + TW_NOTIFY_VERBOSE(_T("--- %s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_GEN_SIG).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(pFCO->GetName()).c_str()); + - const cFCOPropVector& propsToCalc = pSpec->GetPropVector(pSpec->GetSpecMask(pFCO)); // set the appropriate property mask for this fco pCalc->SetPropVector(propsToCalc); // do the calculation pFCO->AcceptVisitor(pCalc->GetVisitor()); - // + // // invalidate unneeded properties.... // I want to invalidate everything that is in the fco but not in the spec... // - cFCOPropVector propsToInvalidate = pFCO->GetPropSet()->GetValidVector(); - propsToInvalidate ^= propsToCalc; - pFCO->GetPropSet()->InvalidateProps( propsToInvalidate ); + cFCOPropVector propsToInvalidate = pFCO->GetPropSet()->GetValidVector(); + propsToInvalidate ^= propsToCalc; + pFCO->GetPropSet()->InvalidateProps(propsToInvalidate); // // load this fco's data into the prop displayer // - if( pPD ) - pPD->InitForFCO( pFCO ); + if (pPD) + pPD->InitForFCO(pFCO); } /////////////////////////////////////////////////////////////////////////////// // RemoveFCOFromDb /////////////////////////////////////////////////////////////////////////////// -bool cTripwireUtil::RemoveFCOFromDb( cFCOName name, cDbDataSourceIter& dbIter) +bool cTripwireUtil::RemoveFCOFromDb(cFCOName name, cDbDataSourceIter& dbIter) { cDebug d("cTripwireUtil::RemoveFCOFromDb"); //cDbDataSourceIter dbIter( &db ); // seek to the fco to be removed.. // - dbIter.SeekToFCO( name, false ); + dbIter.SeekToFCO(name, false); // // error if the fco doesn't exist... // - if( dbIter.Done() || ( ! dbIter.HasFCOData() ) ) + if (dbIter.Done() || (!dbIter.HasFCOData())) { return false; } @@ -104,8 +103,8 @@ bool cTripwireUtil::RemoveFCOFromDb( cFCOName name, cDbDataSourceIter& dbIter) // remove the fco data... // d.TraceDebug(_T(">>> Removing FCO %s\n"), dbIter.GetName().AsString().c_str()); - dbIter.RemoveFCOData() ; - if( ! dbIter.CanDescend() ) + dbIter.RemoveFCOData(); + if (!dbIter.CanDescend()) { // note that this is not sufficient to remove all unused nodes from the database... // @@ -116,19 +115,19 @@ bool cTripwireUtil::RemoveFCOFromDb( cFCOName name, cDbDataSourceIter& dbIter) // get rid of all the empty parents above me... // TODO -- is this the right thing to do all the time? // - while( ! dbIter.AtRoot() ) + while (!dbIter.AtRoot()) { cFCOName parentName = dbIter.GetParentName(); dbIter.Ascend(); - dbIter.SeekTo( parentName.GetShortName() ); - ASSERT( ! dbIter.Done() ); - if( (! dbIter.Done()) && (dbIter.CanRemoveChildArray()) ) + dbIter.SeekTo(parentName.GetShortName()); + ASSERT(!dbIter.Done()); + if ((!dbIter.Done()) && (dbIter.CanRemoveChildArray())) { dbIter.RemoveChildArray(); // // and, remove this node if there is no fco data... // - if( ! dbIter.HasFCOData() ) + if (!dbIter.HasFCOData()) { d.TraceDebug(_T(">>> Removing Database Node %s\n"), dbIter.GetName().AsString().c_str()); dbIter.RemoveFCO(); @@ -136,13 +135,10 @@ bool cTripwireUtil::RemoveFCOFromDb( cFCOName name, cDbDataSourceIter& dbIter) else break; } - else + else break; } - } return true; } - - diff --git a/src/tripwire/tripwireutil.h b/src/tripwire/tripwireutil.h index 51d4857..5a952a6 100644 --- a/src/tripwire/tripwireutil.h +++ b/src/tripwire/tripwireutil.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // tripwireutil.h // -// utility functions for the top-level tripwire functionality implemented in +// utility functions for the top-level tripwire functionality implemented in // cTripwire #ifndef __TRIPWIREUTIL_H #define __TRIPWIREUTIL_H @@ -48,21 +48,19 @@ class cHierDatabase; class cTripwireUtil { public: + static void CalcProps(iFCO* pFCO, const iFCOSpec* pSpec, iFCOPropCalc* pCalc, iFCOPropDisplayer* pPD); + // this method calculates exactly the properties specified by pSpec (invalidating any extra ones) + // for iFCO. It is OK to pass NULL for pPD if you don't want the property calculator run over the fco; + // otherwise, InitForFCO() is called after the property calculation is done. + // TODO -- I should determine what exceptions will come up from this and document it - static void CalcProps( iFCO* pFCO, const iFCOSpec* pSpec, iFCOPropCalc* pCalc, iFCOPropDisplayer* pPD ); - // this method calculates exactly the properties specified by pSpec (invalidating any extra ones) - // for iFCO. It is OK to pass NULL for pPD if you don't want the property calculator run over the fco; - // otherwise, InitForFCO() is called after the property calculation is done. - // TODO -- I should determine what exceptions will come up from this and document it - - static bool RemoveFCOFromDb( cFCOName name, cDbDataSourceIter& dbIter); - // removes the named fco from the passed in database. This asserts that the iterator is not done, - // and gracefully handles the case where there is no fco data associated with the current node. - // also, if there is an empty subtree below this node (ie -- hier nodes with no FCO data) this method - // will remove them from the database. - // this returns true if fco data was actually removed from the database. + static bool RemoveFCOFromDb(cFCOName name, cDbDataSourceIter& dbIter); + // removes the named fco from the passed in database. This asserts that the iterator is not done, + // and gracefully handles the case where there is no fco data associated with the current node. + // also, if there is an empty subtree below this node (ie -- hier nodes with no FCO data) this method + // will remove them from the database. + // this returns true if fco data was actually removed from the database. }; #endif //__TRIPWIREUTIL_H - diff --git a/src/tripwire/twcmdline.cpp b/src/tripwire/twcmdline.cpp index 880b93f..cd17bfc 100644 --- a/src/tripwire/twcmdline.cpp +++ b/src/tripwire/twcmdline.cpp @@ -1,61 +1,61 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // twcmdline.cpp #include "stdtripwire.h" -#include "twcmdline.h" +#include "twcmdline.h" #include "core/cmdlineparser.h" #include "tw/configfile.h" -#include "core/serializerimpl.h" // cSerializerImpl -#include "core/archive.h" // cArchive and friends -#include "fco/fcospeclist.h" // cFCOSpecList -#include "tripwirestrings.h" // tripwire.exe specific strings -#include "twcrypto/keyfile.h" // cKeyFile -- used for encryption +#include "core/serializerimpl.h" // cSerializerImpl +#include "core/archive.h" // cArchive and friends +#include "fco/fcospeclist.h" // cFCOSpecList +#include "tripwirestrings.h" // tripwire.exe specific strings +#include "twcrypto/keyfile.h" // cKeyFile -- used for encryption #include "tw/twutil.h" -#include "twcmdlineutil.h" // utility functions for the cmd line +#include "twcmdlineutil.h" // utility functions for the cmd line #include "tw/fcoreport.h" // for reports #include "tw/textreportviewer.h" // text report viewer -#include "core/usernotify.h" // for notifying the user of events -#include "tw/fcoreportutil.h" // for finalizing report +#include "core/usernotify.h" // for notifying the user of events +#include "tw/fcoreportutil.h" // for finalizing report #include "tw/fcodatabaseutil.h" // for finalizing database -#include "tw/headerinfo.h" // for finalizing database +#include "tw/headerinfo.h" // for finalizing database #include "fco/fcopropdisplayer.h" #include "tw/systeminfo.h" #include "tw/filemanipulator.h" #include "fco/twfactory.h" -#include "mailmessage.h" // used for email reporting +#include "mailmessage.h" // used for email reporting #include "fco/genrespeclist.h" -#include "core/twlimits.h" // for severity limits +#include "core/twlimits.h" // for severity limits #include "core/errorgeneral.h" #include "core/corestrings.h" #include "tw/twerrors.h" @@ -72,31 +72,29 @@ #include "integritycheck.h" #include "updatedb.h" #include "policyupdate.h" +#include "core/platform.h" #ifdef TW_PROFILE #include "tasktimer.h" #endif -#if IS_UNIX -#include "fs/fsdatasourceiter.h" // for cross file systems flag -#include // for _exit() -#endif - +#include "fs/fsdatasourceiter.h" // for cross file systems flag +#include // for _exit() //----------------------------------------------------------------------------- // #defines //----------------------------------------------------------------------------- // this is used to make required condition checking in the Init() functions a little more compact -#define TEST_INIT_REQUIREMENT(t, c, n)\ - if(! t)\ - {\ - cTWUtil::PrintErrorMsg(eTWInitialization(TSS_GetString( c, n ), 0)); \ - return false;\ - } +#define TEST_INIT_REQUIREMENT(t, c, n) \ + if (!t) \ + { \ + cTWUtil::PrintErrorMsg(eTWInitialization(TSS_GetString(c, n), 0)); \ + return false; \ + } -static bool util_GetEditor( TSTRING& strEd ); +static bool util_GetEditor(TSTRING& strEd); //############################################################################# // cTWCmdLine @@ -104,123 +102,121 @@ static bool util_GetEditor( TSTRING& strEd ); /////////////////////////////////////////////////////////////////////////////// -// GetMode -- processes the command line arguments and creates an appropriate +// GetMode -- processes the command line arguments and creates an appropriate // structure for the selected mode, or NULL if an error occurs /////////////////////////////////////////////////////////////////////////////// -iTWMode* cTWCmdLine::GetMode(int argc, const TCHAR *const * argv) +iTWMode* cTWCmdLine::GetMode(int argc, const TCHAR* const* argv) { - // note -- it is assumed the executable name is the first parameter - if(argc < 2) - { - TCOUT << TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - return NULL; - } - - int mode = MODE; - const TCHAR* pcMode; - if(_tcscmp(argv[1], _T("-m")) == 0) - { - if(argc < 3) - { - TCOUT << TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_ERR_NO_MODE) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - return NULL; - } - pcMode = argv[2]; - if (_tcscmp(argv[2], _T("i")) == 0) - mode = MODE_INIT; - else if (_tcscmp(argv[2], _T("c")) == 0) - mode = MODE_CHECK; - else if (_tcscmp(argv[2], _T("u")) == 0) - mode = MODE_UPDATE_DB; - else if (_tcscmp(argv[2], _T("p")) == 0) - mode = MODE_UPDATE_POL; - else if (_tcscmp(argv[2], _T("t")) == 0) - mode = MODE_TEST; - } - else - { - pcMode = argv[1]; - if (_tcscmp(argv[1], _T("--init")) == 0) - mode = MODE_INIT; - else if (_tcscmp(argv[1], _T("--check")) == 0) - mode = MODE_CHECK; - else if (_tcscmp(argv[1], _T("--update")) == 0) - mode = MODE_UPDATE_DB; - else if (_tcscmp(argv[1], _T("--update-policy")) == 0) - mode = MODE_UPDATE_POL; - else if (_tcscmp(argv[1], _T("--version")) == 0) + // note -- it is assumed the executable name is the first parameter + if (argc < 2) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + return NULL; + } + + int mode = MODE; + const TCHAR* pcMode; + if (_tcscmp(argv[1], _T("-m")) == 0) + { + if (argc < 3) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_ERR_NO_MODE) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + return NULL; + } + pcMode = argv[2]; + if (_tcscmp(argv[2], _T("i")) == 0) + mode = MODE_INIT; + else if (_tcscmp(argv[2], _T("c")) == 0) + mode = MODE_CHECK; + else if (_tcscmp(argv[2], _T("u")) == 0) + mode = MODE_UPDATE_DB; + else if (_tcscmp(argv[2], _T("p")) == 0) + mode = MODE_UPDATE_POL; + else if (_tcscmp(argv[2], _T("t")) == 0) + mode = MODE_TEST; + } + else + { + pcMode = argv[1]; + if (_tcscmp(argv[1], _T("--init")) == 0) + mode = MODE_INIT; + else if (_tcscmp(argv[1], _T("--check")) == 0) + mode = MODE_CHECK; + else if (_tcscmp(argv[1], _T("--update")) == 0) + mode = MODE_UPDATE_DB; + else if (_tcscmp(argv[1], _T("--update-policy")) == 0) + mode = MODE_UPDATE_POL; + else if (_tcscmp(argv[1], _T("--version")) == 0) mode = MODE_VERSION; else if (_tcscmp(argv[1], _T("--help")) == 0 || _tcscmp(argv[1], _T("-?")) == 0) - mode = MODE_HELP; - else if (_tcscmp(argv[1], _T("--test")) == 0) - mode = MODE_TEST; - -#ifdef _DEBUG_DB - if (_tcscmp(argv[1], _T("--explore")) == 0) - mode = MODE_EXPLORE; - if (_tcscmp(argv[1], _T("--verifydb")) == 0) - mode = MODE_DEBUG; + mode = MODE_HELP; + else if (_tcscmp(argv[1], _T("--test")) == 0) + mode = MODE_TEST; + +#ifdef DEBUG + if (_tcscmp(argv[1], _T("--explore")) == 0) + mode = MODE_EXPLORE; + if (_tcscmp(argv[1], _T("--verifydb")) == 0) + mode = MODE_DEBUG; #endif + } + if (mode == MODE) + { + // unknown mode switch + cDebug d("cTWCmdLine::GetMode"); + d.TraceError(_T("Error: Bad mode switch: %s\n"), pcMode); + TCERR << TSS_GetString(cTW, tw::STR_UNKNOWN_MODE_SPECIFIED) << pcMode << std::endl + << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; + return NULL; } - - if(mode == MODE) - { - // unknown mode switch - cDebug d("cTWCmdLine::GetMode"); - d.TraceError(_T("Error: Bad mode switch: %s\n"), pcMode); - TCERR << TSS_GetString( cTW, tw::STR_UNKOWN_MODE_SPECIFIED) - << pcMode << std::endl - << TSS_GetString( cTW, tw::STR_GET_HELP) << std::endl; - return NULL; - } - - - iTWMode* pRtn = 0; - switch(mode) - { - case cTWCmdLine::MODE_INIT: - pRtn = new cTWModeDbInit; - break; - case cTWCmdLine::MODE_CHECK: - pRtn = new cTWModeIC; - break; - case cTWCmdLine::MODE_UPDATE_DB: - pRtn = new cTWModeDbUpdate; - break; - case cTWCmdLine::MODE_UPDATE_POL: - pRtn = new cTWModePolUpdate; - break; - case cTWCmdLine::MODE_TEST: - pRtn = new cTWModeTest; - break; - case cTWCmdLine::MODE_HELP: - pRtn = new cTWModeHelp; - break; + + + iTWMode* pRtn = 0; + switch (mode) + { + case cTWCmdLine::MODE_INIT: + pRtn = new cTWModeDbInit; + break; + case cTWCmdLine::MODE_CHECK: + pRtn = new cTWModeIC; + break; + case cTWCmdLine::MODE_UPDATE_DB: + pRtn = new cTWModeDbUpdate; + break; + case cTWCmdLine::MODE_UPDATE_POL: + pRtn = new cTWModePolUpdate; + break; + case cTWCmdLine::MODE_TEST: + pRtn = new cTWModeTest; + break; + case cTWCmdLine::MODE_HELP: + pRtn = new cTWModeHelp; + break; case cTWCmdLine::MODE_VERSION: pRtn = new cTWModeVersion; break; -//Explore and Debug modes are invisible unless _DEBUG_DB is defined. -#ifdef _DEBUG_DB - case cTWCmdLine::MODE_EXPLORE: - pRtn = new cTWModeExploreDb; - break; - case cTWCmdLine::MODE_DEBUG: - pRtn = new cTWModeDebugDb; - break; +//Explore and Debug modes are invisible unless DEBUG is defined. +#ifdef DEBUG + case cTWCmdLine::MODE_EXPLORE: + pRtn = new cTWModeExploreDb; + break; + case cTWCmdLine::MODE_DEBUG: + pRtn = new cTWModeDebugDb; + break; #endif - default: - ASSERT(false); - } + default: + ASSERT(false); + } - return pRtn; + return pRtn; } /////////////////////////////////////////////////////////////////////////////// @@ -229,304 +225,406 @@ iTWMode* cTWCmdLine::GetMode(int argc, const TCHAR *const * argv) /////////////////////////////////////////////////////////////////////////////// static void InitCmdLineCommon(cCmdLineParser& parser) { - parser.AddArg(cTWCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); - //parser.AddArg(cTWCmdLine::NO_BACKUP, TSTRING(_T("B")), TSTRING(_T("nobackup")), cCmdLineParser::PARAM_NONE); - // this was dropped from 1.5 -- mdb - parser.AddArg(cTWCmdLine::LOCAL_PASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")),cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::POL_FILE, TSTRING(_T("p")), TSTRING(_T("polfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::DB_FILE, TSTRING(_T("d")), TSTRING(_T("dbfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWCmdLine::REPORT_FILE, TSTRING(_T("r")), TSTRING(_T("twrfile")), cCmdLineParser::PARAM_ONE); - - // - // mutual exclusions - // - parser.AddMutEx(cTWCmdLine::VERBOSE, cTWCmdLine::SILENT); + parser.AddArg(cTWCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); + //parser.AddArg(cTWCmdLine::NO_BACKUP, TSTRING(_T("B")), TSTRING(_T("nobackup")), cCmdLineParser::PARAM_NONE); + // this was dropped from 1.5 -- mdb + parser.AddArg( + cTWCmdLine::LOCAL_PASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::POL_FILE, TSTRING(_T("p")), TSTRING(_T("polfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::DB_FILE, TSTRING(_T("d")), TSTRING(_T("dbfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWCmdLine::REPORT_FILE, TSTRING(_T("r")), TSTRING(_T("twrfile")), cCmdLineParser::PARAM_ONE); + // + // mutual exclusions + // + parser.AddMutEx(cTWCmdLine::VERBOSE, cTWCmdLine::SILENT); } + /////////////////////////////////////////////////////////////////////////////// -// FillOutConfigInfo -- fills out all the common info with config file information +// Set up temp directory /////////////////////////////////////////////////////////////////////////////// -static void FillOutConfigInfo(cTWModeCommon* pModeInfo, const cConfigFile& cf) +static void util_InitTempDirectory(const cConfigFile& cf) { - TSTRING str; - if(cf.Lookup(TSTRING(_T("POLFILE")), str)) - pModeInfo->mPolFile = str; - if(cf.Lookup(TSTRING(_T("DBFILE")), str)) - pModeInfo->mDbFile = str; - if(cf.Lookup(TSTRING(_T("SITEKEYFILE")), str)) - pModeInfo->mSiteKeyFile = str; - if(cf.Lookup(TSTRING(_T("LOCALKEYFILE")), str)) - pModeInfo->mLocalKeyFile = str; - if(cf.Lookup(TSTRING(_T("REPORTFILE")), str)) - pModeInfo->mReportFile = str; - if(cf.Lookup(TSTRING(_T("EDITOR")), str)) - pModeInfo->mEditor = str; - if(cf.Lookup(TSTRING(_T("LATEPROMPTING")), str)) - { - if (_tcsicmp(str.c_str(), _T("true")) == 0) - pModeInfo->mbLatePassphrase = true; - } - if(cf.Lookup(TSTRING(_T("RESETACCESSTIME")), str)) - { - - -#if IS_UNIX - // We do not support reset access time on Unix, so we issue a warning. - // This used to be a fatal error, however this prevents - // cross platform config files. - cTWUtil::PrintErrorMsg(eTWInvalidConfigFileKey(_T("RESETACCESSTIME"), eError::NON_FATAL)); -#endif + TSTRING temp_directory; + cf.Lookup(TSTRING(_T("TEMPDIRECTORY")), temp_directory); - } - if(cf.Lookup(TSTRING(_T("LOOSEDIRECTORYCHECKING")), str)) + if (temp_directory.empty()) { - if (_tcsicmp(str.c_str(), _T("true")) == 0) - pModeInfo->mfLooseDirs = true; - } - - if (cf.Lookup(TSTRING(_T("TEMPDIRECTORY")), str)) { - - if (str.length() == 0) - str = "/tmp/"; +#if IS_AROS + temp_directory = "T:"; +#elif IS_DOS_DJGPP + temp_directory = "/dev/c/temp/"; +#elif IS_RISCOS + temp_directory = "/!BOOT/Resources/!Scrap/ScrapDirs/ScrapDir"; +#elif IS_REDOX + temp_directory = "/file/tmp/"; +#else + temp_directory = "/tmp/"; +#endif + } +#if !IS_RISCOS // make sure we have a trailing slash -- thanks Jarno... // - if (str[_tcslen(str.c_str())-1] != '/') { - str += '/'; + if (*temp_directory.rbegin() != '/') + { + temp_directory.push_back('/'); } +#endif // make sure it exists... // +#if IS_AROS || IS_RISCOS + temp_directory = cDevicePath::AsNative(temp_directory); +#elif IS_DOS_DJGPP + temp_directory = cDevicePath::AsPosix(temp_directory); +#endif -#ifdef __AROS__ - str = cArosPath::AsNative(str); + if (access(temp_directory.c_str(), F_OK) != 0) + { + TSTRING errStr = TSS_GetString(cCore, core::STR_BAD_TEMPDIRECTORY); + TSTRING tmpStr = _T("Directory: "); + tmpStr += (temp_directory + _T("\n")); + tmpStr += errStr; + throw eTWInvalidTempDirectory(tmpStr); + } + else + { +#if IS_RISCOS + if (*temp_directory.rbegin() != '.') + { + temp_directory.push_back('.'); + } #endif - if (access(str.c_str(), F_OK) != 0) { - TSTRING errStr = TSS_GetString( cCore, core::STR_BAD_TEMPDIRECTORY ); - TSTRING tmpStr = _T("Directory: "); - tmpStr += (str + _T("\n")); - tmpStr += errStr; - throw eTWInvalidTempDirectory(tmpStr); + iFSServices::GetInstance()->SetTempDirName(temp_directory); } - else { - iFSServices::GetInstance()->SetTempDirName(str); +} + + +/////////////////////////////////////////////////////////////////////////////// +// Set up various email reporting options +/////////////////////////////////////////////////////////////////////////////// +static void util_InitEmailOptions(cTWModeCommon* pModeInfo, const cConfigFile& cf) +{ + TSTRING str; + if (cf.Lookup(TSTRING(_T("GLOBALEMAIL")), str)) + { + if (str.length() != 0) + pModeInfo->mGlobalEmail = str; } - } + // + // Set the report-viewing level if one has been specified, use + // default level otherwise. + // + if (cf.Lookup(TSTRING(_T("EMAILREPORTLEVEL")), str)) + { + if (_tcsicmp(str.c_str(), _T("0")) == 0) + pModeInfo->mEmailReportLevel = cTextReportViewer::SINGLE_LINE; + else if (_tcsicmp(str.c_str(), _T("1")) == 0) + pModeInfo->mEmailReportLevel = cTextReportViewer::PARSEABLE; + else if (_tcsicmp(str.c_str(), _T("2")) == 0) + pModeInfo->mEmailReportLevel = cTextReportViewer::SUMMARY_ONLY; + else if (_tcsicmp(str.c_str(), _T("3")) == 0) + pModeInfo->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; + else if (_tcsicmp(str.c_str(), _T("4")) == 0) + pModeInfo->mEmailReportLevel = cTextReportViewer::FULL_REPORT; + else + { + // They specified an illegal level, error. + TSTRING errStr = _T("Invalid Level: "); + errStr += str; + throw eTWInvalidReportLevelCfg(errStr); + } + } + else + { + // no level was specified in the configuration file, use default. + pModeInfo->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; + } - if (cf.Lookup(TSTRING(_T("GLOBALEMAIL")), str)) { + // Decide what mail method should be used to email reports + if (cf.Lookup(TSTRING(_T("MAILMETHOD")), str)) + { + if (_tcsicmp(str.c_str(), _T("SENDMAIL")) == 0) + pModeInfo->mMailMethod = cMailMessage::MAIL_BY_PIPE; + else if (_tcsicmp(str.c_str(), _T("SMTP")) == 0) + pModeInfo->mMailMethod = cMailMessage::MAIL_BY_SMTP; + else + pModeInfo->mMailMethod = cMailMessage::INVALID_METHOD; + } + else + { + pModeInfo->mMailMethod = cMailMessage::NO_METHOD; + } - if (str.length() != 0) - pModeInfo->mGlobalEmail = str; - } +#if !SUPPORTS_NETWORKING + if (pModeInfo->mMailMethod == cMailMessage::MAIL_BY_SMTP) + throw eMailSMTPNotSupported(); +#endif - // - // Set the report-viewing level if one has been specified, use - // default level otherwise. - // - if(cf.Lookup(TSTRING(_T("EMAILREPORTLEVEL")), str)) + // Get the SMTP server + if (cf.Lookup(TSTRING(_T("SMTPHOST")), str)) { - if (_tcsicmp(str.c_str(), _T("0")) == 0) - pModeInfo->mEmailReportLevel = cTextReportViewer::SINGLE_LINE; - else if (_tcsicmp(str.c_str(), _T("1")) == 0) - pModeInfo->mEmailReportLevel = cTextReportViewer::PARSEABLE; - else if (_tcsicmp(str.c_str(), _T("2")) == 0) - pModeInfo->mEmailReportLevel = cTextReportViewer::SUMMARY_ONLY; - else if (_tcsicmp(str.c_str(), _T("3")) == 0) - pModeInfo->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; - else if (_tcsicmp(str.c_str(), _T("4")) == 0) - pModeInfo->mEmailReportLevel = cTextReportViewer::FULL_REPORT; - else - { - // They specified an illegal level, error. - TSTRING errStr = _T("Invalid Level: "); - errStr += str; - throw eTWInvalidReportLevelCfg( errStr ); - } + pModeInfo->mSmtpHost = str; + } + else + { + pModeInfo->mSmtpHost = _T("127.0.0.1"); // this is the default } - else - // no level was specified in the configuration file, use default. - pModeInfo->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; + // Get the SMTP port number + if (cf.Lookup(TSTRING(_T("SMTPPORT")), str)) + { + int i = _ttoi(str.c_str()); + if (i < 0 || i > SHRT_MAX) + throw eTWInvalidPortNumber(str); + pModeInfo->mSmtpPort = static_cast(i); + } + else + { + pModeInfo->mSmtpPort = 25; // this is the default + } - // Decide what mail method should be used to email reports - if(cf.Lookup(TSTRING(_T("MAILMETHOD")), str)) + // Get the mail program to use if we're piping our email + if (cf.Lookup(TSTRING(_T("MAILPROGRAM")), str)) { - if (_tcsicmp(str.c_str(), _T("SENDMAIL")) == 0) - pModeInfo->mMailMethod = cMailMessage::MAIL_BY_PIPE; - else if (_tcsicmp(str.c_str(), _T("MAPI")) == 0) - pModeInfo->mMailMethod = cMailMessage::MAIL_BY_MAPI; // NT support only - else if( _tcsicmp( str.c_str(), _T("SMTP") ) == 0 ) - pModeInfo->mMailMethod = cMailMessage::MAIL_BY_SMTP; - else - pModeInfo->mMailMethod = cMailMessage::INVALID_METHOD; + pModeInfo->mMailProgram = str; } - else + else { - pModeInfo->mMailMethod = cMailMessage::NO_METHOD; + pModeInfo->mMailProgram.erase(); // MAILPROGRAM is not required to be specified } - // Get the SMTP server - if(cf.Lookup(TSTRING(_T("SMTPHOST")), str)) - pModeInfo->mSmtpHost = str; - else - pModeInfo->mSmtpHost = _T("127.0.0.1"); // this is the default + // Get the mail program to use if we're piping our email + if (cf.Lookup(TSTRING(_T("MAILNOVIOLATIONS")), str)) + { + if (_tcsicmp(str.c_str(), _T("true")) == 0) + pModeInfo->mMailNoViolations = true; + else + pModeInfo->mMailNoViolations = false; + } + else + { + pModeInfo->mMailNoViolations = true; // MAILPROGRAM is not required to be specified + } - // Get the SMTP port number - if(cf.Lookup(TSTRING(_T("SMTPPORT")), str)) + if (cf.Lookup(TSTRING(_T("MAILFROMADDRESS")), str)) { - int i = _ttoi( str.c_str() ); - if( i < 0 || i > SHRT_MAX ) - throw eTWInvalidPortNumber( str ); - pModeInfo->mSmtpPort = static_cast( i ); + pModeInfo->mMailFrom = str; } - else - pModeInfo->mSmtpPort = 25; // this is the default +} - // Get the mail program to use if we're piping our email - if(cf.Lookup(TSTRING(_T("MAILPROGRAM")), str)) - pModeInfo->mMailProgram = str; - else - pModeInfo->mMailProgram.erase(); // MAILPROGRAM is not required to be specified - // Get the mail program to use if we're piping our email - if(cf.Lookup(TSTRING(_T("MAILNOVIOLATIONS")), str)) +/////////////////////////////////////////////////////////////////////////////// +// FillOutConfigInfo -- fills out all the common info with config file information +/////////////////////////////////////////////////////////////////////////////// +static void FillOutConfigInfo(cTWModeCommon* pModeInfo, const cConfigFile& cf) +{ + TSTRING str; + if (cf.Lookup(TSTRING(_T("POLFILE")), str)) + { + pModeInfo->mPolFile = str; + } + if (cf.Lookup(TSTRING(_T("DBFILE")), str)) + { + pModeInfo->mDbFile = str; + } + if (cf.Lookup(TSTRING(_T("SITEKEYFILE")), str)) + { + pModeInfo->mSiteKeyFile = str; + } + if (cf.Lookup(TSTRING(_T("LOCALKEYFILE")), str)) + { + pModeInfo->mLocalKeyFile = str; + } + if (cf.Lookup(TSTRING(_T("REPORTFILE")), str)) + { + pModeInfo->mReportFile = str; + } + if (cf.Lookup(TSTRING(_T("EDITOR")), str)) + { + pModeInfo->mEditor = str; + } + if (cf.Lookup(TSTRING(_T("LATEPROMPTING")), str)) + { + if (_tcsicmp(str.c_str(), _T("true")) == 0) + pModeInfo->mbLatePassphrase = true; + } + if (cf.Lookup(TSTRING(_T("RESETACCESSTIME")), str)) + { + // We do not support reset access time on Unix, so we issue a warning. + // This used to be a fatal error, however this prevents + // cross platform config files. + cTWUtil::PrintErrorMsg(eTWInvalidConfigFileKey(_T("RESETACCESSTIME"), eError::NON_FATAL)); + } + if (cf.Lookup(TSTRING(_T("LOOSEDIRECTORYCHECKING")), str)) { - if (_tcsicmp(str.c_str(), _T("true")) == 0) - pModeInfo->mMailNoViolations = true; - else - pModeInfo->mMailNoViolations = false; + if (_tcsicmp(str.c_str(), _T("true")) == 0) + pModeInfo->mfLooseDirs = true; } - else - pModeInfo->mMailNoViolations = true; // MAILPROGRAM is not required to be specified - if(cf.Lookup(TSTRING(_T("MAILFROMADDRESS")), str)) - pModeInfo->mMailFrom = str; + util_InitTempDirectory(cf); - // SYSLOG reporting - if(cf.Lookup(TSTRING(_T("SYSLOGREPORTING")), str)) + util_InitEmailOptions(pModeInfo, cf); + + // SYSLOG reporting + if (cf.Lookup(TSTRING(_T("SYSLOGREPORTING")), str)) + { + if (_tcsicmp(str.c_str(), _T("true")) == 0) + { +#if SUPPORTS_SYSLOG + pModeInfo->mbLogToSyslog = true; +#else + eTWSyslogNotSupported e; + e.SetFatality(false); + cErrorReporter::PrintErrorMsg(e); + pModeInfo->mbLogToSyslog = false; +#endif + } + else + pModeInfo->mbLogToSyslog = false; + } + else { - if (_tcsicmp(str.c_str(), _T("true")) == 0) - pModeInfo->mbLogToSyslog = true; - else pModeInfo->mbLogToSyslog = false; } - else - pModeInfo->mbLogToSyslog = false; - - // Crossing file systems - if(cf.Lookup(TSTRING(_T("CROSSFILESYSTEMS")), str)) - { - if (_tcsicmp(str.c_str(), _T("true")) == 0) - pModeInfo->mbCrossFileSystems = true; - else - pModeInfo->mbCrossFileSystems = false; - } - - // - // turn all of the file names into full paths (they're relative to the exe dir) - // - TSTRING fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mPolFile, cSystemInfo::GetExeDir() )) - pModeInfo->mPolFile = fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mDbFile, cSystemInfo::GetExeDir() )) - pModeInfo->mDbFile = fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mSiteKeyFile, cSystemInfo::GetExeDir() )) - pModeInfo->mSiteKeyFile = fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mLocalKeyFile, cSystemInfo::GetExeDir() )) - pModeInfo->mLocalKeyFile = fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mReportFile, cSystemInfo::GetExeDir() )) - pModeInfo->mReportFile = fullPath; + + // Crossing file systems + if (cf.Lookup(TSTRING(_T("CROSSFILESYSTEMS")), str)) + { + if (_tcsicmp(str.c_str(), _T("true")) == 0) + pModeInfo->mbCrossFileSystems = true; + else + pModeInfo->mbCrossFileSystems = false; + } + + if (cf.Lookup(TSTRING(_T("HASH_DIRECT_IO")), str)) + { +#if SUPPORTS_DIRECT_IO + if (_tcsicmp(str.c_str(), _T("true")) == 0) + { + pModeInfo->mbDirectIO = true; + cArchiveSigGen::SetUseDirectIO(true); + } +#else + throw eTWDirectIONotSupported(); +#endif + } + + if (cf.Lookup(TSTRING(_T("RESOLVE_IDS_TO_NAMES")), str)) + { + if (_tcsicmp(str.c_str(), _T("true")) == 0) + iFSServices::GetInstance()->SetResolveNames(true); + else + iFSServices::GetInstance()->SetResolveNames(false); + } + + // + // turn all of the file names into full paths (they're relative to the exe dir) + // + TSTRING fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mPolFile, cSystemInfo::GetExeDir())) + pModeInfo->mPolFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mDbFile, cSystemInfo::GetExeDir())) + pModeInfo->mDbFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mSiteKeyFile, cSystemInfo::GetExeDir())) + pModeInfo->mSiteKeyFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mLocalKeyFile, cSystemInfo::GetExeDir())) + pModeInfo->mLocalKeyFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mReportFile, cSystemInfo::GetExeDir())) + pModeInfo->mReportFile = fullPath; } /////////////////////////////////////////////////////////////////////////////// -// FillOutCmdLineInfo -- fills out info common to all modes that appears on the +// FillOutCmdLineInfo -- fills out info common to all modes that appears on the // command line. /////////////////////////////////////////////////////////////////////////////// static void FillOutCmdLineInfo(cTWModeCommon* pModeInfo, const cCmdLineParser& cmdLine) -{ - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::VERBOSE: - pModeInfo->mVerbosity = 2; - break; - case cTWCmdLine::SILENT: - pModeInfo->mVerbosity = 0; - break; - case cTWCmdLine::POL_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mPolFile = iter.ParamAt(0); - break; - case cTWCmdLine::SITE_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mSiteKeyFile = iter.ParamAt(0); - break; - case cTWCmdLine::LOCAL_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mLocalKeyFile = iter.ParamAt(0); - break; - case cTWCmdLine::DB_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mDbFile = iter.ParamAt(0); - break; - case cTWCmdLine::REPORT_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mReportFile = iter.ParamAt(0); - break; - case cTWCmdLine::LOCAL_PASSPHRASE: - { +{ + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::VERBOSE: + pModeInfo->mVerbosity = 2; + break; + case cTWCmdLine::SILENT: + pModeInfo->mVerbosity = 0; + break; + case cTWCmdLine::POL_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mPolFile = iter.ParamAt(0); + break; + case cTWCmdLine::SITE_KEY_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mSiteKeyFile = iter.ParamAt(0); + break; + case cTWCmdLine::LOCAL_KEY_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mLocalKeyFile = iter.ParamAt(0); + break; + case cTWCmdLine::DB_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mDbFile = iter.ParamAt(0); + break; + case cTWCmdLine::REPORT_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mReportFile = iter.ParamAt(0); + break; + case cTWCmdLine::LOCAL_PASSPHRASE: + { ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser pModeInfo->mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - pModeInfo->mLocalProvided = true; - } - break; + pModeInfo->mLocalProvided = true; + } + break; /* case cTWCmdLine::NO_BACKUP: pModeInfo->mbBackup = false; break; */ } - } - - // - // turn all of the file names into full paths for nice presentation to the user. - // - TSTRING fullPath; - if(iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mPolFile)) - pModeInfo->mPolFile = fullPath; - if(iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mSiteKeyFile)) - pModeInfo->mSiteKeyFile = fullPath; - if(iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mLocalKeyFile)) - pModeInfo->mLocalKeyFile = fullPath; - if(iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mDbFile)) - pModeInfo->mDbFile = fullPath; - if(iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mReportFile)) - pModeInfo->mReportFile = fullPath; - - - // use the verbosity information - ASSERT((pModeInfo->mVerbosity >= 0) && (pModeInfo->mVerbosity < 3)); - iUserNotify::GetInstance()->SetVerboseLevel(pModeInfo->mVerbosity); - - // if a passphrase was passed on the command line, then late prompting should - // be set to false so that wrong passwords are detected immediately - if( pModeInfo->mLocalProvided && pModeInfo->mbLatePassphrase ) - { - // TODO -- I don't know if we should display this or not -- mdb - //iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHANGE_PROMPT_TIME).c_str() ); - pModeInfo->mbLatePassphrase = false; - } + } + + // + // turn all of the file names into full paths for nice presentation to the user. + // + TSTRING fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mPolFile)) + pModeInfo->mPolFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mSiteKeyFile)) + pModeInfo->mSiteKeyFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mLocalKeyFile)) + pModeInfo->mLocalKeyFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mDbFile)) + pModeInfo->mDbFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mReportFile)) + pModeInfo->mReportFile = fullPath; + + + // use the verbosity information + ASSERT((pModeInfo->mVerbosity >= 0) && (pModeInfo->mVerbosity < 3)); + iUserNotify::GetInstance()->SetVerboseLevel(pModeInfo->mVerbosity); + + // if a passphrase was passed on the command line, then late prompting should + // be set to false so that wrong passwords are detected immediately + if (pModeInfo->mLocalProvided && pModeInfo->mbLatePassphrase) + { + // TODO -- I don't know if we should display this or not -- mdb + //iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHANGE_PROMPT_TIME).c_str() ); + pModeInfo->mbLatePassphrase = false; + } } //############################################################################# @@ -535,10 +633,12 @@ static void FillOutCmdLineInfo(cTWModeCommon* pModeInfo, const cCmdLineParser& c class cTWModeDbInit_i : public cTWModeCommon { public: - bool mbEncryptDb; + bool mbEncryptDb; - // ctor can set up some default values - cTWModeDbInit_i() : cTWModeCommon(), mbEncryptDb(true) {} + // ctor can set up some default values + cTWModeDbInit_i() : cTWModeCommon(), mbEncryptDb(true) + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -546,12 +646,12 @@ class cTWModeDbInit_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeDbInit::cTWModeDbInit() { - mpData = new cTWModeDbInit_i; + mpData = new cTWModeDbInit_i; } cTWModeDbInit::~cTWModeDbInit() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -559,16 +659,16 @@ cTWModeDbInit::~cTWModeDbInit() /////////////////////////////////////////////////////////////////////////////// void cTWModeDbInit::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); - cmdLine.AddArg(cTWCmdLine::MODE_INIT, TSTRING(_T("")), TSTRING(_T("init")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::NO_ENCRYPT, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::MODE_INIT, TSTRING(_T("")), TSTRING(_T("init")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::NO_ENCRYPT, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_NONE); - // mutual exclusion... - cmdLine.AddMutEx(cTWCmdLine::NO_ENCRYPT, cTWCmdLine::LOCAL_PASSPHRASE); - cmdLine.AddMutEx(cTWCmdLine::NO_ENCRYPT, cTWCmdLine::LOCAL_KEY_FILE); + // mutual exclusion... + cmdLine.AddMutEx(cTWCmdLine::NO_ENCRYPT, cTWCmdLine::LOCAL_PASSPHRASE); + cmdLine.AddMutEx(cTWCmdLine::NO_ENCRYPT, cTWCmdLine::LOCAL_KEY_FILE); } /////////////////////////////////////////////////////////////////////////////// @@ -576,53 +676,50 @@ void cTWModeDbInit::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeDbInit::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); - - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); - - // now do the stuff specific to this mode... - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::NO_ENCRYPT: + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); + + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); + + // now do the stuff specific to this mode... + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::NO_ENCRYPT: mpData->mbEncryptDb = false; break; - default: + default: // should I do anything, or just ignore this? ; - } - } - - //---------------------------------------- - // I require the following information: - // - // * local key file - // * site key file - // * policy file - // * db file - //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); - TEST_INIT_REQUIREMENT((! mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); - TEST_INIT_REQUIREMENT((! mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); - - - // make sure that the config file and site key file are in sync... - // - if (cTWUtil::VerifyCfgSiteKey( mstrConfigFile, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); - - #if IS_UNIX + } + } + + //---------------------------------------- + // I require the following information: + // + // * local key file + // * site key file + // * policy file + // * db file + //----------------------------------------- + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); + TEST_INIT_REQUIREMENT((!mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); + TEST_INIT_REQUIREMENT((!mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); + + + // make sure that the config file and site key file are in sync... + // + if (cTWUtil::VerifyCfgSiteKey(mstrConfigFile, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); + // Set the cross file systems flag appropriately. cFSDataSourceIter::SetFileSystemCrossing(mpData->mbCrossFileSystems); - #endif - - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -630,123 +727,126 @@ bool cTWModeDbInit::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// int cTWModeDbInit::Execute(cErrorQueue* pQueue) { - cFCODatabaseFile dbFile; - cFCODatabaseFile::iterator dbIter( dbFile ); - - dbFile.SetFileName( mpData->mDbFile ); - try - { - // don't go any further if we won't be able to write to the db file... - cFileUtil::TestFileWritable(mpData->mDbFile); - - // open the keyfile for early passphrase... - cKeyFile keyfile; - const cElGamalSigPrivateKey* pPrivateKey = 0; - if(mpData->mbEncryptDb) - { - cTWUtil::OpenKeyFile(keyfile, mpData->mLocalKeyFile); - // open the private key for "early passphrase" - if(! mpData->mbLatePassphrase) - pPrivateKey = cTWUtil::CreatePrivateKey(keyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } + cFCODatabaseFile dbFile; + cFCODatabaseFile::iterator dbIter(dbFile); + + dbFile.SetFileName(mpData->mDbFile); + try + { + // don't go any further if we won't be able to write to the db file... + cFileUtil::TestFileWritable(mpData->mDbFile); + + // open the keyfile for early passphrase... + cKeyFile keyfile; + const cElGamalSigPrivateKey* pPrivateKey = 0; + if (mpData->mbEncryptDb) + { + cTWUtil::OpenKeyFile(keyfile, mpData->mLocalKeyFile); + // open the private key for "early passphrase" + if (!mpData->mbLatePassphrase) + pPrivateKey = cTWUtil::CreatePrivateKey( + keyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); + } - //Parse the policy file - cGenreSpecListVector genreSpecList; - cTWCmdLineUtil::ParsePolicyFile(genreSpecList, mpData->mPolFile, mpData->mSiteKeyFile, pQueue); + //Parse the policy file + cGenreSpecListVector genreSpecList; + cTWCmdLineUtil::ParsePolicyFile(genreSpecList, mpData->mPolFile, mpData->mSiteKeyFile, pQueue); + +#ifdef TW_PROFILE + cTaskTimer timer("cTripwire::GenerateDatabase"); + timer.Start(); +#endif - #ifdef TW_PROFILE - cWin32TaskTimer timer("cTripwire::GenerateDatabase"); - timer.Start(); - #endif + iUserNotify::GetInstance()->Notify(1, TSS_GetString(cTripwire, tripwire::STR_GENERATING_DB).c_str()); - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_GENERATING_DB ).c_str() ); - uint32 gdbFlags = 0; - gdbFlags |= ( mpData->mbResetAccessTime ? cGenerateDb::FLAG_ERASE_FOOTPRINTS_GD : 0 ); + gdbFlags |= (mpData->mbResetAccessTime ? cGenerateDb::FLAG_ERASE_FOOTPRINTS_GD : 0); + gdbFlags |= (mpData->mbDirectIO ? cGenerateDb::FLAG_DIRECT_IO : 0); // loop through the genres cGenreSpecListVector::iterator genreIter; for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) { - // make this genre the current genre. - // - cGenreSwitcher::GetInstance()->SelectGenre( genreIter->GetGenre() ); - - // notify the user - // - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString( cTripwire, tripwire::STR_PROCESSING_GENRE ).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( cGenreSwitcher::GetInstance()->CurrentGenre(), true ) ); - - // add an entry to the database for each genre we are parsing - dbFile.AddGenre( genreIter->GetGenre(), &dbIter ); - - // copy the spec list to the database... - dbIter.GetSpecList() = genreIter->GetSpecList(); - - // generate the database... - // TODO -- turn pQueue into an error bucket - cGenerateDb::Execute( dbIter.GetSpecList(), dbIter.GetDb(), dbIter.GetGenreHeader().GetPropDisplayer(), pQueue, gdbFlags ); + // make this genre the current genre. + // + cGenreSwitcher::GetInstance()->SelectGenre(genreIter->GetGenre()); + + // notify the user + // + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, + TSS_GetString(cTripwire, tripwire::STR_PROCESSING_GENRE).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(cGenreSwitcher::GetInstance()->CurrentGenre(), true)); + + // add an entry to the database for each genre we are parsing + dbFile.AddGenre(genreIter->GetGenre(), &dbIter); + + // copy the spec list to the database... + dbIter.GetSpecList() = genreIter->GetSpecList(); + + // generate the database... + // TODO -- turn pQueue into an error bucket + cGenerateDb::Execute( + dbIter.GetSpecList(), dbIter.GetDb(), dbIter.GetGenreHeader().GetPropDisplayer(), pQueue, gdbFlags); } - - cFCODatabaseUtil::CalculateHeader( - dbFile.GetHeader(), - mpData->mPolFile, - mstrConfigFile, - mpData->mDbFile, - mstrCmdLine, - cSystemInfo::GetExeStartTime(), - 0 - ); - #ifdef TW_PROFILE - timer.Stop(); - #endif + cFCODatabaseUtil::CalculateHeader(dbFile.GetHeader(), + mpData->mPolFile, + mstrConfigFile, + mpData->mDbFile, + mstrCmdLine, + cSystemInfo::GetExeStartTime(), + 0); + +#ifdef TW_PROFILE + timer.Stop(); +#endif // write the db to disk... - if(mpData->mbEncryptDb) - { - // open the key file for late passphrase - if(! pPrivateKey) - { - ASSERT(mpData->mbLatePassphrase); - pPrivateKey = cTWUtil::CreatePrivateKey(keyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } + if (mpData->mbEncryptDb) + { + // open the key file for late passphrase + if (!pPrivateKey) + { + ASSERT(mpData->mbLatePassphrase); + pPrivateKey = cTWUtil::CreatePrivateKey( + keyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); + } // backup the file we are about to overwrite cFileUtil::BackupFile(mpData->mDbFile); cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), dbFile, true, pPrivateKey); - keyfile.ReleasePrivateKey(); - } - else - { + keyfile.ReleasePrivateKey(); + } + else + { cFileUtil::BackupFile(mpData->mDbFile); // backup the file we are about to overwrite - cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), dbFile, false, NULL); // false means no encryption - } - } - catch(eError& e) - { + cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), dbFile, false, NULL); // false means no encryption + } + } + catch (eError& e) + { if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_INIT_FAIL_MSG ); - msg.append(cErrorTable::GetInstance()->Get( e.GetID() )); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_INIT_FAIL_MSG); + msg.append(cErrorTable::GetInstance()->Get(e.GetID())); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_ERROR, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_ERROR, msg.c_str()); } - + cTWUtil::PrintErrorMsg(e); - return 8; - } + return 8; + } + + // everything went ok; return 0 + iUserNotify::GetInstance()->Notify(1, TSS_GetString(cTripwire, tripwire::STR_INIT_SUCCESS).c_str()); - // everything went ok; return 0 - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_INIT_SUCCESS ).c_str() ); - if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_INIT_MSG ) + mpData->mDbFile; - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_INIT_MSG) + mpData->mDbFile; + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); } return 0; @@ -755,9 +855,9 @@ int cTWModeDbInit::Execute(cErrorQueue* pQueue) /////////////////////////////////////////////////////////////////////////////// // GetModeUsage /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWModeDbInit::GetModeUsage( void ) +TSTRING cTWModeDbInit::GetModeUsage(void) { - return ( TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT ) ); + return (TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT)); } //############################################################################# @@ -766,35 +866,33 @@ TSTRING cTWModeDbInit::GetModeUsage( void ) class cTWModeIC_i : public cTWModeCommon { public: - bool mbUpdate; // launch the editor after integrity checking is done - bool mbPrintToStdout; // print a text version of the report to stdout? - bool mbEmail; // email the report to the appropriate parties? - TSTRING mIgnoreProps; // symbols of properties to ignore - bool mbEncryptReport; // should the report be encrypted? - int mSeverityLevel; // only policy rules greater than or equal to the specified level will be checked. - bool mbTrimBySeverity; // do we use mSeverityLevel to trim the spec list? - TSTRING mSeverityName; // gets mapped to number, then treated like mSeverityLevel - TSTRING mRuleName; // only the named rule will be checked - TSTRING mGenreName; // if not empty, specifies the genre to check - bool mbAnal; // are we in anal mode? (only valid with mbUpdate == true) - -#ifdef GMMS - bool mbGmms; // Send violation reports via gmms? - TSTRING mGmmsProg; // full path to gmms executable - TSTRING mGmmsOptions; // additional options for gmms command line - int mGmmsVerbosity; // level 1 or 2 verbosity? -#endif + bool mbUpdate; // launch the editor after integrity checking is done + bool mbPrintToStdout; // print a text version of the report to stdout? + bool mbEmail; // email the report to the appropriate parties? + TSTRING mIgnoreProps; // symbols of properties to ignore + bool mbEncryptReport; // should the report be encrypted? + int mSeverityLevel; // only policy rules greater than or equal to the specified level will be checked. + bool mbTrimBySeverity; // do we use mSeverityLevel to trim the spec list? + TSTRING mSeverityName; // gets mapped to number, then treated like mSeverityLevel + TSTRING mRuleName; // only the named rule will be checked + TSTRING mGenreName; // if not empty, specifies the genre to check + bool mbSecureMode; // are we in extra-pedantic mode? (only valid with mbUpdate == true) //TSTRING mCmdLine; // entire command line - std::vector mFilesToCheck; - - // ctor can set up some default values - cTWModeIC_i() : cTWModeCommon(), mbUpdate(false), mbPrintToStdout(true), mbEmail(false), mbEncryptReport(false), - mSeverityLevel(-1), mbTrimBySeverity(false), mbAnal(false) -#ifdef GMMS - , mbGmms(false), mGmmsVerbosity(2) -#endif - {} + std::vector mFilesToCheck; + + // ctor can set up some default values + cTWModeIC_i() + : cTWModeCommon(), + mbUpdate(false), + mbPrintToStdout(true), + mbEmail(false), + mbEncryptReport(false), + mSeverityLevel(-1), + mbTrimBySeverity(false), + mbSecureMode(false) + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -802,12 +900,12 @@ class cTWModeIC_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeIC::cTWModeIC() { - mpData = new cTWModeIC_i; + mpData = new cTWModeIC_i; } cTWModeIC::~cTWModeIC() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -815,273 +913,198 @@ cTWModeIC::~cTWModeIC() /////////////////////////////////////////////////////////////////////////////// void cTWModeIC::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); - - cmdLine.AddArg(cTWCmdLine::MODE_CHECK, TSTRING(_T("")), TSTRING(_T("check")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::INTER_UPDATE, TSTRING(_T("I")), TSTRING(_T("interactive")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::EDITOR, TSTRING(_T("V")), TSTRING(_T("visual")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::NO_TTY, TSTRING(_T("n")), TSTRING(_T("no-tty-output")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::MAIL_REPORT, TSTRING(_T("M")), TSTRING(_T("email-report")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::IGNORE_PROP, TSTRING(_T("i")), TSTRING(_T("ignore")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::ENCRYPT_REPORT, TSTRING(_T("E")), TSTRING(_T("signed-report")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::SEVERITY_LEVEL, TSTRING(_T("l")), TSTRING(_T("severity")), cCmdLineParser::PARAM_ONE); - //cmdLine.AddArg(cTWCmdLine::SEVERITY_NAME, TSTRING(_T("V")), TSTRING(_T("severityname")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::RULE_NAME, TSTRING(_T("R")), TSTRING(_T("rule-name")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::GENRE_NAME, TSTRING(_T("x")), TSTRING(_T("section")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::HEXADECIMAL, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); - - // multiple levels of reporting - cmdLine.AddArg(cTWCmdLine::REPORTLEVEL, TSTRING(_T("t")), TSTRING(_T("email-report-level")), cCmdLineParser::PARAM_ONE); - -#ifdef GMMS - // gmms command line options - cmdLine.AddArg(cTWCmdLine::USE_GMMS, TSTRING(_T("g")), TSTRING(_T("gmms")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::GMMS_VERBOSITY, TSTRING(_T("b")), TSTRING(_T("gmms-verbosity")), cCmdLineParser::PARAM_ONE); -#endif - - - - // mutual exclusion... - // you can't specify any of these 3 things together... - cmdLine.AddMutEx(cTWCmdLine::SEVERITY_LEVEL, cTWCmdLine::RULE_NAME); - cmdLine.AddDependency( cTWCmdLine::REPORTLEVEL, cTWCmdLine::MAIL_REPORT ); - // Report error if the user has specified an editor and we're not in interactive update - // mode: This needs to happen here, so we don't nail someone for having the editor - // specified in the config. file. We should only be this picky if both parameters are - // passed on the command line. - cmdLine.AddDependency( cTWCmdLine::EDITOR, cTWCmdLine::INTER_UPDATE ); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); + + cmdLine.AddArg(cTWCmdLine::MODE_CHECK, TSTRING(_T("")), TSTRING(_T("check")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::INTER_UPDATE, TSTRING(_T("I")), TSTRING(_T("interactive")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::EDITOR, TSTRING(_T("V")), TSTRING(_T("visual")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::NO_TTY, TSTRING(_T("n")), TSTRING(_T("no-tty-output")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::MAIL_REPORT, TSTRING(_T("M")), TSTRING(_T("email-report")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::IGNORE_PROP, TSTRING(_T("i")), TSTRING(_T("ignore")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg( + cTWCmdLine::ENCRYPT_REPORT, TSTRING(_T("E")), TSTRING(_T("signed-report")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::SEVERITY_LEVEL, TSTRING(_T("l")), TSTRING(_T("severity")), cCmdLineParser::PARAM_ONE); + //cmdLine.AddArg(cTWCmdLine::SEVERITY_NAME, TSTRING(_T("V")), TSTRING(_T("severityname")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::RULE_NAME, TSTRING(_T("R")), TSTRING(_T("rule-name")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::GENRE_NAME, TSTRING(_T("x")), TSTRING(_T("section")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::HEXADECIMAL, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); + + // multiple levels of reporting + cmdLine.AddArg( + cTWCmdLine::REPORTLEVEL, TSTRING(_T("t")), TSTRING(_T("email-report-level")), cCmdLineParser::PARAM_ONE); + + // mutual exclusion... + // you can't specify any of these 3 things together... + cmdLine.AddMutEx(cTWCmdLine::SEVERITY_LEVEL, cTWCmdLine::RULE_NAME); + cmdLine.AddDependency(cTWCmdLine::REPORTLEVEL, cTWCmdLine::MAIL_REPORT); + // Report error if the user has specified an editor and we're not in interactive update + // mode: This needs to happen here, so we don't nail someone for having the editor + // specified in the config. file. We should only be this picky if both parameters are + // passed on the command line. + cmdLine.AddDependency(cTWCmdLine::EDITOR, cTWCmdLine::INTER_UPDATE); } /////////////////////////////////////////////////////////////////////////////// // Init /////////////////////////////////////////////////////////////////////////////// bool cTWModeIC::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) -{ - // We will use this to access the parsed cmdLine. - cCmdLineIter iter(cmdLine); - -#ifdef GMMS - - // Get path to gmms executable from config file - TSTRING str; - if(cf.Lookup(TSTRING(_T("GMMS")), str)) - { - // Path was specified in the configuration file - mpData->mGmmsProg = str; - } - else - { - // Path was not specified in the configuration file, try environment variable - const TCHAR *gmmsDeploy = _tgetenv(_T("GEOPLEX_DEPLOY")); - if (gmmsDeploy) - mpData->mGmmsProg = TSTRING(gmmsDeploy) + _T("/bin/gmms"); // Assign by env.var. - else - mpData->mGmmsProg = _T("/home/geoplex/bin/gmms"); // No env.var., Take a wild guess. - } - - // Get any additional command line options for running gmms from config file - if(cf.Lookup(TSTRING(_T("GMMSOPTIONS")), str)) - mpData->mGmmsOptions = str; - - bool bGmmsSpecified=false, bGmmsVerbositySpecified=false; - -#endif - - // First, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); +{ + // We will use this to access the parsed cmdLine. + cCmdLineIter iter(cmdLine); - // Now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); + // First, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); + // Now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); - // now do the stuff specific to this mode.. + // now do the stuff specific to this mode.. - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::INTER_UPDATE: + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::INTER_UPDATE: mpData->mbUpdate = true; break; - case cTWCmdLine::EDITOR: - ASSERT(iter.NumParams() > 0); + case cTWCmdLine::EDITOR: + ASSERT(iter.NumParams() > 0); mpData->mEditor = iter.ParamAt(0); break; - case cTWCmdLine::NO_TTY: + case cTWCmdLine::NO_TTY: mpData->mbPrintToStdout = false; break; - case cTWCmdLine::MAIL_REPORT: + case cTWCmdLine::MAIL_REPORT: mpData->mbEmail = true; break; - case cTWCmdLine::IGNORE_PROP: - ASSERT(iter.NumParams() > 0); + case cTWCmdLine::IGNORE_PROP: + ASSERT(iter.NumParams() > 0); mpData->mIgnoreProps = iter.ParamAt(0); break; - case cTWCmdLine::ENCRYPT_REPORT: + case cTWCmdLine::ENCRYPT_REPORT: mpData->mbEncryptReport = true; break; - case cTWCmdLine::SEVERITY_LEVEL: + case cTWCmdLine::SEVERITY_LEVEL: ASSERT(iter.NumParams() > 0); - if (_istdigit(iter.ParamAt(0).c_str()[0])) - { - // interpret severity value - int iSev; - cSeverityLimits sl; - if( ! sl.InterpretInt( iter.ParamAt(0), &iSev ) ) - throw eICBadSevVal( iter.ParamAt(0) ); + if (_istdigit(iter.ParamAt(0).c_str()[0])) + { + // interpret severity value + int iSev; + cSeverityLimits sl; + if (!sl.InterpretInt(iter.ParamAt(0), &iSev)) + throw eICBadSevVal(iter.ParamAt(0)); - mpData->mSeverityLevel = iSev; + mpData->mSeverityLevel = iSev; mpData->mbTrimBySeverity = true; - } - else - { + } + else + { mpData->mSeverityName = iter.ParamAt(0); - } + } break; - case cTWCmdLine::REPORTLEVEL: + case cTWCmdLine::REPORTLEVEL: + { + if (iter.ParamAt(0) == _T("0")) + mpData->mEmailReportLevel = cTextReportViewer::SINGLE_LINE; + else if (iter.ParamAt(0) == _T("1")) + mpData->mEmailReportLevel = cTextReportViewer::PARSEABLE; + else if (iter.ParamAt(0) == _T("2")) + mpData->mEmailReportLevel = cTextReportViewer::SUMMARY_ONLY; + else if (iter.ParamAt(0) == _T("3")) + mpData->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; + else if (iter.ParamAt(0) == _T("4")) + mpData->mEmailReportLevel = cTextReportViewer::FULL_REPORT; + else { - if ( iter.ParamAt(0) == _T("0")) - mpData->mEmailReportLevel = cTextReportViewer::SINGLE_LINE; - else if( iter.ParamAt(0) == _T("1") ) - mpData->mEmailReportLevel = cTextReportViewer::PARSEABLE; - else if( iter.ParamAt(0) == _T("2") ) - mpData->mEmailReportLevel = cTextReportViewer::SUMMARY_ONLY; - else if( iter.ParamAt(0) == _T("3") ) - mpData->mEmailReportLevel = cTextReportViewer::CONCISE_REPORT; - else if( iter.ParamAt(0) == _T("4") ) - mpData->mEmailReportLevel = cTextReportViewer::FULL_REPORT; - else - { - // They specified an illegal level, error. - TSTRING errStr = _T("Invalid Level: "); - errStr += iter.ParamAt(0); - throw eTWInvalidReportLevel( errStr ); - } + // They specified an illegal level, error. + TSTRING errStr = _T("Invalid Level: "); + errStr += iter.ParamAt(0); + throw eTWInvalidReportLevel(errStr); } - //done with report-level stuff. - break; - case cTWCmdLine::RULE_NAME: - ASSERT(iter.NumParams() > 0); + } + //done with report-level stuff. + break; + case cTWCmdLine::RULE_NAME: + ASSERT(iter.NumParams() > 0); mpData->mRuleName = iter.ParamAt(0); break; - case cTWCmdLine::GENRE_NAME: - ASSERT(iter.NumParams() > 0); + case cTWCmdLine::GENRE_NAME: + ASSERT(iter.NumParams() > 0); mpData->mGenreName = iter.ParamAt(0); break; - case cTWCmdLine::HEXADECIMAL: + case cTWCmdLine::HEXADECIMAL: cArchiveSigGen::SetHex(true); break; - - case cTWCmdLine::PARAMS: + + case cTWCmdLine::PARAMS: + { + // pack all of these onto the files to check list... + mpData->mFilesToCheck.clear(); + for (int i = 0; i < iter.NumParams(); i++) { - // pack all of these onto the files to check list... - mpData->mFilesToCheck.clear(); - for(int i=0; i < iter.NumParams(); i++) - { - mpData->mFilesToCheck.push_back(iter.ParamAt(i)); - } + mpData->mFilesToCheck.push_back(iter.ParamAt(i)); } -#ifdef GMMS - case cTWCmdLine::USE_GMMS: - mpData->mbGmms = true; - bGmmsSpecified = true; - break; - case cTWCmdLine::GMMS_VERBOSITY: - { - const TCHAR* psz = iter.ParamAt(0).c_str(); - if ( psz != 0 ) - while ( _istdigit( *psz ) ) ++psz; + } - /// NOTE:RAD -- Come on man! There isn't even a pStr!!! - // if ( !cStringUtil::StringIsInteger( pStr ) ) - if ( *psz != 0x00 ) - { - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_BAD_GMMS_VERBOSITY ) << std::endl; - return false; - } - else - { - mpData->mGmmsVerbosity = _ttoi(iter.ParamAt(0).c_str()); - if (mpData->mGmmsVerbosity < 1 || mpData->mGmmsVerbosity > 2) { - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_BAD_GMMS_VERBOSITY ) << std::endl; - return false; - } - bGmmsVerbositySpecified = true; - } - break; - } -#endif - default: + default: // should I do anything, or just ignore this? ; - } - } + } + } + - // if an editor is not provided in cfg or on cmdline, try to get it from environment - if( mpData->mbUpdate && mpData->mEditor.empty() ) - util_GetEditor( mpData->mEditor ); - - //---------------------------------------- - // I require the following information: - // - // * local key file - // * site key file - // * policy file - // * db file - // * report file - // * editor (if interactive is specified) - //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); - TEST_INIT_REQUIREMENT((! mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); - TEST_INIT_REQUIREMENT((! mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); - TEST_INIT_REQUIREMENT((! mpData->mReportFile.empty()), cTW, tw::STR_ERR_MISSING_REPORT); - TEST_INIT_REQUIREMENT((! (mpData->mEditor.empty() && mpData->mbUpdate)),cTW, tw::STR_ERR_MISSING_EDITOR); - -#ifdef GMMS - if (bGmmsSpecified==false && bGmmsVerbositySpecified==true) - { - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_GMMS_VERBOSITY_ONLY ) << std::endl; - return false; - } -#endif + if (mpData->mbUpdate && mpData->mEditor.empty()) + util_GetEditor(mpData->mEditor); - /////////////////////////////////////////// - // do some email-related verifications - /////////////////////////////////////////// - if(mpData->mbEmail) - { - // make sure that email reporting and a file list were both not specified... - TEST_INIT_REQUIREMENT( mpData->mFilesToCheck.empty(), cTripwire, tripwire::STR_ERR_IC_EMAIL_AND_FILES ); + //---------------------------------------- + // I require the following information: + // + // * local key file + // * site key file + // * policy file + // * db file + // * report file + // * editor (if interactive is specified) + //----------------------------------------- + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); + TEST_INIT_REQUIREMENT((!mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); + TEST_INIT_REQUIREMENT((!mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); + TEST_INIT_REQUIREMENT((!mpData->mReportFile.empty()), cTW, tw::STR_ERR_MISSING_REPORT); + TEST_INIT_REQUIREMENT((!(mpData->mEditor.empty() && mpData->mbUpdate)), cTW, tw::STR_ERR_MISSING_EDITOR); + + /////////////////////////////////////////// + // do some email-related verifications + /////////////////////////////////////////// + if (mpData->mbEmail) + { + // make sure that email reporting and a file list were both not specified... + TEST_INIT_REQUIREMENT(mpData->mFilesToCheck.empty(), cTripwire, tripwire::STR_ERR_IC_EMAIL_AND_FILES); // make sure that we have a valid mail method - TEST_INIT_REQUIREMENT( ( cMailMessage::NO_METHOD != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_NO_MAIL_METHOD ); - TEST_INIT_REQUIREMENT( ( cMailMessage::INVALID_METHOD != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_INVALID_MAIL_METHOD ); + TEST_INIT_REQUIREMENT( + (cMailMessage::NO_METHOD != mpData->mMailMethod), cTripwire, tripwire::STR_ERR_NO_MAIL_METHOD); + TEST_INIT_REQUIREMENT( + (cMailMessage::INVALID_METHOD != mpData->mMailMethod), cTripwire, tripwire::STR_ERR_INVALID_MAIL_METHOD); // error if method is SENDMAIL and no MAILPROGRAM - TEST_INIT_REQUIREMENT( ( cMailMessage::MAIL_BY_PIPE != mpData->mMailMethod || !mpData->mMailProgram.empty()), - cTripwire, tripwire::STR_ERR_MISSING_MAILPROGRAM ); + TEST_INIT_REQUIREMENT((cMailMessage::MAIL_BY_PIPE != mpData->mMailMethod || !mpData->mMailProgram.empty()), + cTripwire, + tripwire::STR_ERR_MISSING_MAILPROGRAM); + } + + // make sure that the config file and site key file are in sync... + // + if (cTWUtil::VerifyCfgSiteKey(mstrConfigFile, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); -#if !SUPPORTS_MAPI - TEST_INIT_REQUIREMENT( ( cMailMessage::MAIL_BY_MAPI != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_MAPI_NOT_SUPPORTED ); -#endif - } - - // make sure that the config file and site key file are in sync... - // - if (cTWUtil::VerifyCfgSiteKey( mstrConfigFile, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); - - #if IS_UNIX // Set the cross file systems flag appropriately. cFSDataSourceIter::SetFileSystemCrossing(mpData->mbCrossFileSystems); - #endif - - return true; + return true; } @@ -1090,438 +1113,473 @@ bool cTWModeIC::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// int cTWModeIC::Execute(cErrorQueue* pQueue) { - cDebug d("cTWModeIC::Execute"); - - cFCODatabaseFile dbFile; - cFCODatabaseFile::iterator dbIter( dbFile ); - cFCOReport report; - cFCOReportHeader reportHeader; - bool bEncrypted, bCheckMade = false, bEmailError = false; - try - { - - // don't go any further if we won't be able to write the report to disk... - cFileUtil::TestFileWritable(mpData->mReportFile); - - // open the database; note that ReadDatabase will set bEncrypted and open the - // key file if necessary - cKeyFile localKeyfile; + cDebug d("cTWModeIC::Execute"); + + cFCODatabaseFile dbFile; + cFCODatabaseFile::iterator dbIter(dbFile); + cFCOReport report; + cFCOReportHeader reportHeader; + bool bEncrypted, bCheckMade = false, bEmailError = false; + try + { + + // don't go any further if we won't be able to write the report to disk... + cFileUtil::TestFileWritable(mpData->mReportFile); + + // open the database; note that ReadDatabase will set bEncrypted and open the + // key file if necessary + cKeyFile localKeyfile; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); - - cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); - - // - // give a warning if the user that created the database is not the same as the user running right now... - // - TSTRING userName; - if( iFSServices::GetInstance()->GetCurrentUserName( userName ) ) - { - if( dbFile.GetHeader().GetCreator().compare( userName.c_str() ) != 0 ) - { - // TODO -- move these strings to the string table - TOSTRINGSTREAM str; - str << TSS_GetString( cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS1) << dbFile.GetHeader().GetCreator() - << TSS_GetString( cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS2) << userName << std::ends; - cTWUtil::PrintErrorMsg( eICDifferentUsers( str.str(), eError::NON_FATAL ) ); - } - } - - // give a stern warning if the database is not encrypted - if(! bEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) + + cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); + + // + // give a warning if the user that created the database is not the same as the user running right now... + // + TSTRING userName; + if (iFSServices::GetInstance()->GetCurrentUserName(userName)) { - cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (dbFile.GetHeader().GetCreator().compare(userName.c_str()) != 0) + { + // TODO -- move these strings to the string table + TOSTRINGSTREAM str; + str << TSS_GetString(cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS1) << dbFile.GetHeader().GetCreator() + << TSS_GetString(cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS2) << userName << std::ends; + cTWUtil::PrintErrorMsg(eICDifferentUsers(str.str(), eError::NON_FATAL)); + } } - if( (!bEncrypted) && (mpData->mLocalProvided) && (!mpData->mbEncryptReport) ) - { - //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. - cTWUtil::PrintErrorMsg( eTWPassForUnencryptedDb( _T(""), eError::NON_FATAL)); - } + // give a stern warning if the database is not encrypted + if (!bEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) + { + cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); + } + if ((!bEncrypted) && (mpData->mLocalProvided) && (!mpData->mbEncryptReport)) + { + //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. + cTWUtil::PrintErrorMsg(eTWPassForUnencryptedDb(_T(""), eError::NON_FATAL)); + } - // get the password here if they are saving an encrypted report - const cElGamalSigPrivateKey* pPrivateKey = 0; - if(mpData->mbEncryptReport) - { - // if the key file isn't open (ie -- the report wasn't encrypted) then we need to - // open it now... - cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); - - // open the private key for "early passphrase" - if(! mpData->mbLatePassphrase) - { - // OK, here is the deal: if the user specified a password on the command line - // and we are going to do an interactive update after the IC and both the report - // and db are encrypted, then we need to save the passphrase so it doesn't get - // scrambled by CreatePrivateKey - if(mpData->mLocalProvided && mpData->mbUpdate && bEncrypted) - { - wc16_string passPhrase = mpData->mLocalPassphrase.c_str(); - pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, passPhrase.c_str(), cTWUtil::KEY_LOCAL); - } - else - pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } - } - // either integrity check using the policy file or a list of files - if(mpData->mFilesToCheck.size() != 0) - { - // we are checking files... - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_IC_FILES).c_str() ); - //// - // tell the user we are ignoring severity level and rule name, if they specified them... - // - if( ! mpData->mRuleName.empty() ) - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString( cTripwire, tripwire::STR_IC_IGNORING_RULE_NAME).c_str() ); - if( mpData->mbTrimBySeverity ) - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString( cTripwire, tripwire::STR_IC_IGNORING_SEV_NUM).c_str() ); - if( ! mpData->mSeverityName.empty() ) - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString( cTripwire, tripwire::STR_IC_IGNORING_SEV_NAME).c_str() ); - if( ! mpData->mGenreName.empty() ) - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString( cTripwire, tripwire::STR_IC_IGNORING_GENRE_NAME).c_str() ); - // - //// - - //********************************** - // new, experimental stuff.. trying out new command line interface - // - cTWUtil::GenreObjList listOut; - cTWUtil::ParseObjectList( listOut, mpData->mFilesToCheck ); - // - // now, we will iterate over the list, performing an integrity check for each genre - // - for( cTWUtil::GenreObjList::iterator genreIter = listOut.begin(); genreIter != listOut.end(); genreIter++ ) - { - dbIter.SeekToGenre( genreIter->first ); - if( ! dbIter.Done() ) - { - cGenreSwitcher::GetInstance()->SelectGenre( (cGenre::Genre)dbIter.GetGenre() ); - std::auto_ptr pParseUtil (iTWFactory::GetInstance()->CreateParserGenreUtil()); - // - // I have to turn this into a list of cFCONames - // - std::list fcoNames; - for(cTWUtil::ObjList::iterator it = genreIter->second.begin(); it != genreIter->second.end(); it++) - { - // if this is not an absolute path, warn and continue... - // - try - { - fcoNames.push_back( cTWUtil::ParseObjectName( *it ) ); - } - catch( eError& e ) - { - e.SetFatality( false ); - pQueue->AddError( e ); - report.GetErrorQueue()->AddError( e ); - } - } - // TODO -- emit "processing XXX" - cIntegrityCheck ic( (cGenre::Genre)genreIter->first, dbIter.GetSpecList(), dbIter.GetDb(), report, pQueue ); - - uint32 icFlags = 0; - icFlags |= ( mpData->mfLooseDirs ? cIntegrityCheck::FLAG_LOOSE_DIR : 0 ); - icFlags |= ( mpData->mbResetAccessTime ? cIntegrityCheck::FLAG_ERASE_FOOTPRINTS_IC : 0 ); - - ic.ExecuteOnObjectList( fcoNames, icFlags ); - - // put all info into report - cFCOReportGenreIter rgi( report ); - rgi.SeekToGenre( (cGenre::Genre) genreIter->first ); - rgi.GetGenreHeader().SetPropDisplayer( iTWFactory::GetInstance()->CreatePropDisplayer() ); - rgi.GetGenreHeader().GetPropDisplayer()->Merge( dbIter.GetGenreHeader().GetPropDisplayer() ); - rgi.GetGenreHeader().SetObjectsScanned( ic.ObjectsScanned() ); - } - else - { - //TODO -- what is the right thing to do here? - // error and continue or exit? - // - eTWDbDoesntHaveGenre e( cGenreSwitcher::GetInstance()->GenreToString( (cGenre::Genre)genreIter->first, true ) ); - e.SetFatality( false ); - cTWUtil::PrintErrorMsg( e ); - } - } - // - //********************************** - } - else - { - // we are checking a subset of the policy file - - // parse the policy file - cGenreSpecListVector genreSpecList; - cTWCmdLineUtil::ParsePolicyFile(genreSpecList, mpData->mPolFile, mpData->mSiteKeyFile, pQueue); - - // - // make sure the parsed policy is equivelant to the one in the database... - // TODO -- should this go in the report? should I make a report or just bail? I guess - // that for now, I will bail. (it throws an exception on failure - // - cTWCmdLineUtil::VerifyPolicy( genreSpecList, dbFile ) ; - - // - // if they are only checking one genre, figure out which one it is ... - // - cGenre::Genre genreToCheck = cGenre::GENRE_INVALID; - if( ! mpData->mGenreName.empty() ) - { - genreToCheck = cGenreSwitcher::GetInstance()->StringToGenre( mpData->mGenreName.c_str() ); - if( genreToCheck == cGenre::GENRE_INVALID ) + // get the password here if they are saving an encrypted report + const cElGamalSigPrivateKey* pPrivateKey = 0; + if (mpData->mbEncryptReport) + { + // if the key file isn't open (ie -- the report wasn't encrypted) then we need to + // open it now... + cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); + + // open the private key for "early passphrase" + if (!mpData->mbLatePassphrase) { - throw eICUnknownGenre( mpData->mGenreName ); + // OK, here is the deal: if the user specified a password on the command line + // and we are going to do an interactive update after the IC and both the report + // and db are encrypted, then we need to save the passphrase so it doesn't get + // scrambled by CreatePrivateKey + if (mpData->mLocalProvided && mpData->mbUpdate && bEncrypted) + { + wc16_string passPhrase = mpData->mLocalPassphrase.c_str(); + pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, passPhrase.c_str(), cTWUtil::KEY_LOCAL); + } + else + pPrivateKey = + cTWUtil::CreatePrivateKey(localKeyfile, + mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, + cTWUtil::KEY_LOCAL); } - if( ! cGenreSwitcher::GetInstance()->IsGenreAppropriate( genreToCheck ) ) + } + + // either integrity check using the policy file or a list of files + if (mpData->mFilesToCheck.size() != 0) + { + // we are checking files... + iUserNotify::GetInstance()->Notify(1, TSS_GetString(cTripwire, tripwire::STR_IC_FILES).c_str()); + //// + // tell the user we are ignoring severity level and rule name, if they specified them... + // + if (!mpData->mRuleName.empty()) + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, TSS_GetString(cTripwire, tripwire::STR_IC_IGNORING_RULE_NAME).c_str()); + if (mpData->mbTrimBySeverity) + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTripwire, tripwire::STR_IC_IGNORING_SEV_NUM).c_str()); + if (!mpData->mSeverityName.empty()) + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, TSS_GetString(cTripwire, tripwire::STR_IC_IGNORING_SEV_NAME).c_str()); + if (!mpData->mGenreName.empty()) + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, TSS_GetString(cTripwire, tripwire::STR_IC_IGNORING_GENRE_NAME).c_str()); + // + //// + + //********************************** + // new, experimental stuff.. trying out new command line interface + // + cTWUtil::GenreObjList listOut; + cTWUtil::ParseObjectList(listOut, mpData->mFilesToCheck); + // + // now, we will iterate over the list, performing an integrity check for each genre + // + for (cTWUtil::GenreObjList::iterator genreIter = listOut.begin(); genreIter != listOut.end(); ++genreIter) { - throw eICInappropriateGenre( mpData->mGenreName ); + dbIter.SeekToGenre(genreIter->first); + if (!dbIter.Done()) + { + cGenreSwitcher::GetInstance()->SelectGenre((cGenre::Genre)dbIter.GetGenre()); + TW_UNIQUE_PTR pParseUtil(iTWFactory::GetInstance()->CreateParserGenreUtil()); + // + // I have to turn this into a list of cFCONames + // + std::list fcoNames; + for (cTWUtil::ObjList::iterator it = genreIter->second.begin(); it != genreIter->second.end(); ++it) + { + // if this is not an absolute path, warn and continue... + // + try + { + fcoNames.push_back(cTWUtil::ParseObjectName(*it)); + } + catch (eError& e) + { + e.SetFatality(false); + pQueue->AddError(e); + report.GetErrorQueue()->AddError(e); + } + } + // TODO -- emit "processing XXX" + + cIntegrityCheck ic( + (cGenre::Genre)genreIter->first, dbIter.GetSpecList(), dbIter.GetDb(), report, pQueue); + + //If any sort of exception escapes the IC, make sure it goes in the report. + try + { + uint32 icFlags = 0; + icFlags |= (mpData->mfLooseDirs ? cIntegrityCheck::FLAG_LOOSE_DIR : 0); + icFlags |= (mpData->mbResetAccessTime ? cIntegrityCheck::FLAG_ERASE_FOOTPRINTS_IC : 0); + icFlags |= (mpData->mbDirectIO ? cIntegrityCheck::FLAG_DIRECT_IO : 0); + + ic.ExecuteOnObjectList(fcoNames, icFlags); + } + catch (eError& e) + { + if (pQueue) + pQueue->AddError(e); + } + catch (std::exception& e) + { + if (pQueue) + pQueue->AddError(eIC(e.what())); + } + catch (...) + { + if (pQueue) + pQueue->AddError(eIC("Unknown")); + } + // put all info into report + cFCOReportGenreIter rgi(report); + rgi.SeekToGenre((cGenre::Genre)genreIter->first); + rgi.GetGenreHeader().SetPropDisplayer(iTWFactory::GetInstance()->CreatePropDisplayer()); + rgi.GetGenreHeader().GetPropDisplayer()->Merge(dbIter.GetGenreHeader().GetPropDisplayer()); + rgi.GetGenreHeader().SetObjectsScanned(ic.ObjectsScanned()); + } + else + { + //TODO -- what is the right thing to do here? + // error and continue or exit? + // + eTWDbDoesntHaveGenre e( + cGenreSwitcher::GetInstance()->GenreToString((cGenre::Genre)genreIter->first, true)); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + } } + // + //********************************** + } + else + { + // we are checking a subset of the policy file - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString( cTripwire, tripwire::STR_CHECKING_GENRE).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( genreToCheck ) ); - } - + // parse the policy file + cGenreSpecListVector genreSpecList; + cTWCmdLineUtil::ParsePolicyFile(genreSpecList, mpData->mPolFile, mpData->mSiteKeyFile, pQueue); - // iterate over the genres... - // - cGenreSpecListVector::iterator genreIter; - for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) - { - // if they are only checking one genre and it is not this one, then - // skip everything else... // - if( (genreToCheck != cGenre::GENRE_INVALID) && (genreToCheck != genreIter->GetGenre()) ) - continue; - - // make this genre the current genre. + // make sure the parsed policy is equivelant to the one in the database... + // TODO -- should this go in the report? should I make a report or just bail? I guess + // that for now, I will bail. (it throws an exception on failure // - cGenreSwitcher::GetInstance()->SelectGenre( genreIter->GetGenre() ); + cTWCmdLineUtil::VerifyPolicy(genreSpecList, dbFile); + // - // seek the database iter to this genre... + // if they are only checking one genre, figure out which one it is ... // - dbIter.SeekToGenre( genreIter->GetGenre() ); - if( dbIter.Done() ) + cGenre::Genre genreToCheck = cGenre::GENRE_INVALID; + if (!mpData->mGenreName.empty()) { - // TODO -- what is the right thing to do here? throw or warn and continue? - // I think that I should add it to the report's error queue and spit it to - // stderr and continue - // - TCERR << _T("Genre ") << cGenreSwitcher::GetInstance()->GenreToString( genreIter->GetGenre() ) - << _T(" not in database; skipping.") << std::endl; - continue; + genreToCheck = cGenreSwitcher::GetInstance()->StringToGenre(mpData->mGenreName.c_str()); + if (genreToCheck == cGenre::GENRE_INVALID) + { + throw eICUnknownGenre(mpData->mGenreName); + } + if (!cGenreSwitcher::GetInstance()->IsGenreAppropriate(genreToCheck)) + { + throw eICInappropriateGenre(mpData->mGenreName); + } + + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTripwire, tripwire::STR_CHECKING_GENRE).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(genreToCheck)); } - // message to the user... + + + // iterate over the genres... // - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString( cTripwire, tripwire::STR_PROCESSING_GENRE ).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( cGenreSwitcher::GetInstance()->CurrentGenre(), true ) ); + cGenreSpecListVector::iterator genreIter; + for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) + { + // if they are only checking one genre and it is not this one, then + // skip everything else... + // + if ((genreToCheck != cGenre::GENRE_INVALID) && (genreToCheck != genreIter->GetGenre())) + continue; + + // make this genre the current genre. + // + cGenreSwitcher::GetInstance()->SelectGenre(genreIter->GetGenre()); + // + // seek the database iter to this genre... + // + dbIter.SeekToGenre(genreIter->GetGenre()); + if (dbIter.Done()) + { + // TODO -- what is the right thing to do here? throw or warn and continue? + // I think that I should add it to the report's error queue and spit it to + // stderr and continue + // + TCERR << _T("Genre ") << cGenreSwitcher::GetInstance()->GenreToString(genreIter->GetGenre()) + << _T(" not in database; skipping.") << std::endl; + continue; + } + // message to the user... + // + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, + TSS_GetString(cTripwire, tripwire::STR_PROCESSING_GENRE).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(cGenreSwitcher::GetInstance()->CurrentGenre(), true)); - cFCOSpecList specList = genreIter->GetSpecList(); + cFCOSpecList specList = genreIter->GetSpecList(); - // trim ignored properties from the specs... - if(! mpData->mIgnoreProps.empty()) - cTWCmdLineUtil::TrimPropsFromSpecs(specList, mpData->mIgnoreProps); + // trim ignored properties from the specs... + if (!mpData->mIgnoreProps.empty()) + cTWCmdLineUtil::TrimPropsFromSpecs(specList, mpData->mIgnoreProps); // trim ignored rule names from the specs... - if(! mpData->mRuleName.empty()) - cTWCmdLineUtil::TrimSpecsByName(specList, mpData->mRuleName); + if (!mpData->mRuleName.empty()) + cTWCmdLineUtil::TrimSpecsByName(specList, mpData->mRuleName); - // trim spec list based on severity - if(mpData->mbTrimBySeverity) - cTWCmdLineUtil::TrimSpecsBySeverity(specList, mpData->mSeverityLevel); + // trim spec list based on severity + if (mpData->mbTrimBySeverity) + cTWCmdLineUtil::TrimSpecsBySeverity(specList, mpData->mSeverityLevel); - // trim specs by severity name - if(! mpData->mSeverityName.empty()) - cTWCmdLineUtil::TrimSpecsBySeverityName(specList, mpData->mSeverityName); + // trim specs by severity name + if (!mpData->mSeverityName.empty()) + cTWCmdLineUtil::TrimSpecsBySeverityName(specList, mpData->mSeverityName); - // - // only do the integrity check if there is something to check! - // - if( ! specList.IsEmpty() ) - { - bCheckMade = true; //we've checked at least one rule. + // + // only do the integrity check if there is something to check! + // + if (!specList.IsEmpty()) + { + bCheckMade = true; //we've checked at least one rule. - // do the integrity check... - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_INTEGRITY_CHECK).c_str()); + // do the integrity check... + iUserNotify::GetInstance()->Notify(1, + TSS_GetString(cTripwire, tripwire::STR_INTEGRITY_CHECK).c_str()); #ifdef TW_PROFILE - cWin32TaskTimer timer("cTripwire::IntegrityCheck"); - timer.Start(); + cTaskTimer timer("cTripwire::IntegrityCheck"); + timer.Start(); #endif - cIntegrityCheck ic( (cGenre::Genre)dbIter.GetGenre(), specList, dbIter.GetDb(), report, pQueue ); - - uint32 icFlags = 0; - icFlags |= ( mpData->mfLooseDirs ? cIntegrityCheck::FLAG_LOOSE_DIR : 0 ); - icFlags |= ( mpData->mbResetAccessTime ? cIntegrityCheck::FLAG_ERASE_FOOTPRINTS_IC : 0 ); - - ic.Execute( icFlags ); - - // put all display info into report - cFCOReportGenreIter rgi( report ); - rgi.SeekToGenre( (cGenre::Genre) dbIter.GetGenre() ); - rgi.GetGenreHeader().SetPropDisplayer( iTWFactory::GetInstance()->CreatePropDisplayer() ); - rgi.GetGenreHeader().GetPropDisplayer()->Merge( dbIter.GetGenreHeader().GetPropDisplayer() ); - rgi.GetGenreHeader().SetObjectsScanned( ic.ObjectsScanned() ); + cIntegrityCheck ic((cGenre::Genre)dbIter.GetGenre(), specList, dbIter.GetDb(), report, pQueue); + + //If any sort of exception escapes the IC, make sure it goes in the report. + try + { + uint32 icFlags = 0; + icFlags |= (mpData->mfLooseDirs ? cIntegrityCheck::FLAG_LOOSE_DIR : 0); + icFlags |= (mpData->mbResetAccessTime ? cIntegrityCheck::FLAG_ERASE_FOOTPRINTS_IC : 0); + icFlags |= (mpData->mbDirectIO ? cIntegrityCheck::FLAG_DIRECT_IO : 0); + + ic.Execute(icFlags); + } + catch (eError& e) + { + if (pQueue) + pQueue->AddError(e); + } + catch (std::exception& e) + { + if (pQueue) + pQueue->AddError(eIC(e.what())); + } + catch (...) + { + if (pQueue) + pQueue->AddError(eIC("Unknown")); + } + + // put all display info into report + cFCOReportGenreIter rgi(report); + rgi.SeekToGenre((cGenre::Genre)dbIter.GetGenre()); + rgi.GetGenreHeader().SetPropDisplayer(iTWFactory::GetInstance()->CreatePropDisplayer()); + rgi.GetGenreHeader().GetPropDisplayer()->Merge(dbIter.GetGenreHeader().GetPropDisplayer()); + rgi.GetGenreHeader().SetObjectsScanned(ic.ObjectsScanned()); #ifdef TW_PROFILE - timer.Stop(); + timer.Stop(); #endif + } + else + { + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, + TSS_GetString(cTripwire, tripwire::STR_ERR_IC_NO_SPECS_LEFT).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(genreIter->GetGenre(), true)); + } } - else - { - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString( cTripwire, tripwire::STR_ERR_IC_NO_SPECS_LEFT).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( genreIter->GetGenre(), true ) ); + } - } - } - } + // save out the report... + cFCOReportUtil::CalculateHeaderInfo(reportHeader, + mpData->mPolFile, + mstrConfigFile, + mpData->mDbFile, + mstrCmdLine, + cSystemInfo::GetExeStartTime(), + dbFile.GetHeader().GetLastDBUpdateTime()); - // save out the report... - cFCOReportUtil::CalculateHeaderInfo( - reportHeader, - mpData->mPolFile, - mstrConfigFile, - mpData->mDbFile, - mstrCmdLine, - cSystemInfo::GetExeStartTime(), - dbFile.GetHeader().GetLastDBUpdateTime() - ); - - cFCOReportUtil::FinalizeReport( report ); - -#ifdef GMMS - // gmms reporting? - if (mpData->mbGmms) - { - try - { - cTWCmdLineUtil::GmmsReport(reportHeader, report, mpData->mGmmsProg, mpData->mGmmsOptions, mpData->mGmmsVerbosity); - } - catch(eGmmsError& e) - { - cTWUtil::PrintErrorMsg(e); - // Do not return. Gmms errors are not fatal. - } - } -#endif + cFCOReportUtil::FinalizeReport(report); - // email the report if that is desired... - if(mpData->mbEmail) - { - bEmailError = cTWCmdLineUtil::EmailReport(reportHeader, report, mpData) == 0; - - // We should notify them that no email was sent should the following condition - // apply. - if( !bCheckMade ) - { - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString( cTripwire, tripwire::STR_IC_NOEMAIL_SENT).c_str(), - _T("") ); - } - } + // email the report if that is desired... + if (mpData->mbEmail) + { + bEmailError = cTWCmdLineUtil::EmailReport(reportHeader, report, mpData) == 0; + + // We should notify them that no email was sent should the following condition + // apply. + if (!bCheckMade) + { + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, TSS_GetString(cTripwire, tripwire::STR_IC_NOEMAIL_SENT).c_str(), _T("")); + } + } // write the report to disk... - if(mpData->mbEncryptReport) - { - // get the private key for "late passphrase" - if(! pPrivateKey) - { - ASSERT(mpData->mbLatePassphrase); - // OK, here is the deal: if the user specified a password on the command line - // and we are going to do an interactive update after the IC and both the report - // and db are encrypted, then we need to save the passphrase so it doesn't get - // scrambled by CreatePrivateKey - if(mpData->mLocalProvided && mpData->mbUpdate && bEncrypted) + if (mpData->mbEncryptReport) + { + // get the private key for "late passphrase" + if (!pPrivateKey) { - wc16_string passPhrase = mpData->mLocalPassphrase.c_str(); - pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, passPhrase.c_str(), cTWUtil::KEY_LOCAL); + ASSERT(mpData->mbLatePassphrase); + // OK, here is the deal: if the user specified a password on the command line + // and we are going to do an interactive update after the IC and both the report + // and db are encrypted, then we need to save the passphrase so it doesn't get + // scrambled by CreatePrivateKey + if (mpData->mLocalProvided && mpData->mbUpdate && bEncrypted) + { + wc16_string passPhrase = mpData->mLocalPassphrase.c_str(); + pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, passPhrase.c_str(), cTWUtil::KEY_LOCAL); + } + else + pPrivateKey = + cTWUtil::CreatePrivateKey(localKeyfile, + mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, + cTWUtil::KEY_LOCAL); } - else - pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } // backup the file we are about to overwrite cFileUtil::BackupFile(mpData->mReportFile); - // write the report - cTWUtil::WriteReport(mpData->mReportFile.c_str(), reportHeader, report, true, pPrivateKey); - localKeyfile.ReleasePrivateKey(); - } - else - { + // write the report + cTWUtil::WriteReport(mpData->mReportFile.c_str(), reportHeader, report, true, pPrivateKey); + localKeyfile.ReleasePrivateKey(); + } + else + { cFileUtil::BackupFile(mpData->mReportFile); // backup the file we are about to overwrite - cTWUtil::WriteReport(mpData->mReportFile.c_str(), reportHeader, report, false, NULL); // false means no encryption - } - - // print a text version of the report to stdout... - if(mpData->mbPrintToStdout) - { - // print a couple of new lines so that the report isn't butted up against the rest of the output. - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, _T("\n\n")); - cTextReportViewer trv( reportHeader, report ); - trv.PrintTextReport( _T("-"), cTextReportViewer::SUMMARY_ONLY ); - } + cTWUtil::WriteReport( + mpData->mReportFile.c_str(), reportHeader, report, false, NULL); // false means no encryption + } - } - catch(eError& e) - { + // print a text version of the report to stdout... + if (mpData->mbPrintToStdout) + { + // print a couple of new lines so that the report isn't butted up against the rest of the output. + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, _T("\n\n")); + cTextReportViewer trv(reportHeader, report); + trv.PrintTextReport(_T("-"), cTextReportViewer::SUMMARY_ONLY); + } + } + catch (eError& e) + { if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IC_FAIL_MSG ); - msg.append(cErrorTable::GetInstance()->Get( e.GetID() )); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IC_FAIL_MSG); + msg.append(cErrorTable::GetInstance()->Get(e.GetID())); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_ERROR, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_ERROR, msg.c_str()); } - + cTWUtil::PrintErrorMsg(e); - return 8; - //TODO -- send a sad email here if mbEmail == true - } + return 8; + //TODO -- send a sad email here if mbEmail == true + } - // tell the user the report was saved - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_IC_SUCCESS).c_str()); + // tell the user the report was saved + iUserNotify::GetInstance()->Notify(1, TSS_GetString(cTripwire, tripwire::STR_IC_SUCCESS).c_str()); if (mpData->mbLogToSyslog) { - cTextReportViewer trv( reportHeader, report ); - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IC_MSG ); - msg.append(mpData->mDbFile); - msg.append(_T(" ")); - msg.append(trv.SingleLineReport()); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); + cTextReportViewer trv(reportHeader, report); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IC_MSG); + msg.append(mpData->mDbFile); + msg.append(_T(" ")); + msg.append(trv.SingleLineReport()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); } // go directly into interactive update if that is what they want... - // - if(mpData->mbUpdate) - { - cTWModeDbUpdate dbUpdate; - dbUpdate.Init(mpData, &dbFile, &reportHeader, &report, bEncrypted); - int ret = dbUpdate.Execute(pQueue); - - if (ret != 0) - return ret; - } - - // the return level is based on the type of violations that were found: - // 1 = added files - // 2 = removed files - // 4 = changed files - // 8 = ERROR_IC = Execution Error - if(bEmailError) - return (ERROR_IC | cTWCmdLineUtil::GetICReturnValue(report)); - else - return cTWCmdLineUtil::GetICReturnValue(report); + // + if (mpData->mbUpdate) + { + cTWModeDbUpdate dbUpdate; + dbUpdate.Init(mpData, &dbFile, &reportHeader, &report, bEncrypted); + int ret = dbUpdate.Execute(pQueue); + + if (ret != 0) + return ret; + } + + // the return level is based on the type of violations that were found: + // 1 = added files + // 2 = removed files + // 4 = changed files + // 8 = ERROR_IC = Execution Error + if (bEmailError) + return (ERROR_IC | cTWCmdLineUtil::GetICReturnValue(report)); + else + return cTWCmdLineUtil::GetICReturnValue(report); } /////////////////////////////////////////////////////////////////////////////// // GetModeUsage /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWModeIC::GetModeUsage( void ) +TSTRING cTWModeIC::GetModeUsage(void) { - return ( TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK ) ); + return (TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK)); } //############################################################################# @@ -1530,21 +1588,30 @@ TSTRING cTWModeIC::GetModeUsage( void ) class cTWModeDbUpdate_i : public cTWModeCommon { public: - bool mbInteractive; // don't do interactive update; just integrate the report file - bool mbAnal; // are we in anal mode? - //std::string mSitePassphrase; // pass phrase for site key + bool mbInteractive; // don't do interactive update; just integrate the report file + bool mbSecureMode; // are we in extra-pedantic mode? + //std::string mSitePassphrase; // pass phrase for site key //bool mSiteProvided; - // these members are only used when this mode is entered after integrity checking. - // they are set to variables that are on cTWModeIC's stack, so they should _not_ be deleted. - // if they are non-null when Execute() is called, they should be used as the db and report. - bool mbEncryptDb; - cFCOReport* mpReport; - cFCODatabaseFile* mpDbFile; - cFCOReportHeader* mpReportHeader; - - // ctor can set up some default values - cTWModeDbUpdate_i() : cTWModeCommon(), mbInteractive(true), mbAnal(true), /*mSiteProvided(false),*/ mpReport(0), mpDbFile(0), mpReportHeader(0) {} + // these members are only used when this mode is entered after integrity checking. + // they are set to variables that are on cTWModeIC's stack, so they should _not_ be deleted. + // if they are non-null when Execute() is called, they should be used as the db and report. + bool mbEncryptDb; + cFCOReport* mpReport; + cFCODatabaseFile* mpDbFile; + cFCOReportHeader* mpReportHeader; + + // ctor can set up some default values + cTWModeDbUpdate_i() + : cTWModeCommon(), + mbInteractive(true), + mbSecureMode(true), + mbEncryptDb(true), + /*mSiteProvided(false),*/ mpReport(0), + mpDbFile(0), + mpReportHeader(0) + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -1552,14 +1619,13 @@ class cTWModeDbUpdate_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeDbUpdate::cTWModeDbUpdate() { - mpData = new cTWModeDbUpdate_i; + mpData = new cTWModeDbUpdate_i; } - cTWModeDbUpdate::~cTWModeDbUpdate() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -1567,17 +1633,17 @@ cTWModeDbUpdate::~cTWModeDbUpdate() /////////////////////////////////////////////////////////////////////////////// void cTWModeDbUpdate::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); - cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_DB, TSTRING(_T("")), TSTRING(_T("update")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::ACCEPT_ALL, TSTRING(_T("a")), TSTRING(_T("accept-all")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::ANAL_LEVEL, TSTRING(_T("Z")), TSTRING(_T("secure-mode")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::EDITOR, TSTRING(_T("V")), TSTRING(_T("visual")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_DB, TSTRING(_T("")), TSTRING(_T("update")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::ACCEPT_ALL, TSTRING(_T("a")), TSTRING(_T("accept-all")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::SECURE_MODE, TSTRING(_T("Z")), TSTRING(_T("secure-mode")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::EDITOR, TSTRING(_T("V")), TSTRING(_T("visual")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_NONE); - // mutual exclusion... - cmdLine.AddMutEx(cTWCmdLine::ACCEPT_ALL, cTWCmdLine::EDITOR); + // mutual exclusion... + cmdLine.AddMutEx(cTWCmdLine::ACCEPT_ALL, cTWCmdLine::EDITOR); } /////////////////////////////////////////////////////////////////////////////// @@ -1585,114 +1651,112 @@ void cTWModeDbUpdate::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeDbUpdate::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); - - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); - - // now do the stuff specific to this mode... - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::ACCEPT_ALL: + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); + + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); + + // now do the stuff specific to this mode... + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::ACCEPT_ALL: mpData->mbInteractive = false; break; - case cTWCmdLine::ANAL_LEVEL: - ASSERT(iter.NumParams() > 0); - if(iter.ParamAt(0).compare(_T("high")) == 0) - mpData->mbAnal = true; - else if(iter.ParamAt(0).compare(_T("low")) == 0) - mpData->mbAnal = false; + case cTWCmdLine::SECURE_MODE: + ASSERT(iter.NumParams() > 0); + if (iter.ParamAt(0).compare(_T("high")) == 0) + mpData->mbSecureMode = true; + else if (iter.ParamAt(0).compare(_T("low")) == 0) + mpData->mbSecureMode = false; else { - // invalid parameter to anal switch... - // TODO -- print this to stderr; how do I display (1) the switch name - // and (2) the possible values? - // TODO -- move {high, low} somewhere else - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_BAD_PARAM) << _T(" : ") - << iter.ParamAt(0).c_str() << _T("; must be {high, low}") << std::endl; - return false; + // invalid parameter to secure mode switch... + // TODO -- print this to stderr; how do I display (1) the switch name + // and (2) the possible values? + // TODO -- move {high, low} somewhere else + TCERR << TSS_GetString(cTripwire, tripwire::STR_ERR_BAD_PARAM) << _T(" : ") << iter.ParamAt(0).c_str() + << _T("; must be {high, low}") << std::endl; + return false; } break; - case cTWCmdLine::EDITOR: - ASSERT(iter.NumParams() > 0); + case cTWCmdLine::EDITOR: + ASSERT(iter.NumParams() > 0); mpData->mEditor = iter.ParamAt(0); break; - default: + default: // should I do anything, or just ignore this? ; - } - } + } + } // if an editor is not provided in cfg or on cmdline, try to get it from environment - if( mpData->mbInteractive && mpData->mEditor.empty() ) - util_GetEditor( mpData->mEditor ); - - //---------------------------------------- - // I require the following information: - // - // * local key file - // * site key file - // * policy file - // * db file - // * report file - // * editor (if accept all is not specified) - //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); - TEST_INIT_REQUIREMENT((! mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); - TEST_INIT_REQUIREMENT((! mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); - TEST_INIT_REQUIREMENT((! mpData->mReportFile.empty()), cTW, tw::STR_ERR_MISSING_REPORT); - TEST_INIT_REQUIREMENT(((!mpData->mEditor.empty()) || (!mpData->mbInteractive)), cTW, tw::STR_ERR_MISSING_EDITOR); - - // make sure that the config file and site key file are in sync... - // - if (cTWUtil::VerifyCfgSiteKey( mstrConfigFile, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); - - #if IS_UNIX + if (mpData->mbInteractive && mpData->mEditor.empty()) + util_GetEditor(mpData->mEditor); + + //---------------------------------------- + // I require the following information: + // + // * local key file + // * site key file + // * policy file + // * db file + // * report file + // * editor (if accept all is not specified) + //----------------------------------------- + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); + TEST_INIT_REQUIREMENT((!mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); + TEST_INIT_REQUIREMENT((!mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); + TEST_INIT_REQUIREMENT((!mpData->mReportFile.empty()), cTW, tw::STR_ERR_MISSING_REPORT); + TEST_INIT_REQUIREMENT(((!mpData->mEditor.empty()) || (!mpData->mbInteractive)), cTW, tw::STR_ERR_MISSING_EDITOR); + + // make sure that the config file and site key file are in sync... + // + if (cTWUtil::VerifyCfgSiteKey(mstrConfigFile, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); + // Set the cross file systems flag appropriately. cFSDataSourceIter::SetFileSystemCrossing(mpData->mbCrossFileSystems); - #endif - - return true; + return true; } -void cTWModeDbUpdate::Init(const cTWModeIC_i* pICData, cFCODatabaseFile* dbFile, cFCOReportHeader* prh, cFCOReport* pReport, bool bEncryptDb) +void cTWModeDbUpdate::Init( + const cTWModeIC_i* pICData, cFCODatabaseFile* dbFile, cFCOReportHeader* prh, cFCOReport* pReport, bool bEncryptDb) { - mpData->mbInteractive = true; // always interactive - mpData->mbAnal = pICData->mbAnal; - //mpData->mbBackup = pICData->mbBackup; - mpData->mDbFile = pICData->mDbFile; - mpData->mLocalKeyFile = pICData->mLocalKeyFile; - mpData->mLocalPassphrase= pICData->mLocalPassphrase; - mpData->mLocalProvided = pICData->mLocalProvided; - mpData->mPolFile = pICData->mPolFile; - mpData->mReportFile = pICData->mReportFile; - mpData->mSiteKeyFile = pICData->mSiteKeyFile; - mpData->mVerbosity = pICData->mVerbosity; - mpData->mEditor = pICData->mEditor; - mpData->mbLatePassphrase= pICData->mbLatePassphrase; - - - mpData->mbEncryptDb = bEncryptDb; - mpData->mpDbFile = dbFile; - - if(pReport) - { - ASSERT(prh != 0); - mpData->mpReport = pReport; - mpData->mpReportHeader = prh; - } - else - { - mpData->mpReport = 0; - mpData->mpReportHeader = 0; - } + mpData->mbInteractive = true; // always interactive + mpData->mbSecureMode = pICData->mbSecureMode; + //mpData->mbBackup = pICData->mbBackup; + mpData->mDbFile = pICData->mDbFile; + mpData->mLocalKeyFile = pICData->mLocalKeyFile; + mpData->mLocalPassphrase = pICData->mLocalPassphrase; + mpData->mLocalProvided = pICData->mLocalProvided; + mpData->mPolFile = pICData->mPolFile; + mpData->mReportFile = pICData->mReportFile; + mpData->mSiteKeyFile = pICData->mSiteKeyFile; + mpData->mVerbosity = pICData->mVerbosity; + mpData->mEditor = pICData->mEditor; + mpData->mbLatePassphrase = pICData->mbLatePassphrase; + + + mpData->mbEncryptDb = bEncryptDb; + mpData->mpDbFile = dbFile; + + if (pReport) + { + ASSERT(prh != 0); + mpData->mpReport = pReport; + mpData->mpReportHeader = prh; + } + else + { + mpData->mpReport = 0; + mpData->mpReportHeader = 0; + } } @@ -1701,200 +1765,207 @@ void cTWModeDbUpdate::Init(const cTWModeIC_i* pICData, cFCODatabaseFile* dbFile, /////////////////////////////////////////////////////////////////////////////// int cTWModeDbUpdate::Execute(cErrorQueue* pQueue) { - try - { - // don't go any further if we won't be able to write to the db file... - cFileUtil::TestFileWritable(mpData->mDbFile); + try + { + // don't go any further if we won't be able to write to the db file... + cFileUtil::TestFileWritable(mpData->mDbFile); - // open the database - cFCODatabaseFile dbFile; - cKeyFile localKeyfile; - bool bDbEncrypted, bReportEncrypted; + // open the database + cFCODatabaseFile dbFile; + cKeyFile localKeyfile; + bool bDbEncrypted, bReportEncrypted; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); - if(! mpData->mpDbFile) - { - // open the database; note that ReadDatabase will set bEncrypted and open the - // key file if necessary - cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bDbEncrypted); - mpData->mpDbFile = &dbFile; - } - else - { - // we were passed the database; we should open the key file now if the db needs - // to be saved encrypted... - if(mpData->mbEncryptDb) - bDbEncrypted = true; - else - bDbEncrypted = false; - } - - if( (!bDbEncrypted) && (mpData->mLocalProvided) ) - { - //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. - cTWUtil::PrintErrorMsg( eTWPassForUnencryptedDb( _T(""), eError::NON_FATAL)); - } + if (!mpData->mpDbFile) + { + // open the database; note that ReadDatabase will set bEncrypted and open the + // key file if necessary + cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bDbEncrypted); + mpData->mpDbFile = &dbFile; + } + else + { + // we were passed the database; we should open the key file now if the db needs + // to be saved encrypted... + if (mpData->mbEncryptDb) + bDbEncrypted = true; + else + bDbEncrypted = false; + } + if ((!bDbEncrypted) && (mpData->mLocalProvided)) + { + //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. + cTWUtil::PrintErrorMsg(eTWPassForUnencryptedDb(_T(""), eError::NON_FATAL)); + } - // open the report... - cFCOReport report; - cFCOReportHeader reportHeader; - if(! mpData->mpReport) - { - cTWUtil::ReadReport(mpData->mReportFile.c_str(), reportHeader, report, localKeyfile.GetPublicKey(), false, bReportEncrypted); - mpData->mpReport = &report; - mpData->mpReportHeader = &reportHeader; - } - else - ASSERT(mpData->mpReportHeader != 0); - // open the private key for "early passphrase" - // I don't think that early passphrase should apply to db update; there is no reason the user - // would want to enter the passphrase before editing the report .. mdb + // open the report... + cFCOReport report; + cFCOReportHeader reportHeader; + if (!mpData->mpReport) + { + cTWUtil::ReadReport(mpData->mReportFile.c_str(), + reportHeader, + report, + localKeyfile.GetPublicKey(), + false, + bReportEncrypted); + mpData->mpReport = &report; + mpData->mpReportHeader = &reportHeader; + } + else + ASSERT(mpData->mpReportHeader != 0); + + // open the private key for "early passphrase" + // I don't think that early passphrase should apply to db update; there is no reason the user + // would want to enter the passphrase before editing the report .. mdb // TODO: Well ok, can we remove this commented out code then? - const cElGamalSigPrivateKey* pPrivateKey = 0; - /* + const cElGamalSigPrivateKey* pPrivateKey = 0; + /* if(bDbEncrypted && (! mpData->mbLatePassphrase)) { pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0); } */ - // have the user modify the report, if they want to - if(mpData->mbInteractive) - { - // put a try/catch here to allow ourselves to print a message - // saying the editor launch failed - try - { - cTextReportViewer trv( *mpData->mpReportHeader, *mpData->mpReport ); - trv.DisplayReportAndHaveUserUpdateIt( mpData->mEditor, cTextReportViewer::FULL_REPORT ); - } - catch(...) - { - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_UPDATE_ED_LAUNCH) << std::endl; - throw; - } - } + // have the user modify the report, if they want to + if (mpData->mbInteractive) + { + // put a try/catch here to allow ourselves to print a message + // saying the editor launch failed + try + { + cTextReportViewer trv(*mpData->mpReportHeader, *mpData->mpReport); + trv.DisplayReportAndHaveUserUpdateIt(mpData->mEditor, cTextReportViewer::FULL_REPORT); + } + catch (...) + { + TCERR << TSS_GetString(cTripwire, tripwire::STR_ERR_UPDATE_ED_LAUNCH) << std::endl; + throw; + } + } - // if the report is empty, there is no need to do the update... - if(! cTWCmdLineUtil::ReportContainsFCO(*mpData->mpReport)) - { - // tell them ... - iUserNotify::GetInstance()->Notify(1, TSS_GetString( cTripwire, tripwire::STR_REPORT_EMPTY).c_str()); - // keep those pesky ASSERTs from cKeyFile away! - if(pPrivateKey) - localKeyfile.ReleasePrivateKey(); - return 0; // is this the right return val? - } + // if the report is empty, there is no need to do the update... + if (!cTWCmdLineUtil::ReportContainsFCO(*mpData->mpReport)) + { + // tell them ... + iUserNotify::GetInstance()->Notify(1, TSS_GetString(cTripwire, tripwire::STR_REPORT_EMPTY).c_str()); + // keep those pesky ASSERTs from cKeyFile away! + if (pPrivateKey) + localKeyfile.ReleasePrivateKey(); + return 0; // is this the right return val? + } - // give a stern warning if the database is not encrypted - if(! bDbEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) + // give a stern warning if the database is not encrypted + if (!bDbEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) { - // warn if the database is not encrytped - cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + // warn if the database is not encrytped + cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } // iterate over all the genres in the report... - // - cFCOReportGenreIter genreIter( *mpData->mpReport ); - for( genreIter.SeekBegin(); ! genreIter.Done(); genreIter.Next() ) - { - cGenreSwitcher::GetInstance()->SelectGenre( genreIter.GetGenre() ); - // - // seek the db iter to the current genre... - // - cFCODatabaseFile::iterator dbIter( *mpData->mpDbFile ); - dbIter.SeekToGenre( genreIter.GetGenre() ); - if( dbIter.Done() ) - { - //TODO -- what is the right thing to do here? + // + cFCOReportGenreIter genreIter(*mpData->mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { + cGenreSwitcher::GetInstance()->SelectGenre(genreIter.GetGenre()); + // + // seek the db iter to the current genre... + // + cFCODatabaseFile::iterator dbIter(*mpData->mpDbFile); + dbIter.SeekToGenre(genreIter.GetGenre()); + if (dbIter.Done()) + { + //TODO -- what is the right thing to do here? + // + ASSERT(false); + throw eTWDbDoesntHaveGenre(); + } + // + // actually do the integrity check... // - ASSERT( false ); - throw eTWDbDoesntHaveGenre(); - } - // - // actually do the integrity check... - // uint32 udFlags = 0; - udFlags |= ( mpData->mbResetAccessTime ? cUpdateDb::FLAG_ERASE_FOOTPRINTS_UD : 0 ); + udFlags |= (mpData->mbResetAccessTime ? cUpdateDb::FLAG_ERASE_FOOTPRINTS_UD : 0); - cUpdateDb update( dbIter.GetDb(), *mpData->mpReport, pQueue ); - if( (! update.Execute( udFlags )) && mpData->mbAnal ) - { - // we will not perform the update; simply exit. - TCOUT << TSS_GetString( cTripwire, tripwire::STR_DB_NOT_UPDATED) << std::endl; - return 8; - } + cUpdateDb update(dbIter.GetDb(), *mpData->mpReport, pQueue); + if ((!update.Execute(udFlags)) && mpData->mbSecureMode) + { + // we will not perform the update; simply exit. + TCOUT << TSS_GetString(cTripwire, tripwire::STR_DB_NOT_UPDATED) << std::endl; + return 8; + } + + // + // update the header info for the database... + // + // merge the prop displayers... + dbIter.GetGenreHeader().GetPropDisplayer()->Merge(genreIter.GetGenreHeader().GetPropDisplayer()); + } - // - // update the header info for the database... - // - // merge the prop displayers... - dbIter.GetGenreHeader().GetPropDisplayer()->Merge( genreIter.GetGenreHeader().GetPropDisplayer() ); - } - // Update the header // Note: We DO NOT call cFCODatabaseUtil::CalculateHeader() here. We only // want to update these entries. mpData->mpDbFile->GetHeader().SetCreator(cTWUtil::GetCurrentUser()); - mpData->mpDbFile->GetHeader().SetLastDBUpdateTime( cSystemInfo::GetExeStartTime() ); + mpData->mpDbFile->GetHeader().SetLastDBUpdateTime(cSystemInfo::GetExeStartTime()); // - // write the db to disk... - // - if(bDbEncrypted) - { - // open the private key for "late prompting" - if(! pPrivateKey) - { - pPrivateKey = cTWUtil::CreatePrivateKey(localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } + // write the db to disk... + // + if (bDbEncrypted) + { + // open the private key for "late prompting" + if (!pPrivateKey) + { + pPrivateKey = cTWUtil::CreatePrivateKey( + localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); + } // backup the file we are about to overwrite cFileUtil::BackupFile(mpData->mDbFile); - cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), *mpData->mpDbFile, true, pPrivateKey); - localKeyfile.ReleasePrivateKey(); - } - else - { + cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), *mpData->mpDbFile, true, pPrivateKey); + localKeyfile.ReleasePrivateKey(); + } + else + { cFileUtil::BackupFile(mpData->mDbFile); // backup the file we are about to overwrite - cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), *mpData->mpDbFile, false, NULL); // false means no encryption - } - } - catch(eError& e) - { + cTWUtil::WriteDatabase( + mpData->mDbFile.c_str(), *mpData->mpDbFile, false, NULL); // false means no encryption + } + } + catch (eError& e) + { if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_UP_FAIL_MSG ); - msg.append(cErrorTable::GetInstance()->Get( e.GetID() )); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_UP_FAIL_MSG); + msg.append(cErrorTable::GetInstance()->Get(e.GetID())); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_ERROR, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_ERROR, msg.c_str()); } - - cTWUtil::PrintErrorMsg(e); - return 8; - } + + cTWUtil::PrintErrorMsg(e); + return 8; + } if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_UP_MSG ); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_UP_MSG); msg.append(mpData->mDbFile); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); } // everything went ok; return 0 - return 0; + return 0; } /////////////////////////////////////////////////////////////////////////////// // GetModeUsage /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWModeDbUpdate::GetModeUsage( void ) +TSTRING cTWModeDbUpdate::GetModeUsage(void) { - return ( TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE ) ); + return (TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE)); } //############################################################################# @@ -1903,13 +1974,15 @@ TSTRING cTWModeDbUpdate::GetModeUsage( void ) class cTWModePolUpdate_i : public cTWModeCommon { public: - TSTRING mTextPolFile; - wc16_string mSitePassphrase; - bool mSiteProvided; - bool mbAnal; + TSTRING mTextPolFile; + wc16_string mSitePassphrase; + bool mSiteProvided; + bool mbSecureMode; - // ctor can set up some default values - cTWModePolUpdate_i() : cTWModeCommon(), mSiteProvided(false), mbAnal(true) {} + // ctor can set up some default values + cTWModePolUpdate_i() : cTWModeCommon(), mSiteProvided(false), mbSecureMode(true) + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -1917,12 +1990,12 @@ class cTWModePolUpdate_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModePolUpdate::cTWModePolUpdate() { - mpData = new cTWModePolUpdate_i; + mpData = new cTWModePolUpdate_i; } cTWModePolUpdate::~cTWModePolUpdate() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -1930,14 +2003,17 @@ cTWModePolUpdate::~cTWModePolUpdate() /////////////////////////////////////////////////////////////////////////////// void cTWModePolUpdate::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); - - cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_POL, TSTRING(_T("")), TSTRING(_T("update-policy")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::TEXT_POL_FILE, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::LOCAL_PASSPHRASE,TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::SITE_PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - cmdLine.AddArg(cTWCmdLine::ANAL_LEVEL, TSTRING(_T("Z")), TSTRING(_T("secure-mode")), cCmdLineParser::PARAM_ONE); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); + + cmdLine.AddArg( + cTWCmdLine::MODE_UPDATE_POL, TSTRING(_T("")), TSTRING(_T("update-policy")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::TEXT_POL_FILE, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg( + cTWCmdLine::LOCAL_PASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg( + cTWCmdLine::SITE_PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + cmdLine.AddArg(cTWCmdLine::SECURE_MODE, TSTRING(_T("Z")), TSTRING(_T("secure-mode")), cCmdLineParser::PARAM_ONE); } /////////////////////////////////////////////////////////////////////////////// @@ -1945,94 +2021,90 @@ void cTWModePolUpdate::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModePolUpdate::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); - - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); - - // now do the stuff specific to this mode... - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - TSTRING fullPath; - switch(iter.ArgId()) - { - case cTWCmdLine::TEXT_POL_FILE: - ASSERT(iter.NumParams() > 0); + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); + + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); + + // now do the stuff specific to this mode... + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + TSTRING fullPath; + switch (iter.ArgId()) + { + case cTWCmdLine::TEXT_POL_FILE: + ASSERT(iter.NumParams() > 0); mpData->mTextPolFile = iter.ParamAt(0); // // convert it to a full path // - if( iFSServices::GetInstance()->FullPath( fullPath, mpData->mTextPolFile ) ) - mpData->mTextPolFile = fullPath; + if (iFSServices::GetInstance()->FullPath(fullPath, mpData->mTextPolFile)) + mpData->mTextPolFile = fullPath; break; - case cTWCmdLine::SITE_PASSPHRASE: - ASSERT(iter.NumParams() > 0); + case cTWCmdLine::SITE_PASSPHRASE: + ASSERT(iter.NumParams() > 0); mpData->mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mpData->mSiteProvided = true; + mpData->mSiteProvided = true; break; - case cTWCmdLine::ANAL_LEVEL: - ASSERT(iter.NumParams() > 0); - if(iter.ParamAt(0).compare(_T("high")) == 0) - mpData->mbAnal = true; - else if(iter.ParamAt(0).compare(_T("low")) == 0) - mpData->mbAnal = false; + case cTWCmdLine::SECURE_MODE: + ASSERT(iter.NumParams() > 0); + if (iter.ParamAt(0).compare(_T("high")) == 0) + mpData->mbSecureMode = true; + else if (iter.ParamAt(0).compare(_T("low")) == 0) + mpData->mbSecureMode = false; else { - // invalid parameter to anal switch... - // TODO -- print this to stderr; how do I display (1) the switch name - // and (2) the possible values? - // TODO -- move {high, low} somewhere else - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_BAD_PARAM) << _T(" : ") - << iter.ParamAt(0).c_str() << _T("; must be {high, low}") << std::endl; - return false; + // invalid parameter to secure mode switch... + // TODO -- print this to stderr; how do I display (1) the switch name + // and (2) the possible values? + // TODO -- move {high, low} somewhere else + TCERR << TSS_GetString(cTripwire, tripwire::STR_ERR_BAD_PARAM) << _T(" : ") << iter.ParamAt(0).c_str() + << _T("; must be {high, low}") << std::endl; + return false; } break; - default: + default: // should I do anything, or just ignore this? ; - } - } - - //---------------------------------------- - // I require the following information: - // - // * local key file - // * site key file - // * policy file - // * db file - //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); - TEST_INIT_REQUIREMENT((! mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); - TEST_INIT_REQUIREMENT((! mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); - - // if a passphrase was passed on the command line, then late prompting should - // be set to false so that wrong passwords are detected immediately - // - // Note that the local passphrase was already checked against in FillOutCmdLineInfo(), - // so I only need to test the site passphrase - if( mpData->mSiteProvided && mpData->mbLatePassphrase ) - { - // TODO -- I don't know if we should display this or not -- mdb - //iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHANGE_PROMPT_TIME).c_str() ); - mpData->mbLatePassphrase = false; - } - - // make sure that the config file and site key file are in sync... - // - if (cTWUtil::VerifyCfgSiteKey( mstrConfigFile, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); - - - #if IS_UNIX + } + } + + //---------------------------------------- + // I require the following information: + // + // * local key file + // * site key file + // * policy file + // * db file + //----------------------------------------- + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), cTW, tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mSiteKeyFile.empty()), cTW, tw::STR_ERR_MISSING_SITE_KEY); + TEST_INIT_REQUIREMENT((!mpData->mPolFile.empty()), cTW, tw::STR_ERR_MISSING_POLICY); + TEST_INIT_REQUIREMENT((!mpData->mDbFile.empty()), cTW, tw::STR_ERR_MISSING_DB); + + // if a passphrase was passed on the command line, then late prompting should + // be set to false so that wrong passwords are detected immediately + // + // Note that the local passphrase was already checked against in FillOutCmdLineInfo(), + // so I only need to test the site passphrase + if (mpData->mSiteProvided && mpData->mbLatePassphrase) + { + // TODO -- I don't know if we should display this or not -- mdb + //iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString( cTripwire, tripwire::STR_NOTIFY_CHANGE_PROMPT_TIME).c_str() ); + mpData->mbLatePassphrase = false; + } + + // make sure that the config file and site key file are in sync... + // + if (cTWUtil::VerifyCfgSiteKey(mstrConfigFile, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); + // Set the cross file systems flag appropriately. cFSDataSourceIter::SetFileSystemCrossing(mpData->mbCrossFileSystems); - #endif - - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -2040,222 +2112,245 @@ bool cTWModePolUpdate::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine /////////////////////////////////////////////////////////////////////////////// int cTWModePolUpdate::Execute(cErrorQueue* pQueue) { - try - { - // make sure all of the files are accessable - cFileUtil::TestFileWritable(mpData->mPolFile); - cFileUtil::TestFileWritable(mpData->mDbFile); - - // open and parse the new policy file... - cGenreSpecListVector genreSpecList; - cTWCmdLineUtil::ParseTextPolicyFile(genreSpecList, mpData->mTextPolFile, mpData->mSiteKeyFile, pQueue); - - cFCODatabaseFile dbFile; - cKeyFile localKeyfile, siteKeyfile; - cPrivateKeyProxy privateLocal, privateSite; + try + { + // make sure all of the files are accessable + cFileUtil::TestFileWritable(mpData->mPolFile); + cFileUtil::TestFileWritable(mpData->mDbFile); + + // open and parse the new policy file... + cGenreSpecListVector genreSpecList; + cTWCmdLineUtil::ParseTextPolicyFile(genreSpecList, mpData->mTextPolFile, mpData->mSiteKeyFile, pQueue); + + cFCODatabaseFile dbFile; + cKeyFile localKeyfile, siteKeyfile; + cPrivateKeyProxy privateLocal, privateSite; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); cTWUtil::OpenKeyFile(siteKeyfile, mpData->mSiteKeyFile); - // open the old database; note that ReadDatabase will set bEncrypted and open the - // key file if necessary - bool bDbEncrypted; - bool bPolEncrypted = true; + // open the old database; note that ReadDatabase will set bEncrypted and open the + // key file if necessary + bool bDbEncrypted; + bool bPolEncrypted = true; - cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bDbEncrypted); + cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bDbEncrypted); + + // + // give a warning if the user that created the database is not the same as the user running right now... + // + TSTRING userName; + if (iFSServices::GetInstance()->GetCurrentUserName(userName)) + { + if (dbFile.GetHeader().GetCreator().compare(userName.c_str()) != 0) + { + // TODO -- move these strings to the string table + TOSTRINGSTREAM str; + str << TSS_GetString(cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS1) << dbFile.GetHeader().GetCreator() + << TSS_GetString(cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS2) << userName << std::ends; + cTWUtil::PrintErrorMsg(eICDifferentUsers(str.str(), eError::NON_FATAL)); + } + } - // - // give a warning if the user that created the database is not the same as the user running right now... - // - TSTRING userName; - if( iFSServices::GetInstance()->GetCurrentUserName( userName ) ) - { - if( dbFile.GetHeader().GetCreator().compare( userName.c_str() ) != 0 ) - { - // TODO -- move these strings to the string table - TOSTRINGSTREAM str; - str << TSS_GetString( cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS1) << dbFile.GetHeader().GetCreator() - << TSS_GetString( cTripwire, tripwire::STR_ERR2_DIFFERENT_USERS2) << userName << std::ends; - cTWUtil::PrintErrorMsg( eICDifferentUsers( str.str(), eError::NON_FATAL ) ); - } - } - // warn if the database is not encrytped - if(! bDbEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) + if (!bDbEncrypted && iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) { - cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - - if( (!bDbEncrypted) && (mpData->mLocalProvided) ) - { - //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. - cTWUtil::PrintErrorMsg( eTWPassForUnencryptedDb( _T(""), eError::NON_FATAL)); - } + if ((!bDbEncrypted) && (mpData->mLocalProvided)) + { + //Issue a warning if a passphrase has been supplied, and the database is NOT encrypted. + cTWUtil::PrintErrorMsg(eTWPassForUnencryptedDb(_T(""), eError::NON_FATAL)); + } - try + + try { cFileManipulator polManipulator(mpData->mPolFile.c_str()); - polManipulator.Init(); + polManipulator.Init(); bPolEncrypted = polManipulator.GetEncoding() == cFileHeader::ASYM_ENCRYPTION; } - catch (eError&) {} + catch (eError&) + { + } - // - // get the passwords for early prompting - // - if(! mpData->mbLatePassphrase) - { - if(bDbEncrypted) - cTWUtil::CreatePrivateKey(privateLocal, localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); + // + // get the passwords for early prompting + // + if (!mpData->mbLatePassphrase) + { + if (bDbEncrypted) + cTWUtil::CreatePrivateKey(privateLocal, + localKeyfile, + mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, + cTWUtil::KEY_LOCAL); + + if (bPolEncrypted) + cTWUtil::CreatePrivateKey(privateSite, + siteKeyfile, + mpData->mSiteProvided ? mpData->mSitePassphrase.c_str() : 0, + cTWUtil::KEY_SITE); + } - if(bPolEncrypted) - cTWUtil::CreatePrivateKey(privateSite, siteKeyfile, mpData->mSiteProvided ? mpData->mSitePassphrase.c_str() : 0, cTWUtil::KEY_SITE); - } - - - ///////////////////////////////////////////////////////// - // iterate through all the genres in the new policy... - ///////////////////////////////////////////////////////// - cFCODatabaseFile::iterator dbIter( dbFile ); - cGenreSpecListVector::iterator genreIter; - for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) - { - // make this genre the current genre. - // - cGenreSwitcher::GetInstance()->SelectGenre( genreIter->GetGenre() ); - // - // seek the database iter to this genre... - // - dbIter.SeekToGenre( genreIter->GetGenre() ); - if( ! dbIter.Done() ) - { - // perform the policy update - // - cPolicyUpdate pu( genreIter->GetGenre(), dbIter.GetSpecList(), genreIter->GetSpecList(), dbIter.GetDb(), pQueue ); - uint32 puFlags = 0; - puFlags |= mpData->mbAnal ? cPolicyUpdate::ANAL : 0; - puFlags |= ( mpData->mbResetAccessTime ? cPolicyUpdate::FLAG_ERASE_FOOTPRINTS_PU : 0 ); - if( (! pu.Execute(puFlags)) && (mpData->mbAnal) ) - { - // they were in anal mode and errors occured; an error condition - TCOUT << TSS_GetString( cTripwire, tripwire::STR_ERR_POL_UPDATE) << std::endl; - return 8; - } - // we need to update the database's prop set... + + ///////////////////////////////////////////////////////// + // iterate through all the genres in the new policy... + ///////////////////////////////////////////////////////// + cFCODatabaseFile::iterator dbIter(dbFile); + cGenreSpecListVector::iterator genreIter; + for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) + { + // make this genre the current genre. // - dbIter.GetSpecList() = genreIter->GetSpecList(); - // - // TODO -- do some header stuff here? + cGenreSwitcher::GetInstance()->SelectGenre(genreIter->GetGenre()); // - } - else - { - // do a database init for this genre; it did not appear in the old policy... + // seek the database iter to this genre... // - TW_NOTIFY_NORMAL( TSS_GetString( cTripwire, tripwire::STR_PU_ADDING_GENRE ).c_str(), - cGenreSwitcher::GetInstance()->GenreToString( genreIter->GetGenre(), true ) ); - dbFile.AddGenre( genreIter->GetGenre(), &dbIter ); + dbIter.SeekToGenre(genreIter->GetGenre()); + if (!dbIter.Done()) + { + // perform the policy update + // + cPolicyUpdate pu( + genreIter->GetGenre(), dbIter.GetSpecList(), genreIter->GetSpecList(), dbIter.GetDb(), pQueue); + uint32 puFlags = 0; + puFlags |= mpData->mbSecureMode ? cPolicyUpdate::FLAG_SECURE_MODE : 0; + puFlags |= (mpData->mbResetAccessTime ? cPolicyUpdate::FLAG_ERASE_FOOTPRINTS_PU : 0); + puFlags |= (mpData->mbDirectIO ? cPolicyUpdate::FLAG_DIRECT_IO : 0); + + if ((!pu.Execute(puFlags)) && (mpData->mbSecureMode)) + { + // they were in secure mode and errors occured; an error condition + TCOUT << TSS_GetString(cTripwire, tripwire::STR_ERR_POL_UPDATE) << std::endl; + return 8; + } + // we need to update the database's prop set... + // + dbIter.GetSpecList() = genreIter->GetSpecList(); + // + // TODO -- do some header stuff here? + // + } + else + { + // do a database init for this genre; it did not appear in the old policy... + // + TW_NOTIFY_NORMAL(TSS_GetString(cTripwire, tripwire::STR_PU_ADDING_GENRE).c_str(), + cGenreSwitcher::GetInstance()->GenreToString(genreIter->GetGenre(), true)); + dbFile.AddGenre(genreIter->GetGenre(), &dbIter); - // copy the spec list to the database... - dbIter.GetSpecList() = genreIter->GetSpecList(); + // copy the spec list to the database... + dbIter.GetSpecList() = genreIter->GetSpecList(); - // generate the database... - // TODO -- turn pQueue into an error bucket - - uint32 gdbFlags = 0; - gdbFlags |= ( mpData->mbResetAccessTime ? cGenerateDb::FLAG_ERASE_FOOTPRINTS_GD : 0 ); - cGenerateDb::Execute( dbIter.GetSpecList(), dbIter.GetDb(), dbIter.GetGenreHeader().GetPropDisplayer(), pQueue, gdbFlags ); + // generate the database... + // TODO -- turn pQueue into an error bucket - //TODO -- what other prop displayer stuff do I have to do here? - } - } - ////////////////////////////////////////////////////////////////////////////////////// - // now, we need to prune genres that are in the database but not in the new policy... - ////////////////////////////////////////////////////////////////////////////////////// - for( dbIter.SeekBegin(); ! dbIter.Done(); ) - { - bool bFoundGenre = false; - for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) - { - if( genreIter->GetGenre() == dbIter.GetGenre() ) + uint32 gdbFlags = 0; + gdbFlags |= (mpData->mbResetAccessTime ? cGenerateDb::FLAG_ERASE_FOOTPRINTS_GD : 0); + gdbFlags |= (mpData->mbDirectIO ? cGenerateDb::FLAG_DIRECT_IO : 0); + + cGenerateDb::Execute( + dbIter.GetSpecList(), dbIter.GetDb(), dbIter.GetGenreHeader().GetPropDisplayer(), pQueue, gdbFlags); + + //TODO -- what other prop displayer stuff do I have to do here? + } + } + ////////////////////////////////////////////////////////////////////////////////////// + // now, we need to prune genres that are in the database but not in the new policy... + ////////////////////////////////////////////////////////////////////////////////////// + for (dbIter.SeekBegin(); !dbIter.Done();) + { + bool bFoundGenre = false; + for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) { - bFoundGenre = true; - break; + if (genreIter->GetGenre() == dbIter.GetGenre()) + { + bFoundGenre = true; + break; + } } - } - if( ! bFoundGenre ) - { - // we need to remove this genre from the db... - // - dbIter.Remove(); - } - else - dbIter.Next() ; - } + if (!bFoundGenre) + { + // we need to remove this genre from the db... + // + dbIter.Remove(); + } + else + dbIter.Next(); + } - // let's go ahead and update the database and policy file... + // let's go ahead and update the database and policy file... - // - // open the site key file and get the site passphrase - // - if(!privateSite.Valid() && bPolEncrypted) - cTWUtil::CreatePrivateKey(privateSite, siteKeyfile, mpData->mSiteProvided ? mpData->mSitePassphrase.c_str() : 0, cTWUtil::KEY_SITE); - // - // get the passphrase for the database, if necessary (it is important that we get both - // private keys before saving anything - // - if(bDbEncrypted && !privateLocal.Valid()) - { - ASSERT(mpData->mbLatePassphrase); - cTWUtil::CreatePrivateKey(privateLocal, localKeyfile, mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - } + // + // open the site key file and get the site passphrase + // + if (!privateSite.Valid() && bPolEncrypted) + cTWUtil::CreatePrivateKey(privateSite, + siteKeyfile, + mpData->mSiteProvided ? mpData->mSitePassphrase.c_str() : 0, + cTWUtil::KEY_SITE); + // + // get the passphrase for the database, if necessary (it is important that we get both + // private keys before saving anything + // + if (bDbEncrypted && !privateLocal.Valid()) + { + ASSERT(mpData->mbLatePassphrase); + cTWUtil::CreatePrivateKey(privateLocal, + localKeyfile, + mpData->mLocalProvided ? mpData->mLocalPassphrase.c_str() : 0, + cTWUtil::KEY_LOCAL); + } // backup the file we are about to overwrite cFileUtil::BackupFile(mpData->mPolFile); - - // - // write the policy file - // - cTWUtil::UpdatePolicyFile(mpData->mPolFile.c_str(), mpData->mTextPolFile.c_str(), bPolEncrypted, bPolEncrypted ? privateSite.GetKey() : 0); // - // update the header info - // + // write the policy file + // + cTWUtil::UpdatePolicyFile(mpData->mPolFile.c_str(), + mpData->mTextPolFile.c_str(), + bPolEncrypted, + bPolEncrypted ? privateSite.GetKey() : 0); + + // + // update the header info + // // Note: We DO NOT call cFCODatabaseUtil::CalculateHeader() here. We only // want to update these entries. dbFile.GetHeader().SetCreator(cTWUtil::GetCurrentUser()); - dbFile.GetHeader().SetPolicyFilename(mpData->mPolFile); - dbFile.GetHeader().SetConfigFilename(mstrConfigFile); - dbFile.GetHeader().SetLastDBUpdateTime( cSystemInfo::GetExeStartTime() ); + dbFile.GetHeader().SetPolicyFilename(mpData->mPolFile); + dbFile.GetHeader().SetConfigFilename(mstrConfigFile); + dbFile.GetHeader().SetLastDBUpdateTime(cSystemInfo::GetExeStartTime()); // backup the file we are about to overwrite cFileUtil::BackupFile(mpData->mDbFile); - - // - // write the db to disk... - // + + // + // write the db to disk... + // cTWUtil::WriteDatabase(mpData->mDbFile.c_str(), dbFile, bDbEncrypted, bDbEncrypted ? privateLocal.GetKey() : 0); - } - catch(eError& e) - { + } + catch (eError& e) + { if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_POLUP_FAIL_MSG ); - msg.append(cErrorTable::GetInstance()->Get( e.GetID() )); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_POLUP_FAIL_MSG); + msg.append(cErrorTable::GetInstance()->Get(e.GetID())); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_ERROR, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_ERROR, msg.c_str()); } - - cTWUtil::PrintErrorMsg(e); - return 8; - } + + cTWUtil::PrintErrorMsg(e); + return 8; + } if (mpData->mbLogToSyslog) { - TSTRING msg = TSS_GetString( cTripwire, tripwire::STR_SYSLOG_POLUP_MSG ); + TSTRING msg = TSS_GetString(cTripwire, tripwire::STR_SYSLOG_POLUP_MSG); msg.append(mpData->mDbFile); - cSyslog::Log(TSS_GetString( cTripwire, tripwire::STR_SYSLOG_IDENT ).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); + cSyslog::Log(TSS_GetString(cTripwire, tripwire::STR_SYSLOG_IDENT).c_str(), cSyslog::LOG_SUCCESS, msg.c_str()); } return 0; @@ -2264,9 +2359,9 @@ int cTWModePolUpdate::Execute(cErrorQueue* pQueue) /////////////////////////////////////////////////////////////////////////////// // GetModeUsage /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWModePolUpdate::GetModeUsage( void ) +TSTRING cTWModePolUpdate::GetModeUsage(void) { - return ( TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY ) ); + return (TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY)); } //############################################################################# @@ -2276,12 +2371,19 @@ TSTRING cTWModePolUpdate::GetModeUsage( void ) class cTWModeTest_i : public cTWModeCommon { public: - cTWModeTest_i() : cTWModeCommon() { mMode=TEST_INVALID; } + cTWModeTest_i() : cTWModeCommon() + { + mMode = TEST_INVALID; + } + + enum TestMode + { + TEST_INVALID, + TEST_EMAIL + }; - enum TestMode { TEST_INVALID, TEST_EMAIL }; - - TestMode mMode; - TSTRING mEmailAddress; + TestMode mMode; + TSTRING mEmailAddress; }; /////////////////////////////////////////////////////////////////////////////// @@ -2289,12 +2391,12 @@ class cTWModeTest_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeTest::cTWModeTest() { - mpData = new cTWModeTest_i; + mpData = new cTWModeTest_i; } cTWModeTest::~cTWModeTest() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -2302,15 +2404,15 @@ cTWModeTest::~cTWModeTest() /////////////////////////////////////////////////////////////////////////////// void cTWModeTest::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); - // The only allowed test mode syntax so far is - // "tripwire --test --email name@domain.com" or "tripwire -t -e name@domain.com". - cmdLine.AddArg(cTWCmdLine::MODE_TEST, TSTRING(_T("")), TSTRING(_T("test")), cCmdLineParser::PARAM_NONE); - cmdLine.AddArg(cTWCmdLine::TEST_EMAIL, TSTRING(_T("e")), TSTRING(_T("email")), cCmdLineParser::PARAM_ONE); + // The only allowed test mode syntax so far is + // "tripwire --test --email name@domain.com" or "tripwire -t -e name@domain.com". + cmdLine.AddArg(cTWCmdLine::MODE_TEST, TSTRING(_T("")), TSTRING(_T("test")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::TEST_EMAIL, TSTRING(_T("e")), TSTRING(_T("email")), cCmdLineParser::PARAM_ONE); - cmdLine.AddDependency( cTWCmdLine::MODE_TEST, cTWCmdLine::TEST_EMAIL ); + cmdLine.AddDependency(cTWCmdLine::MODE_TEST, cTWCmdLine::TEST_EMAIL); } /////////////////////////////////////////////////////////////////////////////// @@ -2318,39 +2420,38 @@ void cTWModeTest::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeTest::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::TEST_EMAIL: - mpData->mMode = cTWModeTest_i::TEST_EMAIL; + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::TEST_EMAIL: + mpData->mMode = cTWModeTest_i::TEST_EMAIL; mpData->mEmailAddress = iter.ParamAt(0); break; - default: + default: // should I do anything, or just ignore this? ; - } - } + } + } // make sure that we have a valid operation - TEST_INIT_REQUIREMENT( ( mpData->mMode != cTWModeTest_i::TEST_INVALID ), cTripwire, tripwire::STR_ERR_NO_TEST_MODE ); - - if( mpData->mMode == cTWModeTest_i::TEST_EMAIL ) + TEST_INIT_REQUIREMENT((mpData->mMode != cTWModeTest_i::TEST_INVALID), cTripwire, tripwire::STR_ERR_NO_TEST_MODE); + + if (mpData->mMode == cTWModeTest_i::TEST_EMAIL) { // make sure that we have a valid mail method - TEST_INIT_REQUIREMENT( ( cMailMessage::NO_METHOD != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_NO_MAIL_METHOD ); - TEST_INIT_REQUIREMENT( ( cMailMessage::INVALID_METHOD != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_INVALID_MAIL_METHOD ); -#if !SUPPORTS_MAPI - TEST_INIT_REQUIREMENT( ( cMailMessage::MAIL_BY_MAPI != mpData->mMailMethod ), cTripwire, tripwire::STR_ERR_MAPI_NOT_SUPPORTED ); -#endif + TEST_INIT_REQUIREMENT( + (cMailMessage::NO_METHOD != mpData->mMailMethod), cTripwire, tripwire::STR_ERR_NO_MAIL_METHOD); + TEST_INIT_REQUIREMENT( + (cMailMessage::INVALID_METHOD != mpData->mMailMethod), cTripwire, tripwire::STR_ERR_INVALID_MAIL_METHOD); } return true; @@ -2361,25 +2462,25 @@ bool cTWModeTest::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// int cTWModeTest::Execute(cErrorQueue* pQueue) { - cDebug d("cTWModeTest::Execute"); + cDebug d("cTWModeTest::Execute"); - switch (mpData->mMode) - { - case cTWModeTest_i::TEST_EMAIL: - { - cTWCmdLineUtil::SendEmailTestMessage(mpData->mEmailAddress, mpData); - } - default: - // should I do anything, or just ignore this? - ; - } + switch (mpData->mMode) + { + case cTWModeTest_i::TEST_EMAIL: + { + cTWCmdLineUtil::SendEmailTestMessage(mpData->mEmailAddress, mpData); + } + default: + // should I do anything, or just ignore this? + ; + } return 0; } -TSTRING cTWModeTest::GetModeUsage( ) +TSTRING cTWModeTest::GetModeUsage() { - return ( TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST ) ); + return (TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST)); } //############################################################################# @@ -2389,13 +2490,17 @@ TSTRING cTWModeTest::GetModeUsage( ) class cTWModeHelp_i : public cTWModeCommon { public: - cTWModeHelp_i() {} - ~cTWModeHelp_i() {} - - std::set< TSTRING > mModes; - // A set of modes to output usage statements for a specific mode. - std::set< TSTRING > mPrinted; - // A set for making sure we don't print the same help twice. + cTWModeHelp_i() + { + } + ~cTWModeHelp_i() + { + } + + std::set mModes; + // A set of modes to output usage statements for a specific mode. + std::set mPrinted; + // A set for making sure we don't print the same help twice. }; @@ -2404,12 +2509,12 @@ class cTWModeHelp_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeHelp::cTWModeHelp() { - mpData = new cTWModeHelp_i(); + mpData = new cTWModeHelp_i(); } cTWModeHelp::~cTWModeHelp() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -2417,18 +2522,19 @@ cTWModeHelp::~cTWModeHelp() /////////////////////////////////////////////////////////////////////////////// void cTWModeHelp::InitCmdLineParser(cCmdLineParser& cmdLine) { - // We're only interested in one parameter, that being help. Anything else - // passed to this mode should be a cmdlineparser error. - cmdLine.AddArg(cTWCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true); - cmdLine.AddArg(cTWCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_INIT, TSTRING(_T("i")), TSTRING(_T("init")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_CHECK, TSTRING(_T("c")), TSTRING(_T("check")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_DB, TSTRING(_T("u")), TSTRING(_T("update")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_POL, TSTRING(_T("p")), TSTRING(_T("update-policy")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_TEST, TSTRING(_T("t")), TSTRING(_T("test")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_EXPLORE, TSTRING(_T("")), TSTRING(_T("explore")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWCmdLine::MODE_DEBUG, TSTRING(_T("")), TSTRING(_T("verify")), cCmdLineParser::PARAM_MANY); + // We're only interested in one parameter, that being help. Anything else + // passed to this mode should be a cmdlineparser error. + cmdLine.AddArg(cTWCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true); + cmdLine.AddArg(cTWCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_INIT, TSTRING(_T("i")), TSTRING(_T("init")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_CHECK, TSTRING(_T("c")), TSTRING(_T("check")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_UPDATE_DB, TSTRING(_T("u")), TSTRING(_T("update")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg( + cTWCmdLine::MODE_UPDATE_POL, TSTRING(_T("p")), TSTRING(_T("update-policy")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_TEST, TSTRING(_T("t")), TSTRING(_T("test")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_EXPLORE, TSTRING(_T("")), TSTRING(_T("explore")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWCmdLine::MODE_DEBUG, TSTRING(_T("")), TSTRING(_T("verify")), cCmdLineParser::PARAM_MANY); } /////////////////////////////////////////////////////////////////////////////// @@ -2436,62 +2542,62 @@ void cTWModeHelp::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeHelp::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - cCmdLineIter iter(cmdLine); + cCmdLineIter iter(cmdLine); - // Grab the arguments from the help parameter: - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - switch(iter.ArgId()) - { - case cTWCmdLine::MODE_HELP: - { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - { - mpData->mModes.insert( iter.ParamAt(i) ); - } - } - break; - case cTWCmdLine::MODE: + // Grab the arguments from the help parameter: + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + switch (iter.ArgId()) + { + case cTWCmdLine::MODE_HELP: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - { - mpData->mModes.insert( iter.ParamAt(i) ); - } + mpData->mModes.insert(iter.ParamAt(i)); } - break; - // allow users to enter the mode - // names with "--" prepended. We have to do this, since - // the cmdlineparser treats them as switches. - case cTWCmdLine::MODE_HELP_ALL: // fall through - case cTWCmdLine::MODE_INIT: // fall through - case cTWCmdLine::MODE_CHECK: // fall through - case cTWCmdLine::MODE_UPDATE_DB: // fall through - case cTWCmdLine::MODE_UPDATE_POL: // fall through - case cTWCmdLine::MODE_TEST: // fall through - case cTWCmdLine::MODE_EXPLORE: // fall through - case cTWCmdLine::MODE_DEBUG: + } + break; + case cTWCmdLine::MODE: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) { - int i; - // push back the parameter that was actually passed. - TSTRING str = iter.ActualParam(); - // Kill off the initial "--" or "-" - str.erase( 0, 1 ); - if( str.length() != 1) - str.erase( 0, 1 ); - - mpData->mModes.insert( str ); - for( i = 0; i < iter.NumParams(); ++i ) - mpData->mModes.insert( iter.ParamAt(i) ); + mpData->mModes.insert(iter.ParamAt(i)); } - break; - default: + } + break; + // allow users to enter the mode + // names with "--" prepended. We have to do this, since + // the cmdlineparser treats them as switches. + case cTWCmdLine::MODE_HELP_ALL: // fall through + case cTWCmdLine::MODE_INIT: // fall through + case cTWCmdLine::MODE_CHECK: // fall through + case cTWCmdLine::MODE_UPDATE_DB: // fall through + case cTWCmdLine::MODE_UPDATE_POL: // fall through + case cTWCmdLine::MODE_TEST: // fall through + case cTWCmdLine::MODE_EXPLORE: // fall through + case cTWCmdLine::MODE_DEBUG: + { + int i; + // push back the parameter that was actually passed. + TSTRING str = iter.ActualParam(); + // Kill off the initial "--" or "-" + str.erase(0, 1); + if (str.length() != 1) + str.erase(0, 1); + + mpData->mModes.insert(str); + for (i = 0; i < iter.NumParams(); ++i) + mpData->mModes.insert(iter.ParamAt(i)); + } + break; + default: // should I do anything, or just ignore this? // cmdlineparser will catch the bad args. ; - } - } + } + } return true; } @@ -2501,102 +2607,102 @@ bool cTWModeHelp::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// int cTWModeHelp::Execute(cErrorQueue* pQueue) { - cDebug d("cTWModeHelp::Execute"); - - // The iterator we will use to traverse the list of arguments: - std::set::iterator it = mpData->mModes.begin(); - - // We'll want to output the version information, regardless: - TCOUT << TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; - - if( it == mpData->mModes.end() ) // all that was passed was --help - { - // Output a short usage summary for each mode. - TCOUT << TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_USAGE_SUMMARY ); - // - // That's it, return. - return 8; - } - - for( ; it != mpData->mModes.end(); ++it ) - { - if( _tcscmp( (*it).c_str(), _T("all")) == 0 ) - { - //Since --help all was passed, emit all help messages and return. - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT ); - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK ); - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE ); - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY ); - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST ); -#ifdef _DEBUG_DB - // TODO: Do we need help messages for these modes? DRA + cDebug d("cTWModeHelp::Execute"); + + // The iterator we will use to traverse the list of arguments: + std::set::iterator it = mpData->mModes.begin(); + + // We'll want to output the version information, regardless: + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + + if (it == mpData->mModes.end()) // all that was passed was --help + { + // Output a short usage summary for each mode. + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_USAGE_SUMMARY); + // + // That's it, return. + return 8; + } + + for (; it != mpData->mModes.end(); ++it) + { + if (_tcscmp((*it).c_str(), _T("all")) == 0) + { + //Since --help all was passed, emit all help messages and return. + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT); + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK); + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE); + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY); + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST); +#ifdef DEBUG + // TODO: Do we need help messages for these modes? DRA #endif - //We're done, return - return 8; - } - } - - //We need some subset of the usage statements. Figure out which modes have - //been specified: - it = mpData->mModes.begin(); - for( ; it != mpData->mModes.end(); ++it ) - { - // This is going to be ugly code... - if ( _tcscmp( (*it).c_str(), _T("init") ) == 0 || _tcscmp( (*it).c_str(), _T("i") ) == 0 ) - { - //make sure we don't print the same help twice... - if( mpData->mPrinted.find( _T("init") ) == mpData->mPrinted.end() ) - { - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT ); - mpData->mPrinted.insert( _T("init") ); - } - } - else if( _tcscmp( (*it).c_str(), _T("check") ) == 0 || _tcscmp( (*it).c_str(), _T("c") ) == 0 ) - { - if( mpData->mPrinted.find( _T("check") ) == mpData->mPrinted.end() ) - { - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK ); - mpData->mPrinted.insert( _T("check") ); - } - } - else if( _tcscmp( (*it).c_str(), _T("update") ) == 0 || _tcscmp( (*it).c_str(), _T("u") ) == 0 ) - { - if( mpData->mPrinted.find( _T("update") ) == mpData->mPrinted.end() ) - { - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE ); - mpData->mPrinted.insert( _T("update") ); - } - } - else if( _tcscmp( (*it).c_str(), _T("update-policy") ) == 0 || _tcscmp( (*it).c_str(), _T("p") ) == 0 ) - { - if( mpData->mPrinted.find( _T("update-policy") ) == mpData->mPrinted.end() ) - { - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY ); - mpData->mPrinted.insert( _T("update-policy") ); - } - } - else if( _tcscmp( (*it).c_str(), _T("test") ) == 0 || _tcscmp( (*it).c_str(), _T("t") ) == 0 ) - { - if( mpData->mPrinted.find( _T("test") ) == mpData->mPrinted.end() ) - { - TCOUT<< TSS_GetString( cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST ); - mpData->mPrinted.insert( _T("test") ); - } - } - else if( _tcscmp( (*it).c_str(), _T("explore") ) == 0 ) - TCOUT<< _T(""); //we currently don't have usage statements for this mode. - else if( _tcscmp( (*it).c_str(), _T("verify") ) == 0 ) - TCOUT<< _T(""); //we currently don't have usage statements for this mode. - else - { - cTWUtil::PrintErrorMsg( eTWHelpInvalidModeSwitch((*it), eError::NON_FATAL) ); - TCOUT << std::endl; - // emit error string, this mode does not exist - } - } + //We're done, return + return 8; + } + } + + //We need some subset of the usage statements. Figure out which modes have + //been specified: + it = mpData->mModes.begin(); + for (; it != mpData->mModes.end(); ++it) + { + // This is going to be ugly code... + if (_tcscmp((*it).c_str(), _T("init")) == 0 || _tcscmp((*it).c_str(), _T("i")) == 0) + { + //make sure we don't print the same help twice... + if (mpData->mPrinted.find(_T("init")) == mpData->mPrinted.end()) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_INIT); + mpData->mPrinted.insert(_T("init")); + } + } + else if (_tcscmp((*it).c_str(), _T("check")) == 0 || _tcscmp((*it).c_str(), _T("c")) == 0) + { + if (mpData->mPrinted.find(_T("check")) == mpData->mPrinted.end()) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_CHECK); + mpData->mPrinted.insert(_T("check")); + } + } + else if (_tcscmp((*it).c_str(), _T("update")) == 0 || _tcscmp((*it).c_str(), _T("u")) == 0) + { + if (mpData->mPrinted.find(_T("update")) == mpData->mPrinted.end()) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE); + mpData->mPrinted.insert(_T("update")); + } + } + else if (_tcscmp((*it).c_str(), _T("update-policy")) == 0 || _tcscmp((*it).c_str(), _T("p")) == 0) + { + if (mpData->mPrinted.find(_T("update-policy")) == mpData->mPrinted.end()) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_UPDATE_POLICY); + mpData->mPrinted.insert(_T("update-policy")); + } + } + else if (_tcscmp((*it).c_str(), _T("test")) == 0 || _tcscmp((*it).c_str(), _T("t")) == 0) + { + if (mpData->mPrinted.find(_T("test")) == mpData->mPrinted.end()) + { + TCOUT << TSS_GetString(cTripwire, tripwire::STR_TRIPWIRE_HELP_TEST); + mpData->mPrinted.insert(_T("test")); + } + } + else if (_tcscmp((*it).c_str(), _T("explore")) == 0) + TCOUT << _T(""); //we currently don't have usage statements for this mode. + else if (_tcscmp((*it).c_str(), _T("verify")) == 0) + TCOUT << _T(""); //we currently don't have usage statements for this mode. + else + { + cTWUtil::PrintErrorMsg(eTWHelpInvalidModeSwitch((*it), eError::NON_FATAL)); + TCOUT << std::endl; + // emit error string, this mode does not exist + } + } - //Everything went okay + //Everything went okay return 8; } @@ -2604,30 +2710,30 @@ int cTWModeHelp::Execute(cErrorQueue* pQueue) // UTIL FUNCTIONS //================================================================ -bool util_GetEditor( TSTRING& strEd ) +bool util_GetEditor(TSTRING& strEd) { // see if VISUAL environment var is set - TCHAR* pchEd = _tgetenv( _T("VISUAL") ); - if( pchEd != NULL && pchEd[0] != _T('\0') ) + TCHAR* pchEd = _tgetenv(_T("VISUAL")); + if (pchEd != NULL && pchEd[0] != _T('\0')) { strEd = pchEd; return true; } // see if EDITOR environment var is set - pchEd = _tgetenv( _T("EDITOR") ); - if( pchEd != NULL && pchEd[0] != _T('\0') ) + pchEd = _tgetenv(_T("EDITOR")); + if (pchEd != NULL && pchEd[0] != _T('\0')) { strEd = pchEd; return true; } - + return false; } //Encase the explore and debug modes in this ifdef, since they are for internal -//use only. -#ifdef _DEBUG_DB +//use only. +#ifdef DEBUG //############################################################################# // cTWModeExploreDb @@ -2637,7 +2743,9 @@ bool util_GetEditor( TSTRING& strEd ) class cTWModeExploreDb_i : public cTWModeCommon { public: - cTWModeExploreDb_i() : cTWModeCommon() {} + cTWModeExploreDb_i() : cTWModeCommon() + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -2645,12 +2753,12 @@ class cTWModeExploreDb_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeExploreDb::cTWModeExploreDb() { - mpData = new cTWModeExploreDb_i; + mpData = new cTWModeExploreDb_i; } cTWModeExploreDb::~cTWModeExploreDb() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -2658,10 +2766,10 @@ cTWModeExploreDb::~cTWModeExploreDb() /////////////////////////////////////////////////////////////////////////////// void cTWModeExploreDb::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); - cmdLine.AddArg(cTWCmdLine::MODE_EXPLORE, TSTRING(_T("")), TSTRING(_T("explore")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::MODE_EXPLORE, TSTRING(_T("")), TSTRING(_T("explore")), cCmdLineParser::PARAM_NONE); } /////////////////////////////////////////////////////////////////////////////// @@ -2669,14 +2777,14 @@ void cTWModeExploreDb::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeExploreDb::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -2684,38 +2792,38 @@ bool cTWModeExploreDb::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine /////////////////////////////////////////////////////////////////////////////// int cTWModeExploreDb::Execute(cErrorQueue* pQueue) { - cDebug d("cTWModeExploreDb::Execute"); + cDebug d("cTWModeExploreDb::Execute"); - cFCODatabaseFile dbFile; - cFCODatabaseFile::iterator dbIter( dbFile ); - try - { - cKeyFile localKeyfile; + cFCODatabaseFile dbFile; + cFCODatabaseFile::iterator dbIter(dbFile); + try + { + cKeyFile localKeyfile; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); - - bool bEncrypted; - cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); - // - // seek to the first genre in the db... - // - dbIter.SeekBegin(); - if( dbIter.Done() ) - { - //TODO -- what is the right thing to do here? - // - ASSERT( false ); - throw eTWDbHasNoGenres(); - } - // - // ok, time to explore the database! - // - cDbExplore::Execute( dbIter ); - } - catch(eError& e) - { - cTWUtil::PrintErrorMsg(e); - return 8; - } + + bool bEncrypted; + cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); + // + // seek to the first genre in the db... + // + dbIter.SeekBegin(); + if (dbIter.Done()) + { + //TODO -- what is the right thing to do here? + // + ASSERT(false); + throw eTWDbHasNoGenres(); + } + // + // ok, time to explore the database! + // + cDbExplore::Execute(dbIter); + } + catch (eError& e) + { + cTWUtil::PrintErrorMsg(e); + return 8; + } return 0; } @@ -2728,7 +2836,9 @@ int cTWModeExploreDb::Execute(cErrorQueue* pQueue) class cTWModeDebugDb_i : public cTWModeCommon { public: - cTWModeDebugDb_i() : cTWModeCommon() {} + cTWModeDebugDb_i() : cTWModeCommon() + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -2736,12 +2846,12 @@ class cTWModeDebugDb_i : public cTWModeCommon /////////////////////////////////////////////////////////////////////////////// cTWModeDebugDb::cTWModeDebugDb() { - mpData = new cTWModeDebugDb_i; + mpData = new cTWModeDebugDb_i; } cTWModeDebugDb::~cTWModeDebugDb() { - delete mpData; + delete mpData; } /////////////////////////////////////////////////////////////////////////////// @@ -2749,10 +2859,10 @@ cTWModeDebugDb::~cTWModeDebugDb() /////////////////////////////////////////////////////////////////////////////// void cTWModeDebugDb::InitCmdLineParser(cCmdLineParser& cmdLine) { - // initialize the switches common to all modes... - InitCmdLineCommon(cmdLine); + // initialize the switches common to all modes... + InitCmdLineCommon(cmdLine); - cmdLine.AddArg(cTWCmdLine::MODE_DEBUG, TSTRING(_T("")), TSTRING(_T("verifydb")), cCmdLineParser::PARAM_NONE); + cmdLine.AddArg(cTWCmdLine::MODE_DEBUG, TSTRING(_T("")), TSTRING(_T("verifydb")), cCmdLineParser::PARAM_NONE); } /////////////////////////////////////////////////////////////////////////////// @@ -2760,14 +2870,14 @@ void cTWModeDebugDb::InitCmdLineParser(cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// bool cTWModeDebugDb::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) { - // first, fill out everything with the config file info... - FillOutConfigInfo(mpData, cf); + // first, fill out everything with the config file info... + FillOutConfigInfo(mpData, cf); - // now, parse the command line... - // this takes care of the common stuff... - FillOutCmdLineInfo(mpData, cmdLine); + // now, parse the command line... + // this takes care of the common stuff... + FillOutCmdLineInfo(mpData, cmdLine); - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -2775,43 +2885,41 @@ bool cTWModeDebugDb::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) /////////////////////////////////////////////////////////////////////////////// int cTWModeDebugDb::Execute(cErrorQueue* pQueue) { - cDebug d("cTWModeDebugDb::Execute"); + cDebug d("cTWModeDebugDb::Execute"); - cFCODatabaseFile dbFile; - cFCODatabaseFile::iterator dbIter( dbFile ); - try - { - cKeyFile localKeyfile; + cFCODatabaseFile dbFile; + cFCODatabaseFile::iterator dbIter(dbFile); + try + { + cKeyFile localKeyfile; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); - - bool bEncrypted; - cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); - // - // seek to the first genre in the db... - // - dbIter.SeekBegin(); - if( dbIter.Done() ) - { - //TODO -- what is the right thing to do here? - // - ASSERT( false ); - throw eTWDbHasNoGenres(); - } - // - // debug the database. - // - cDbDebug::Execute( dbIter, mpData->mDbFile ); - } - catch(eError& e) - { - cTWUtil::PrintErrorMsg(e); - return 8; - } + + bool bEncrypted; + cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), dbFile, localKeyfile.GetPublicKey(), bEncrypted); + // + // seek to the first genre in the db... + // + dbIter.SeekBegin(); + if (dbIter.Done()) + { + //TODO -- what is the right thing to do here? + // + ASSERT(false); + throw eTWDbHasNoGenres(); + } + // + // debug the database. + // + cDbDebug::Execute(dbIter, mpData->mDbFile); + } + catch (eError& e) + { + cTWUtil::PrintErrorMsg(e); + return 8; + } return 0; } -#endif //_DEBUG_DB - - +#endif //DEBUG diff --git a/src/tripwire/twcmdline.h b/src/tripwire/twcmdline.h index bb02d2e..fb62866 100644 --- a/src/tripwire/twcmdline.h +++ b/src/tripwire/twcmdline.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // twcmdline.h -// +// // cTWCmdLine -- holds all information on tripwire's command line // iTWMode -- abstract base class for a mode of operation in tripwire #ifndef __TWCMDLINE_H @@ -46,10 +46,10 @@ #endif #ifndef __MAILMESSAGE_H -#include "mailmessage.h" // used for email reporting +#include "mailmessage.h" // used for email reporting #endif -#ifndef __TEXTREPORTVIEWER_H // for multiple levels of reporting +#ifndef __TEXTREPORTVIEWER_H // for multiple levels of reporting #include "tw/textreportviewer.h" #endif @@ -67,14 +67,17 @@ class cFCOReport; class cFCODbHeader; class cFCOReportHeader; -TSS_EXCEPTION( eTWHelpInvalidModeSwitch, eError ); -TSS_EXCEPTION( eTWInitialization, eError ); -TSS_EXCEPTION( eTWInvalidConfigFileKey, eError ); -TSS_EXCEPTION( eTWInvalidReportLevel, eError ); -TSS_EXCEPTION( eTWInvalidReportLevelCfg, eError ); -TSS_EXCEPTION( eTWInvalidPortNumber, eError ); -TSS_EXCEPTION( eTWPassForUnencryptedDb, eError ); -TSS_EXCEPTION( eTWInvalidTempDirectory, eError ); +TSS_EXCEPTION(eTWHelpInvalidModeSwitch, eError); +TSS_EXCEPTION(eTWInitialization, eError); +TSS_EXCEPTION(eTWInvalidConfigFileKey, eError); +TSS_EXCEPTION(eTWInvalidReportLevel, eError); +TSS_EXCEPTION(eTWInvalidReportLevelCfg, eError); +TSS_EXCEPTION(eTWInvalidPortNumber, eError); +TSS_EXCEPTION(eTWPassForUnencryptedDb, eError); +TSS_EXCEPTION(eTWInvalidTempDirectory, eError); + +TSS_EXCEPTION(eTWSyslogNotSupported, eError); +TSS_EXCEPTION(eTWDirectIONotSupported, eError); /////////////////////////////////////////////////////////////////////////////// // cTWCmdLine -- class with a bunch of static member functions helpful in parsing @@ -83,71 +86,65 @@ TSS_EXCEPTION( eTWInvalidTempDirectory, eError ); class cTWCmdLine { public: - //static void InitCmdLineParser(cCmdLineParser& parser); - // call this to initialize the command line parser + //static void InitCmdLineParser(cCmdLineParser& parser); + // call this to initialize the command line parser - static iTWMode* GetMode(int argc, const TCHAR *const * argv); - // this will look at the beginning of the command line, determine the appropriate - // mode to create, and returns it. If the mode can't be determined, an error message - // is printed and null is returned. + static iTWMode* GetMode(int argc, const TCHAR* const* argv); + // this will look at the beginning of the command line, determine the appropriate + // mode to create, and returns it. If the mode can't be determined, an error message + // is printed and null is returned. - // constants for all the command line arguments - enum CmdLineArgs - { + // constants for all the command line arguments + enum CmdLineArgs + { HELP, - // modes - MODE, // generic -m - MODE_INIT, - MODE_CHECK, - MODE_UPDATE_DB, - MODE_UPDATE_POL, - MODE_TEST, - MODE_EXPLORE, - MODE_DEBUG, - MODE_HELP, - MODE_HELP_ALL, + // modes + MODE, // generic -m + MODE_INIT, + MODE_CHECK, + MODE_UPDATE_DB, + MODE_UPDATE_POL, + MODE_TEST, + MODE_EXPLORE, + MODE_DEBUG, + MODE_HELP, + MODE_HELP_ALL, MODE_VERSION, - VERBOSE, - SILENT, - POL_FILE, - CFG_FILE, - SITE_KEY_FILE, - LOCAL_KEY_FILE, - DB_FILE, - REPORT_FILE, + VERBOSE, + SILENT, + POL_FILE, + CFG_FILE, + SITE_KEY_FILE, + LOCAL_KEY_FILE, + DB_FILE, + REPORT_FILE, LOOSE_DIRS, - NO_BACKUP, - NO_ENCRYPT, - INTER_UPDATE, // interactive update after integrity check - EDITOR, - NO_TTY, - MAIL_REPORT, - IGNORE_PROP, - ENCRYPT_REPORT, - SEVERITY_LEVEL, - //SEVERITY_NAME, - RULE_NAME, - GENRE_NAME, - ACCEPT_ALL, // update db with entire report - ANAL_LEVEL, - TEXT_POL_FILE, - LOCAL_PASSPHRASE, - SITE_PASSPHRASE, - TEST_EMAIL, - REPORTLEVEL, - HEXADECIMAL, - -#ifdef GMMS - USE_GMMS, - GMMS_VERBOSITY, -#endif - - PARAMS, // the final parameters - - NUM_CMDLINEARGS - }; + NO_BACKUP, + NO_ENCRYPT, + INTER_UPDATE, // interactive update after integrity check + EDITOR, + NO_TTY, + MAIL_REPORT, + IGNORE_PROP, + ENCRYPT_REPORT, + SEVERITY_LEVEL, + //SEVERITY_NAME, + RULE_NAME, + GENRE_NAME, + ACCEPT_ALL, // update db with entire report + SECURE_MODE, + TEXT_POL_FILE, + LOCAL_PASSPHRASE, + SITE_PASSPHRASE, + TEST_EMAIL, + REPORTLEVEL, + HEXADECIMAL, + PARAMS, // the final parameters + + NUM_CMDLINEARGS + }; }; //############################################################################# @@ -156,71 +153,84 @@ class cTWCmdLine //############################################################################# class cTWModeCommon { - public: - int mVerbosity; // must be 0 <= n <= 2 - wc16_string mLocalPassphrase; // pass phrase for private key - bool mLocalProvided; - TSTRING mPolFile; - TSTRING mSiteKeyFile; - TSTRING mLocalKeyFile; - TSTRING mDbFile; - TSTRING mReportFile; - TSTRING mEditor; - TSTRING mTempDirectory; // where we create our temp files... - TSTRING mGlobalEmail; // a list of email addr's - - bool mbLatePassphrase; // do we ask for the passphrase at the end of the operation or the beginning? - bool mfLooseDirs; // do we do loose directory checking? - bool mbResetAccessTime; // do we reset access time when calculating properties of files? - bool mbLogToSyslog; // log significant events and level 0 reports to SYSLOG - bool mbCrossFileSystems; // automatically recurse across mount points on Unis FS genre - - cTextReportViewer::ReportingLevel mEmailReportLevel; // What level of email reporting we should use - cMailMessage::MailMethod mMailMethod; // What mechanism should we use to send the report - - TSTRING mSmtpHost; // name of SMTP host to use - unsigned short mSmtpPort; // port number of that SMTP host - TSTRING mMailProgram; // full path to executable to use for piped mail - bool mMailNoViolations; // Email out reports with no violations? - TSTRING mMailFrom; - - cTWModeCommon() : mVerbosity(1), - mLocalProvided(false), - mbLatePassphrase(false), - mfLooseDirs(false), - mbResetAccessTime(false), - mbLogToSyslog(false), - mbCrossFileSystems(false) +public: + int mVerbosity; // must be 0 <= n <= 2 + wc16_string mLocalPassphrase; // pass phrase for private key + bool mLocalProvided; + TSTRING mPolFile; + TSTRING mSiteKeyFile; + TSTRING mLocalKeyFile; + TSTRING mDbFile; + TSTRING mReportFile; + TSTRING mEditor; + TSTRING mTempDirectory; // where we create our temp files... + TSTRING mGlobalEmail; // a list of email addr's + + bool mbLatePassphrase; // do we ask for the passphrase at the end of the operation or the beginning? + bool mfLooseDirs; // do we do loose directory checking? + bool mbResetAccessTime; // do we reset access time when calculating properties of files? + bool mbLogToSyslog; // log significant events and level 0 reports to SYSLOG + bool mbCrossFileSystems; // automatically recurse across mount points on Unis FS genre + bool mbDirectIO; // Use direct i/o when scanning files, if platform supports it. + + cTextReportViewer::ReportingLevel mEmailReportLevel; // What level of email reporting we should use + cMailMessage::MailMethod mMailMethod; // What mechanism should we use to send the report + + TSTRING mSmtpHost; // name of SMTP host to use + unsigned short mSmtpPort; // port number of that SMTP host + TSTRING mMailProgram; // full path to executable to use for piped mail + bool mMailNoViolations; // Email out reports with no violations? + TSTRING mMailFrom; + + cTWModeCommon() + : mVerbosity(1), + mLocalProvided(false), + mbLatePassphrase(false), + mfLooseDirs(false), + mbResetAccessTime(false), + mbLogToSyslog(false), + mbCrossFileSystems(false), + mbDirectIO(false), + mMailMethod(cMailMessage::NO_METHOD), + mSmtpPort(25), + mMailNoViolations(true) { } }; /////////////////////////////////////////////////////////////////////////////// -// iTWMode -- base class that contains an interface for initializing tripwire +// iTWMode -- base class that contains an interface for initializing tripwire // in a mode of operation and executing in that mode; a class is derived // from this for each mode of operation /////////////////////////////////////////////////////////////////////////////// class iTWMode { public: - virtual void InitCmdLineParser(cCmdLineParser& cmdLine) = 0; - // fills out the command line parser with all the switches that are appropriate for - // the given mode. - virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) = 0; - // call this to ask the mode object to initialize all of its data structures - // with the passed in information. If it returns false, it can be assumed that an error - // message was spit to stderr. - virtual int Execute(cErrorQueue* pQueue) = 0; - // go to work! TODO -- I don't know how errors (or return values) should be conveyed - // I think that maybe this guy should return an int indicating the return value - virtual TSTRING GetModeUsage( void ) = 0; - // Return a usage string particular to the concrete mode. - virtual cTWCmdLine::CmdLineArgs GetModeID() = 0; - // return the MODE_* enumeration for a given mode. - void SetCmdLine( const TSTRING& str ) { mstrCmdLine = str; }; - void SetConfigFile( const TSTRING& str ) { mstrConfigFile = str; }; - - virtual ~iTWMode() {}; + virtual void InitCmdLineParser(cCmdLineParser& cmdLine) = 0; + // fills out the command line parser with all the switches that are appropriate for + // the given mode. + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) = 0; + // call this to ask the mode object to initialize all of its data structures + // with the passed in information. If it returns false, it can be assumed that an error + // message was spit to stderr. + virtual int Execute(cErrorQueue* pQueue) = 0; + // go to work! TODO -- I don't know how errors (or return values) should be conveyed + // I think that maybe this guy should return an int indicating the return value + virtual TSTRING GetModeUsage(void) = 0; + // Return a usage string particular to the concrete mode. + virtual cTWCmdLine::CmdLineArgs GetModeID() = 0; + // return the MODE_* enumeration for a given mode. + void SetCmdLine(const TSTRING& str) + { + mstrCmdLine = str; + }; + void SetConfigFile(const TSTRING& str) + { + mstrConfigFile = str; + }; + + virtual ~iTWMode(){}; + protected: TSTRING mstrCmdLine; TSTRING mstrConfigFile; @@ -233,16 +243,20 @@ class cTWModeDbInit_i; class cTWModeDbInit : public iTWMode { public: - cTWModeDbInit(); - virtual ~cTWModeDbInit(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( void ); - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_INIT; } + cTWModeDbInit(); + virtual ~cTWModeDbInit(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(void); + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_INIT; + } + private: - cTWModeDbInit_i* mpData; + cTWModeDbInit_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -252,21 +266,25 @@ class cTWModeIC_i; class cTWModeIC : public iTWMode { public: - enum { - ERROR_IC = 8 - }; - - cTWModeIC(); - virtual ~cTWModeIC(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ); - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_CHECK; } + enum + { + ERROR_IC = 8 + }; + + cTWModeIC(); + virtual ~cTWModeIC(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_CHECK; + } private: - cTWModeIC_i* mpData; + cTWModeIC_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -276,26 +294,33 @@ class cTWModeDbUpdate_i; class cTWModeDbUpdate : public iTWMode { public: - cTWModeDbUpdate(); - virtual ~cTWModeDbUpdate(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - void Init (const cTWModeIC_i* pICData, cFCODatabaseFile* dbFile, cFCOReportHeader* prh, cFCOReport* pReport, bool bEncryptDb); - // this Init is used when you want to automatically launch into db update - // mode from integrity checking mode. It is called by cTWModeIC after it - // is totally done with the integrity check. - // The database and report are passed in becuase they are already loaded - // into memory when IC is done, so it doesn't make sense for this class to - // load them again. If bEncrypt is true, then the database should be encrypted when - // saved. - - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ); - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_UPDATE_DB; } + cTWModeDbUpdate(); + virtual ~cTWModeDbUpdate(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + void Init(const cTWModeIC_i* pICData, + cFCODatabaseFile* dbFile, + cFCOReportHeader* prh, + cFCOReport* pReport, + bool bEncryptDb); + // this Init is used when you want to automatically launch into db update + // mode from integrity checking mode. It is called by cTWModeIC after it + // is totally done with the integrity check. + // The database and report are passed in becuase they are already loaded + // into memory when IC is done, so it doesn't make sense for this class to + // load them again. If bEncrypt is true, then the database should be encrypted when + // saved. + + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_UPDATE_DB; + } private: - cTWModeDbUpdate_i* mpData; + cTWModeDbUpdate_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -305,17 +330,20 @@ class cTWModePolUpdate_i; class cTWModePolUpdate : public iTWMode { public: - cTWModePolUpdate(); - virtual ~cTWModePolUpdate(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ); - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_UPDATE_POL; } + cTWModePolUpdate(); + virtual ~cTWModePolUpdate(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_UPDATE_POL; + } private: - cTWModePolUpdate_i* mpData; + cTWModePolUpdate_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -325,17 +353,20 @@ class cTWModeTest_i; class cTWModeTest : public iTWMode { public: - cTWModeTest(); - virtual ~cTWModeTest(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ); - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_TEST; } + cTWModeTest(); + virtual ~cTWModeTest(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_TEST; + } private: - cTWModeTest_i* mpData; + cTWModeTest_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -346,21 +377,27 @@ class cTWModeHelp_i; class cTWModeHelp : public iTWMode { public: - cTWModeHelp(); - virtual ~cTWModeHelp(); + cTWModeHelp(); + virtual ~cTWModeHelp(); - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ) { return _T(""); } - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_HELP; } + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return _T(""); + } + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_HELP; + } private: - cTWModeHelp_i* mpData; + cTWModeHelp_i* mpData; }; -//These two modes are invisible if _DEBUG_DB is not defined. -#ifdef _DEBUG_DB +//These two modes are invisible if DEBUG is not defined. +#ifdef DEBUG /////////////////////////////////////////////////////////////////////////////// // Explore Db @@ -369,17 +406,23 @@ class cTWModeExploreDb_i; class cTWModeExploreDb : public iTWMode { public: - cTWModeExploreDb(); - virtual ~cTWModeExploreDb(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ) { return _T(""); } - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_EXPLORE; } + cTWModeExploreDb(); + virtual ~cTWModeExploreDb(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return _T(""); + } + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_EXPLORE; + } private: - cTWModeExploreDb_i* mpData; + cTWModeExploreDb_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -389,20 +432,26 @@ class cTWModeDebugDb_i; class cTWModeDebugDb : public iTWMode { public: - cTWModeDebugDb(); - virtual ~cTWModeDebugDb(); - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage( ) { return _T(""); } - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_DEBUG; } + cTWModeDebugDb(); + virtual ~cTWModeDebugDb(); + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return _T(""); + } + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_DEBUG; + } private: - cTWModeDebugDb_i* mpData; + cTWModeDebugDb_i* mpData; }; -#endif //_DEBUG_DB +#endif //DEBUG /////////////////////////////////////////////////////////////////////////////// // Version Mode @@ -410,17 +459,38 @@ class cTWModeDebugDb : public iTWMode class cTWModeVersion : public iTWMode { public: - cTWModeVersion() {} - virtual ~cTWModeVersion() {} - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine) { ASSERT(false); } - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine) { ASSERT(false); return true; } - virtual int Execute (cErrorQueue* pQueue) { ASSERT(false); return 0; } - virtual TSTRING GetModeUsage( ) { ASSERT(false); return _T(""); } - virtual cTWCmdLine::CmdLineArgs GetModeID() { return cTWCmdLine::MODE_VERSION; } + cTWModeVersion() + { + } + virtual ~cTWModeVersion() + { + } + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine) + { + ASSERT(false); + } + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) + { + ASSERT(false); + return true; + } + virtual int Execute(cErrorQueue* pQueue) + { + ASSERT(false); + return 0; + } + virtual TSTRING GetModeUsage() + { + ASSERT(false); + return _T(""); + } + virtual cTWCmdLine::CmdLineArgs GetModeID() + { + return cTWCmdLine::MODE_VERSION; + } private: }; #endif - diff --git a/src/tripwire/twcmdlineutil.cpp b/src/tripwire/twcmdlineutil.cpp index 421d80a..4005041 100644 --- a/src/tripwire/twcmdlineutil.cpp +++ b/src/tripwire/twcmdlineutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,7 +36,7 @@ #include "fco/fcospeclist.h" #include "twparser/policyparser.h" -#include "twparser/parserhelper.h" // used in TripPropsFromSpecs below +#include "twparser/parserhelper.h" // used in TripPropsFromSpecs below #include "fco/parsergenreutil.h" #include "fco/fcopropvector.h" #include "core/fsservices.h" @@ -46,8 +46,8 @@ #include "tw/twutil.h" #include "tw/textreportviewer.h" #include "core/archive.h" -#include // used to open plain text policy file -#include "mailmessage.h" // used for email reporting +#include // used to open plain text policy file +#include "mailmessage.h" // used for email reporting #include "fco/twfactory.h" #include "tripwirestrings.h" #include "twcmdline.h" @@ -67,70 +67,70 @@ #include -#ifdef GMMS - -// local helper functions for GMMS notification -static TSTRING FormatGmmsReportSummary(int32 date, int violationCount, int maxSeverity); -static TSTRING FormatGmmsViolationSummary(int32 date, const TSTRING& rulename, const TSTRING& filename, int severity); -static void SendGmmsAlert(const TSTRING& gmmsProg, const TSTRING& gmmsOptions, const TSTRING& alerts); // throw (eGmmsError) - -#endif - /////////////////////////////////////////////////////////////////////////////// // ParsePolicyFile /////////////////////////////////////////////////////////////////////////////// -void cTWCmdLineUtil::ParsePolicyFile(cGenreSpecListVector& genreSpecList, const TSTRING& fileName, TSTRING& strSiteKeyFile, cErrorQueue* pQueue) +void cTWCmdLineUtil::ParsePolicyFile(cGenreSpecListVector& genreSpecList, + const TSTRING& fileName, + TSTRING& strSiteKeyFile, + cErrorQueue* pQueue) { // get site public key - cKeyFile siteKeyfile; - cTWUtil::OpenKeyFile( siteKeyfile, strSiteKeyFile ); + cKeyFile siteKeyfile; + cTWUtil::OpenKeyFile(siteKeyfile, strSiteKeyFile); // read in and unencrypt policy file std::string strPolicyText; - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_POLICY_FILE).c_str(), - cDisplayEncoder::EncodeInline( fileName ).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_POLICY_FILE).c_str(), + cDisplayEncoder::EncodeInline(fileName).c_str()); // warn user if policy file is unencrypted { cFileManipulator policyManipulator(fileName.c_str()); policyManipulator.Init(); if (policyManipulator.GetEncoding() != cFileHeader::ASYM_ENCRYPTION) - cTWUtil::PrintErrorMsg(eTWPolUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + cTWUtil::PrintErrorMsg(eTWPolUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - - cTWUtil::ReadPolicyText( fileName.c_str(), strPolicyText, siteKeyfile.GetPublicKey() ); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_PARSING_POLICY).c_str(), - cDisplayEncoder::EncodeInline( fileName ).c_str()); - - // set up parser and parser policy file - std::istringstream in( strPolicyText ); - cPolicyParser parser( in ); - parser.Execute( genreSpecList, pQueue ); + + cTWUtil::ReadPolicyText(fileName.c_str(), strPolicyText, siteKeyfile.GetPublicKey()); + + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_PARSING_POLICY).c_str(), + cDisplayEncoder::EncodeInline(fileName).c_str()); + + // set up parser and parser policy file + std::istringstream in(strPolicyText); + cPolicyParser parser(in); + parser.Execute(genreSpecList, pQueue); } /////////////////////////////////////////////////////////////////////////////// // ParseTextPolicyFile /////////////////////////////////////////////////////////////////////////////// -void cTWCmdLineUtil::ParseTextPolicyFile(cGenreSpecListVector& genreSpecList, const TSTRING& fileName, TSTRING& strSiteKeyFile, cErrorQueue* pQueue) +void cTWCmdLineUtil::ParseTextPolicyFile(cGenreSpecListVector& genreSpecList, + const TSTRING& fileName, + TSTRING& strSiteKeyFile, + cErrorQueue* pQueue) { - std::ifstream in; - in.open(cStringUtil::TstrToStr(fileName).c_str()); - if(in.fail()) - { - throw eOpen( fileName ); - } - - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_PARSING_POLICY).c_str(), - cDisplayEncoder::EncodeInline( fileName ).c_str()); - - cPolicyParser parser(in); - parser.Execute(genreSpecList, pQueue); + std::ifstream in; + in.open(cStringUtil::TstrToStr(fileName).c_str()); + if (in.fail()) + { + throw eOpen(fileName); + } + + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_PARSING_POLICY).c_str(), + cDisplayEncoder::EncodeInline(fileName).c_str()); + + cPolicyParser parser(in); + parser.Execute(genreSpecList, pQueue); } @@ -143,24 +143,24 @@ void cTWCmdLineUtil::ParseTextPolicyFile(cGenreSpecListVector& genreSpecList, co /////////////////////////////////////////////////////////////////////////////// static TSTRING util_NextPropToken(TSTRING::const_iterator& i, const TSTRING& src, bool& bGenreName) { - TSTRING ret; - TSTRING::const_iterator begin = i; - for(; i != src.end(); i++ ) - { - if( (*i == _T(':')) || (*i == _T(',')) ) - break; - } - if( (i == src.end()) || (*i != _T(':')) ) - bGenreName = false; - else - bGenreName = true; - ret.assign( begin, i ); - // - // move the iter to the beginning of the next token - // - if( i != src.end() ) - i++; - return ret; + TSTRING ret; + TSTRING::const_iterator begin = i; + for (; i != src.end(); i++) + { + if ((*i == _T(':')) || (*i == _T(','))) + break; + } + if ((i == src.end()) || (*i != _T(':'))) + bGenreName = false; + else + bGenreName = true; + ret.assign(begin, i); + // + // move the iter to the beginning of the next token + // + if (i != src.end()) + i++; + return ret; } /////////////////////////////////////////////////////////////////////////////// @@ -168,101 +168,103 @@ static TSTRING util_NextPropToken(TSTRING::const_iterator& i, const TSTRING& src /////////////////////////////////////////////////////////////////////////////// void cTWCmdLineUtil::TrimPropsFromSpecs(cFCOSpecList& specList, const TSTRING& propsToIgnore) { - cDebug d("cTWCmdLineUtil::TrimPropsFromSpecs"); - d.TraceDebug("Entering...\n"); - cFCOPropVector v; + cDebug d("cTWCmdLineUtil::TrimPropsFromSpecs"); + d.TraceDebug("Entering...\n"); + cFCOPropVector v; iParserGenreUtil* pHelper = iTWFactory::GetInstance()->CreateParserGenreUtil(); - // - // trim only the properties appropriate for the current genre... - // - TSTRING propStr, ignoreStr; - cGenre::Genre sysGenre = cGenreSwitcher::GetInstance()->CurrentGenre(); + // + // trim only the properties appropriate for the current genre... + // + TSTRING propStr, ignoreStr; + cGenre::Genre sysGenre = cGenreSwitcher::GetInstance()->CurrentGenre(); cGenre::Genre curGenre = cGenreSwitcher::GetInstance()->GetDefaultGenre(); - iParserGenreUtil* pGU = iTWFactory::GetInstance()->CreateParserGenreUtil(); - TSTRING::const_iterator i = propsToIgnore.begin(); - TSTRING curToken; - bool bGenreName; - // - // the main token-getting loop - // - while( true ) - { - curToken = util_NextPropToken( i, propsToIgnore, bGenreName ); - if( curToken.empty() ) - break; // all done - // - // handle the genre switching token... - // - if( bGenreName ) - { - curGenre = cGenreSwitcher::GetInstance()->StringToGenre( curToken.c_str() ); - if( curGenre == cGenre::GENRE_INVALID ) - { - throw eTWUnknownSectionName( curToken ); - } - } - else - { - if( curGenre == sysGenre ) - { + iParserGenreUtil* pGU = iTWFactory::GetInstance()->CreateParserGenreUtil(); + TSTRING::const_iterator i = propsToIgnore.begin(); + TSTRING curToken; + bool bGenreName; + // + // the main token-getting loop + // + while (true) + { + curToken = util_NextPropToken(i, propsToIgnore, bGenreName); + if (curToken.empty()) + break; // all done + // + // handle the genre switching token... + // + if (bGenreName) + { + curGenre = cGenreSwitcher::GetInstance()->StringToGenre(curToken.c_str()); + if (curGenre == cGenre::GENRE_INVALID) + { + throw eTWUnknownSectionName(curToken); + } + } + else + { + if (curGenre == sysGenre) + { // put together a string to pass to parsing code. // Single letter properties can be simply concatenated, where // long property names must have a '&' between them. - if( pGU->HasSingleLetterProps() ) + if (pGU->HasSingleLetterProps()) propStr += curToken; else propStr += _T("&") + curToken; - // - // this string is used to tell the user what we are ignoring - // - if( ignoreStr.empty() ) - ignoreStr = curToken; - else - ignoreStr += _T(", ") + curToken; - } - } - } - // - // if there is nothing to remove, just return... - // - if( propStr.empty() ) - return; - - try - { - cParserUtil::CreatePropVector( propStr, v, pHelper ); + // + // this string is used to tell the user what we are ignoring + // + if (ignoreStr.empty()) + ignoreStr = curToken; + else + ignoreStr += _T(", ") + curToken; + } + } + } + // + // if there is nothing to remove, just return... + // + if (propStr.empty()) + return; + + try + { + cParserUtil::CreatePropVector(propStr, v, pHelper); delete pHelper; - } - catch(eParserHelper&) - { + } + catch (eParserHelper&) + { delete pHelper; - d.TraceError("CreatePropVector failed!!\n"); - throw eTWBadPropsToIgnore( propsToIgnore ); - } - - d.TraceDebug("We are ignoring these properties:\n"); - v.TraceContents(); - - iUserNotify::GetInstance()->Notify(1, _T("%s %s\n"), TSS_GetString( cTripwire, tripwire::STR_IGNORE_PROPS).c_str(), - cDisplayEncoder::EncodeInline( ignoreStr ).c_str()); - - - // okay, now let's change the specs! - cFCOSpecListAddedIter iter(specList); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) - { - // TODO -- when we have multiple masks, we will need to iterate through all of the masks. - cFCOPropVector specVector = iter.Spec()->GetPropVector(iFCOSpecMask::GetDefaultMask()); - cFCOPropVector newSpecVector = (specVector & v) ^ specVector; - iter.Spec()->SetPropVector(iFCOSpecMask::GetDefaultMask(), newSpecVector); - - d.TraceDebug("Spec's prop set\n-----before:\n"); - specVector.TraceContents(); - d.TraceDebug("-----after:\n"); - newSpecVector.TraceContents(); - } + d.TraceError("CreatePropVector failed!!\n"); + throw eTWBadPropsToIgnore(propsToIgnore); + } + + d.TraceDebug("We are ignoring these properties:\n"); + v.TraceContents(); + + iUserNotify::GetInstance()->Notify(1, + _T("%s %s\n"), + TSS_GetString(cTripwire, tripwire::STR_IGNORE_PROPS).c_str(), + cDisplayEncoder::EncodeInline(ignoreStr).c_str()); + + + // okay, now let's change the specs! + cFCOSpecListAddedIter iter(specList); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) + { + // TODO -- when we have multiple masks, we will need to iterate through all of the masks. + cFCOPropVector specVector = iter.Spec()->GetPropVector(iFCOSpecMask::GetDefaultMask()); + cFCOPropVector newSpecVector = (specVector & v) ^ specVector; + iter.Spec()->SetPropVector(iFCOSpecMask::GetDefaultMask(), newSpecVector); + + d.TraceDebug("Spec's prop set\n-----before:\n"); + specVector.TraceContents(); + d.TraceDebug("-----after:\n"); + newSpecVector.TraceContents(); + } } /////////////////////////////////////////////////////////////////////////////// @@ -270,27 +272,27 @@ void cTWCmdLineUtil::TrimPropsFromSpecs(cFCOSpecList& specList, const TSTRING& p /////////////////////////////////////////////////////////////////////////////// void cTWCmdLineUtil::TrimSpecsByName(cFCOSpecList& specList, const TSTRING specName) { - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_CHECKING_SPECS_NAMED).c_str(), - cDisplayEncoder::EncodeInline( specName ).c_str()); - - cFCOSpecListAddedIter iter(specList); - for(iter.SeekBegin(); ! iter.Done(); ) - { - //if(iter.Attr()->GetName().compare(specName) == 0) - // right now, names are stored in the spec, but soon they will be in the - // attributes (see commented out code above) - if(iter.Spec()->GetName().compare(specName) == 0) - { - // found one! - iter.Next(); - } - else - { - iter.Remove(); - } - } + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_CHECKING_SPECS_NAMED).c_str(), + cDisplayEncoder::EncodeInline(specName).c_str()); + + cFCOSpecListAddedIter iter(specList); + for (iter.SeekBegin(); !iter.Done();) + { + //if(iter.Attr()->GetName().compare(specName) == 0) + // right now, names are stored in the spec, but soon they will be in the + // attributes (see commented out code above) + if (iter.Spec()->GetName().compare(specName) == 0) + { + // found one! + iter.Next(); + } + else + { + iter.Remove(); + } + } } /////////////////////////////////////////////////////////////////////////////// @@ -298,31 +300,32 @@ void cTWCmdLineUtil::TrimSpecsByName(cFCOSpecList& specList, const TSTRING specN /////////////////////////////////////////////////////////////////////////////// void cTWCmdLineUtil::TrimSpecsBySeverity(cFCOSpecList& specList, int severity) { - cDebug d("cTWCmdLineUtil::TrimSpecsBySeverity"); - d.TraceDebug("Entering; severity=%d\n", severity); - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - _T("%s%d\n"), - TSS_GetString( cTripwire, tripwire::STR_IC_SEVERITY_LEVEL).c_str(), - severity); - - cFCOSpecListAddedIter iter(specList); - for(iter.SeekBegin(); ! iter.Done(); ) - { - if(iter.Attr()->GetSeverity() < severity) - { - d.TraceDetail("Removing spec %s (severity=%d)\n", iter.Spec()->GetStartPoint().AsString().c_str(), - iter.Attr()->GetSeverity()); - - TW_NOTIFY_VERBOSE( TSS_GetString( cTripwire, tripwire::STR_IC_IGNORING_SEVERITY).c_str(), - iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay - ( iter.Spec()->GetStartPoint() ).c_str(), - iter.Attr()->GetSeverity()); - - iter.Remove(); - } - else - iter.Next(); - } + cDebug d("cTWCmdLineUtil::TrimSpecsBySeverity"); + d.TraceDebug("Entering; severity=%d\n", severity); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%d\n"), + TSS_GetString(cTripwire, tripwire::STR_IC_SEVERITY_LEVEL).c_str(), + severity); + + cFCOSpecListAddedIter iter(specList); + for (iter.SeekBegin(); !iter.Done();) + { + if (iter.Attr()->GetSeverity() < severity) + { + d.TraceDetail("Removing spec %s (severity=%d)\n", + iter.Spec()->GetStartPoint().AsString().c_str(), + iter.Attr()->GetSeverity()); + + TW_NOTIFY_VERBOSE( + TSS_GetString(cTripwire, tripwire::STR_IC_IGNORING_SEVERITY).c_str(), + iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(iter.Spec()->GetStartPoint()).c_str(), + iter.Attr()->GetSeverity()); + + iter.Remove(); + } + else + iter.Next(); + } } /////////////////////////////////////////////////////////////////////////////// @@ -330,17 +333,17 @@ void cTWCmdLineUtil::TrimSpecsBySeverity(cFCOSpecList& specList, int severity) /////////////////////////////////////////////////////////////////////////////// void cTWCmdLineUtil::TrimSpecsBySeverityName(cFCOSpecList& specList, const TSTRING& severity) { - // for now, the names are hard coded, but they might not be in the future... - if(_tcsicmp(severity.c_str(), _T("low")) == 0) - TrimSpecsBySeverity(specList, 33); - else if(_tcsicmp(severity.c_str(), _T("medium")) == 0) - TrimSpecsBySeverity(specList, 66); - else if(_tcsicmp(severity.c_str(), _T("high")) == 0) - TrimSpecsBySeverity(specList, 100); - else - { - throw eTWBadSeverityName( severity ); - } + // for now, the names are hard coded, but they might not be in the future... + if (_tcsicmp(severity.c_str(), _T("low")) == 0) + TrimSpecsBySeverity(specList, 33); + else if (_tcsicmp(severity.c_str(), _T("medium")) == 0) + TrimSpecsBySeverity(specList, 66); + else if (_tcsicmp(severity.c_str(), _T("high")) == 0) + TrimSpecsBySeverity(specList, 100); + else + { + throw eTWBadSeverityName(severity); + } } /////////////////////////////////////////////////////////////////////////////// @@ -348,105 +351,108 @@ void cTWCmdLineUtil::TrimSpecsBySeverityName(cFCOSpecList& specList, const TSTRI /////////////////////////////////////////////////////////////////////////////// bool cTWCmdLineUtil::ReportContainsFCO(const cFCOReport& report) { - cFCOReportGenreIter genreIter( report ); - for(genreIter.SeekBegin(); ! genreIter.Done(); genreIter.Next()) + cFCOReportGenreIter genreIter(report); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { - cFCOReportSpecIter specIter( genreIter ); - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) - { - if( (! specIter.GetAddedSet()->IsEmpty()) || - (! specIter.GetRemovedSet()->IsEmpty()) || - ( specIter.GetNumChanged() != 0)) - return true; - } + cFCOReportSpecIter specIter(genreIter); + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) + { + if ((!specIter.GetAddedSet()->IsEmpty()) || (!specIter.GetRemovedSet()->IsEmpty()) || + (specIter.GetNumChanged() != 0)) + return true; + } } - return false; + return false; } /////////////////////////////////////////////////////////////////////////////// // GetICReturnValue /////////////////////////////////////////////////////////////////////////////// -int cTWCmdLineUtil::GetICReturnValue(const cFCOReport& report ) +int cTWCmdLineUtil::GetICReturnValue(const cFCOReport& report) { - enum { ADDED = 1, REMOVED = 2, CHANGED = 4 }; + enum + { + ADDED = 1, + REMOVED = 2, + CHANGED = 4 + }; - int rtn = 0; - cFCOReportGenreIter genreIter( report ); - for(genreIter.SeekBegin(); ! genreIter.Done(); genreIter.Next()) + int rtn = 0; + cFCOReportGenreIter genreIter(report); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { cFCOReportSpecIter specIter(report, genreIter.GetGenre()); - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) - { - if(! specIter.GetAddedSet()->IsEmpty()) - rtn |= ADDED; - if(! specIter.GetRemovedSet()->IsEmpty()) - rtn |= REMOVED; - if(specIter.GetNumChanged() != 0) - rtn |= CHANGED; - } + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) + { + if (!specIter.GetAddedSet()->IsEmpty()) + rtn |= ADDED; + if (!specIter.GetRemovedSet()->IsEmpty()) + rtn |= REMOVED; + if (specIter.GetNumChanged() != 0) + rtn |= CHANGED; + } } - return rtn; + return rtn; } /////////////////////////////////////////////////////////////////////////////// // VerifySpecs // /////////////////////////////////////////////////////////////////////////////// -void cTWCmdLineUtil::VerifySpecs( const cFCOSpecList& parsedList, const cFCOSpecList& dbList ) +void cTWCmdLineUtil::VerifySpecs(const cFCOSpecList& parsedList, const cFCOSpecList& dbList) { - cFCOSpecListCanonicalIter policyItr (parsedList); - cFCOSpecListCanonicalIter dbItr (dbList); + cFCOSpecListCanonicalIter policyItr(parsedList); + cFCOSpecListCanonicalIter dbItr(dbList); - if( parsedList.Size() != dbList.Size() ) - { - throw eICBadPol(); - } + if (parsedList.Size() != dbList.Size()) + { + throw eICBadPol(); + } - for ( policyItr.SeekBegin(), dbItr.SeekBegin(); ! policyItr.Done(); policyItr.Next(), dbItr.Next() ) + for (policyItr.SeekBegin(), dbItr.SeekBegin(); !policyItr.Done(); policyItr.Next(), dbItr.Next()) { - if( ! iFCOSpecUtil::FCOSpecEqual(*policyItr.Spec(), *dbItr.Spec()) ) - { - throw eICBadPol(); - } - // make sure the vectors are the same... - // TODO -- this won't work when we get spec masks - // - if( policyItr.Spec()->GetPropVector( iFCOSpecMask::GetDefaultMask() ) != - dbItr.Spec()->GetPropVector( iFCOSpecMask::GetDefaultMask() ) ) - { - throw eICBadPol(); - } - } + if (!iFCOSpecUtil::FCOSpecEqual(*policyItr.Spec(), *dbItr.Spec())) + { + throw eICBadPol(); + } + // make sure the vectors are the same... + // TODO -- this won't work when we get spec masks + // + if (policyItr.Spec()->GetPropVector(iFCOSpecMask::GetDefaultMask()) != + dbItr.Spec()->GetPropVector(iFCOSpecMask::GetDefaultMask())) + { + throw eICBadPol(); + } + } } /////////////////////////////////////////////////////////////////////////////// // VerifyPolicy /////////////////////////////////////////////////////////////////////////////// -void cTWCmdLineUtil::VerifyPolicy( cGenreSpecListVector& genreSpecList, cFCODatabaseFile& dbFile ) +void cTWCmdLineUtil::VerifyPolicy(cGenreSpecListVector& genreSpecList, cFCODatabaseFile& dbFile) { - cGenreSpecListVector::iterator genreIter; - cFCODatabaseFile::iterator dbIter( dbFile ); - - // make sure the number of genres in each is the same. - // - if( genreSpecList.size() != (size_t)dbIter.Size() ) - throw eICBadPol(); - - // iterate over all of the genres... - // - for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) - { - dbIter.SeekToGenre( genreIter->GetGenre() ); - if( dbIter.Done() ) - { - throw eICBadPol(); - } - // now, compare the two property sets... - // - VerifySpecs( genreIter->GetSpecList(), dbIter.GetSpecList()); - - } + cGenreSpecListVector::iterator genreIter; + cFCODatabaseFile::iterator dbIter(dbFile); + + // make sure the number of genres in each is the same. + // + if (genreSpecList.size() != (size_t)dbIter.Size()) + throw eICBadPol(); + + // iterate over all of the genres... + // + for (genreIter = genreSpecList.begin(); genreIter != genreSpecList.end(); ++genreIter) + { + dbIter.SeekToGenre(genreIter->GetGenre()); + if (dbIter.Done()) + { + throw eICBadPol(); + } + // now, compare the two property sets... + // + VerifySpecs(genreIter->GetSpecList(), dbIter.GetSpecList()); + } } @@ -456,78 +462,79 @@ void cTWCmdLineUtil::VerifyPolicy( cGenreSpecListVector& genreSpecList, cFCOData // the report. // //////////////////////////////////////////////////////////////////////////////// -static void GetEmailRecipients(std::vector &vstrRecipients, - const cFCOReport& report, - const cTWModeCommon *modeCommon) { +static void +GetEmailRecipients(std::vector& vstrRecipients, const cFCOReport& report, const cTWModeCommon* modeCommon) +{ - // loop through all generes - cFCOReportGenreIter genreIter(report); - for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { + // loop through all generes + cFCOReportGenreIter genreIter(report); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { - // loop through all specs - cFCOReportSpecIter specIter(report, genreIter.GetGenre()); + // loop through all specs + cFCOReportSpecIter specIter(report, genreIter.GetGenre()); - for (specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) { + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) + { - // loop through all email addresses for this spec - cFCOSpecAttrEmailIter emailIter(*specIter.GetAttr()); + // loop through all email addresses for this spec + cFCOSpecAttrEmailIter emailIter(*specIter.GetAttr()); - for(emailIter.SeekBegin(); ! emailIter.Done(); emailIter.Next()) { + for (emailIter.SeekBegin(); !emailIter.Done(); emailIter.Next()) + { - TSTRING address = emailIter.EmailAddress(); - std::vector::iterator i; + TSTRING address = emailIter.EmailAddress(); + std::vector::iterator i; - // see if the address is already in the list - i = std::find(vstrRecipients.begin(), - vstrRecipients.end(), - address); + // see if the address is already in the list + i = std::find(vstrRecipients.begin(), vstrRecipients.end(), address); - if (i == vstrRecipients.end()) { - vstrRecipients.push_back(address); + if (i == vstrRecipients.end()) + { + vstrRecipients.push_back(address); + } + } } - - } } - } } -static void GetGlobalEmailRecipients(std::vector &vstrRecipients, - const cFCOReport& report, - const cTWModeCommon *modeCommon) { +static void GetGlobalEmailRecipients(std::vector& vstrRecipients, + const cFCOReport& report, + const cTWModeCommon* modeCommon) +{ - // let's check for global emailto's... - // - if (modeCommon->mGlobalEmail.length() != 0) { + // let's check for global emailto's... + // + if (modeCommon->mGlobalEmail.length() != 0) + { - std::vector addys; - const std::string delims = ";,"; + std::vector addys; + const std::string delims = ";,"; - cStringUtil::splitstring(addys, modeCommon->mGlobalEmail, delims); - - while (!addys.empty()) { + cStringUtil::splitstring(addys, modeCommon->mGlobalEmail, delims); - std::vector::iterator p; - TSTRING addr = addys.back(); + while (!addys.empty()) + { - // make sure it's not already in there... - // - p = std::find(vstrRecipients.begin(), - vstrRecipients.end(), - addr); + std::vector::iterator p; + TSTRING addr = addys.back(); - // put it away if it's unique... - // - if (p == vstrRecipients.end()) { - vstrRecipients.push_back(addr); - } + // make sure it's not already in there... + // + p = std::find(vstrRecipients.begin(), vstrRecipients.end(), addr); - addys.pop_back(); // remove that one... + // put it away if it's unique... + // + if (p == vstrRecipients.end()) + { + vstrRecipients.push_back(addr); + } + addys.pop_back(); // remove that one... + } } - } - } @@ -536,117 +543,114 @@ static void GetGlobalEmailRecipients(std::vector &vstrRecipients, // EmailReportTo - send only the relevant portions of the report the address // /////////////////////////////////////////////////////////////////////////////// -static bool EmailReportTo(const TSTRING &toAddress, const cFCOReportHeader& header, const cFCOReport& report, - const cTWModeCommon *modeCommon, - const bool bForceFullReport) +static bool EmailReportTo(const TSTRING& toAddress, + const cFCOReportHeader& header, + const cFCOReport& report, + const cTWModeCommon* modeCommon, + const bool bForceFullReport) { - std::auto_ptr reportMail; + TW_UNIQUE_PTR reportMail; - // allocate the right kind of emailer object based on what came out of the config file. - switch (modeCommon->mMailMethod) + // allocate the right kind of emailer object based on what came out of the config file. + switch (modeCommon->mMailMethod) { - default: - ASSERT(false); - return false; +#if SUPPORTS_NETWORKING case cMailMessage::MAIL_BY_SMTP: - reportMail = std::auto_ptr(new cSMTPMailMessage(modeCommon->mSmtpHost, modeCommon->mSmtpPort)); - break; - case cMailMessage::MAIL_BY_PIPE: - reportMail = std::auto_ptr(new cPipedMailMessage(modeCommon->mMailProgram)); - break; - case cMailMessage::MAIL_BY_MAPI: -#if SUPPORTS_MAPI - reportMail = std::auto_ptr(new cMAPIMailMessage); - break; -#else - ASSERT(false); - return false; + reportMail = TW_UNIQUE_PTR(new cSMTPMailMessage(modeCommon->mSmtpHost, modeCommon->mSmtpPort)); + break; #endif + case cMailMessage::MAIL_BY_PIPE: + reportMail = TW_UNIQUE_PTR(new cPipedMailMessage(modeCommon->mMailProgram)); + break; + default: + return false; } - TSTRING strTempFilename; + TSTRING strTempFilename; - // send the report - try + // send the report + try { - // we have to write the text report to a temporary file... - iFSServices::GetInstance()->GetTempDirName( strTempFilename ); - strTempFilename += _T("tripwire-report-XXXXXX"); - iFSServices::GetInstance()->MakeTempFilename( strTempFilename ); - strTempFilename += _T(".txt"); - - // print the report - cEmailReportViewer trv( header, report, toAddress, bForceFullReport ); - trv.PrintTextReport( strTempFilename, modeCommon->mEmailReportLevel ); - - // format the subject line with number of violations and the most severe violation found - // set up the cMailMessage class, and send it if they need it or want it - // (Yes, it seems odd to generate the report, only to potentially delete it without sending it.) - if ( trv.GetNumberViolations() > 0 || modeCommon->mMailNoViolations ) + // we have to write the text report to a temporary file... + iFSServices::GetInstance()->GetTempDirName(strTempFilename); + strTempFilename += _T("tripwire-report-XXXXXX"); + iFSServices::GetInstance()->MakeTempFilename(strTempFilename); + strTempFilename += _T(".txt"); + + // print the report + cEmailReportViewer trv(header, report, toAddress, bForceFullReport); + trv.PrintTextReport(strTempFilename, modeCommon->mEmailReportLevel); + + // format the subject line with number of violations and the most severe violation found + // set up the cMailMessage class, and send it if they need it or want it + // (Yes, it seems odd to generate the report, only to potentially delete it without sending it.) + if (trv.GetNumberViolations() > 0 || modeCommon->mMailNoViolations) { - // print message that we're emailing to this specific recipient - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s %s\n"), - TSS_GetString( cTripwire, tripwire::STR_EMAIL_REPORT_TO).c_str(), - cDisplayEncoder::EncodeInline( toAddress ).c_str()); - reportMail->AddRecipient(toAddress); - - if (!modeCommon->mMailFrom.empty()) - reportMail->SetFrom(modeCommon->mMailFrom); - else - { - TSTRING machineName; - iFSServices::GetInstance()->GetMachineNameFullyQualified(machineName); - reportMail->SetFrom(TSS_GetString( cTripwire, tripwire::STR_EMAIL_FROM) + machineName); - } - - reportMail->SetFromName(TSS_GetString(cTW, tw::STR_TSS_PRODUCT_NAME)); - - reportMail->SetSubject( trv.SingleLineReport() ); - - // don't attach a report if the user just requests a subject line - if( cTextReportViewer::SINGLE_LINE == modeCommon->mEmailReportLevel ) - reportMail->SetBody( _T(" ") ); - else - reportMail->AttachFile( strTempFilename.c_str() ); - - reportMail->Send(); + // print message that we're emailing to this specific recipient + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s %s\n"), + TSS_GetString(cTripwire, tripwire::STR_EMAIL_REPORT_TO).c_str(), + cDisplayEncoder::EncodeInline(toAddress).c_str()); + reportMail->AddRecipient(toAddress); + + if (!modeCommon->mMailFrom.empty()) + reportMail->SetFrom(modeCommon->mMailFrom); + else + { + TSTRING machineName; + iFSServices::GetInstance()->GetMachineNameFullyQualified(machineName); + reportMail->SetFrom(TSS_GetString(cTripwire, tripwire::STR_EMAIL_FROM) + machineName); + } + + reportMail->SetFromName(TSS_GetString(cTW, tw::STR_TSS_PRODUCT_NAME)); + + reportMail->SetSubject(trv.SingleLineReport()); + + // don't attach a report if the user just requests a subject line + if (cTextReportViewer::SINGLE_LINE == modeCommon->mEmailReportLevel) + reportMail->SetBody(_T(" ")); + else + reportMail->AttachFile(strTempFilename.c_str()); + + reportMail->Send(); } - // delete temp file - iFSServices::GetInstance()->FileDelete( strTempFilename ); + // delete temp file + iFSServices::GetInstance()->FileDelete(strTempFilename); } - catch(eError& e) + catch (eError& e) { - e.SetFatality( false ); // we want to continue from email errors, so make them non-fatal - cTWUtil::PrintErrorMsg(e); - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_EMAIL_REPORT) << std::endl; - // delete temp file - iFSServices::GetInstance()->FileDelete( strTempFilename ); - return false; + e.SetFatality(false); // we want to continue from email errors, so make them non-fatal + cTWUtil::PrintErrorMsg(e); + TCERR << TSS_GetString(cTripwire, tripwire::STR_ERR_EMAIL_REPORT) << std::endl; + // delete temp file + iFSServices::GetInstance()->FileDelete(strTempFilename); + return false; } - return true; + return true; } -static bool DoEmailReports(const std::vector &vstrRecipients, - const cFCOReportHeader& header, - const cFCOReport& report, - const cTWModeCommon *modeCommon, - const bool bForceFullReport) { +static bool DoEmailReports(const std::vector& vstrRecipients, + const cFCOReportHeader& header, + const cFCOReport& report, + const cTWModeCommon* modeCommon, + const bool bForceFullReport) +{ - // send each report out. - bool ret = true; - for (std::vector::size_type i=0; i::size_type i = 0; i < vstrRecipients.size(); i++) { - TSTRING addr; - cStringUtil::Convert(addr, vstrRecipients[i]); - bool success = EmailReportTo(addr, header, report, modeCommon, bForceFullReport); - if (!success) - ret = false; + TSTRING addr; + cStringUtil::Convert(addr, vstrRecipients[i]); + bool success = EmailReportTo(addr, header, report, modeCommon, bForceFullReport); + if (!success) + ret = false; } - return (ret); + return (ret); } @@ -657,300 +661,103 @@ static bool DoEmailReports(const std::vector &vstrRecipients, // in the policy file. // /////////////////////////////////////////////////////////////////////////////// -bool cTWCmdLineUtil::EmailReport(const cFCOReportHeader& header, const cFCOReport& report, - const cTWModeCommon *modeCommon) +bool cTWCmdLineUtil::EmailReport(const cFCOReportHeader& header, + const cFCOReport& report, + const cTWModeCommon* modeCommon) { - // print message that says that we're emailing - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s\n"), - TSS_GetString( cTripwire, - tripwire::STR_EMAIL_BEGIN).c_str()); - - bool emailSent = false; - bool ret = true; + // print message that says that we're emailing + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, _T("%s\n"), TSS_GetString(cTripwire, tripwire::STR_EMAIL_BEGIN).c_str()); - // Get the list of recipients - std::vector vstrRecipients; + bool emailSent = false; + bool ret = true; - GetEmailRecipients(vstrRecipients, report, modeCommon); - emailSent |= (vstrRecipients.size() != 0); + // Get the list of recipients + std::vector vstrRecipients; - if (vstrRecipients.size() != 0) - ret = DoEmailReports(vstrRecipients, header, report, modeCommon, false); - - if (ret) { // if not, probably catostrophic - - vstrRecipients.clear(); - GetGlobalEmailRecipients(vstrRecipients, report, modeCommon); + GetEmailRecipients(vstrRecipients, report, modeCommon); emailSent |= (vstrRecipients.size() != 0); if (vstrRecipients.size() != 0) - ret = DoEmailReports(vstrRecipients, header, report, modeCommon, true); - - } - + ret = DoEmailReports(vstrRecipients, header, report, modeCommon, false); - if (!emailSent) { + if (ret) + { // if not, probably catostrophic - // Send a message to the user, alerting them that no email has been sent. - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NO_EMAIL_RECIPIENTS).c_str()); - } - - return ret; -} - - -bool cTWCmdLineUtil::SendEmailTestMessage(const TSTRING &mAddress, const cTWModeCommon *modeCommon) -{ - std::auto_ptr reportMail; - - // allocate the right kind of emailer object based on what came out of the config file. - switch (modeCommon->mMailMethod) - { - default: - ASSERT(false); - return false; - case cMailMessage::MAIL_BY_SMTP: - reportMail = std::auto_ptr(new cSMTPMailMessage(modeCommon->mSmtpHost, modeCommon->mSmtpPort)); - break; - case cMailMessage::MAIL_BY_PIPE: - reportMail = std::auto_ptr(new cPipedMailMessage(modeCommon->mMailProgram)); - break; - case cMailMessage::MAIL_BY_MAPI: -#if SUPPORTS_MAPI - reportMail = std::auto_ptr(new cMAPIMailMessage); - break; -#else - ASSERT(false); - return false; -#endif - } - - - // print message that we're emailing to this specific recipient - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s %s\n"), - TSS_GetString( cTripwire, tripwire::STR_TEST_EMAIL_TO).c_str(), - cDisplayEncoder::EncodeInline( mAddress ).c_str()); - - // send the report - try - { - // set up the cMailMessage class, and send it - reportMail->AddRecipient(mAddress); - - if (!modeCommon->mMailFrom.empty()) - reportMail->SetFrom(modeCommon->mMailFrom); - else - { - TSTRING machineName; - iFSServices::GetInstance()->GetMachineNameFullyQualified(machineName); - reportMail->SetFrom(TSS_GetString( cTripwire, tripwire::STR_EMAIL_FROM) + machineName); - } - - reportMail->SetFromName(TSS_GetString(cTW, tw::STR_TSS_PRODUCT_NAME)); - - reportMail->SetSubject (TSS_GetString( cTripwire, tripwire::STR_TEST_EMAIL_SUBJECT)); - reportMail->SetBody (TSS_GetString( cTripwire, tripwire::STR_TEST_EMAIL_BODY)); - reportMail->Send(); - } - catch(eError& e) - { - cTWUtil::PrintErrorMsg(e); - TCERR << TSS_GetString( cTripwire, tripwire::STR_ERR_EMAIL_TEST) << std::endl; - return false; - } - - return true; -} - - -#ifdef GMMS + vstrRecipients.clear(); + GetGlobalEmailRecipients(vstrRecipients, report, modeCommon); + emailSent |= (vstrRecipients.size() != 0); -// -// Use gmms to send violation notification -// -// verbosity==1 One line summary of whole report -// verbosity==2 One line summary of each violation -// -bool cTWCmdLineUtil::GmmsReport(const cFCOReportHeader& header, const cFCOReport& report, - const TSTRING &gmmsProg, const TSTRING &gmmsOptions, int verbosity) // throw (eGmmsError) -{ - int violationCount = 0, maxSeverity = 0; - TSTRING alerts; + if (vstrRecipients.size() != 0) + ret = DoEmailReports(vstrRecipients, header, report, modeCommon, true); + } - // loop through all generes - cFCOReportGenreIter genreIter(report); - for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) - { - // loop through all specs - cFCOReportSpecIter specIter(report, genreIter.GetGenre()); - for (specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) - { - - ASSERT(true); - - // Get severity - int32 severity = specIter.GetAttr()->GetSeverity(); - - // Get rulename - TSTRING rulename = specIter.GetAttr()->GetName(); - - // Go through all of the added file rule violations - cIterProxy addedIter(specIter.GetAddedSet()->GetIter()); - for (addedIter->SeekBegin(); !addedIter->Done(); addedIter->Next()) - { - if (severity > maxSeverity) - maxSeverity = severity; - - if (verbosity == 2) - { - // get filename, send one line summary of this violation - TSTRING filename = addedIter->FCO()->GetName().AsString(); - alerts += FormatGmmsViolationSummary(header.GetCreationTime(), rulename, filename, severity); - alerts += _T("\n"); - } - - violationCount++; - } - - // Go through all of the removed file rule violations - cIterProxy removedIter(specIter.GetRemovedSet()->GetIter()); - for (removedIter->SeekBegin(); !removedIter->Done(); removedIter->Next()) - { - if (severity > maxSeverity) - maxSeverity = severity; - - if (verbosity == 2) - { - // get filename, send one line summary of this violation - TSTRING filename = removedIter->FCO()->GetName().AsString(); - alerts += FormatGmmsViolationSummary(header.GetCreationTime(), rulename, filename, severity); - alerts += _T("\n"); - } - violationCount++; - } + if (!emailSent) + { - // Go through all of the changed file rule violations - cFCOReportChangeIter changedIter(specIter); - for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) - { - if (severity > maxSeverity) - maxSeverity = severity; + // Send a message to the user, alerting them that no email has been sent. + iUserNotify::GetInstance()->Notify( + iUserNotify::V_NORMAL, _T("%s\n"), TSS_GetString(cTripwire, tripwire::STR_NO_EMAIL_RECIPIENTS).c_str()); + } - if (verbosity == 2) - { - // get filename, send one line summary of this violation - TSTRING filename = changedIter.GetOld()->GetName().AsString(); - alerts += FormatGmmsViolationSummary(header.GetCreationTime(), rulename, filename, severity); - alerts += _T("\n"); - } + return ret; +} - violationCount++; - } - } - } - // Send one line summary of the whole report if that's what they want, - // or if there were no violations and the verbosity level is 2. That way - // verbosity level 2 and no violations will still send an all-is-well notification. - if (verbosity == 1 || (verbosity == 2 && violationCount==0)) - { - alerts += FormatGmmsReportSummary(header.GetCreationTime(), violationCount, maxSeverity); - alerts += _T("\n"); - } +bool cTWCmdLineUtil::SendEmailTestMessage(const TSTRING& mAddress, const cTWModeCommon* modeCommon) +{ + TW_UNIQUE_PTR reportMail; - ASSERT(!alerts.empty()); - SendGmmsAlert(gmmsProg, gmmsOptions, alerts); + // allocate the right kind of emailer object based on what came out of the config file. + switch (modeCommon->mMailMethod) + { +#if SUPPORTS_NETWORKING + case cMailMessage::MAIL_BY_SMTP: + reportMail = TW_UNIQUE_PTR(new cSMTPMailMessage(modeCommon->mSmtpHost, modeCommon->mSmtpPort)); + break; +#endif + case cMailMessage::MAIL_BY_PIPE: + reportMail = TW_UNIQUE_PTR(new cPipedMailMessage(modeCommon->mMailProgram)); + break; + default: + return false; + } - return true; -} + // print message that we're emailing to this specific recipient + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s %s\n"), + TSS_GetString(cTripwire, tripwire::STR_TEST_EMAIL_TO).c_str(), + cDisplayEncoder::EncodeInline(mAddress).c_str()); -// -// Use this with gmms verbosity level 1 -// -TSTRING FormatGmmsReportSummary(int32 date, int violationCount, int maxSeverity) -{ - TSTRING strDate; - cTWLocale::FormatTime(date, strDate); - - TOSTRINGSTREAM summary; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_START); - summary << strDate; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_VERBOSITY1A); - summary << violationCount; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_VERBOSITY1B); - summary << maxSeverity; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_END); - - return summary.str(); -} + // send the report + try + { + // set up the cMailMessage class, and send it + reportMail->AddRecipient(mAddress); + if (!modeCommon->mMailFrom.empty()) + reportMail->SetFrom(modeCommon->mMailFrom); + else + { + TSTRING machineName; + iFSServices::GetInstance()->GetMachineNameFullyQualified(machineName); + reportMail->SetFrom(TSS_GetString(cTripwire, tripwire::STR_EMAIL_FROM) + machineName); + } -// -// Use this with gmms verbosity level 2 -// -TSTRING FormatGmmsViolationSummary(int32 date, const TSTRING& rulename, const TSTRING& filename, int severity) -{ - TSTRING strDate; - cTWLocale::FormatTime(date, strDate); - - TOSTRINGSTREAM summary; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_START); - summary << strDate; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_VERBOSITY2A); - summary << rulename; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_VERBOSITY2B); - summary << filename; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_VERBOSITY2C); - summary << severity; - summary << TSS_GetString( cTripwire, tripwire::STR_GMMS_END); - - return summary.str(); -} + reportMail->SetFromName(TSS_GetString(cTW, tw::STR_TSS_PRODUCT_NAME)); -static void SendGmmsAlert(const TSTRING& gmmsProg, const TSTRING& gmmsOptions, const TSTRING& alerts) // throw (eGmmsError) -{ -#if IS_UNIX - - // construct the command line for starting gmms - TSTRING command = gmmsProg + _T(" ") + gmmsOptions; - - // preserve environment variables necessary for gmms to run - le_set("GEOPLEX_DEPLOY"); - le_set("LD_LIBRARY_PATH"); - le_set("PATH"); - - // open the process - FILE *mpFile = mpopen((char*)command.c_str(), _T("w")); - if(!mpFile) - throw eGmmsError(eGmmsError::ERR_COULDNT_OPEN_PIPE, gmmsProg); - - // write the alert(s) to the process's standard-in. - if (_ftprintf(mpFile, "%s", alerts.c_str()) < 0) - throw eGmmsError(eGmmsError::ERR_COULDNT_WRITE_TO_PIPE, gmmsProg); - - // end the process by closing standard-in - int result = mpclose( mpFile ); - if (result != 0) - { - // complain about gmms returning an error code. - throw eGmmsError(eGmmsError::ERR_CMD_FAILED, gmmsProg); - } - - // unset environment variables necessary for gmms to run - le_unset("GEOPLEX_DEPLOY"); - le_unset("LD_LIBRARY_PATH"); - le_unset("PATH"); - -#else - - // GMMS is not for NT, so just do something cheap and easy for debugging purposes. - std::cerr << cStringUtil::TstrToStr(alerts); + reportMail->SetSubject(TSS_GetString(cTripwire, tripwire::STR_TEST_EMAIL_SUBJECT)); + reportMail->SetBody(TSS_GetString(cTripwire, tripwire::STR_TEST_EMAIL_BODY)); + reportMail->Send(); + } + catch (eError& e) + { + cTWUtil::PrintErrorMsg(e); + TCERR << TSS_GetString(cTripwire, tripwire::STR_ERR_EMAIL_TEST) << std::endl; + return false; + } -#endif + return true; } - -#endif - diff --git a/src/tripwire/twcmdlineutil.h b/src/tripwire/twcmdlineutil.h index ce070b8..e306c7a 100644 --- a/src/tripwire/twcmdlineutil.h +++ b/src/tripwire/twcmdlineutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,67 +48,60 @@ class cTWModeCommon; class cErrorBucket; class cFCODatabaseFile; -TSS_EXCEPTION( eGmmsError, eError ); -TSS_EXCEPTION( eGmmsCouldntOpenPipe, eGmmsError ); -TSS_EXCEPTION( eGmmsCouldntWritePipe, eGmmsError ); -TSS_EXCEPTION( eGmmsCmdFailed, eGmmsError ); - class cTWCmdLineUtil { public: - - static void ParsePolicyFile(cGenreSpecListVector& genreSpecList, const TSTRING& fileName, TSTRING& strSiteKeyFile, cErrorQueue* pQueue); // throw (eError) - // this parses the given (encrypted) policy file and puts the results into the passed in specList. If an error occurs, - // pQueue will be filled up and an exception will be thrown. - // Note: If the policy file is not encrypted, an warning message will be printed to standard error. - static void ParseTextPolicyFile(cGenreSpecListVector& genreSpecList, const TSTRING& fileName, TSTRING& strSiteKeyFile, cErrorQueue* pQueue); // throw (eError) - // same as ParsePolicyFile above, but it expects a plain text policy file as input. Used during policy update - // mode + static void ParsePolicyFile(cGenreSpecListVector& genreSpecList, + const TSTRING& fileName, + TSTRING& strSiteKeyFile, + cErrorQueue* pQueue); // throw (eError) + // this parses the given (encrypted) policy file and puts the results into the passed in specList. If an error occurs, + // pQueue will be filled up and an exception will be thrown. + // Note: If the policy file is not encrypted, an warning message will be printed to standard error. + static void ParseTextPolicyFile(cGenreSpecListVector& genreSpecList, + const TSTRING& fileName, + TSTRING& strSiteKeyFile, + cErrorQueue* pQueue); // throw (eError) + // same as ParsePolicyFile above, but it expects a plain text policy file as input. Used during policy update + // mode static void TrimPropsFromSpecs(cFCOSpecList& specList, const TSTRING& propsToIgnore); // throw (eError) // converts propsToIgnore into a property vector and removes all the properties in the // vector from all specs in specList; throws eError() the string is in an invalid format. - static void TrimSpecsByName(cFCOSpecList& specList, const TSTRING specName); // throw (eError) + static void TrimSpecsByName(cFCOSpecList& specList, const TSTRING specName); // throw (eError) // removes all specs from the list whose name doesn't match specName. If every name is // removed from the spec list, an error msg is printed and eError is thrown - static void TrimSpecsBySeverity(cFCOSpecList& specList, int severity); // throw (eError) - // removes all specs from the list whose severity is less than the passed in value. + static void TrimSpecsBySeverity(cFCOSpecList& specList, int severity); // throw (eError) + // removes all specs from the list whose severity is less than the passed in value. // If every name is removed from the spec list, an error msg is printed and eError is thrown static void TrimSpecsBySeverityName(cFCOSpecList& specList, const TSTRING& severity); // throe (eError) - // converts the severity name to a number and calls TrimSpecsBySeverity(). Prints an error + // converts the severity name to a number and calls TrimSpecsBySeverity(). Prints an error // message and throws eError() if it falis (can't convert name to int) static bool ReportContainsFCO(const cFCOReport& report); - // returns true if the report contains at least one FCO in it. + // returns true if the report contains at least one FCO in it. static int GetICReturnValue(const cFCOReport& report); - // determines the appropriate return value for an integrity check; the following - // values are ORed together to produce the final return value: - // 1 = files were added - // 2 = files were removed - // 4 = files were changed + // determines the appropriate return value for an integrity check; the following + // values are ORed together to produce the final return value: + // 1 = files were added + // 2 = files were removed + // 4 = files were changed - static bool EmailReport(const cFCOReportHeader& header, const cFCOReport& report, const cTWModeCommon *modeCommon); - // email all interested parties the contents of this report, by opening a pipe to - // the given email program (sendmail or some other MTA) and writing the report in - // its text form. This only works in unix. - // if an error occurs, then a message is displayed and false is returned + static bool EmailReport(const cFCOReportHeader& header, const cFCOReport& report, const cTWModeCommon* modeCommon); + // email all interested parties the contents of this report, by opening a pipe to + // the given email program (sendmail or some other MTA) and writing the report in + // its text form. This only works in unix. + // if an error occurs, then a message is displayed and false is returned - static bool SendEmailTestMessage(const TSTRING &mAddress, const cTWModeCommon *modeCommon); - // email a test message to the specified address + static bool SendEmailTestMessage(const TSTRING& mAddress, const cTWModeCommon* modeCommon); + // email a test message to the specified address - static void VerifyPolicy( cGenreSpecListVector& genreSpecList, cFCODatabaseFile& dbFile );//throw (eError) - // makes sure that the given policy is appropriate for the given database. It is appropriate if it is + static void VerifyPolicy(cGenreSpecListVector& genreSpecList, cFCODatabaseFile& dbFile); //throw (eError) + // makes sure that the given policy is appropriate for the given database. It is appropriate if it is // _exactly_ the same, including equal numbers and types of genres. - static void VerifySpecs( const cFCOSpecList& parsedList, const cFCOSpecList& dbList );//throw (eError) + static void VerifySpecs(const cFCOSpecList& parsedList, const cFCOSpecList& dbList); //throw (eError) // determines whether the policy in the policy file (parsedList) is equal to the database's current // policy (dbList). If it is not, an exception is thrown - -#ifdef GMMS - static bool GmmsReport(const cFCOReportHeader& header, const cFCOReport& report, - const TSTRING &gmmsProg, const TSTRING &gmmsOptions, int verbosity); // throw (eGmmsError) - // Use gmms to send violation notification -#endif }; #endif - diff --git a/src/tripwire/updatedb.cpp b/src/tripwire/updatedb.cpp index c957606..e6af76e 100644 --- a/src/tripwire/updatedb.cpp +++ b/src/tripwire/updatedb.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,71 +52,69 @@ // class cUpdateDb //============================================================================= -cUpdateDb::cUpdateDb( cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket ) -: mDb ( db ), - mReport ( report ), - mpBucket( pBucket ) +cUpdateDb::cUpdateDb(cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket) + : mDb(db), mReport(report), mpBucket(pBucket) { } /////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// -bool cUpdateDb::Execute( uint32 flags ) +bool cUpdateDb::Execute(uint32 flags) { cDebug d("cUpdateDb::Execute"); - bool bResult = true; + bool bResult = true; // I will assume that the current genre is correct... // - cFCOReportSpecIter specIter( mReport, cGenreSwitcher::GetInstance()->CurrentGenre() ); - cDbDataSourceIter dbIter ( &mDb ); + cFCOReportSpecIter specIter(mReport, cGenreSwitcher::GetInstance()->CurrentGenre()); + cDbDataSourceIter dbIter(&mDb); dbIter.SetErrorBucket(mpBucket); iFCONameTranslator* pTrans = iTWFactory::GetInstance()->GetNameTranslator(); - + // // set flags // - if( flags & FLAG_ERASE_FOOTPRINTS_UD ) + if (flags & FLAG_ERASE_FOOTPRINTS_UD) { - dbIter.SetIterFlags( iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS ); + dbIter.SetIterFlags(iFCODataSourceIter::DO_NOT_MODIFY_OBJECTS); } // // iterate through all the specs... // - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next()) + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next()) { // skip this spec if there is nothing to update... // - if( (specIter.GetAddedSet()->IsEmpty()) && - (specIter.GetRemovedSet()->IsEmpty()) && - (specIter.GetNumChanged() == 0) ) + if ((specIter.GetAddedSet()->IsEmpty()) && (specIter.GetRemovedSet()->IsEmpty()) && + (specIter.GetNumChanged() == 0)) { continue; } // // Add all of the "Added" files... // - cIterProxy fcoIter (specIter.GetAddedSet()->GetIter()); - for(fcoIter->SeekBegin(); ! fcoIter->Done(); fcoIter->Next()) + cIterProxy fcoIter(specIter.GetAddedSet()->GetIter()); + for (fcoIter->SeekBegin(); !fcoIter->Done(); fcoIter->Next()) { - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_DB_ADDING ).c_str(), - pTrans->ToStringDisplay( fcoIter->FCO()->GetName() ).c_str() ); + TW_NOTIFY_VERBOSE(_T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_DB_ADDING).c_str(), + pTrans->ToStringDisplay(fcoIter->FCO()->GetName()).c_str()); // // seek to the new FCO, creating the path if necessary.. // - dbIter.CreatePath( fcoIter->FCO()->GetName() ); + dbIter.CreatePath(fcoIter->FCO()->GetName()); // // report an error if this already exists in the db // - if( dbIter.HasFCOData() ) + if (dbIter.HasFCOData()) { - d.TraceError(_T("Report says to add fco %s that already exists in the db!\n"), fcoIter->FCO()->GetName().AsString().c_str()); - if( mpBucket ) - mpBucket->AddError( eUpdateDbAddedFCO( pTrans->ToStringDisplay( fcoIter->FCO()->GetName() ), - eError::SUPRESS_THIRD_MSG) ); + d.TraceError(_T("Report says to add fco %s that already exists in the db!\n"), + fcoIter->FCO()->GetName().AsString().c_str()); + if (mpBucket) + mpBucket->AddError(eUpdateDbAddedFCO(pTrans->ToStringDisplay(fcoIter->FCO()->GetName()), + eError::SUPRESS_THIRD_MSG)); bResult = false; } else @@ -124,52 +122,53 @@ bool cUpdateDb::Execute( uint32 flags ) // add the fco to the database... // d.TraceDebug(_T(">>> Adding FCO %s\n"), fcoIter->FCO()->GetName().AsString().c_str()); - dbIter.SetFCOData( fcoIter->FCO() ); + dbIter.SetFCOData(fcoIter->FCO()); } } // // remove all of the "Removed" files // cIterProxy rmIter(specIter.GetRemovedSet()->GetIter()); - for(rmIter->SeekBegin(); ! rmIter->Done(); rmIter->Next()) + for (rmIter->SeekBegin(); !rmIter->Done(); rmIter->Next()) { - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_DB_REMOVING ).c_str(), - pTrans->ToStringDisplay( rmIter->FCO()->GetName() ).c_str() ); + TW_NOTIFY_VERBOSE(_T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_DB_REMOVING).c_str(), + pTrans->ToStringDisplay(rmIter->FCO()->GetName()).c_str()); - - if(! cTripwireUtil::RemoveFCOFromDb( rmIter->FCO()->GetName(), dbIter ) ) + + if (!cTripwireUtil::RemoveFCOFromDb(rmIter->FCO()->GetName(), dbIter)) { - d.TraceError(_T("Report says to remove fco %s that doesn't exist in the db!\n"), rmIter->FCO()->GetName().AsString().c_str()); - if( mpBucket ) - mpBucket->AddError( eUpdateDbRemovedFCO( pTrans->ToStringDisplay( rmIter->FCO()->GetName() ), - eError::SUPRESS_THIRD_MSG) ); + d.TraceError(_T("Report says to remove fco %s that doesn't exist in the db!\n"), + rmIter->FCO()->GetName().AsString().c_str()); + if (mpBucket) + mpBucket->AddError(eUpdateDbRemovedFCO(pTrans->ToStringDisplay(rmIter->FCO()->GetName()), + eError::SUPRESS_THIRD_MSG)); bResult = false; } - } + } // // change all the "Changed" fcos.... // - cFCOCompare compareObj; - cFCOReportChangeIter changeIter(specIter); - for(changeIter.SeekBegin(); ! changeIter.Done(); changeIter.Next()) + cFCOCompare compareObj; + cFCOReportChangeIter changeIter(specIter); + for (changeIter.SeekBegin(); !changeIter.Done(); changeIter.Next()) { - TW_NOTIFY_VERBOSE( _T("%s%s\n"), - TSS_GetString( cTripwire, tripwire::STR_NOTIFY_DB_CHANGING ).c_str(), - pTrans->ToStringDisplay( changeIter.GetOld()->GetName() ).c_str() ); - + TW_NOTIFY_VERBOSE(_T("%s%s\n"), + TSS_GetString(cTripwire, tripwire::STR_NOTIFY_DB_CHANGING).c_str(), + pTrans->ToStringDisplay(changeIter.GetOld()->GetName()).c_str()); + d.TraceDebug(">>> Changing FCO %s\n", changeIter.GetOld()->GetName().AsString().c_str()); // // error if the fco isn't in the database // - dbIter.SeekToFCO( changeIter.GetOld()->GetName() ); - if( dbIter.Done() || ( ! dbIter.HasFCOData() ) ) + dbIter.SeekToFCO(changeIter.GetOld()->GetName()); + if (dbIter.Done() || (!dbIter.HasFCOData())) { - d.TraceError("Report says to change fco %s but it doesn't exist in the db!\n", - changeIter.GetOld()->GetName().AsString().c_str()); - if( mpBucket ) - mpBucket->AddError( eUpdateDbRemovedFCO( pTrans->ToStringDisplay( changeIter.GetOld()->GetName() ), - eError::SUPRESS_THIRD_MSG) ); + d.TraceError("Report says to change fco %s but it doesn't exist in the db!\n", + changeIter.GetOld()->GetName().AsString().c_str()); + if (mpBucket) + mpBucket->AddError(eUpdateDbRemovedFCO(pTrans->ToStringDisplay(changeIter.GetOld()->GetName()), + eError::SUPRESS_THIRD_MSG)); bResult = false; continue; } @@ -177,15 +176,15 @@ bool cUpdateDb::Execute( uint32 flags ) // iFCO* pDbFCO = dbIter.CreateFCO(); compareObj.SetPropsToCmp(changeIter.GetOld()->GetPropSet()->GetValidVector()); - if( (compareObj.Compare(changeIter.GetOld(), pDbFCO) & cFCOCompare::EQUAL) == 0 ) + if ((compareObj.Compare(changeIter.GetOld(), pDbFCO) & cFCOCompare::EQUAL) == 0) { - d.TraceError("FCO %s in report doesn't match current db values for properties!\n", - changeIter.GetOld()->GetName().AsString().c_str()); - changeIter.GetOld()->TraceContents (cDebug::D_ERROR); - pDbFCO->TraceContents (cDebug::D_ERROR); - if( mpBucket ) - mpBucket->AddError( eUpdateDbChangedFCO( pTrans->ToStringDisplay( pDbFCO->GetName() ), - eError::SUPRESS_THIRD_MSG) ); + d.TraceError("FCO %s in report doesn't match current db values for properties!\n", + changeIter.GetOld()->GetName().AsString().c_str()); + changeIter.GetOld()->TraceContents(cDebug::D_ERROR); + pDbFCO->TraceContents(cDebug::D_ERROR); + if (mpBucket) + mpBucket->AddError( + eUpdateDbChangedFCO(pTrans->ToStringDisplay(pDbFCO->GetName()), eError::SUPRESS_THIRD_MSG)); pDbFCO->Release(); bResult = false; continue; @@ -197,31 +196,30 @@ bool cUpdateDb::Execute( uint32 flags ) //dbFcoIter->FCO()->GetPropSet()->CopyProps(changeIter.GetNew()->GetPropSet(), changeIter.GetNew()->GetPropSet()->GetValidVector()); // dbIter.RemoveFCOData(); - if( flags & FLAG_REPLACE_PROPS ) + if (flags & FLAG_REPLACE_PROPS) { // replace the old fco's data with the new data // - dbIter.SetFCOData( changeIter.GetNew() ); + dbIter.SetFCOData(changeIter.GetNew()); } else { iFCO* pNewFCO = changeIter.GetNew()->Clone(); - // + // // we need to fold in all properties that are in the old FCO but not valid in the new one // (in case an integrity check ignored certain properties, we need to keep the old values in the // database) -- 5 feb 99 mdb // - cFCOPropVector propsToCopy = pDbFCO->GetPropSet()->GetValidVector() ^ - pNewFCO->GetPropSet()->GetValidVector(); + cFCOPropVector propsToCopy = + pDbFCO->GetPropSet()->GetValidVector() ^ pNewFCO->GetPropSet()->GetValidVector(); propsToCopy &= pDbFCO->GetPropSet()->GetValidVector(); - pNewFCO->GetPropSet()->CopyProps( pDbFCO->GetPropSet(), propsToCopy ); + pNewFCO->GetPropSet()->CopyProps(pDbFCO->GetPropSet(), propsToCopy); - dbIter.SetFCOData( pNewFCO ); + dbIter.SetFCOData(pNewFCO); - pNewFCO->Release(); + pNewFCO->Release(); } pDbFCO->Release(); - } } diff --git a/src/tripwire/updatedb.h b/src/tripwire/updatedb.h index a73eaec..ccd0925 100644 --- a/src/tripwire/updatedb.h +++ b/src/tripwire/updatedb.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,43 +46,44 @@ class cErrorBucket; //////////////////////////////////////////////////////////// // Update Db Exceptions //////////////////////////////////////////////////////////// -TSS_EXCEPTION( eUpdateDb, eError ); -TSS_EXCEPTION( eUpdateDbAddedFCO, eUpdateDb ); -TSS_EXCEPTION( eUpdateDbRemovedFCO, eUpdateDb ); -TSS_EXCEPTION( eUpdateDbChangedFCO, eUpdateDb ); +TSS_EXCEPTION(eUpdateDb, eError); +TSS_EXCEPTION(eUpdateDbAddedFCO, eUpdateDb); +TSS_EXCEPTION(eUpdateDbRemovedFCO, eUpdateDb); +TSS_EXCEPTION(eUpdateDbChangedFCO, eUpdateDb); class cUpdateDb { public: - cUpdateDb( cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket ); + cUpdateDb(cHierDatabase& db, cFCOReport& report, cErrorBucket* pBucket); - bool Execute( uint32 flags = 0 ); - // returns false if there were any conflicts in updating - // the database - // TODO -- what kind of exceptions can come up from here? + bool Execute(uint32 flags = 0); + // returns false if there were any conflicts in updating + // the database + // TODO -- what kind of exceptions can come up from here? enum Flags { - FLAG_REPLACE_PROPS = 0x00000001, - // if this flag is passed to execute, then them - // database's FCO's property set is completely - // replaced with the reports property set. - // (That means that invalid properties in the - // report will be invalidated in the database. - // This behavior is only desireable right now for - // policy update, when we want to get rid of stale - // information) - FLAG_ERASE_FOOTPRINTS_UD = 0x00000002 - // when this flag is set, UpdateDb will attempt - // undo any inadvertant modifications it may make - // when executing. + FLAG_REPLACE_PROPS = 0x00000001, + // if this flag is passed to execute, then them + // database's FCO's property set is completely + // replaced with the reports property set. + // (That means that invalid properties in the + // report will be invalidated in the database. + // This behavior is only desireable right now for + // policy update, when we want to get rid of stale + // information) + FLAG_ERASE_FOOTPRINTS_UD = 0x00000002 + // when this flag is set, UpdateDb will attempt + // undo any inadvertant modifications it may make + // when executing. + + }; private: - cHierDatabase& mDb; - cFCOReport& mReport; - cErrorBucket* mpBucket; + cHierDatabase& mDb; + cFCOReport& mReport; + cErrorBucket* mpBucket; }; #endif - diff --git a/src/tw/Makefile.am b/src/tw/Makefile.am index 30eb44b..1bea795 100644 --- a/src/tw/Makefile.am +++ b/src/tw/Makefile.am @@ -1,8 +1,9 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtw.a +libtw_adir=. libtw_a_SOURCES = \ configfile.cpp dbdatasource.cpp dbdebug.cpp dbexplore.cpp \ fcodatabasefile.cpp fcodatabaseutil.cpp fcoreport.cpp \ @@ -11,7 +12,15 @@ libtw_a_SOURCES = \ textreportviewer.cpp tw.cpp twerrors.cpp twinit.cpp \ twstrings.cpp twutil.cpp +libtw_a_HEADERS = \ + configfile.h dbdatasource.h dbdebug.h dbexplore.h \ + fcodatabasefile.h fcodatabaseutil.h fcoreport.h \ + fcoreportutil.h filemanipulator.h headerinfo.h policyfile.h \ + stdtw.h systeminfo.h textdbviewer.h textreportviewer.h \ + tw.h twerrors.h twinit.h twstrings.h twutil.h + DEFS = @DEFS@ -DCONFIG_DIR=\"$(sysconfdir)\" +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtw_a_OBJECTS) diff --git a/src/tw/Makefile.in b/src/tw/Makefile.in index 2fc8f3e..8749f14 100644 --- a/src/tw/Makefile.in +++ b/src/tw/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libtw_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/tw -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libtw_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libtw_a_AR = $(AR) $(ARFLAGS) libtw_a_LIBADD = am_libtw_a_OBJECTS = configfile.$(OBJEXT) dbdatasource.$(OBJEXT) \ @@ -62,23 +120,95 @@ am_libtw_a_OBJECTS = configfile.$(OBJEXT) dbdatasource.$(OBJEXT) \ twerrors.$(OBJEXT) twinit.$(OBJEXT) twstrings.$(OBJEXT) \ twutil.$(OBJEXT) libtw_a_OBJECTS = $(am_libtw_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libtw_a_SOURCES) DIST_SOURCES = $(libtw_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libtw_adir)" +HEADERS = $(libtw_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -102,6 +232,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -113,6 +244,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -129,21 +261,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -173,15 +308,20 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtw.a +libtw_adir = . libtw_a_SOURCES = \ configfile.cpp dbdatasource.cpp dbdebug.cpp dbexplore.cpp \ fcodatabasefile.cpp fcodatabaseutil.cpp fcoreport.cpp \ @@ -190,6 +330,14 @@ libtw_a_SOURCES = \ textreportviewer.cpp tw.cpp twerrors.cpp twinit.cpp \ twstrings.cpp twutil.cpp +libtw_a_HEADERS = \ + configfile.h dbdatasource.h dbdebug.h dbexplore.h \ + fcodatabasefile.h fcodatabaseutil.h fcoreport.h \ + fcoreportutil.h filemanipulator.h headerinfo.h policyfile.h \ + stdtw.h systeminfo.h textdbviewer.h textreportviewer.h \ + tw.h twerrors.h twinit.h twstrings.h twutil.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -198,15 +346,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/tw/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/tw/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/tw/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/tw/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -223,13 +370,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libtw.a: $(libtw_a_OBJECTS) $(libtw_a_DEPENDENCIES) - -rm -f libtw.a - $(libtw_a_AR) libtw.a $(libtw_a_OBJECTS) $(libtw_a_LIBADD) - $(RANLIB) libtw.a + +libtw.a: $(libtw_a_OBJECTS) $(libtw_a_DEPENDENCIES) $(EXTRA_libtw_a_DEPENDENCIES) + $(AM_V_at)-rm -f libtw.a + $(AM_V_AR)$(libtw_a_AR) libtw.a $(libtw_a_OBJECTS) $(libtw_a_LIBADD) + $(AM_V_at)$(RANLIB) libtw.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -238,91 +387,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libtw_aHEADERS: $(libtw_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libtw_a_HEADERS)'; test -n "$(libtw_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libtw_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libtw_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libtw_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libtw_adir)" || exit $$?; \ + done + +uninstall-libtw_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libtw_a_HEADERS)'; test -n "$(libtw_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libtw_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libtw_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -333,16 +512,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -362,18 +548,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libtw_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -392,22 +598,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libtw_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libtw_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libtw_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtw_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/tw/configfile.cpp b/src/tw/configfile.cpp index 7302564..a144400 100644 --- a/src/tw/configfile.cpp +++ b/src/tw/configfile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -72,126 +72,90 @@ // UTIL FUNCTION PROTOTYPES //========================================================================= -static bool PopNextLine( TSTRING& fileIn, TSTRING& sLine, int& nLine ); -static bool IsReturnChar( TCHAR tch ); -static bool IsComment( const TSTRING& sLine ); +static bool PopNextLine(TSTRING& fileIn, TSTRING& sLine, int& nLine); +static bool IsReturnChar(TCHAR tch); +static bool IsComment(const TSTRING& sLine); //static void GetKeyValuePair( const TSTRING& sLine, TSTRING& sKey, TSTRING& sVal ); // throw( eConfigFile ); -static TSTRING& util_MakeTripwireDateString( TSTRING& strBuf ); +static TSTRING& util_MakeTripwireDateString(TSTRING& strBuf); //========================================================================= // UTIL FUNCTIONS //========================================================================= -static bool IsReturnChar( TCHAR tch ) +static bool IsReturnChar(TCHAR tch) { - return( tch == _T('\n') || tch == _T('\r') ); + return (tch == _T('\n') || tch == _T('\r')); } -static bool IsWhiteSpace( TCHAR tch ) +static bool IsWhiteSpace(TCHAR tch) { - return( ( tch >= 0x09 && tch <= 0x0D ) || tch == 0x20 ); + return ((tch >= 0x09 && tch <= 0x0D) || tch == 0x20); } -static bool IsPoundSymbol( TCHAR tch ) +static bool IsPoundSymbol(TCHAR tch) { - return( tch == _T('#') ); + return (tch == _T('#')); } -static bool IsRightParen( TCHAR tch ) +static bool IsRightParen(TCHAR tch) { - return( tch == _T(')') ); + return (tch == _T(')')); } -static bool IsLeftParen( TCHAR tch ) +static bool IsLeftParen(TCHAR tch) { - return( tch == _T('(') ); + return (tch == _T('(')); } -static bool IsDollarSign( TCHAR tch ) +static bool IsDollarSign(TCHAR tch) { - return( tch == _T('$') ); + return (tch == _T('$')); } -static bool IsEqualsSign( TCHAR tch ) +static bool IsEqualsSign(TCHAR tch) { - return( tch == _T('=') ); + return (tch == _T('=')); } -static bool IsSingleTchar( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsSingleTchar(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( first + 1 == last ); + return (first + 1 == last); } -static bool IsReturnChar( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsReturnChar(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsReturnChar( *first ) - ); + return (IsSingleTchar(first, last) && IsReturnChar(*first)); } -static bool IsWhiteSpace( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsWhiteSpace(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsWhiteSpace( *first ) - ); + return (IsSingleTchar(first, last) && IsWhiteSpace(*first)); } -static bool IsPoundSymbol( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsPoundSymbol(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsPoundSymbol( *first ) - ); + return (IsSingleTchar(first, last) && IsPoundSymbol(*first)); } -static bool IsRightParen( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsRightParen(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsRightParen( *first ) - ); + return (IsSingleTchar(first, last) && IsRightParen(*first)); } -static bool IsLeftParen( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsLeftParen(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsLeftParen( *first ) - ); + return (IsSingleTchar(first, last) && IsLeftParen(*first)); } -static bool IsDollarSign( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsDollarSign(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsDollarSign( *first ) - ); + return (IsSingleTchar(first, last) && IsDollarSign(*first)); } -static bool IsEqualsSign( TSTRING::const_iterator first, - TSTRING::const_iterator last ) +static bool IsEqualsSign(TSTRING::const_iterator first, TSTRING::const_iterator last) { - return( - IsSingleTchar( first, last ) - && - IsEqualsSign( *first ) - ); + return (IsSingleTchar(first, last) && IsEqualsSign(*first)); } @@ -202,8 +166,7 @@ static bool IsEqualsSign( TSTRING::const_iterator first, /////////////////////////////////////////////////////////////////////////////// // ctor, dtor /////////////////////////////////////////////////////////////////////////////// -cConfigFile::cConfigFile() : - mStringHashTable(HASH_VERY_SMALL), mnLine(1) +cConfigFile::cConfigFile() : mStringHashTable(HASH_VERY_SMALL), mnLine(1) { // we make the hash table very small (17 slots) because we don't expect very many things // in the config file -- mdb @@ -211,19 +174,18 @@ cConfigFile::cConfigFile() : cConfigFile::~cConfigFile() { - } -void cConfigFile::WriteString( TSTRING& configText ) // throw( eFSServices ) +void cConfigFile::WriteString(TSTRING& configText) // throw( eFSServices ) { TOSTRINGSTREAM out; - TSTRING sKey, sVal; - cHashTableIter< TSTRING, TSTRING > hashTableIter( mStringHashTable ); + TSTRING sKey, sVal; + cHashTableIter hashTableIter(mStringHashTable); // for all name-value pairs, print them out as "name=value\n" - for( hashTableIter.SeekBegin(); ! hashTableIter.Done(); hashTableIter.Next() ) + for (hashTableIter.SeekBegin(); !hashTableIter.Done(); hashTableIter.Next()) { sKey = hashTableIter.Key(); sVal = hashTableIter.Val(); @@ -238,40 +200,38 @@ void cConfigFile::WriteString( TSTRING& configText ) // throw( eFSServices ) void cConfigFile::ReadString(const TSTRING configText) // throw( eConfigFile ); { -#ifdef _DEBUG +#ifdef DEBUG // NOTE:BAM -- debug only code ! TCERR << _T("*** begin config text ***") << std::endl; - TCERR << configText << std::endl; + TCERR << configText << std::endl; TCERR << _T("*** end config text ***") << std::endl; TCERR << std::endl; // NOTE:BAM -- debug only code ! -#endif +#endif TSTRING sLine; TSTRING sConfigBuf; - for( sConfigBuf = configText; - PopNextLine( sConfigBuf, sLine, mnLine ); - sLine.erase() ) + for (sConfigBuf = configText; PopNextLine(sConfigBuf, sLine, mnLine); sLine.erase()) { // ignore comments - if( ! IsComment( sLine ) ) + if (!IsComment(sLine)) { TSTRING sKey, sVal; - GetKeyValuePair( sLine, sKey, sVal ); - DoVarSubst( sVal ); - mStringHashTable.Insert( sKey, sVal ); + GetKeyValuePair(sLine, sKey, sVal); + DoVarSubst(sVal); + mStringHashTable.Insert(sKey, sVal); } } CheckThatAllMandatoryKeyWordsExists(); -#ifdef _DEBUG +#ifdef DEBUG // NOTE:BAM -- debug only code ! TSTRING sTemp; - WriteString( sTemp ); + WriteString(sTemp); TCERR << _T("*** begin config read as ***") << std::endl; - TCERR << sTemp << std::endl; + TCERR << sTemp << std::endl; TCERR << _T("*** end config read as ***") << std::endl; TCERR << std::endl; // NOTE:BAM -- debug only code ! @@ -280,28 +240,40 @@ void cConfigFile::ReadString(const TSTRING configText) // throw( eConfigFile ); return; } -bool cConfigFile::Lookup( const TSTRING& sKey, TSTRING& sVal ) const +bool cConfigFile::Lookup(const TSTRING& sKey, TSTRING& sVal) const { bool fFound = false; - if( mStringHashTable.Lookup( sKey, sVal ) ) + if (mStringHashTable.Lookup(sKey, sVal)) { // key was found fFound = true; } - return( fFound ); + return (fFound); +} + +void cConfigFile::Insert(const TSTRING& sKey, const TSTRING& sVal) +{ + mStringHashTable.Insert(sKey, sVal); } /////////////////////////////////////////////////////////////////////////////// // GetFileHeaderID() /////////////////////////////////////////////////////////////////////////////// -struct cConfigFileFHID { +struct cConfigFileFHID +{ cFileHeaderID* configID; - cConfigFileFHID() { configID = 0; } - ~cConfigFileFHID() { delete configID; } + cConfigFileFHID() + { + configID = 0; + } + ~cConfigFileFHID() + { + delete configID; + } } gConfigFileFHID; const cFileHeaderID& cConfigFile::GetFileHeaderID() @@ -319,32 +291,32 @@ const cFileHeaderID& cConfigFile::GetFileHeaderID() // UTIL FUNCTION CODE //========================================================================= -static bool PopNextLine( TSTRING& sIn, TSTRING& sLine, int& nLine ) +static bool PopNextLine(TSTRING& sIn, TSTRING& sLine, int& nLine) { bool fGotNextLine = false; - TSTRING::const_iterator cur = sIn.begin(); // pointer to working position in sIn - const TSTRING::const_iterator end = sIn.end(); // end of sIn - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character + TSTRING::const_iterator cur = sIn.begin(); // pointer to working position in sIn + const TSTRING::const_iterator end = sIn.end(); // end of sIn + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character // eat up all return chars // while peek next char (does not update cur) - while( cCharUtil::PeekNextChar( cur, end, first, last ) ) + while (cCharUtil::PeekNextChar(cur, end, first, last)) { // is it a return char? (all return chars are single char) - if( IsSingleTchar( first, last ) ) + if (IsSingleTchar(first, last)) { - if( _T('\n') == *first ) + if (_T('\n') == *first) { // eat up return and increment line number nLine++; - cCharUtil::PopNextChar( cur, end, first, last ); + cCharUtil::PopNextChar(cur, end, first, last); } - else if( _T('\r') == *first ) + else if (_T('\r') == *first) { // eat up return but don't count it as another line - cCharUtil::PopNextChar( cur, end, first, last ); + cCharUtil::PopNextChar(cur, end, first, last); } else { @@ -360,12 +332,12 @@ static bool PopNextLine( TSTRING& sIn, TSTRING& sLine, int& nLine ) } // get line - while( cCharUtil::PopNextChar( cur, end, first, last ) ) - { - if( ! IsReturnChar( first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) + { + if (!IsReturnChar(first, last)) { fGotNextLine = true; // we'll say we've got the next line if we get at least one char - sLine.append( first, last ); + sLine.append(first, last); } else { @@ -377,29 +349,29 @@ static bool PopNextLine( TSTRING& sIn, TSTRING& sLine, int& nLine ) // Pop line of of input string TSTRING sTmp; - sTmp.assign( first, end ); + sTmp.assign(first, end); sIn = sTmp; - return( fGotNextLine ); + return (fGotNextLine); } -static bool IsComment( const TSTRING& sLine ) +static bool IsComment(const TSTRING& sLine) { - TSTRING::const_iterator cur = sLine.begin(); // pointer to working position in sLine - const TSTRING::const_iterator end = sLine.end(); // end of sLine - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character + TSTRING::const_iterator cur = sLine.begin(); // pointer to working position in sLine + const TSTRING::const_iterator end = sLine.end(); // end of sLine + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character // while pop next char (updates cur) - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { - if( ! IsWhiteSpace( first, last ) ) + if (!IsWhiteSpace(first, last)) break; } // it is a comment if it is an empty line or it starts with a # - return( first == end || IsPoundSymbol( first, last ) ); + return (first == end || IsPoundSymbol(first, last)); } /////////////////////////////////////////////////////////////////////////////// @@ -407,26 +379,26 @@ static bool IsComment( const TSTRING& sLine ) /////////////////////////////////////////////////////////////////////////////// static void TrimSpace(TSTRING& s) { - TSTRING::const_iterator cur = s.begin(); // pointer to working position in s - const TSTRING::const_iterator end = s.end(); // end of s - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character - TSTRING::const_iterator firstNW = end; // identifies beginning of first non-whitespace character - TSTRING::const_iterator firstTW = end; // identifies beginning of first trailing whitespace character + TSTRING::const_iterator cur = s.begin(); // pointer to working position in s + const TSTRING::const_iterator end = s.end(); // end of s + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character + TSTRING::const_iterator firstNW = end; // identifies beginning of first non-whitespace character + TSTRING::const_iterator firstTW = end; // identifies beginning of first trailing whitespace character // find first non-whitespace char - while( cCharUtil::PeekNextChar( cur, end, first, last ) ) + while (cCharUtil::PeekNextChar(cur, end, first, last)) { - if( IsWhiteSpace( first, last ) ) + if (IsWhiteSpace(first, last)) { - cCharUtil::PopNextChar( cur, end, first, last ); + cCharUtil::PopNextChar(cur, end, first, last); } else { break; } } - if( first == end ) // no non-whitespace char, so lose it all + if (first == end) // no non-whitespace char, so lose it all { s.erase(); return; @@ -437,11 +409,11 @@ static void TrimSpace(TSTRING& s) // find first of trailing whitespace bool fInWhitespace = false; - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { - if( IsWhiteSpace( first, last ) ) + if (IsWhiteSpace(first, last)) { - if( ! fInWhitespace ) + if (!fInWhitespace) { firstTW = first; } @@ -452,72 +424,71 @@ static void TrimSpace(TSTRING& s) else { fInWhitespace = false; - firstTW = end; // clear old trailing WS marker + firstTW = end; // clear old trailing WS marker } } - ASSERT( first == end ); - ASSERT( firstNW < firstTW ); + ASSERT(first == end); + ASSERT(firstNW < firstTW); TSTRING sTmp; - sTmp.assign( firstNW, firstTW ); + sTmp.assign(firstNW, firstTW); s = sTmp; } -void cConfigFile::GetKeyValuePair( const TSTRING& sLine, TSTRING& sKey, TSTRING& sVal ) // throw (eConfigFile) +void cConfigFile::GetKeyValuePair(const TSTRING& sLine, TSTRING& sKey, TSTRING& sVal) // throw (eConfigFile) { // erase old values sKey.erase(); sVal.erase(); - - TSTRING::const_iterator cur = sLine.begin(); // pointer to working position in sLine - const TSTRING::const_iterator end = sLine.end(); // end of sLine - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character - while( cCharUtil::PopNextChar( cur, end, first, last ) ) + TSTRING::const_iterator cur = sLine.begin(); // pointer to working position in sLine + const TSTRING::const_iterator end = sLine.end(); // end of sLine + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character + + while (cCharUtil::PopNextChar(cur, end, first, last)) { - if( IsEqualsSign( first, last ) ) + if (IsEqualsSign(first, last)) { break; } } - if( first == end ) + if (first == end) { - throw eConfigFileNoEq( MakeErrorString() ); + throw eConfigFileNoEq(MakeErrorString()); } // get the two strings.. - sKey.assign( sLine.begin(), first ); - sVal.assign( last, sLine.end() ); - + sKey.assign(sLine.begin(), first); + sVal.assign(last, sLine.end()); + // trim the white space from the beginning and end... - TrimSpace( sKey ); - TrimSpace( sVal ); + TrimSpace(sKey); + TrimSpace(sVal); // // find more errors - // + // // 1. empty key string // 2. assignment to a predefined var // // allow empty values, but emit warning // TSTRING tstrDummy; - - if( sKey.empty() ) + + if (sKey.empty()) { - throw eConfigFileNoKey( MakeErrorString() ); + throw eConfigFileNoKey(MakeErrorString()); } - else if( IsPredefinedVar( sKey, tstrDummy ) ) + else if (IsPredefinedVar(sKey, tstrDummy)) { - throw eConfigFileAssignToPredefVar - ( MakeErrorString( sKey ) ); + throw eConfigFileAssignToPredefVar(MakeErrorString(sKey)); } - else if( sVal.empty() ) + else if (sVal.empty()) { - cTWUtil::PrintErrorMsg( eConfigFileEmptyVariable( MakeErrorString( sKey ), eError::NON_FATAL ) ); + cTWUtil::PrintErrorMsg(eConfigFileEmptyVariable(MakeErrorString(sKey), eError::NON_FATAL)); } // everything went ok. @@ -530,10 +501,10 @@ void cConfigFile::GetKeyValuePair( const TSTRING& sLine, TSTRING& sKey, TSTRING& // fails if symbol isn't found /////////////////////////////////////////////////////////////////////////////// -void cConfigFile::DoVarSubst( TSTRING& s ) const //throw( eConfigFile ) +void cConfigFile::DoVarSubst(TSTRING& s) const //throw( eConfigFile ) { cDebug d("cConfigFile::DoVarSubst()"); - d.TraceDebug( _T("ORIG: %s\n"), s.c_str() ); + d.TraceDebug(_T("ORIG: %s\n"), s.c_str()); TSTRING sOut; @@ -545,126 +516,117 @@ void cConfigFile::DoVarSubst( TSTRING& s ) const //throw( eConfigFile ) // substitute subset // continue iterating - - TSTRING::const_iterator cur = s.begin(); // pointer to working position in s - const TSTRING::const_iterator end = s.end(); // end of s - TSTRING::const_iterator first = end; // identifies beginning of current character - TSTRING::const_iterator last = end; // identifies end of current character + + TSTRING::const_iterator cur = s.begin(); // pointer to working position in s + const TSTRING::const_iterator end = s.end(); // end of s + TSTRING::const_iterator first = end; // identifies beginning of current character + TSTRING::const_iterator last = end; // identifies end of current character // look for '$(' do { - if( cCharUtil::PeekNextChar( cur, end, first, last ) && - IsDollarSign( first, last ) ) + if (cCharUtil::PeekNextChar(cur, end, first, last) && IsDollarSign(first, last)) { - cCharUtil::PopNextChar( cur, end, first, last ); + cCharUtil::PopNextChar(cur, end, first, last); - if( cCharUtil::PeekNextChar( cur, end, first, last ) && - IsLeftParen( first, last ) ) - { - TSTRING::const_iterator firstRP = end; // identifies beginning of rparen character - TSTRING::const_iterator lastRP = end; // identifies end of rparen character + if (cCharUtil::PeekNextChar(cur, end, first, last) && IsLeftParen(first, last)) + { + TSTRING::const_iterator firstRP = end; // identifies beginning of rparen character + TSTRING::const_iterator lastRP = end; // identifies end of rparen character // [first,last) now identifies left paren - while( cCharUtil::PeekNextChar( cur, end, firstRP, lastRP ) ) + while (cCharUtil::PeekNextChar(cur, end, firstRP, lastRP)) { - if( IsRightParen( firstRP, lastRP ) ) + if (IsRightParen(firstRP, lastRP)) break; else - cCharUtil::PopNextChar( cur, end, firstRP, lastRP ); + cCharUtil::PopNextChar(cur, end, firstRP, lastRP); } // [firstRP,lastRP) identifies right paren - if( ! IsRightParen( firstRP, lastRP ) ) + if (!IsRightParen(firstRP, lastRP)) { - throw eConfigFileMissingRightParen( MakeErrorString( s ) ); + throw eConfigFileMissingRightParen(MakeErrorString(s)); } // now get text between parens TSTRING sVarName; - sVarName.assign( last, firstRP ); - d.TraceDebug( _T("symbol = %s\n"), sVarName.c_str() ); - + sVarName.assign(last, firstRP); + d.TraceDebug(_T("symbol = %s\n"), sVarName.c_str()); + // look up in symbol table TSTRING sVarValue; - if( ! IsPredefinedVar( sVarName, sVarValue ) && ! mStringHashTable.Lookup( sVarName, sVarValue ) ) + if (!IsPredefinedVar(sVarName, sVarValue) && !mStringHashTable.Lookup(sVarName, sVarValue)) { - throw eConfigFileUseUndefVar( MakeErrorString( sVarName ) ); + throw eConfigFileUseUndefVar(MakeErrorString(sVarName)); } sOut += sVarValue; } else { - sOut.append( first, last ); + sOut.append(first, last); } } else { - sOut.append( first, last ); + sOut.append(first, last); } - } - while( cCharUtil::PopNextChar( cur, end, first, last ) ); + } while (cCharUtil::PopNextChar(cur, end, first, last)); - d.TraceDebug( _T("DONE: %s\n"), sOut.c_str()); + d.TraceDebug(_T("DONE: %s\n"), sOut.c_str()); s = sOut; } -bool cConfigFile::IsPredefinedVar( const TSTRING& var, TSTRING& val ) const +bool cConfigFile::IsPredefinedVar(const TSTRING& var, TSTRING& val) const { bool fRecognizeVar = false; - if( 0 == var.compare( _T("HOSTNAME") ) ) + if (0 == var.compare(_T("HOSTNAME"))) { fRecognizeVar = true; try { - iFSServices::GetInstance()->GetMachineName( val); + iFSServices::GetInstance()->GetMachineName(val); if (val.empty()) val = _T("localhost"); } - catch( eFSServices& ) + catch (eFSServices&) { val = _T("localhost"); } } - else if( 0 == var.compare( _T("DATE") ) ) - { - util_MakeTripwireDateString( val ); + else if (0 == var.compare(_T("DATE"))) + { + util_MakeTripwireDateString(val); fRecognizeVar = true; } - return( fRecognizeVar ); + return (fRecognizeVar); } void cConfigFile::CheckThatAllMandatoryKeyWordsExists() // throw( eConfigFile ) { - TSTRING astrMandatoryKeys[] = - { - // I don't think ROOT should be manditory, since we don't really use it - // for anything -- mdb - //_T("ROOT"), - _T("POLFILE"), - _T("DBFILE"), - _T("REPORTFILE"), - _T("SITEKEYFILE"), - _T("LOCALKEYFILE"), -#ifdef GMMS - _T("GMMS"), - _T("GMMSOPTIONS") -#endif - }; + TSTRING astrMandatoryKeys[] = { + // I don't think ROOT should be manditory, since we don't really use it + // for anything -- mdb + //_T("ROOT"), + _T("POLFILE"), + _T("DBFILE"), + _T("REPORTFILE"), + _T("SITEKEYFILE"), + _T("LOCALKEYFILE"), + }; TSTRING strNotFound; - bool fAllFound = true; + bool fAllFound = true; - for( int i = 0; i < (int)countof(astrMandatoryKeys); i++ ) + for (int i = 0; i < (int)countof(astrMandatoryKeys); i++) { TSTRING strDummy; - if( !mStringHashTable.Lookup( astrMandatoryKeys[i], strDummy ) || - strDummy.empty() ) + if (!mStringHashTable.Lookup(astrMandatoryKeys[i], strDummy) || strDummy.empty()) { strNotFound += astrMandatoryKeys[i]; strNotFound += _T(" "); @@ -673,42 +635,42 @@ void cConfigFile::CheckThatAllMandatoryKeyWordsExists() // throw( eConfigFile ) } } - if( ! fAllFound ) + if (!fAllFound) { - throw eConfigFileMissReqKey( MakeErrorString( strNotFound, false ) ); + throw eConfigFileMissReqKey(MakeErrorString(strNotFound, false)); } } /////////////////////////////////////////////////////////////////////////////// // MakeErrorString /////////////////////////////////////////////////////////////////////////////// -TSTRING cConfigFile::MakeErrorString( const TSTRING& strMsg, bool fShowLineNum ) const +TSTRING cConfigFile::MakeErrorString(const TSTRING& strMsg, bool fShowLineNum) const { TOSTRINGSTREAM strErr; - + strErr << strMsg; - - if( fShowLineNum ) + + if (fShowLineNum) { // separate the message from the line number - if( ! strMsg.empty() ) + if (!strMsg.empty()) strErr << _T(": "); // output the line number - strErr << TSS_GetString( cTW, tw::STR_CUR_LINE ) << mnLine; + strErr << TSS_GetString(cTW, tw::STR_CUR_LINE) << mnLine; } return strErr.str(); } -TSTRING& util_MakeTripwireDateString( TSTRING& strBuf ) +TSTRING& util_MakeTripwireDateString(TSTRING& strBuf) { - struct tm* ptmLocal = cTimeUtil::TimeToDateLocal( cSystemInfo::GetExeStartTime() ); + struct tm* ptmLocal = cTimeUtil::TimeToDateLocal(cSystemInfo::GetExeStartTime()); TOSTRINGSTREAM ostr; - ostr.imbue( std::locale::classic() ); + ostr.imbue(std::locale::classic()); // format is YYYYMMDD-HHMMSS - ostr.fill( _T('0') ); + ostr.fill(_T('0')); ostr << std::setw(4) << ptmLocal->tm_year + 1900; ostr << std::setw(2) << ptmLocal->tm_mon + 1; ostr << std::setw(2) << ptmLocal->tm_mday; diff --git a/src/tw/configfile.h b/src/tw/configfile.h index b7100a4..de04373 100644 --- a/src/tw/configfile.h +++ b/src/tw/configfile.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,15 +42,15 @@ #ifndef __TCHAR_H #include "core/tchar.h" -#endif//__TCHAR_H +#endif //__TCHAR_H #ifndef __ERROR_H #include "core/error.h" -#endif//__ERROR_H +#endif //__ERROR_H #ifndef __HASHTABLE_H #include "core/hashtable.h" -#endif//__HASHTABLE_H +#endif //__HASHTABLE_H #ifndef __FSSERVICES_H #include "core/fsservices.h" @@ -58,7 +58,7 @@ #ifndef __DEBUG_H #include "core/debug.h" -#endif//__DEBUG_H +#endif //__DEBUG_H //========================================================================= // DEFINES AND MACROS @@ -81,14 +81,14 @@ class cFileHeaderID; // DECLARATION OF CLASSES //========================================================================= -TSS_EXCEPTION( eConfigFile, eError ); -TSS_EXCEPTION( eConfigFileNoEq, eConfigFile ); -TSS_EXCEPTION( eConfigFileNoKey, eConfigFile ); -TSS_EXCEPTION( eConfigFileAssignToPredefVar, eConfigFile ); -TSS_EXCEPTION( eConfigFileUseUndefVar, eConfigFile ); -TSS_EXCEPTION( eConfigFileMissReqKey, eConfigFile ); -TSS_EXCEPTION( eConfigFileEmptyVariable, eConfigFile ); -TSS_EXCEPTION( eConfigFileMissingRightParen, eConfigFile ); +TSS_EXCEPTION(eConfigFile, eError); +TSS_EXCEPTION(eConfigFileNoEq, eConfigFile); +TSS_EXCEPTION(eConfigFileNoKey, eConfigFile); +TSS_EXCEPTION(eConfigFileAssignToPredefVar, eConfigFile); +TSS_EXCEPTION(eConfigFileUseUndefVar, eConfigFile); +TSS_EXCEPTION(eConfigFileMissReqKey, eConfigFile); +TSS_EXCEPTION(eConfigFileEmptyVariable, eConfigFile); +TSS_EXCEPTION(eConfigFileMissingRightParen, eConfigFile); /////////////////////////////////////////////////////////////////////////////// // cConfigFile @@ -105,30 +105,34 @@ class cConfigFile cConfigFile(); virtual ~cConfigFile(); - bool Lookup( const TSTRING& tstrKey, TSTRING& tstrVal ) const; - // returns true if key is found in internal container and returns its value in tstrVal. - void WriteString( TSTRING& configText ); - // writes all key/value pairs from internal container to filename as "name=value\n" - void ReadString( const TSTRING configText ); // throw( eConfigFile ); + bool Lookup(const TSTRING& tstrKey, TSTRING& tstrVal) const; + // returns true if key is found in internal container and returns its value in tstrVal. + + void Insert(const TSTRING& tstrKey, const TSTRING& tstrVal); + // add key+value to config data. visible for unit testing. + + void WriteString(TSTRING& configText); + // writes all key/value pairs from internal container to filename as "name=value\n" + void ReadString(const TSTRING configText); // throw( eConfigFile ); // reads "name=value[\r\n]+" from file and puts all pairs into internal container static const cFileHeaderID& GetFileHeaderID(); // Return a cFileHeaderID for all databases private: - void GetKeyValuePair( const TSTRING& tstrLine, TSTRING& tstrKey, TSTRING& tstrVal ); // throw (eConfigFile) - bool IsPredefinedVar( const TSTRING& var, TSTRING& val ) const; - void DoVarSubst( TSTRING& rval ) const; //throw( eConfigFile ) + void GetKeyValuePair(const TSTRING& tstrLine, TSTRING& tstrKey, TSTRING& tstrVal); // throw (eConfigFile) + bool IsPredefinedVar(const TSTRING& var, TSTRING& val) const; + void DoVarSubst(TSTRING& rval) const; //throw( eConfigFile ) void CheckThatAllMandatoryKeyWordsExists(); // throw( eConfigFile ) - - TSTRING MakeErrorString( const TSTRING& strMsg = _T(""), bool fShowLineNum = true ) const; - // conststructs an error string. Appends "Line number: X" - // if fShowLineNum is true - // This string can then be passed to the exception ctor. - cHashTable< TSTRING, TSTRING > mStringHashTable; + TSTRING MakeErrorString(const TSTRING& strMsg = _T(""), bool fShowLineNum = true) const; + // conststructs an error string. Appends "Line number: X" + // if fShowLineNum is true + // This string can then be passed to the exception ctor. + + cHashTable mStringHashTable; friend class cConfigFileIter; - int mnLine; + int mnLine; }; @@ -140,23 +144,23 @@ class cConfigFile class cConfigFileIter { public: - cConfigFileIter( cConfigFile& cf); + explicit cConfigFileIter(cConfigFile& cf); virtual ~cConfigFileIter(); - void SeekBegin() const; - bool Done() const; - void Next() const; - const TSTRING& Key() const; - TSTRING& Val(); + void SeekBegin() const; + bool Done() const; + void Next() const; + const TSTRING& Key() const; + TSTRING& Val(); + protected: - cHashTableIter mIter; + cHashTableIter mIter; }; //----------------------------------------------------------------------------- // inline implementation //----------------------------------------------------------------------------- -inline cConfigFileIter::cConfigFileIter( cConfigFile& cf) : - mIter( cf.mStringHashTable ) +inline cConfigFileIter::cConfigFileIter(cConfigFile& cf) : mIter(cf.mStringHashTable) { mIter.SeekBegin(); } @@ -165,34 +169,32 @@ inline cConfigFileIter::~cConfigFileIter() { } -inline void cConfigFileIter::SeekBegin() const +inline void cConfigFileIter::SeekBegin() const { mIter.SeekBegin(); } -inline bool cConfigFileIter::Done() const +inline bool cConfigFileIter::Done() const { return mIter.Done(); } -inline void cConfigFileIter::Next() const +inline void cConfigFileIter::Next() const { mIter.Next(); } inline const TSTRING& cConfigFileIter::Key() const { - ASSERT(! Done()); + ASSERT(!Done()); return mIter.Key(); } inline TSTRING& cConfigFileIter::Val() { - ASSERT(! Done()); + ASSERT(!Done()); return mIter.Val(); } - #endif //__CONFIGFILE_H - diff --git a/src/tw/dbdatasource.cpp b/src/tw/dbdatasource.cpp index db2f2b6..c9524a0 100644 --- a/src/tw/dbdatasource.cpp +++ b/src/tw/dbdatasource.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -49,53 +49,49 @@ /////////////////////////////////////////////////////////////////////////////// // ctor /////////////////////////////////////////////////////////////////////////////// -cDbDataSourceIter::cDbDataSourceIter(cHierDatabase* pDb, int genreNum ) -: iFCODataSourceIter (), - mDbIter (pDb), - mFlags (0), - mpErrorBucket (0) +cDbDataSourceIter::cDbDataSourceIter(cHierDatabase* pDb, int genreNum) + : iFCODataSourceIter(), mDbIter(pDb), mFlags(0), mpErrorBucket(0) { // // remember the fco creation function... - // TODO -- Note that this couples this file with cGenreSwitcher; perhaps this should take the fco creation + // TODO -- Note that this couples this file with cGenreSwitcher; perhaps this should take the fco creation // function instead... // - if( genreNum == -1 ) - genreNum = cGenreSwitcher::GetInstance()->CurrentGenre(); - mFCOCreateFunc = cGenreSwitcher::GetInstance()->GetFactoryForGenre( (cGenre::Genre)genreNum )->GetCreateFunc(); + if (genreNum == -1) + genreNum = cGenreSwitcher::GetInstance()->CurrentGenre(); + mFCOCreateFunc = cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genreNum)->GetCreateFunc(); -#ifdef _DEBUG +#ifdef DEBUG // // make some assertions about the current genre's name info // - iFCONameInfo* pNameInfo = cGenreSwitcher::GetInstance()->GetFactoryForGenre( (cGenre::Genre)genreNum )->GetNameInfo(); - ASSERT( pDb->IsCaseSensitive() == pNameInfo->IsCaseSensitive() ); - ASSERT( pDb->GetDelimitingChar() == pNameInfo->GetDelimitingChar() ); -#endif //#ifdef _DEBUG + iFCONameInfo* pNameInfo = cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genreNum)->GetNameInfo(); + ASSERT(pDb->IsCaseSensitive() == pNameInfo->IsCaseSensitive()); + ASSERT(pDb->GetDelimitingChar() == pNameInfo->GetDelimitingChar()); +#endif //#ifdef DEBUG } /////////////////////////////////////////////////////////////////////////////// // cDbDataSourceIter /////////////////////////////////////////////////////////////////////////////// -cDbDataSourceIter::cDbDataSourceIter( const cDbDataSourceIter& rhs ) -: iFCODataSourceIter(), - mDbIter ( rhs.mDbIter ), - mFCOCreateFunc ( rhs.mFCOCreateFunc ), - mFlags ( rhs.mFlags ), - mpErrorBucket ( rhs.mpErrorBucket ) +cDbDataSourceIter::cDbDataSourceIter(const cDbDataSourceIter& rhs) + : iFCODataSourceIter(), + mDbIter(rhs.mDbIter), + mFCOCreateFunc(rhs.mFCOCreateFunc), + mFlags(rhs.mFlags), + mpErrorBucket(rhs.mpErrorBucket) { - } /////////////////////////////////////////////////////////////////////////////// // operator= /////////////////////////////////////////////////////////////////////////////// -cDbDataSourceIter& cDbDataSourceIter::operator=( const cDbDataSourceIter& rhs ) +cDbDataSourceIter& cDbDataSourceIter::operator=(const cDbDataSourceIter& rhs) { - mDbIter = rhs.mDbIter ; - mFCOCreateFunc = rhs.mFCOCreateFunc ; - mFlags = rhs.mFlags; - mpErrorBucket = rhs.mpErrorBucket; + mDbIter = rhs.mDbIter; + mFCOCreateFunc = rhs.mFCOCreateFunc; + mFlags = rhs.mFlags; + mpErrorBucket = rhs.mpErrorBucket; return (*this); } @@ -103,15 +99,14 @@ cDbDataSourceIter& cDbDataSourceIter::operator=( const cDbDataSourceIter& rhs ) /////////////////////////////////////////////////////////////////////////////// // dtor /////////////////////////////////////////////////////////////////////////////// -cDbDataSourceIter::~cDbDataSourceIter() +cDbDataSourceIter::~cDbDataSourceIter() { - } /////////////////////////////////////////////////////////////////////////////// // CreateCopy /////////////////////////////////////////////////////////////////////////////// -iFCODataSourceIter* cDbDataSourceIter::CreateCopy() const +iFCODataSourceIter* cDbDataSourceIter::CreateCopy() const { //TODO -- implement this with a memory pool? return new cDbDataSourceIter(*this); @@ -121,12 +116,12 @@ iFCODataSourceIter* cDbDataSourceIter::CreateCopy() const /////////////////////////////////////////////////////////////////////////////// // GetName /////////////////////////////////////////////////////////////////////////////// -cFCOName cDbDataSourceIter::GetName() const +cFCOName cDbDataSourceIter::GetName() const { - ASSERT( ! Done() ); + ASSERT(!Done()); - cFCOName rtn( mDbIter.GetCwd() ); - rtn.Push( mDbIter.GetName() ); + cFCOName rtn(mDbIter.GetCwd()); + rtn.Push(mDbIter.GetName()); return rtn; } @@ -139,27 +134,27 @@ cFCOName cDbDataSourceIter::GetName() const /////////////////////////////////////////////////////////////////////////////// iFCO* cDbDataSourceIter::CreateFCO() //throw (eError) { - ASSERT( ! Done() ); + ASSERT(!Done()); // // ok, first, we will create the new fco... // - iFCO* pFCO = static_cast( (*mFCOCreateFunc)() ); - pFCO->SetName( GetName() ); + iFCO* pFCO = static_cast((*mFCOCreateFunc)()); + pFCO->SetName(GetName()); try { - ASSERT( mDbIter.HasData() ); + ASSERT(mDbIter.HasData()); int32 length; int8* pData = mDbIter.GetData(length); // // associate a serializer with this memory and read in the property set... // - cFixedMemArchive arch( pData, length ); - cSerializerImpl ser ( arch, cSerializerImpl::S_READ ); + cFixedMemArchive arch(pData, length); + cSerializerImpl ser(arch, cSerializerImpl::S_READ); ser.Init(); - ser.ReadObject( pFCO->GetPropSet() ); + ser.ReadObject(pFCO->GetPropSet()); ser.Finit(); } - catch(...) + catch (...) { pFCO->Release(); throw; @@ -173,45 +168,46 @@ iFCO* cDbDataSourceIter::CreateFCO() //throw (eError) /////////////////////////////////////////////////////////////////////////////// bool cDbDataSourceIter::HasFCOData() const { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) return false; - return ( mDbIter.HasData() ); + return (mDbIter.HasData()); } /////////////////////////////////////////////////////////////////////////////// // SeekToFCO /////////////////////////////////////////////////////////////////////////////// -void cDbDataSourceIter::SeekToFCO(const cFCOName& name, bool bCreatePeers) //throw(eFCODataSourceIter) +void cDbDataSourceIter::SeekToFCO(const cFCOName& name, bool bCreatePeers) //throw(eFCODataSourceIter) { - ASSERT( name.GetSize() > 0 ); + ASSERT(name.GetSize() > 0); cFCOName parentName = name; parentName.Pop(); - if(! SeekToDirectory( parentName, false ) ) + if (!SeekToDirectory(parentName, false)) { // make myself Done() and return... // - while( ! Done() ) Next(); + while (!Done()) + Next(); return; } // // note that this is Done() if it fails, so we are good... // - mDbIter.SeekTo( name.GetShortName() ) ; + mDbIter.SeekTo(name.GetShortName()); } /////////////////////////////////////////////////////////////////////////////// // AddFCO /////////////////////////////////////////////////////////////////////////////// -void cDbDataSourceIter::AddFCO( const TSTRING& shortName, const iFCO* pFCO ) //throw (eFCODataSourceIter, eError) +void cDbDataSourceIter::AddFCO(const TSTRING& shortName, const iFCO* pFCO) //throw (eFCODataSourceIter, eError) { - mDbIter.CreateEntry( shortName ); + mDbIter.CreateEntry(shortName); // // we are now pointing at the entry we just created, so now let's add the data... // - SetFCOData( pFCO ); + SetFCOData(pFCO); } /////////////////////////////////////////////////////////////////////////////// @@ -219,14 +215,14 @@ void cDbDataSourceIter::AddFCO( const TSTRING& shortName, const iFCO* pFCO ) //t /////////////////////////////////////////////////////////////////////////////// void cDbDataSourceIter::RemoveFCO() //throw (eError) { - if( (! Done()) && (! HasFCOData()) ) + if ((!Done()) && (!HasFCOData())) { mDbIter.DeleteEntry(); } else { // this was called in inappropriate circumastances - ASSERT( false ); + ASSERT(false); } } @@ -235,9 +231,9 @@ void cDbDataSourceIter::RemoveFCO() //throw (eError) /////////////////////////////////////////////////////////////////////////////// void cDbDataSourceIter::RemoveFCOData() //throw (eError) { - ASSERT( ! Done() ); - ASSERT( HasFCOData() ); - if( HasFCOData() ) + ASSERT(!Done()); + ASSERT(HasFCOData()); + if (HasFCOData()) { mDbIter.RemoveData(); } @@ -246,37 +242,41 @@ void cDbDataSourceIter::RemoveFCOData() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // SetFCOData /////////////////////////////////////////////////////////////////////////////// -void cDbDataSourceIter::SetFCOData( const iFCO* pFCO ) //throw (eError) +void cDbDataSourceIter::SetFCOData(const iFCO* pFCO) //throw (eError) { - ASSERT( ! Done() ); - if( Done() ) + ASSERT(!Done()); + if (Done()) { - throw eHierDatabase( _T("Attempt to set FCO data when the iterator is done.") ); + throw eHierDatabase(_T("Attempt to set FCO data when the iterator is done.")); } // TODO -- assert and throw if the fco's type is not the same as our creation function // There is no way to do this through the serializable interface, but when there is, // we should do the above assertion. // - // if data already exists here, we first remove it; + // if data already exists here, we first remove it; // - if( mDbIter.HasData() ) + if (mDbIter.HasData()) { mDbIter.RemoveData(); } - // - // write the fco's property set to a memory archive... - // - // TODO -- does this need to be static? - static cMemoryArchive arch; - arch.Seek ( 0, cBidirArchive::BEGINNING ); - cSerializerImpl ser (arch, cSerializerImpl::S_WRITE); - ser.Init(); - ser.WriteObject ( pFCO->GetPropSet() ); - ser.Finit(); - // - // write this to the archive... - // - mDbIter.SetData( arch.GetMemory(), arch.CurrentPos() ); + + if (pFCO) + { + // + // write the fco's property set to a memory archive... + // + // TODO -- does this need to be static? + static cMemoryArchive arch; + arch.Seek(0, cBidirArchive::BEGINNING); + cSerializerImpl ser(arch, cSerializerImpl::S_WRITE); + ser.Init(); + ser.WriteObject(pFCO->GetPropSet()); + ser.Finit(); + // + // write this to the archive... + // + mDbIter.SetData(arch.GetMemory(), arch.CurrentPos()); + } } /////////////////////////////////////////////////////////////////////////////// @@ -284,8 +284,8 @@ void cDbDataSourceIter::SetFCOData( const iFCO* pFCO ) //throw (eError) /////////////////////////////////////////////////////////////////////////////// void cDbDataSourceIter::AddChildArray() //throw (eError) { - ASSERT( ! Done() ); - ASSERT( ! CanDescend() ); + ASSERT(!Done()); + ASSERT(!CanDescend()); mDbIter.CreateChildArray(); } @@ -293,7 +293,7 @@ void cDbDataSourceIter::AddChildArray() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // RemoveChildArray /////////////////////////////////////////////////////////////////////////////// -void cDbDataSourceIter::RemoveChildArray() //throw (eError) +void cDbDataSourceIter::RemoveChildArray() //throw (eError) { //NOTE -- the hier db iter does all of the proper asserting... // @@ -303,16 +303,16 @@ void cDbDataSourceIter::RemoveChildArray() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // CreatePath /////////////////////////////////////////////////////////////////////////////// -void cDbDataSourceIter::CreatePath( const cFCOName& name ) //throw (eError) +void cDbDataSourceIter::CreatePath(const cFCOName& name) //throw (eError) { - ASSERT( name.GetSize() > 0 ); + ASSERT(name.GetSize() > 0); cFCOName parentName = name; parentName.Pop(); - SeekToDirectory( parentName, true ); - if( ! mDbIter.SeekTo( name.GetShortName() ) ) + SeekToDirectory(parentName, true); + if (!mDbIter.SeekTo(name.GetShortName())) { - mDbIter.CreateEntry( name.GetShortName() ); + mDbIter.CreateEntry(name.GetShortName()); } } @@ -320,78 +320,79 @@ void cDbDataSourceIter::CreatePath( const cFCOName& name ) //throw (eError) /////////////////////////////////////////////////////////////////////////////// // SeekToDirectory /////////////////////////////////////////////////////////////////////////////// -bool cDbDataSourceIter::SeekToDirectory( const cFCOName& parentName, bool bCreate ) +bool cDbDataSourceIter::SeekToDirectory(const cFCOName& parentName, bool bCreate) { - cDebug d( "cDbDataSourceIter::SeekToDirectory" ); + cDebug d("cDbDataSourceIter::SeekToDirectory"); // - // the first task is to ascend until we are in a directory that we can descend into to + // the first task is to ascend until we are in a directory that we can descend into to // reach parentName... // cFCOName curParent = GetParentName(); - d.TraceDebug( _T("Entering... Seeking to %s (cwd = %s)\n"), parentName.AsString().c_str(), curParent.AsString().c_str() ); - int ascendCount ; - switch( curParent.GetRelationship( parentName ) ) + d.TraceDebug( + _T("Entering... Seeking to %s (cwd = %s)\n"), parentName.AsString().c_str(), curParent.AsString().c_str()); + int ascendCount; + switch (curParent.GetRelationship(parentName)) { - case cFCOName::REL_BELOW: - // - // we must ascend... - // - ascendCount = curParent.GetSize() - parentName.GetSize(); - d.TraceDetail( _T("\tAscending %d times...\n"), ascendCount ); - ASSERT( ascendCount > 0 ); - for( ; ascendCount > 0; ascendCount-- ) - Ascend(); - break; - case cFCOName::REL_ABOVE: - // - // we are above the needed directory; nothing else to do here... - // - d.TraceDetail( _T("\tAbove; not ascending...\n") ); - break; - case cFCOName::REL_EQUAL: - // - // we need to do nothing else here... - // - d.TraceDetail( _T("\tEqual; doing nothing...\n") ); - SeekBegin(); - return true; - case cFCOName::REL_UNRELATED: - // - // we have to go all the way to the root... - // - d.TraceDetail( _T("\tUnrelated; seeking to root...\n") ); - SeekToRoot(); - break; - default: - // unreachable - ASSERT( false ); - return false; + case cFCOName::REL_BELOW: + // + // we must ascend... + // + ascendCount = curParent.GetSize() - parentName.GetSize(); + d.TraceDetail(_T("\tAscending %d times...\n"), ascendCount); + ASSERT(ascendCount > 0); + for (; ascendCount > 0; ascendCount--) + Ascend(); + break; + case cFCOName::REL_ABOVE: + // + // we are above the needed directory; nothing else to do here... + // + d.TraceDetail(_T("\tAbove; not ascending...\n")); + break; + case cFCOName::REL_EQUAL: + // + // we need to do nothing else here... + // + d.TraceDetail(_T("\tEqual; doing nothing...\n")); + SeekBegin(); + return true; + case cFCOName::REL_UNRELATED: + // + // we have to go all the way to the root... + // + d.TraceDetail(_T("\tUnrelated; seeking to root...\n")); + SeekToRoot(); + break; + default: + // unreachable + ASSERT(false); + return false; } curParent = GetParentName(); - if( parentName.GetSize() == curParent.GetSize() ) + if (parentName.GetSize() == curParent.GetSize()) return true; // // now we will descend to the parent directory we are interested in... // cFCOName::iterator i(parentName); - i.SeekTo( curParent.GetSize() ); - for(; (! i.Done()); i.Next() ) + i.SeekTo(curParent.GetSize()); + for (; (!i.Done()); i.Next()) { - if( ! mDbIter.SeekTo( i.GetName() ) ) + if (!mDbIter.SeekTo(i.GetName())) { // this needs to be created! - if( bCreate ) - mDbIter.CreateEntry( i.GetName() ); + if (bCreate) + mDbIter.CreateEntry(i.GetName()); else return false; } // // create the child array and descend // - if( ! mDbIter.CanDescend() ) + if (!mDbIter.CanDescend()) { - if( bCreate ) + if (bCreate) mDbIter.CreateChildArray(); else return false; @@ -400,5 +401,3 @@ bool cDbDataSourceIter::SeekToDirectory( const cFCOName& parentName, bool bCreat } return true; } - - diff --git a/src/tw/dbdatasource.h b/src/tw/dbdatasource.h index 2196ae5..3018392 100644 --- a/src/tw/dbdatasource.h +++ b/src/tw/dbdatasource.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,93 +48,92 @@ class cDbDataSourceIter : public iFCODataSourceIter { public: - cDbDataSourceIter( cHierDatabase* pDb, int genreNum = -1) ; //throw (eError) + cDbDataSourceIter(cHierDatabase* pDb, int genreNum = -1); //throw (eError) // this ctor asserts that the case-sensitiveness and delimiting char match that of the passed in genre... // if -1 is passed for the genre num, then the current genre is used. - cDbDataSourceIter ( const cDbDataSourceIter& rhs ); - cDbDataSourceIter& operator=( const cDbDataSourceIter& rhs ); + cDbDataSourceIter(const cDbDataSourceIter& rhs); + cDbDataSourceIter& operator=(const cDbDataSourceIter& rhs); virtual ~cDbDataSourceIter(); - virtual iFCODataSourceIter* CreateCopy() const ; + virtual iFCODataSourceIter* CreateCopy() const; + + virtual const TCHAR* GetShortName() const; + virtual cFCOName GetName() const; + virtual cFCOName GetParentName() const; - virtual const TCHAR* GetShortName() const ; - virtual cFCOName GetName() const ; - virtual cFCOName GetParentName() const ; + virtual bool AtRoot() const; //throw (eError) + virtual bool CanDescend() const; //throw (eError) + virtual void Descend(); //throw (eError) + virtual void Ascend(); //throw (eError) - virtual bool AtRoot() const ; //throw (eError) - virtual bool CanDescend() const ; //throw (eError) - virtual void Descend() ; //throw (eError) - virtual void Ascend() ; //throw (eError) - - virtual void SeekBegin() ; - virtual bool Done() const ; - virtual void Next() ; - virtual bool SeekTo( const TCHAR* shortName ); - virtual bool IsCaseSensitive() const; + virtual void SeekBegin(); + virtual bool Done() const; + virtual void Next(); + virtual bool SeekTo(const TCHAR* shortName); + virtual bool IsCaseSensitive() const; - virtual iFCO* CreateFCO() ; //throw (eError) - virtual void SetErrorBucket( cErrorBucket* pBucket ); + virtual iFCO* CreateFCO(); //throw (eError) + virtual void SetErrorBucket(cErrorBucket* pBucket); /////////////////////////////////////////////// // This stuff is in this derived class _only_ - void SeekToRoot(); //throw( eError ) + void SeekToRoot(); //throw( eError ) // seeks to the root of the database - virtual void AddFCO( const TSTRING& shortName, const iFCO* pFCO ) ; //throw (eFCODataSourceIter, eError) + virtual void AddFCO(const TSTRING& shortName, const iFCO* pFCO); //throw (eFCODataSourceIter, eError) // adds the fco to the current directory; this throws an exception if - // the insert fails or an fco already named the same exists in the directory. After the insertion, + // the insert fails or an fco already named the same exists in the directory. After the insertion, // the iterator points at the new node. - virtual void RemoveFCO() ; //throw (eError) + virtual void RemoveFCO(); //throw (eError) // removes the current fco; iterator then points at the next object or done() is true if it is at the end. - virtual void SetFCOData( const iFCO* pFCO ) ; //throw (eError) - // sets the data associated with the current FCO. This method pays no attention to the FCO's name. (maybe I + virtual void SetFCOData(const iFCO* pFCO); //throw (eError) + // sets the data associated with the current FCO. This method pays no attention to the FCO's name. (maybe I // should assert?) - virtual void RemoveFCOData() ; //throw (eError) + virtual void RemoveFCOData(); //throw (eError) // removes the fco data associated with the current fco. This asserts the iterator is not done and contains - // data. - bool HasFCOData() const; - // this returns true if the current node contains fco data. If this returns false, then it is not - // legal to call CreateFCO() - void CreatePath( const cFCOName& name ) ; //throw (eError) + // data. + bool HasFCOData() const; + // this returns true if the current node contains fco data. If this returns false, then it is not + // legal to call CreateFCO() + void CreatePath(const cFCOName& name); //throw (eError) // a convenience method that creates the named path (or any part that is currently not created) // the iterator ends up with the named path as the current item (ie -- it will be returned from // GetName()) - void AddChildArray() ; //throw (eError) + void AddChildArray(); //throw (eError) // this adds a child array to the current FCO. This asserts that one does not currently exist and // that Done() is not true - void RemoveChildArray() ; //throw (eError) + void RemoveChildArray(); //throw (eError) //this asserts that Done() is not true, and the child array contains nothing. - bool CanRemoveChildArray(); //throw (eError) + bool CanRemoveChildArray(); //throw (eError) // returns true if the child array is empty, and can thus be removed with RemoveChildArray() - void Refresh(); // throw (eError) + void Refresh(); // throw (eError) // /////////////////////////////////////////////// - virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true) ; //throw(eFCODataSourceIter) + virtual void SeekToFCO(const cFCOName& name, bool bCreatePeers = true); //throw(eFCODataSourceIter) // NOTE -- this class ignores bCreatePeers - virtual int GetIterFlags() const; - virtual void SetIterFlags(int i); + virtual int GetIterFlags() const; + virtual void SetIterFlags(int i); private: // // helper methods // - bool SeekToDirectory( const cFCOName& parentName, bool bCreate = false ); - // seeks the iterator to the named directory. This method attempts to take the most direct route possible, - // seeking from the current working directory instead of seeking to the root and then descending to the - // named directory. When this operation returns, it is positioned at the first element in the named directory - // unless false is returned, in which case the iterator is positioned at an undefined location. If bCreate - // is true, the directory is created if it does not currently exist. - - - - cHierDatabase::iterator mDbIter; - iSerRefCountObj::CreateFunc mFCOCreateFunc; // points to the function that creates the fcos we return - uint32 mFlags; // flags used for iteration - cErrorBucket* mpErrorBucket; + bool SeekToDirectory(const cFCOName& parentName, bool bCreate = false); + // seeks the iterator to the named directory. This method attempts to take the most direct route possible, + // seeking from the current working directory instead of seeking to the root and then descending to the + // named directory. When this operation returns, it is positioned at the first element in the named directory + // unless false is returned, in which case the iterator is positioned at an undefined location. If bCreate + // is true, the directory is created if it does not currently exist. + + + cHierDatabase::iterator mDbIter; + iSerRefCountObj::CreateFunc mFCOCreateFunc; // points to the function that creates the fcos we return + uint32 mFlags; // flags used for iteration + cErrorBucket* mpErrorBucket; }; //############################################################################# @@ -149,7 +148,7 @@ inline void cDbDataSourceIter::Refresh() /////////////////////////////////////////////////////////////////////////////// // SeekTo /////////////////////////////////////////////////////////////////////////////// -inline bool cDbDataSourceIter::SeekTo( const TCHAR* shortName ) +inline bool cDbDataSourceIter::SeekTo(const TCHAR* shortName) { return mDbIter.SeekTo(shortName); } @@ -166,32 +165,32 @@ inline void cDbDataSourceIter::SeekToRoot() /////////////////////////////////////////////////////////////////////////////// // GetParentName /////////////////////////////////////////////////////////////////////////////// -inline cFCOName cDbDataSourceIter::GetParentName() const +inline cFCOName cDbDataSourceIter::GetParentName() const { - cFCOName rtn( mDbIter.GetCwd() ); + cFCOName rtn(mDbIter.GetCwd()); return rtn; } /////////////////////////////////////////////////////////////////////////////// // AtRoot /////////////////////////////////////////////////////////////////////////////// -inline bool cDbDataSourceIter::AtRoot() const //throw (eError) +inline bool cDbDataSourceIter::AtRoot() const //throw (eError) { - return ( mDbIter.AtRoot() ); + return (mDbIter.AtRoot()); } /////////////////////////////////////////////////////////////////////////////// // CanDescend /////////////////////////////////////////////////////////////////////////////// -inline bool cDbDataSourceIter::CanDescend() const //throw (eError) +inline bool cDbDataSourceIter::CanDescend() const //throw (eError) { - return ( mDbIter.CanDescend() ); + return (mDbIter.CanDescend()); } /////////////////////////////////////////////////////////////////////////////// // Descend /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::Descend() //throw (eError) +inline void cDbDataSourceIter::Descend() //throw (eError) { mDbIter.Descend(); } @@ -199,7 +198,7 @@ inline void cDbDataSourceIter::Descend() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // Ascend /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::Ascend() //throw (eError) +inline void cDbDataSourceIter::Ascend() //throw (eError) { mDbIter.Ascend(); } @@ -207,7 +206,7 @@ inline void cDbDataSourceIter::Ascend() //throw (eError) /////////////////////////////////////////////////////////////////////////////// // SeekBegin /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::SeekBegin() +inline void cDbDataSourceIter::SeekBegin() { mDbIter.SeekBegin(); } @@ -215,15 +214,15 @@ inline void cDbDataSourceIter::SeekBegin() /////////////////////////////////////////////////////////////////////////////// // Done /////////////////////////////////////////////////////////////////////////////// -inline bool cDbDataSourceIter::Done() const +inline bool cDbDataSourceIter::Done() const { - return ( mDbIter.Done() ); + return (mDbIter.Done()); } /////////////////////////////////////////////////////////////////////////////// // Next /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::Next() +inline void cDbDataSourceIter::Next() { mDbIter.Next(); } @@ -239,9 +238,9 @@ inline bool cDbDataSourceIter::IsCaseSensitive() const /////////////////////////////////////////////////////////////////////////////// // GetShortName /////////////////////////////////////////////////////////////////////////////// -inline const TCHAR* cDbDataSourceIter::GetShortName() const +inline const TCHAR* cDbDataSourceIter::GetShortName() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return mDbIter.GetName(); } @@ -249,9 +248,9 @@ inline const TCHAR* cDbDataSourceIter::GetShortName() const /////////////////////////////////////////////////////////////////////////////// // CanRemoveChildArray /////////////////////////////////////////////////////////////////////////////// -inline bool cDbDataSourceIter::CanRemoveChildArray() +inline bool cDbDataSourceIter::CanRemoveChildArray() { - return ( mDbIter.ChildArrayEmpty() ); + return (mDbIter.ChildArrayEmpty()); } /////////////////////////////////////////////////////////////////////////////// @@ -265,7 +264,7 @@ inline int cDbDataSourceIter::GetIterFlags() const /////////////////////////////////////////////////////////////////////////////// // SetIterFlags /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::SetIterFlags( int i ) +inline void cDbDataSourceIter::SetIterFlags(int i) { mFlags = i; } @@ -273,10 +272,9 @@ inline void cDbDataSourceIter::SetIterFlags( int i ) /////////////////////////////////////////////////////////////////////////////// // SetIterFlags /////////////////////////////////////////////////////////////////////////////// -inline void cDbDataSourceIter::SetErrorBucket( cErrorBucket* pBucket ) -{ +inline void cDbDataSourceIter::SetErrorBucket(cErrorBucket* pBucket) +{ mpErrorBucket = pBucket; } #endif - diff --git a/src/tw/dbdebug.cpp b/src/tw/dbdebug.cpp index c5b0220..fe49cee 100644 --- a/src/tw/dbdebug.cpp +++ b/src/tw/dbdebug.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -68,7 +68,7 @@ ////////////////////////////////////////////////////////////////////////////////////////////////// // //static void util_PrintFCO(const iFCO* pFCO, iFCOPropDisplayer * pPropDisplayer); -static void util_InitBlockArray( cBlockRecordArray& block ); +static void util_InitBlockArray(cBlockRecordArray& block); //static void util_MapHierRoot( std::map< std::pair< int, int>, int > dbMap ); ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -76,20 +76,21 @@ static void util_InitBlockArray( cBlockRecordArray& block ); ////////////////////////////////////////////////////////////////////////////////////////////////// struct cDbDebug_i { - cDbDebug_i() {}; - ~cDbDebug_i() {}; + cDbDebug_i(){}; + ~cDbDebug_i(){}; - typedef std::map< std::pair, int > hierDbMap; + typedef std::map, int> hierDbMap; // This is the data structure that we will use to match the information stored in a quantum database // with its hierarchical representation! For now, it will hold the tuples representing // valid offsets in each block (referenced by a block number). The bool value will be set to false - // on the first run, and then flipped to true for each entry that is found while traversing the + // on the first run, and then flipped to true for each entry that is found while traversing the // hierarchical database. - typedef std::list< std::pair< int, int> > AddressList; + typedef std::list > AddressList; - hierDbMap mDbMap; // The map itself. - AddressList mlMissingFromBlockFile; // A list for keeping track of nodes found in the hierarchy, but not the blockfile - AddressList mlMissingFromHierarchy; // The opposite case. + hierDbMap mDbMap; // The map itself. + AddressList + mlMissingFromBlockFile; // A list for keeping track of nodes found in the hierarchy, but not the blockfile + AddressList mlMissingFromHierarchy; // The opposite case. }; cDbDebug::cDbDebug() @@ -106,9 +107,9 @@ cDbDebug::~cDbDebug() /////////////////////////////////////////////////////////////////////////////// // util_InitBlockArray /////////////////////////////////////////////////////////////////////////////// -static void util_InitBlockArray( cBlockRecordArray& block ) +static void util_InitBlockArray(cBlockRecordArray& block) { - if( ! block.Initialized() ) + if (!block.Initialized()) { block.InitForExistingBlock(); } @@ -117,18 +118,18 @@ static void util_InitBlockArray( cBlockRecordArray& block ) /////////////////////////////////////////////////////////////////////////////// // util_MapHierRoot : Map the Root and RootArray in the HierDatabase: /////////////////////////////////////////////////////////////////////////////// -static void util_MapHierRoot( std::map< std::pair< int, int>, int >* dbMap ) +static void util_MapHierRoot(std::map, int>* dbMap) { - cDbDebug_i::hierDbMap::iterator i = dbMap->find( std::pair ( 0, 0 ) ); + cDbDebug_i::hierDbMap::iterator i = dbMap->find(std::pair(0, 0)); //dbMap->insert( cDbDebug_i::hierDbMap::value_type( std::pair< int, int > ( 0, 0 ), 1 ) ); // // This insert statement should work to change the value, but it doesn't ???? (*i).second = 1; - i = dbMap->find( std::pair ( 0, 1 ) ); + i = dbMap->find(std::pair(0, 1)); (*i).second = 1; - i = dbMap->find( std::pair ( 0, 2 ) ); + i = dbMap->find(std::pair(0, 2)); (*i).second = 1; } @@ -139,21 +140,22 @@ void cDbDebug::DisplayDbMap() { int loop_count = 0; - for(cDbDebug_i::hierDbMap::iterator i = cDbDebug::mpData->mDbMap.begin(); i!= cDbDebug::mpData->mDbMap.end(); ++i, ++loop_count) + for (cDbDebug_i::hierDbMap::iterator i = cDbDebug::mpData->mDbMap.begin(); i != cDbDebug::mpData->mDbMap.end(); + ++i, ++loop_count) { TCOUT.width(6); - TCOUT<< (*i).first.first << _T(",") << (*i).first.second<<_T(" "); - TCOUT<<_T("(")<< (*i).second<<_T(")"); - if( (loop_count % 5) == 0 ) - TCOUT<< std::endl; + TCOUT << (*i).first.first << _T(",") << (*i).first.second << _T(" "); + TCOUT << _T("(") << (*i).second << _T(")"); + if ((loop_count % 5) == 0) + TCOUT << std::endl; } - TCOUT<mDbMap); } @@ -162,30 +164,30 @@ cDbDebug::hierDbMap* cDbDebug::GetHierDbMap( void ) // Execute : // Drives the DebugDb mode of tripwire, which will only be used for internal use. ////////////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::Execute( cFCODatabaseFileIter& dbIter, const TSTRING& dbFile ) +void cDbDebug::Execute(cFCODatabaseFileIter& dbIter, const TSTRING& dbFile) { - - cDebug d("cDebugDb::Execute"); + + cDebug d("cDebugDb::Execute"); cDbDebug DbDebug; // //A derived class with extra methods for obtaining blockfile information. cDebugHierDb* db; // // Cast the database object that we have inherited from the "common" command line - // information to a cDebugHierDb. This will expose all the information that we + // information to a cDebugHierDb. This will expose all the information that we // need to debug the database. // db = static_cast(&(dbIter.GetDb())); try { - cDebugHierDbIter pIter( db ); + cDebugHierDbIter pIter(db); // - //First, map the state of the underlying quantyum database. Store this info. in + //First, map the state of the underlying quantyum database. Store this info. in //the hierDbMap. // - DbDebug.MapQuantumDatabase( *db ); + DbDebug.MapQuantumDatabase(*db); //DbDebug.DisplayDbMap(); //TODO : get rid of these display calls. @@ -196,14 +198,14 @@ void cDbDebug::Execute( cFCODatabaseFileIter& dbIter, const TSTRING& dbFile ) // Next, traverse the hierarchical overlay and "tag" all entries in the map that // we see: - ASSERT( pIter.AtRoot() ); - // - // check to make sure we are at the root of the hierarchy, if so, map the root - // before calling the recursive traversal function. - // - util_MapHierRoot( DbDebug.GetHierDbMap() ); + ASSERT(pIter.AtRoot()); + // + // check to make sure we are at the root of the hierarchy, if so, map the root + // before calling the recursive traversal function. + // + util_MapHierRoot(DbDebug.GetHierDbMap()); - DbDebug.TraverseHierarchy( pIter /*, db*/ ); + DbDebug.TraverseHierarchy(pIter /*, db*/); //DbDebug.DisplayDbMap(); //TODO: get rid of these display calls. // @@ -216,13 +218,12 @@ void cDbDebug::Execute( cFCODatabaseFileIter& dbIter, const TSTRING& dbFile ) // DbDebug.OutputResults(); - }//try + } //try - catch( eError& e ) + catch (eError& e) { - cErrorReporter::PrintErrorMsg( e ); + cErrorReporter::PrintErrorMsg(e); } - } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -235,14 +236,14 @@ void cDbDebug::Execute( cFCODatabaseFileIter& dbIter, const TSTRING& dbFile ) // Addition: 2/15/99: We want to print out statistics on the current state of the block // file, so let's do it here ( since we're traversing it to map the addresses, anyway ). ////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::MapQuantumDatabase( cDebugHierDb& db ) +void cDbDebug::MapQuantumDatabase(cDebugHierDb& db) { //mirroring the implementation in blockrecordfile.h: - typedef std::vector BlockArray; + typedef std::vector BlockArray; //Using the two added methods to gain access to the low-level implementation of the //quantum database. - BlockArray* pBlkArray = db.myGetBlockArray(); + BlockArray* pBlkArray = db.myGetBlockArray(); // Print some statistics on the blockfile if we're in debug mode: #ifdef _BLOCKFILE_DEBUG @@ -252,12 +253,12 @@ void cDbDebug::MapQuantumDatabase( cDebugHierDb& db ) // assessed. // time to iterate over the database: - std::vector< cBlockRecordArray >::iterator i; - int count = 0; + std::vector::iterator i; + int count = 0; - for( i = (*pBlkArray).begin(); i != (*pBlkArray).end(); ++i, ++count ) + for (i = (*pBlkArray).begin(); i != (*pBlkArray).end(); ++i, ++count) { - util_InitBlockArray( *i ); + util_InitBlockArray(*i); //This is necessary to make sure that each block is initialized as we iterate //over the block array. // @@ -270,18 +271,18 @@ void cDbDebug::MapQuantumDatabase( cDebugHierDb& db ) //Search through all the indexes and determine which of them references valid //information. Store these pairs ( the first int being the value of //count.... - for( int j = 0; j <= i->GetNumItems(); ++j ) + for (int j = 0; j <= i->GetNumItems(); ++j) { - if( i->IsItemValid( j ) ) + if (i->IsItemValid(j)) { // // We found a valid node in the database, so store it in the map. // - mpData->mDbMap.insert( cDbDebug_i::hierDbMap::value_type( std::pair (count, j) , 0 )); + mpData->mDbMap.insert(cDbDebug_i::hierDbMap::value_type(std::pair(count, j), 0)); } // if not, just don't store it. The index is no longer valid. } - } + } } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -291,9 +292,9 @@ void cDbDebug::MapQuantumDatabase( cDebugHierDb& db ) // structures that make up the object. Looks at data addresses as well as structures that are // necessary to maintain the hierarchy ( namely cHierArrayInfo records ). //////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::TraverseHierarchy( cDebugHierDbIter pIter) +void cDbDebug::TraverseHierarchy(cDebugHierDbIter pIter) { - if( ! pIter.CanDescend() ) + if (!pIter.CanDescend()) return; //Done with this call. pIter.Descend(); @@ -301,59 +302,73 @@ void cDbDebug::TraverseHierarchy( cDebugHierDbIter pIter) //Descend once from the root, into the first child set. Also, descend once for each recursive call. // - for( pIter.SeekBegin(); !pIter.Done(); pIter.Next() ) + for (pIter.SeekBegin(); !pIter.Done(); pIter.Next()) { - //Try to match the parent's address in the database. - if( !pIter.Done() ) + //Try to match the parent's address in the database. + if (!pIter.Done()) + { + if (pIter.myGetEntryArrayIt() == pIter.myGetEntryArray().begin()) + //We're dealing with a cHierArrayInfo object, so treat it differently. + { + // + // Let's map the parent address, and the array address, so we account for all the data structures + // that make up this particular node. + // + MapHierDbNodes(mpData->mDbMap, + std::pair(pIter.myGetArrayInfo().mParent.mBlockNum, + pIter.myGetArrayInfo().mParent.mIndex), + pIter); + // and the array... + MapHierDbNodes( + mpData->mDbMap, + std::pair(pIter.myGetArrayInfo().mArray.mBlockNum, pIter.myGetArrayInfo().mArray.mIndex), + pIter); + } + else + //This is a regular cHierEntry, so look at the Data and Child (if it exists ). { - if( pIter.myGetEntryArrayIt() == pIter.myGetEntryArray().begin() ) - //We're dealing with a cHierArrayInfo object, so treat it differently. - { - // - // Let's map the parent address, and the array address, so we account for all the data structures - // that make up this particular node. - // - MapHierDbNodes( mpData->mDbMap, std::pair(pIter.myGetArrayInfo().mParent.mBlockNum, pIter.myGetArrayInfo().mParent.mIndex), pIter ); - // and the array... - MapHierDbNodes( mpData->mDbMap, std::pair(pIter.myGetArrayInfo().mArray.mBlockNum, pIter.myGetArrayInfo().mArray.mIndex), pIter ); - } - else - //This is a regular cHierEntry, so look at the Data and Child (if it exists ). - { - cDebugHierDbIter::EntryArray::iterator lEntryArrayIt = pIter.myGetEntryArrayIt(); + cDebugHierDbIter::EntryArray::iterator lEntryArrayIt = pIter.myGetEntryArrayIt(); - MapHierDbNodes( mpData->mDbMap, std::pair(lEntryArrayIt->mData.mBlockNum, lEntryArrayIt->mData.mIndex), pIter ); + MapHierDbNodes(mpData->mDbMap, + std::pair(lEntryArrayIt->mData.mBlockNum, lEntryArrayIt->mData.mIndex), + pIter); - --lEntryArrayIt; - // Get the address of this node by examining the previous next pointer in the entry list. - // + --lEntryArrayIt; + // Get the address of this node by examining the previous next pointer in the entry list. + // - // - // Map the next peer entry in the list. TODO: This may very well be overkill... if so, lose this call to MapHierDbNodes. - // - MapHierDbNodes( mpData->mDbMap, std::pair(lEntryArrayIt->mNext.mBlockNum, lEntryArrayIt->mNext.mIndex), pIter ); - // - // We also want to map the address of the child array, if non-null. - // - if( lEntryArrayIt->mChild.mBlockNum != -1 ) - MapHierDbNodes( mpData->mDbMap, std::pair(lEntryArrayIt->mChild.mBlockNum, lEntryArrayIt->mChild.mIndex), pIter ); - // - // Finally, map the address of the data. - // - MapHierDbNodes( mpData->mDbMap, std::pair(lEntryArrayIt->mData.mBlockNum, lEntryArrayIt->mData.mIndex), pIter ); - } + // + // Map the next peer entry in the list. TODO: This may very well be overkill... if so, lose this call to MapHierDbNodes. + // + MapHierDbNodes(mpData->mDbMap, + std::pair(lEntryArrayIt->mNext.mBlockNum, lEntryArrayIt->mNext.mIndex), + pIter); + // + // We also want to map the address of the child array, if non-null. + // + if (lEntryArrayIt->mChild.mBlockNum != -1) + MapHierDbNodes(mpData->mDbMap, + std::pair(lEntryArrayIt->mChild.mBlockNum, lEntryArrayIt->mChild.mIndex), + pIter); + // + // Finally, map the address of the data. + // + MapHierDbNodes(mpData->mDbMap, + std::pair(lEntryArrayIt->mData.mBlockNum, lEntryArrayIt->mData.mIndex), + pIter); + } - }//if + } //if // // Check to see if this particular node has a child array. If so, make recursive call. // - if( pIter.CanDescend() ) + if (pIter.CanDescend()) { //This node has children, call myself - TraverseHierarchy( pIter ); + TraverseHierarchy(pIter); } - }//for + } //for } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -362,17 +377,19 @@ void cDbDebug::TraverseHierarchy( cDebugHierDbIter pIter) // Maps a given address in the hierarchy. This function looks up the address in the map and flips an integer flag // to record the event. If the address is not found, it is placed in a list of addresses for error output. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::MapHierDbNodes( std::map< std::pair< int, int > , int >& dbMap, std::pair address, cDebugHierDbIter& pIter ) +void cDbDebug::MapHierDbNodes(std::map, int>& dbMap, + std::pair address, + cDebugHierDbIter& pIter) { - cDbDebug_i::hierDbMap::iterator i = dbMap.find( std::pair< int, int> (address.first, address.second) ); + cDbDebug_i::hierDbMap::iterator i = dbMap.find(std::pair(address.first, address.second)); - if( i != dbMap.end() ) + if (i != dbMap.end()) { (*i).second = 1; //Flip the integer flag to 1, since we've found the address in the hierarchy. } else - mpData->mlMissingFromBlockFile.push_back( std::pair (address.first, address.second)); + mpData->mlMissingFromBlockFile.push_back(std::pair(address.first, address.second)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -382,18 +399,18 @@ void cDbDebug::MapHierDbNodes( std::map< std::pair< int, int > , int >& dbMap, s // hierarchy traversal. If there are, push the offending addresses onto the address list. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::CongruencyTest( void ) +void cDbDebug::CongruencyTest(void) { cDbDebug_i::hierDbMap::iterator i = mpData->mDbMap.begin(); - for( ; i != mpData->mDbMap.end(); ++i ) + for (; i != mpData->mDbMap.end(); ++i) { - if ( (*i).second != 1 ) + if ((*i).second != 1) { - //We've found something in the blockfile map that is not accounted for by the + //We've found something in the blockfile map that is not accounted for by the //hierarchy. Add this address to the appropriate list. //TCOUT<< (*i).first.first << _T(",") << (*i).first.second << std::endl; //TCOUT<< (*i).second <mlMissingFromHierarchy.push_back( std::pair< int, int> ( (*i).first.first, (*i).first.second ) ); + mpData->mlMissingFromHierarchy.push_back(std::pair((*i).first.first, (*i).first.second)); } } } @@ -402,47 +419,47 @@ void cDbDebug::CongruencyTest( void ) // OutputResults -- // // Output the results of the congruency test. Print information contained in the two -// "error lists" if they have entries. +// "error lists" if they have entries. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void cDbDebug::OutputResults( void ) +void cDbDebug::OutputResults(void) { - TCOUT<< _T("\nResults of Blockfile / Hierarchy congruency tests: \n") << std::endl; - + TCOUT << _T("\nResults of Blockfile / Hierarchy congruency tests: \n") << std::endl; + // Check to see if our error lists are empty. If so, output a message that indicates - // that the two databases checked clean. - if( mpData->mlMissingFromHierarchy.empty() && mpData->mlMissingFromBlockFile.empty() ) - TCOUT<< _T("The database representations match!\n") << std::endl; + // that the two databases checked clean. + if (mpData->mlMissingFromHierarchy.empty() && mpData->mlMissingFromBlockFile.empty()) + TCOUT << _T("The database representations match!\n") << std::endl; else { // Check to see if there was anything in the hierarchy that was not accounted for by the // blockfile (quantum database). - if( !mpData->mlMissingFromBlockFile.empty() ) + if (!mpData->mlMissingFromBlockFile.empty()) { - TCOUT<< _T(" Objects (referenced by address) found in the hierarchy that were not\n"); - TCOUT<< _T(" accounted for by the underlying quantum database: \n"); + TCOUT << _T(" Objects (referenced by address) found in the hierarchy that were not\n"); + TCOUT << _T(" accounted for by the underlying quantum database: \n"); cDbDebug_i::AddressList::iterator i = mpData->mlMissingFromBlockFile.begin(); - for( ; i != mpData->mlMissingFromBlockFile.end(); ++i ) + for (; i != mpData->mlMissingFromBlockFile.end(); ++i) TCOUT << _T("(") << (*i).first << _T(",") << (*i).second << _T(")") << std::endl; } else - TCOUT<< _T(" All objects in Blockfile accounted for!\n"); + TCOUT << _T(" All objects in Blockfile accounted for!\n"); - //check to see if there was anything in the blockfile that was not accounted for by the + //check to see if there was anything in the blockfile that was not accounted for by the // hierarchy: - if ( !mpData->mlMissingFromHierarchy.empty() ) + if (!mpData->mlMissingFromHierarchy.empty()) { - TCOUT<< _T(" Database information (referenced by a address)\n"); - TCOUT<< _T(" not accounted for by the hierarchy :\n"); + TCOUT << _T(" Database information (referenced by a address)\n"); + TCOUT << _T(" not accounted for by the hierarchy :\n"); cDbDebug_i::AddressList::iterator i = mpData->mlMissingFromHierarchy.begin(); - for( ; i != mpData->mlMissingFromHierarchy.end(); ++i ) + for (; i != mpData->mlMissingFromHierarchy.end(); ++i) TCOUT << _T("(") << (*i).first << _T(",") << (*i).second << _T(")") << std::endl; } else - TCOUT<<_T("All objects in Hierarchy accounted for!\n"); - }//else + TCOUT << _T("All objects in Hierarchy accounted for!\n"); + } //else } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -450,6 +467,7 @@ void cDbDebug::OutputResults( void ) // Begin code for manipulating Database -- This is just a straight port from the DbExplore code. It's presence is // purely for convenience, and for debugging this class. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/* static inline bool IsSpace( TCHAR c ) { return ( (c == _T(' ')) || (c == _T('\t')) || (c == _T('\r')) || (c == _T('\n')) || (c == _T('\0')) ); @@ -460,7 +478,6 @@ static inline bool IsEnd( TCHAR c ) return ( (c == _T('\0')) ); } -/* /////////////////////////////////////////////////////////////////////////////// // util_PrintFCO /////////////////////////////////////////////////////////////////////////////// diff --git a/src/tw/dbdebug.h b/src/tw/dbdebug.h index 857630d..d9355c3 100644 --- a/src/tw/dbdebug.h +++ b/src/tw/dbdebug.h @@ -1,35 +1,35 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // -//dbdebug.h +//dbdebug.h #ifndef __DBDEBUG_H #define __DBDEBUG_H @@ -48,10 +48,10 @@ #endif // STL stuff... -#include -#include -#include -#include +#include +#include +#include +#include //////////////////////////////////////////////////////////////////////////////// // FORWARD DECLARATIONS @@ -73,15 +73,24 @@ class cFCOName; class cDebugHierDb : public cHierDatabase { public: - cDebugHierDb() : cHierDatabase() {} + cDebugHierDb() : cHierDatabase() + { + } - typedef std::vector BlockArray; + typedef std::vector BlockArray; // // Methods for accessing the two data members of cBlockRecordFile that we // are interested in. - cBlockFile* myGetBlockFile () { return GetBlockFile(); } - BlockArray* myGetBlockArray () { return GetBlockArray(); } + cBlockFile* myGetBlockFile() + { + return GetBlockFile(); + } + BlockArray* myGetBlockArray() + { + return GetBlockArray(); + } + private: }; @@ -94,16 +103,23 @@ class cDebugHierDbIter : public cHierDatabaseIter // // Type Defines: // - typedef std::vector< cHierEntry > EntryArray; + typedef std::vector EntryArray; // Ctor, Dtor: - ~cDebugHierDbIter () {} - cDebugHierDbIter ( cHierDatabase* pDb ) : cHierDatabaseIter( pDb ) {} + ~cDebugHierDbIter() + { + } + explicit cDebugHierDbIter(cHierDatabase* pDb) : cHierDatabaseIter(pDb) + { + } // // Methods for obtaining protected members of cHierDatabaseIter: // - cHierAddr myGetCurrentAddr() { return GetCurrentAddr(); } + cHierAddr myGetCurrentAddr() + { + return GetCurrentAddr(); + } // We need this method to match the hierarchy information with that of the // quantum database. @@ -111,12 +127,26 @@ class cDebugHierDbIter : public cHierDatabaseIter // Methods for accessing data members: // TODO: Get rid of the stuff I don't end up using. // - EntryArray::iterator& myGetEntryArrayIt() { return mIter; } - EntryArray& myGetEntryArray() { return mEntries; } - cHierArrayInfo& myGetArrayInfo() { return mInfo; } - cHierAddr& myGetInfoAddr() { return mInfoAddr; } - cHierDbPath& myGetCurrPath() { return mCurPath; } - + EntryArray::iterator& myGetEntryArrayIt() + { + return mIter; + } + EntryArray& myGetEntryArray() + { + return mEntries; + } + cHierArrayInfo& myGetArrayInfo() + { + return mInfo; + } + cHierAddr& myGetInfoAddr() + { + return mInfoAddr; + } + cHierDbPath& myGetCurrPath() + { + return mCurPath; + } }; ///////////////////////////////////////////////////////////////////////////////// @@ -131,29 +161,29 @@ class cDbDebug cDbDebug(); ~cDbDebug(); - static void Execute ( cFCODatabaseFileIter& dbIter, const TSTRING& dbFile ); - void MapQuantumDatabase ( cDebugHierDb& db ); - // Traverses a blockfile and records all valid addresses - void TraverseHierarchy ( cDebugHierDbIter pIter ); - // Traverses a hierarchical database and "updates" the map for addresses that it finds. - void MapHierDbNodes ( std::map< std::pair, int >& dbMap, std::pair, cDebugHierDbIter& ); - // Changes the map for a given address, in order to record entries that were found in the hierarchy. - void CongruencyTest ( void ); - // Looks at the map to see if all entries have been accounted for. - void OutputResults ( void ); - // Gives a clean report only if the two database representations match exactly. - + static void Execute(cFCODatabaseFileIter& dbIter, const TSTRING& dbFile); + void MapQuantumDatabase(cDebugHierDb& db); + // Traverses a blockfile and records all valid addresses + void TraverseHierarchy(cDebugHierDbIter pIter); + // Traverses a hierarchical database and "updates" the map for addresses that it finds. + void MapHierDbNodes(std::map, int>& dbMap, std::pair, cDebugHierDbIter&); + // Changes the map for a given address, in order to record entries that were found in the hierarchy. + void CongruencyTest(void); + // Looks at the map to see if all entries have been accounted for. + void OutputResults(void); + // Gives a clean report only if the two database representations match exactly. + // // The map that will be used to test for congruency between the quantum database // and the hierarchical database. // - typedef std::map< std::pair< int, int > , int > hierDbMap; + typedef std::map, int> hierDbMap; - hierDbMap* GetHierDbMap ( void ); - void DisplayDbMap ( void ); - // Displays the whole map TODO: Somehow the spacing in the output got messed up... + hierDbMap* GetHierDbMap(void); + void DisplayDbMap(void); + // Displays the whole map TODO: Somehow the spacing in the output got messed up... //void ManipDb ( cFCODatabaseFileIter& dbIter ); - // A hook to DbExplore-like code. For convenience only. + // A hook to DbExplore-like code. For convenience only. private: // (somewhat) Insulated implementation: @@ -162,4 +192,3 @@ class cDbDebug #endif //__DBDEBUG_H - diff --git a/src/tw/dbexplore.cpp b/src/tw/dbexplore.cpp index 8897708..e474827 100644 --- a/src/tw/dbexplore.cpp +++ b/src/tw/dbexplore.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,18 +48,18 @@ #include "fco/fconametranslator.h" // -// TODO -- make an "associate with new genre" method for the db iter so we don't have to +// TODO -- make an "associate with new genre" method for the db iter so we don't have to // delete and create a new one when we switch genres. // -static inline bool IsSpace( TCHAR c ) +static inline bool IsSpace(TCHAR c) { - return ( (c == _T(' ')) || (c == _T('\t')) || (c == _T('\r')) || (c == _T('\n')) || (c == _T('\0')) ); + return ((c == _T(' ')) || (c == _T('\t')) || (c == _T('\r')) || (c == _T('\n')) || (c == _T('\0'))); } -static inline bool IsEnd( TCHAR c ) +static inline bool IsEnd(TCHAR c) { - return ( (c == _T('\0')) ); + return ((c == _T('\0'))); } @@ -68,47 +68,47 @@ static inline bool IsEnd( TCHAR c ) // note -- you can only call this once after the verb (it eats the rest // of the line!) /////////////////////////////////////////////////////////////////////////////// -static void GetNoun( TSTRING& noun ) +static void GetNoun(TSTRING& noun) { static TSTRING prevNoun; - TCHAR buf[1024]; + TCHAR buf[1024]; - TCIN.getline( buf, 1024 ); + TCIN.getline(buf, 1024); // // find the end of the noun... // - TCHAR* pStart = buf; - TCHAR* end = &buf[1023]; - while( IsSpace(*pStart) && (! IsEnd(*pStart)) && (pStart < end) ) + TCHAR* pStart = buf; + TCHAR* end = &buf[1023]; + while (IsSpace(*pStart) && (!IsEnd(*pStart)) && (pStart < end)) pStart++; - if( IsEnd( *pStart ) || (pStart >= end) ) + if (IsEnd(*pStart) || (pStart >= end)) { // no noun! noun = _T(""); return; } - TCHAR* pCur = pStart; - bool bQuote = false; - if( *pCur == _T('\"') ) + TCHAR* pCur = pStart; + bool bQuote = false; + if (*pCur == _T('\"')) { bQuote = true; pCur++; pStart++; } - while( pCur < end ) + while (pCur < end) { - if( (! bQuote) && IsSpace(*pCur) ) + if ((!bQuote) && IsSpace(*pCur)) break; - if( *pCur == _T('\"') && bQuote) + if (*pCur == _T('\"') && bQuote) break; pCur++; } noun.assign(pStart, (pCur - pStart)); - if( noun.compare( _T("!$") ) == 0 ) + if (noun.compare(_T("!$")) == 0) { noun = prevNoun; } @@ -116,82 +116,79 @@ static void GetNoun( TSTRING& noun ) } /////////////////////////////////////////////////////////////////////////////// -// SeekTo -- seeks to the named noun; this takes care of interpriting special +// SeekTo -- seeks to the named noun; this takes care of interpriting special // nouns. If the seek fails, then Done() is true and false is returned. // If noun is a special character, then it is altered to what it mapped to. /////////////////////////////////////////////////////////////////////////////// -static bool SeekTo(cDbDataSourceIter* pIter, TSTRING& noun ) +static bool SeekTo(cDbDataSourceIter* pIter, TSTRING& noun) { - if( noun[0] == _T('*') ) + if (noun[0] == _T('*')) { // interprite the rest of the string as a number index to seek to... - int index = _ttoi( &noun[1] ); - if( index < 0 ) + int index = _ttoi(&noun[1]); + if (index < 0) return false; pIter->SeekBegin(); - for( int i=0; ((i < index) && (! pIter->Done())); i++, pIter->Next() ) + for (int i = 0; ((i < index) && (!pIter->Done())); i++, pIter->Next()) { - } - if( pIter->Done() ) + if (pIter->Done()) return false; noun = pIter->GetShortName(); return true; } else - return ( pIter->SeekTo( noun.c_str() ) ); + return (pIter->SeekTo(noun.c_str())); } /////////////////////////////////////////////////////////////////////////////// // PrintFCO /////////////////////////////////////////////////////////////////////////////// -static void PrintFCO( const iFCO* pFCO, const iFCOPropDisplayer* pDisplayer ) +static void PrintFCO(const iFCO* pFCO, const iFCOPropDisplayer* pDisplayer) { TCOUT.setf(std::ios::left); - - TCOUT << _T("------- ") - << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( pFCO->GetName() ) - << _T(" -------") - << std::endl; + + TCOUT << _T("------- ") << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(pFCO->GetName()) + << _T(" -------") << std::endl; // // iterate over all of the properties // const iFCOPropSet* pPropSet = pFCO->GetPropSet(); - cFCOPropVector v = pPropSet->GetValidVector(); - for( int i=0; i < pPropSet->GetNumProps(); i++ ) - { - if( v.ContainsItem( i ) ) + cFCOPropVector v = pPropSet->GetValidVector(); + for (int i = 0; i < pPropSet->GetNumProps(); i++) + { + if (v.ContainsItem(i)) { TCOUT << _T("["); TCOUT.width(2); - TCOUT << i << _T("]") ; + TCOUT << i << _T("]"); TCOUT.width(25); TCOUT << pPropSet->GetPropName(i); TCOUT.width(0); - TCOUT << pDisplayer->PropAsString( pFCO, i ) << std::endl; + TCOUT << pDisplayer->PropAsString(pFCO, i) << std::endl; } } TCOUT << _T("--------------------------------------------") << std::endl; } -static void SplitString( const TSTRING& str, TCHAR c, std::vector& vStrings ) +static void SplitString(const TSTRING& str, TCHAR c, std::vector& vStrings) { vStrings.clear(); TSTRING::const_iterator i, prev; - for( prev = i = str.begin(); i != str.end(); i++ ) + for (prev = i = str.begin(); i != str.end(); ++i) { - if( *i == c ) + if (*i == c) { vStrings.push_back(TSTRING()); - vStrings.back().assign( prev, i ); - prev = i+1; + vStrings.back().assign(prev, i); + prev = i + 1; } } - if( prev != i ) + if (prev != i) { vStrings.push_back(TSTRING()); - vStrings.back().assign( prev, i ); + vStrings.back().assign(prev, i); } } @@ -199,17 +196,17 @@ static void SplitString( const TSTRING& str, TCHAR c, std::vector& vStr /////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// -void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) +void cDbExplore::Execute(cFCODatabaseFileIter& dbIter) { - ASSERT( ! dbIter.Done() ); + ASSERT(!dbIter.Done()); - cDbDataSourceIter* pIter = new cDbDataSourceIter( &dbIter.GetDb(), dbIter.GetGenre() ); + cDbDataSourceIter* pIter = new cDbDataSourceIter(&dbIter.GetDb(), dbIter.GetGenre()); const iFCOPropDisplayer* pDisplayer = dbIter.GetGenreHeader().GetPropDisplayer(); //////////////////////////// // the main event loop... //////////////////////////// - while( true ) + while (true) { TSTRING verb, noun; TCOUT << _T(">>"); @@ -220,7 +217,7 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) //----------------------------------------------------------------- // quit //----------------------------------------------------------------- - if( verb.compare( _T("quit") ) == 0 ) + if (verb.compare(_T("quit")) == 0) { // the quit command... break; @@ -228,15 +225,15 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) //----------------------------------------------------------------- // print //----------------------------------------------------------------- - if( verb.compare( _T("print") ) == 0 ) + if (verb.compare(_T("print")) == 0) { GetNoun(noun); - if( SeekTo( pIter, noun ) ) + if (SeekTo(pIter, noun)) { - if( pIter->HasFCOData() ) + if (pIter->HasFCOData()) { iFCO* pFCO = pIter->CreateFCO(); - PrintFCO( pFCO, pDisplayer ); + PrintFCO(pFCO, pDisplayer); pFCO->Release(); } else @@ -250,28 +247,127 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) } } //----------------------------------------------------------------- + // mkdir + //----------------------------------------------------------------- + else if (verb.compare(_T("mkdir")) == 0) + { + GetNoun(noun); + TCOUT << "Making a child of " << noun << std::endl; + if (pIter->SeekTo(noun.c_str())) + { + pIter->AddChildArray(); + } + else + { + TCOUT << "Unable to find object " << noun << std::endl; + } + } + //----------------------------------------------------------------- + // mk + //----------------------------------------------------------------- + else if (verb.compare(_T("mk")) == 0) + { + GetNoun(noun); + TCOUT << "Making object " << noun << std::endl; + if (pIter->SeekTo(noun.c_str())) + { + TCOUT << "Error: object already exists!" << std::endl; + } + else + { + pIter->AddFCO(noun, 0); // add a null fco for now + } + } + //----------------------------------------------------------------- + // rmdir + //----------------------------------------------------------------- + else if (verb.compare(_T("rmdir")) == 0) + { + GetNoun(noun); + TCOUT << "Removing the child of " << noun << std::endl; + if (pIter->SeekTo(noun.c_str())) + { + if (pIter->CanRemoveChildArray()) + { + pIter->RemoveChildArray(); + } + else + { + TCOUT << "Can't delete object; it still has children." << std::endl; + } + } + else + { + TCOUT << "Unable to find object " << noun << std::endl; + } + } + //----------------------------------------------------------------- + // rm + //----------------------------------------------------------------- + else if (verb.compare(_T("rm")) == 0) + { + GetNoun(noun); + TCOUT << "Removing object " << noun << std::endl; + if (pIter->SeekTo(noun.c_str())) + { + if (pIter->CanDescend()) + { + TCOUT << "Can't delete object; it still has children." << std::endl; + } + else + { + pIter->RemoveFCO(); + } + } + else + { + TCOUT << "Unable to find object " << noun << std::endl; + } + } + else if (verb.compare(_T("rmdata")) == 0) + { + GetNoun(noun); + TCOUT << "Removing object data " << noun << std::endl; + if (pIter->SeekTo(noun.c_str())) + { + if (pIter->CanDescend()) + { + TCOUT << "Can't delete object; it still has children." << std::endl; + } + else + { + pIter->RemoveFCOData(); + } + } + else + { + TCOUT << "Unable to find object " << noun << std::endl; + } + } + //----------------------------------------------------------------- // pwd //----------------------------------------------------------------- - else if( verb.compare( _T("pwd") ) == 0 ) + else if (verb.compare(_T("pwd")) == 0) { - TCOUT << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( pIter->GetParentName() ) << std::endl; + TCOUT << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay(pIter->GetParentName()) + << std::endl; } //----------------------------------------------------------------- // ls //----------------------------------------------------------------- - else if( verb.compare( _T("ls") ) == 0 ) + else if (verb.compare(_T("ls")) == 0) { int cnt = 0; - for( pIter->SeekBegin(); ! pIter->Done(); pIter->Next(), cnt++ ) + for (pIter->SeekBegin(); !pIter->Done(); pIter->Next(), cnt++) { - TCOUT << _T("[") << cnt ; - if( pIter->CanDescend() ) + TCOUT << _T("[") << cnt; + if (pIter->CanDescend()) { - TCOUT << _T("]*\t") ; + TCOUT << _T("]*\t"); } else { - TCOUT << _T("]\t") ; + TCOUT << _T("]\t"); } TCOUT << pIter->GetShortName() << std::endl; } @@ -279,17 +375,17 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) //----------------------------------------------------------------- // cd //----------------------------------------------------------------- - else if( verb.compare( _T("cd") ) == 0 ) + else if (verb.compare(_T("cd")) == 0) { GetNoun(noun); std::vector vDirs; - SplitString( noun, pIter->GetParentName().GetDelimiter(), vDirs ); - for( std::vector::iterator i = vDirs.begin(); i != vDirs.end(); i++ ) + SplitString(noun, pIter->GetParentName().GetDelimiter(), vDirs); + for (std::vector::iterator i = vDirs.begin(); i != vDirs.end(); ++i) { - - if( i->compare( _T("..") ) == 0 ) + + if (i->compare(_T("..")) == 0) { - if( pIter->AtRoot() ) + if (pIter->AtRoot()) { TCOUT << _T("Can't ascend above root.") << std::endl; break; @@ -302,9 +398,9 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) } else { - if( SeekTo( pIter, *i ) ) + if (SeekTo(pIter, *i)) { - if( pIter->CanDescend() ) + if (pIter->CanDescend()) { TCOUT << _T("Descending into ") << *i << std::endl; pIter->Descend(); @@ -326,16 +422,16 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) //----------------------------------------------------------------- // cg //----------------------------------------------------------------- - else if( verb.compare( _T("cg") ) == 0 ) + else if (verb.compare(_T("cg")) == 0) { GetNoun(noun); - cGenre::Genre newGenre = cGenreSwitcher::GetInstance()->StringToGenre( noun.c_str() ); + cGenre::Genre newGenre = cGenreSwitcher::GetInstance()->StringToGenre(noun.c_str()); if (newGenre != cGenre::GENRE_INVALID) { - dbIter.SeekToGenre( newGenre ); - if( !dbIter.Done() ) + dbIter.SeekToGenre(newGenre); + if (!dbIter.Done()) { TCOUT << _T("Changing to Genre ") << noun << std::endl; // @@ -343,7 +439,7 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) // assocaited with a single genre :-( ) // delete pIter; - pIter = new cDbDataSourceIter( &dbIter.GetDb(), newGenre ); + pIter = new cDbDataSourceIter(&dbIter.GetDb(), newGenre); } else { @@ -358,38 +454,37 @@ void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) //----------------------------------------------------------------- // pwg //----------------------------------------------------------------- - else if( verb.compare( _T("pwg") ) == 0 ) + else if (verb.compare(_T("pwg")) == 0) { - TCOUT << _T("Current Genre: ") << cGenreSwitcher::GetInstance()->GenreToString( (cGenre::Genre)dbIter.GetGenre(), true ) << std::endl; + TCOUT << _T("Current Genre: ") + << cGenreSwitcher::GetInstance()->GenreToString((cGenre::Genre)dbIter.GetGenre(), true) << std::endl; } //----------------------------------------------------------------- // help //----------------------------------------------------------------- - if( verb.compare( _T("help") ) == 0 ) + if (verb.compare(_T("help")) == 0) { - TCOUT << _T("Commands: ") << std::endl - << _T(" cd ") << std::endl - << _T(" pwd ") << std::endl - << _T(" ls ") << std::endl - << _T(" print ") << std::endl - << _T(" cg (FS | NTFS | NTREG)")<< std::endl - << _T(" pwg") << std::endl - << _T(" quit") << std::endl; + TCOUT << _T("Commands: ") << std::endl + << _T(" cd ") << std::endl + << _T(" pwd ") << std::endl + << _T(" ls ") << std::endl + << _T(" print ") << std::endl + << _T(" cg (FS | NTFS | NTREG)") << std::endl + << _T(" pwg") << std::endl + << _T(" quit") << std::endl; } // make sure the file is still valid... // - /* + #ifdef _BLOCKFILE_DEBUG - db.AssertAllBlocksValid() ; + dbIter.GetDb().AssertAllBlocksValid(); #endif - */ } delete pIter; TCOUT << _T("Exiting...") << std::endl; - } /////////////////////////////////////////////////////////////////////////////// diff --git a/src/tw/dbexplore.h b/src/tw/dbexplore.h index 388a1e4..ae6a112 100644 --- a/src/tw/dbexplore.h +++ b/src/tw/dbexplore.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,9 +40,8 @@ class cFCODatabaseFileIter; class cDbExplore { public: - static void Execute( cFCODatabaseFileIter& dbIter ); + static void Execute(cFCODatabaseFileIter& dbIter); }; #endif //__DBEXPLORE_H - diff --git a/src/tw/fcodatabasefile.cpp b/src/tw/fcodatabasefile.cpp index 1332f5c..d3de1d5 100644 --- a/src/tw/fcodatabasefile.cpp +++ b/src/tw/fcodatabasefile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,27 +52,26 @@ IMPLEMENT_TYPEDSERIALIZABLE(cFCODatabaseFile, _T("cFCODatabaseFile"), 0, 1) -cFCODatabaseFile::tEntry::tEntry( cGenre::Genre genre ) -//TODO -- ugh, this sucks! I need to add another interface to the database! -: mDb ( cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genre)->GetNameInfo()->IsCaseSensitive(), - cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genre)->GetNameInfo()->GetDelimitingChar() - ), - mGenre( genre ) +cFCODatabaseFile::tEntry::tEntry(cGenre::Genre genre) + //TODO -- ugh, this sucks! I need to add another interface to the database! + : mDb(cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genre)->GetNameInfo()->IsCaseSensitive(), + cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)genre)->GetNameInfo()->GetDelimitingChar()), + mGenre(genre) { } cFCODatabaseFile::cFCODatabaseFile() -#ifdef _DEBUG -: mFileName( _T("Unknown file name") ) +#ifdef DEBUG + : mFileName(_T("Unknown file name")) #else -: mFileName( _T("") ) // If we don't know the filename, lets just not have one in release mode. + : mFileName(_T("")) // If we don't know the filename, lets just not have one in release mode. #endif { } cFCODatabaseFile::~cFCODatabaseFile() { - for( DbList::iterator i = mDbList.begin(); i != mDbList.end(); i++ ) + for (DbList::iterator i = mDbList.begin(); i != mDbList.end(); ++i) { delete *i; } @@ -86,53 +85,55 @@ void cFCODatabaseFile::Read(iSerializer* pSerializer, int32 version) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("Database Read"))); - + // // read the db header.. // - pSerializer->ReadObject( &mHeader ); + pSerializer->ReadObject(&mHeader); int32 numGenre; - pSerializer->ReadInt32( numGenre ); - for( int i=0; i < numGenre; i++ ) + pSerializer->ReadInt32(numGenre); + for (int i = 0; i < numGenre; i++) { // read the genre number and throw if it is incorrect // int32 iGenre; - pSerializer->ReadInt32( iGenre ); - cGenre::Genre genre = (cGenre::Genre) iGenre; + pSerializer->ReadInt32(iGenre); + cGenre::Genre genre = (cGenre::Genre)iGenre; - if( ! cGenreSwitcher::GetInstance()->IsGenreRegistered( genre ) ) + if (!cGenreSwitcher::GetInstance()->IsGenreRegistered(genre)) { - throw eSerializerInputStreamFmt(_T("Encountered unknown genre. Can not read database on this platform."), mFileName, eSerializer::TY_FILE); + throw eSerializerInputStreamFmt(_T("Encountered unknown genre. Can not read database on this platform."), + mFileName, + eSerializer::TY_FILE); } - mDbList.push_back( new tEntry( genre ) ); + mDbList.push_back(new tEntry(genre)); tEntry& entry = *(mDbList.back()); // // read the db genre header.. // - pSerializer->ReadObject( &entry.mGenreHeader ); + pSerializer->ReadObject(&entry.mGenreHeader); // // get the spec list // - pSerializer->ReadObject( &entry.mSpecList ); + pSerializer->ReadObject(&entry.mSpecList); // // get the database data // int32 fileSize; - pSerializer->ReadInt32( fileSize ); + pSerializer->ReadInt32(fileSize); // // write the hier database into a temp file... // cLockedTemporaryFileArchive* pArch = new cLockedTemporaryFileArchive(); pArch->OpenReadWrite(); - cSerializerUtil::Copy( pArch, pSerializer, fileSize ); + cSerializerUtil::Copy(pArch, pSerializer, fileSize); // // associate the database with this file... // - entry.mDb.Open( pArch ); + entry.mDb.Open(pArch); } } @@ -140,37 +141,37 @@ void cFCODatabaseFile::Read(iSerializer* pSerializer, int32 version) // Write /////////////////////////////////////////////////////////////////////////////// void cFCODatabaseFile::Write(iSerializer* pSerializer) const //throw( eFCODbFileTooBig ) -{ +{ // // write the db header.. // - pSerializer->WriteObject( &mHeader ); + pSerializer->WriteObject(&mHeader); // iterate through the genres, writing each one... // - pSerializer->WriteInt32( mDbList.size() ); + pSerializer->WriteInt32(mDbList.size()); // // TODO -- the database is not really const-correct; therefore I have the sick casts below... // - for( DbList::iterator i = const_cast(&mDbList)->begin(); i != const_cast(&mDbList)->end(); i++ ) + for (DbList::iterator i = const_cast(&mDbList)->begin(); i != const_cast(&mDbList)->end(); ++i) { - pSerializer->WriteInt32 ( (*i)->mGenre ); - pSerializer->WriteObject ( &(*i)->mGenreHeader ); - pSerializer->WriteObject ( &(*i)->mSpecList ); + pSerializer->WriteInt32((*i)->mGenre); + pSerializer->WriteObject(&(*i)->mGenreHeader); + pSerializer->WriteObject(&(*i)->mSpecList); // // copy the database's data into the archive... // (*i)->mDb.Flush(); cBidirArchive* pDbArch = (*i)->mDb.GetArchive(); - pDbArch->Seek( 0, cBidirArchive::BEGINNING ); + pDbArch->Seek(0, cBidirArchive::BEGINNING); // TODO:BAM -- eventually we should write it as a 64 bit, // but that would change the db format - if( pDbArch->Length() > TSS_INT32_MAX ) + if (pDbArch->Length() > TSS_INT32_MAX) throw eFCODbFileTooBig(); - pSerializer->WriteInt32( static_cast( pDbArch->Length() ) ); - cSerializerUtil::Copy( pSerializer, pDbArch, pDbArch->Length() ); + pSerializer->WriteInt32(static_cast(pDbArch->Length())); + cSerializerUtil::Copy(pSerializer, pDbArch, pDbArch->Length()); } } @@ -188,34 +189,33 @@ const cFileHeaderID& cFCODatabaseFile::GetFileHeaderID() /////////////////////////////////////////////////////////////////////////////// // AddGenre /////////////////////////////////////////////////////////////////////////////// -void cFCODatabaseFile::AddGenre( cGenre::Genre genreId, cFCODatabaseFileIter* pIter ) +void cFCODatabaseFile::AddGenre(cGenre::Genre genreId, cFCODatabaseFileIter* pIter) { // // first, lets make sure this genre doesn't exist... // - for( DbList::iterator i = mDbList.begin(); i != mDbList.end(); i++ ) + for (DbList::iterator i = mDbList.begin(); i != mDbList.end(); ++i) { - if( (*i)->mGenre == genreId ) + if ((*i)->mGenre == genreId) { - ASSERT( false ); + ASSERT(false); return; } } - // + // // just add it to the front; I don't care about order // - mDbList.push_back( new tEntry( genreId ) ); - if( pIter ) + mDbList.push_back(new tEntry(genreId)); + if (pIter) { - pIter->mIter = mDbList.end()-1; + pIter->mIter = mDbList.end() - 1; } // // create a new prop displayer for the header. // - mDbList.back()->mGenreHeader.SetPropDisplayer - ( - cGenreSwitcher::GetInstance()->GetFactoryForGenre((cGenre::Genre)mDbList.back()->mGenre)->CreatePropDisplayer() - ); + mDbList.back()->mGenreHeader.SetPropDisplayer(cGenreSwitcher::GetInstance() + ->GetFactoryForGenre((cGenre::Genre)mDbList.back()->mGenre) + ->CreatePropDisplayer()); // // open the database // @@ -224,29 +224,27 @@ void cFCODatabaseFile::AddGenre( cGenre::Genre genreId, cFCODatabaseFileIter* pI // cLockedTemporaryFileArchive* pArch = new cLockedTemporaryFileArchive(); pArch->OpenReadWrite(); - mDbList.back()->mDb.Open( pArch ); - + mDbList.back()->mDb.Open(pArch); } - void cFCODatabaseFile::SetFileName( const TSTRING& name ) +void cFCODatabaseFile::SetFileName(const TSTRING& name) { mFileName = name; } - TSTRING cFCODatabaseFile::GetFileName() const +TSTRING cFCODatabaseFile::GetFileName() const { return mFileName; -} +} //----------------------------------------------------------------------------- // cFCODatabaseFileIter //----------------------------------------------------------------------------- -cFCODatabaseFileIter::cFCODatabaseFileIter( cFCODatabaseFile& dbFile ) -: mDbFile( dbFile ) -{ - SeekBegin(); +cFCODatabaseFileIter::cFCODatabaseFileIter(cFCODatabaseFile& dbFile) : mDbFile(dbFile) +{ + SeekBegin(); } - + void cFCODatabaseFileIter::SeekBegin() { mIter = mDbFile.mDbList.begin(); @@ -254,74 +252,71 @@ void cFCODatabaseFileIter::SeekBegin() void cFCODatabaseFileIter::Next() { - mIter++; + ++mIter; } bool cFCODatabaseFileIter::Done() const { - return ( mIter == mDbFile.mDbList.end() ); + return (mIter == mDbFile.mDbList.end()); } void cFCODatabaseFileIter::SeekToGenre(cGenre::Genre genreId) { - for( SeekBegin(); ! Done(); Next() ) + for (SeekBegin(); !Done(); Next()) { - if( GetGenre() == genreId ) + if (GetGenre() == genreId) return; } } void cFCODatabaseFileIter::Remove() { - ASSERT( ! Done() ); - if( ! Done() ) + ASSERT(!Done()); + if (!Done()) { delete *mIter; - mIter = mDbFile.mDbList.erase( mIter ); + mIter = mDbFile.mDbList.erase(mIter); } } -cGenre::Genre cFCODatabaseFileIter::GetGenre() const +cGenre::Genre cFCODatabaseFileIter::GetGenre() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mGenre; } -cHierDatabase& cFCODatabaseFileIter::GetDb() +cHierDatabase& cFCODatabaseFileIter::GetDb() { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mDb; } const cHierDatabase& cFCODatabaseFileIter::GetDb() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mDb; - } cFCOSpecList& cFCODatabaseFileIter::GetSpecList() { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mSpecList; } const cFCOSpecList& cFCODatabaseFileIter::GetSpecList() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mSpecList; } const cFCODbGenreHeader& cFCODatabaseFileIter::GetGenreHeader() const { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mGenreHeader; } cFCODbGenreHeader& cFCODatabaseFileIter::GetGenreHeader() { - ASSERT( ! Done() ); + ASSERT(!Done()); return (*mIter)->mGenreHeader; } - - diff --git a/src/tw/fcodatabasefile.h b/src/tw/fcodatabasefile.h index 907596d..ddf7e18 100644 --- a/src/tw/fcodatabasefile.h +++ b/src/tw/fcodatabasefile.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -55,10 +55,10 @@ class cElGamalSigPrivateKey; #endif #ifndef __SERIALIZABLE_H #include "core/serializable.h" -#endif +#endif #ifndef __HEADERINFO_H #include "tw/headerinfo.h" -#endif +#endif #ifndef __ERROR_H #include "core/error.h" #endif @@ -72,8 +72,8 @@ class cElGamalSigPrivateKey; // TODO -- figure out some way to templatize this class based on encryption method // -TSS_EXCEPTION( eFCODbFile, eError ); -TSS_EXCEPTION( eFCODbFileTooBig, eFCODbFile ); +TSS_EXCEPTION(eFCODbFile, eError); +TSS_EXCEPTION(eFCODbFileTooBig, eFCODbFile); //----------------------------------------------------------------------------- // cFCODatabaseFile -- class that manages a set of databases (for different genres @@ -85,12 +85,12 @@ class cFCODatabaseFile : public iTypedSerializable cFCODatabaseFile(); virtual ~cFCODatabaseFile(); - void SetFileName( const TSTRING& name ); + void SetFileName(const TSTRING& name); TSTRING GetFileName() const; - // the file name is only used in exception throwing; it is not necessary to set it. + // the file name is only used in exception throwing; it is not necessary to set it. - void AddGenre( cGenre::Genre genreId, cFCODatabaseFileIter* pIter = 0 ); //throw (eArchive) - // if pIter is not null, then it is pointing at the new node. This asserts that the + void AddGenre(cGenre::Genre genreId, cFCODatabaseFileIter* pIter = 0); //throw (eArchive) + // if pIter is not null, then it is pointing at the new node. This asserts that the // genre doesn't currently exist cFCODbHeader& GetHeader(); @@ -100,42 +100,41 @@ class cFCODatabaseFile : public iTypedSerializable /////////////////////////////// // serialization interface /////////////////////////////// - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + - typedef cFCODatabaseFileIter iterator; //------------------------------------------------------------------------- - // cEntry -- a single entry in the database -- represents a genre's database + // cEntry -- a single entry in the database -- represents a genre's database // note that if the entry hasn't been loaded from disk yet, all of its // data members are NULL //------------------------------------------------------------------------- struct tEntry { - tEntry( cGenre::Genre genre ); - // the ctor will get the appropriate database construction parameters - // based on the genre number. - ~tEntry( ) + explicit tEntry(cGenre::Genre genre); + // the ctor will get the appropriate database construction parameters + // based on the genre number. + ~tEntry() { - } - cHierDatabase mDb; // the database; - cFCODbGenreHeader mGenreHeader; - cFCOSpecList mSpecList; // the spec used to create the database - cGenre::Genre mGenre; // the genre this is associated with + cHierDatabase mDb; // the database; + cFCODbGenreHeader mGenreHeader; + cFCOSpecList mSpecList; // the spec used to create the database + cGenre::Genre mGenre; // the genre this is associated with }; private: - cFCODatabaseFile( const cFCODatabaseFile& rhs ); //not impl - void operator= ( const cFCODatabaseFile& rhs ); //not impl - + cFCODatabaseFile(const cFCODatabaseFile& rhs); //not impl + void operator=(const cFCODatabaseFile& rhs); //not impl + typedef std::vector DbList; friend class cFCODatabaseFileIter; - cFCODbHeader mHeader; - DbList mDbList; // the list of databases - TSTRING mFileName; // for cosmetic purposes only + cFCODbHeader mHeader; + DbList mDbList; // the list of databases + TSTRING mFileName; // for cosmetic purposes only DECLARE_TYPEDSERIALIZABLE() }; @@ -146,29 +145,32 @@ class cFCODatabaseFile : public iTypedSerializable class cFCODatabaseFileIter { public: - cFCODatabaseFileIter( cFCODatabaseFile& dbFile ); + explicit cFCODatabaseFileIter(cFCODatabaseFile& dbFile); - void SeekBegin(); - void Next(); - bool Done() const; - int Size() const { return mDbFile.mDbList.size(); } + void SeekBegin(); + void Next(); + bool Done() const; + int Size() const + { + return mDbFile.mDbList.size(); + } void SeekToGenre(cGenre::Genre genreId); - // Done() is true if the genre doesn't exist + // Done() is true if the genre doesn't exist void Remove(); - // removes the current node from the database file + // removes the current node from the database file - cGenre::Genre GetGenre() const; - cHierDatabase& GetDb() ; - const cHierDatabase& GetDb() const; - cFCOSpecList& GetSpecList(); - const cFCOSpecList& GetSpecList() const; - cFCODbGenreHeader& GetGenreHeader(); - const cFCODbGenreHeader& GetGenreHeader() const; + cGenre::Genre GetGenre() const; + cHierDatabase& GetDb(); + const cHierDatabase& GetDb() const; + cFCOSpecList& GetSpecList(); + const cFCOSpecList& GetSpecList() const; + cFCODbGenreHeader& GetGenreHeader(); + const cFCODbGenreHeader& GetGenreHeader() const; private: - cFCODatabaseFile& mDbFile ; - cFCODatabaseFile::DbList::iterator mIter; + cFCODatabaseFile& mDbFile; + cFCODatabaseFile::DbList::iterator mIter; friend class cFCODatabaseFile; }; @@ -183,4 +185,3 @@ inline cFCODbHeader& cFCODatabaseFile::GetHeader() } #endif //__FCODATABASEFILE_H - diff --git a/src/tw/fcodatabaseutil.cpp b/src/tw/fcodatabaseutil.cpp index a300cf2..9aee185 100644 --- a/src/tw/fcodatabaseutil.cpp +++ b/src/tw/fcodatabaseutil.cpp @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////////////// -//fcodatabaseutil.cpp : Implements functions for maintaining +//fcodatabaseutil.cpp : Implements functions for maintaining // fcodatabase objects. #include "stdtw.h" @@ -53,28 +53,24 @@ // cFCODatabaseUtil /////////////////////////////////////////////////////////////////////////////////////// -void cFCODatabaseUtil::CalculateHeader( - cFCODbHeader& dbHeader, - const TSTRING& policyFilename, - const TSTRING& configFilename, - const TSTRING& dbFilename, - const TSTRING& commandLineParams, - int64 createTime, - int64 lastDBUpdateTime - ) +void cFCODatabaseUtil::CalculateHeader(cFCODbHeader& dbHeader, + const TSTRING& policyFilename, + const TSTRING& configFilename, + const TSTRING& dbFilename, + const TSTRING& commandLineParams, + int64 createTime, + int64 lastDBUpdateTime) { cDebug d("cFCODatabaseUtil::CalculateHeaderInfo"); - dbHeader.SetPolicyFilename (policyFilename); - dbHeader.SetConfigFilename (configFilename); - dbHeader.SetDBFilename (dbFilename); - dbHeader.SetSystemName (cTWUtil::GetSystemName()); - dbHeader.SetCommandLineParams (commandLineParams); - dbHeader.SetIPAddress (cTWUtil::GetIPAddress()); - dbHeader.SetCreator (cTWUtil::GetCurrentUser()); - dbHeader.SetHostID (cTWUtil::GetHostID()); - dbHeader.SetCreationTime (createTime); - dbHeader.SetLastDBUpdateTime (lastDBUpdateTime); + dbHeader.SetPolicyFilename(policyFilename); + dbHeader.SetConfigFilename(configFilename); + dbHeader.SetDBFilename(dbFilename); + dbHeader.SetSystemName(cTWUtil::GetSystemName()); + dbHeader.SetCommandLineParams(commandLineParams); + dbHeader.SetIPAddress(cTWUtil::GetIPAddress()); + dbHeader.SetCreator(cTWUtil::GetCurrentUser()); + dbHeader.SetHostID(cTWUtil::GetHostID()); + dbHeader.SetCreationTime(createTime); + dbHeader.SetLastDBUpdateTime(lastDBUpdateTime); } - - diff --git a/src/tw/fcodatabaseutil.h b/src/tw/fcodatabaseutil.h index 5ab2d72..95f8419 100644 --- a/src/tw/fcodatabaseutil.h +++ b/src/tw/fcodatabaseutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,33 +40,30 @@ #endif #ifndef __FCODATABASEUTIL_H -#define __FCODATABASEUTIL_H +# define __FCODATABASEUTIL_H //Forward Class Declarations: class cFCODbHeader; class cFCODBHeaderInfo; //============================================================================= -// cFCODatabaseUtil -- A Utility class for cFCODatabase Objects. Contains static -// functions for calculating and storing system properties before saving a +// cFCODatabaseUtil -- A Utility class for cFCODatabase Objects. Contains static +// functions for calculating and storing system properties before saving a // database object. //============================================================================= -class cFCODatabaseUtil +class cFCODatabaseUtil { public: - static void CalculateHeader( - cFCODbHeader& dbHeader, - const TSTRING& policyFilename, - const TSTRING& configFilename, - const TSTRING& dbFilename, - const TSTRING& commandLineParams, - int64 createTime, - int64 lastDBUpdateTime - ); - //Calculates and gathers header data, stores results in header. + static void CalculateHeader(cFCODbHeader& dbHeader, + const TSTRING& policyFilename, + const TSTRING& configFilename, + const TSTRING& dbFilename, + const TSTRING& commandLineParams, + int64 createTime, + int64 lastDBUpdateTime); + //Calculates and gathers header data, stores results in header. private: }; #endif //__FCODATABASEUTIL_H - diff --git a/src/tw/fcoreport.cpp b/src/tw/fcoreport.cpp index 9084cac..a5f5ca8 100644 --- a/src/tw/fcoreport.cpp +++ b/src/tw/fcoreport.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -57,7 +57,7 @@ // class cFCOReport_i //============================================================================= -class cFCOReport_i +class cFCOReport_i { public: cFCOReport_i(); @@ -67,25 +67,25 @@ class cFCOReport_i // and will be Release()d when deleted. struct cChangeNode { - const iFCO* mpOldFCO; - const iFCO* mpNewFCO; - cFCOPropVector mChangeVector; - + const iFCO* mpOldFCO; + const iFCO* mpNewFCO; + cFCOPropVector mChangeVector; + cChangeNode(); cChangeNode(const cChangeNode& rhs); ~cChangeNode(); void Clear(); }; - + struct cNode { - iFCOSpec* mpSpec; // _must_ be valid (non-0) - const cFCOSpecAttr* mpSpecAttr; // _must_ be valid (non-0) - cFCOSetWS mAdded; // these two sets make sure their fcos are in mpSpec. - cFCOSetWS mRemoved; - std::list mChanged; - cErrorQueue mErrorQueue; - int32 mnObjectsScanned; + iFCOSpec* mpSpec; // _must_ be valid (non-0) + const cFCOSpecAttr* mpSpecAttr; // _must_ be valid (non-0) + cFCOSetWS mAdded; // these two sets make sure their fcos are in mpSpec. + cFCOSetWS mRemoved; + std::list mChanged; + cErrorQueue mErrorQueue; + int32 mnObjectsScanned; cNode(); cNode(const cNode& rhs); @@ -94,27 +94,27 @@ class cFCOReport_i }; - typedef std::list SpecList; - + typedef std::list SpecList; + struct cGenreNode { - cGenreNode() {}; - cGenreNode( const cGenreNode& rhs ); - cFCOReportGenreHeader mGenreHeader; - cGenre::Genre mGenre; - SpecList mSpecList; + cGenreNode(){}; + cGenreNode(const cGenreNode& rhs); + cFCOReportGenreHeader mGenreHeader; + cGenre::Genre mGenre; + SpecList mSpecList; }; - typedef std::list GenreSpecList; - + typedef std::list GenreSpecList; + // data members - cErrorQueue mErrorQueue; // the general error queue - GenreSpecList mGenreList; + cErrorQueue mErrorQueue; // the general error queue + GenreSpecList mGenreList; }; -cFCOReport_i::cGenreNode::cGenreNode( const cFCOReport_i::cGenreNode& rhs ) - : mGenreHeader( rhs.mGenreHeader ), mGenre( rhs.mGenre ), mSpecList( rhs.mSpecList ) +cFCOReport_i::cGenreNode::cGenreNode(const cFCOReport_i::cGenreNode& rhs) + : mGenreHeader(rhs.mGenreHeader), mGenre(rhs.mGenre), mSpecList(rhs.mSpecList) { } @@ -127,9 +127,7 @@ cFCOReport_i::~cFCOReport_i() } -cFCOReport_i::cChangeNode::cChangeNode() -: mpOldFCO(0), - mpNewFCO(0) +cFCOReport_i::cChangeNode::cChangeNode() : mpOldFCO(0), mpNewFCO(0) { } @@ -153,25 +151,18 @@ cFCOReport_i::cChangeNode::~cChangeNode() void cFCOReport_i::cChangeNode::Clear() { - if(mpOldFCO) + if (mpOldFCO) mpOldFCO->Release(); - if(mpNewFCO) + if (mpNewFCO) mpNewFCO->Release(); mpOldFCO = mpNewFCO = 0; } -cFCOReport_i::cNode::cNode() : - mpSpec(0), - mpSpecAttr(0), - mAdded(0), - mRemoved(0), - mnObjectsScanned(0) +cFCOReport_i::cNode::cNode() : mpSpec(0), mpSpecAttr(0), mAdded(0), mRemoved(0), mnObjectsScanned(0) { } -cFCOReport_i::cNode::cNode(const cFCOReport_i::cNode& rhs) -: mAdded(rhs.mAdded), - mRemoved(rhs.mRemoved) +cFCOReport_i::cNode::cNode(const cFCOReport_i::cNode& rhs) : mAdded(rhs.mAdded), mRemoved(rhs.mRemoved) { mpSpec = rhs.mpSpec; if (mpSpec) @@ -181,8 +172,8 @@ cFCOReport_i::cNode::cNode(const cFCOReport_i::cNode& rhs) if (mpSpecAttr) mpSpecAttr->AddRef(); - mChanged = rhs.mChanged; - mErrorQueue = rhs.mErrorQueue; + mChanged = rhs.mChanged; + mErrorQueue = rhs.mErrorQueue; mnObjectsScanned = rhs.mnObjectsScanned; } @@ -199,12 +190,12 @@ void cFCOReport_i::cNode::Clear() mRemoved.SetSpec(0); mChanged.clear(); mErrorQueue.Clear(); - if(mpSpec) + if (mpSpec) mpSpec->Release(); - if(mpSpecAttr) + if (mpSpecAttr) mpSpecAttr->Release(); - mpSpec = 0; - mpSpecAttr = 0; + mpSpec = 0; + mpSpecAttr = 0; mnObjectsScanned = 0; } @@ -215,8 +206,8 @@ void cFCOReport_i::cNode::Clear() class cFCOReportGenreIter_i { public: - cFCOReport_i::GenreSpecList* mpList; - cFCOReport_i::GenreSpecList::iterator mIter; + cFCOReport_i::GenreSpecList* mpList; + cFCOReport_i::GenreSpecList::iterator mIter; }; cFCOReportGenreIter::cFCOReportGenreIter(const cFCOReport& report) @@ -224,7 +215,7 @@ cFCOReportGenreIter::cFCOReportGenreIter(const cFCOReport& report) mpData = new cFCOReportGenreIter_i; mpData->mpList = &report.mpData->mGenreList; - mpData->mIter = mpData->mpList->begin(); + mpData->mIter = mpData->mpList->begin(); } cFCOReportGenreIter::cFCOReportGenreIter(const cFCOReportGenreIter& rhs) @@ -239,10 +230,12 @@ cFCOReportGenreIter::~cFCOReportGenreIter() delete mpData; } -void cFCOReportGenreIter::operator=(const cFCOReportGenreIter& rhs) +cFCOReportGenreIter& cFCOReportGenreIter::operator=(const cFCOReportGenreIter& rhs) { mpData->mpList = rhs.mpData->mpList; - mpData->mIter = rhs.mpData->mIter; + mpData->mIter = rhs.mpData->mIter; + + return *this; } // iteration methods @@ -264,7 +257,7 @@ bool cFCOReportGenreIter::Done() const // seeks to specific genre. Returns false if genre does not exist in report bool cFCOReportGenreIter::SeekToGenre(cGenre::Genre genre) { - for (mpData->mIter = mpData->mpList->begin(); ; ++mpData->mIter) + for (mpData->mIter = mpData->mpList->begin();; ++mpData->mIter) { if (mpData->mIter == mpData->mpList->end()) return false; @@ -290,7 +283,7 @@ cFCOReportGenreHeader& cFCOReportGenreIter::GetGenreHeader() const } // Get current genre -cGenre::Genre cFCOReportGenreIter::GetGenre() const +cGenre::Genre cFCOReportGenreIter::GetGenre() const { if (mpData->mIter == mpData->mpList->end()) { @@ -308,8 +301,8 @@ cGenre::Genre cFCOReportGenreIter::GetGenre() const class cFCOReportSpecIter_i { public: - cFCOReport_i::SpecList* mpList; - cFCOReport_i::SpecList::iterator mIter; + cFCOReport_i::SpecList* mpList; + cFCOReport_i::SpecList::iterator mIter; }; ///////////////////////// @@ -320,7 +313,7 @@ cFCOReportSpecIter::cFCOReportSpecIter(const cFCOReport& report, cGenre::Genre g mpData = 0; cFCOReport_i::GenreSpecList::iterator genreIter; - for (genreIter = report.mpData->mGenreList.begin(); ; ++genreIter) + for (genreIter = report.mpData->mGenreList.begin();; ++genreIter) { if (genreIter == report.mpData->mGenreList.end()) { @@ -332,7 +325,7 @@ cFCOReportSpecIter::cFCOReportSpecIter(const cFCOReport& report, cGenre::Genre g break; } - mpData = new cFCOReportSpecIter_i(); + mpData = new cFCOReportSpecIter_i(); mpData->mpList = &genreIter->mSpecList; mpData->mIter = mpData->mpList->begin(); } @@ -342,7 +335,7 @@ cFCOReportSpecIter::cFCOReportSpecIter(cFCOReport& report, cGenre::Genre genre) mpData = 0; cFCOReport_i::GenreSpecList::iterator genreIter; - for (genreIter = report.mpData->mGenreList.begin(); ; ++genreIter) + for (genreIter = report.mpData->mGenreList.begin();; ++genreIter) { if (genreIter == report.mpData->mGenreList.end()) { @@ -357,14 +350,14 @@ cFCOReportSpecIter::cFCOReportSpecIter(cFCOReport& report, cGenre::Genre genre) break; } - mpData = new cFCOReportSpecIter_i(); + mpData = new cFCOReportSpecIter_i(); mpData->mpList = &genreIter->mSpecList; mpData->mIter = mpData->mpList->begin(); } cFCOReportSpecIter::cFCOReportSpecIter(const cFCOReportGenreIter& genreIter) { - mpData = new cFCOReportSpecIter_i(); + mpData = new cFCOReportSpecIter_i(); mpData->mpList = &genreIter.mpData->mIter->mSpecList; mpData->mIter = mpData->mpList->begin(); } @@ -377,25 +370,27 @@ cFCOReportSpecIter::~cFCOReportSpecIter() cFCOReportSpecIter::cFCOReportSpecIter(const cFCOReportSpecIter& rhs) { mpData = new cFCOReportSpecIter_i(); - *this = rhs; + *this = rhs; } -void cFCOReportSpecIter::operator=(const cFCOReportSpecIter& rhs) +cFCOReportSpecIter& cFCOReportSpecIter::operator=(const cFCOReportSpecIter& rhs) { if (mpData == 0) mpData = new cFCOReportSpecIter_i(); - mpData->mpList = rhs.mpData->mpList; - mpData->mIter = rhs.mpData->mIter; + mpData->mpList = rhs.mpData->mpList; + mpData->mIter = rhs.mpData->mIter; + + return *this; } int cFCOReportSpecIter::GetNumChanged() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? mpData->mIter->mChanged.size() : 0; } -void cFCOReportSpecIter::SetObjectsScanned( int nObjectsScanned ) +void cFCOReportSpecIter::SetObjectsScanned(int nObjectsScanned) { ASSERT(mpData != 0); if (mpData == 0) @@ -406,13 +401,13 @@ void cFCOReportSpecIter::SetObjectsScanned( int nObjectsScanned ) int cFCOReportSpecIter::GetObjectsScanned() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? mpData->mIter->mnObjectsScanned : 0; } void cFCOReportSpecIter::Remove() { - ASSERT(! Done()); + ASSERT(!Done()); mpData->mIter->Clear(); mpData->mIter = mpData->mpList->erase(mpData->mIter); } @@ -429,7 +424,7 @@ void cFCOReportSpecIter::SeekBegin() const void cFCOReportSpecIter::Next() const { ASSERT(mpData != 0); - mpData->mIter++; + ++(mpData->mIter); } bool cFCOReportSpecIter::Done() const @@ -439,16 +434,16 @@ bool cFCOReportSpecIter::Done() const const iFCOSpec* cFCOReportSpecIter::GetSpec() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (mpData->mIter->mpSpec) : 0; } bool cFCOReportSpecIter::SeekToSpec(const iFCOSpec* pSpec) { if (mpData) - for(mpData->mIter = mpData->mpList->begin(); mpData->mIter != mpData->mpList->end(); mpData->mIter++) + for (mpData->mIter = mpData->mpList->begin(); mpData->mIter != mpData->mpList->end(); ++(mpData->mIter)) { - if(iFCOSpecUtil::FCOSpecEqual(*mpData->mIter->mpSpec, *pSpec)) + if (iFCOSpecUtil::FCOSpecEqual(*mpData->mIter->mpSpec, *pSpec)) return true; } @@ -457,43 +452,43 @@ bool cFCOReportSpecIter::SeekToSpec(const iFCOSpec* pSpec) const cFCOSpecAttr* cFCOReportSpecIter::GetAttr() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (mpData->mIter->mpSpecAttr) : 0; } const cErrorQueue* cFCOReportSpecIter::GetErrorQueue() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mErrorQueue) : 0; } -cErrorQueue* cFCOReportSpecIter::GetErrorQueue() +cErrorQueue* cFCOReportSpecIter::GetErrorQueue() { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mErrorQueue) : 0; } -const iFCOSet* cFCOReportSpecIter::GetAddedSet() const +const iFCOSet* cFCOReportSpecIter::GetAddedSet() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mAdded) : 0; } iFCOSet* cFCOReportSpecIter::GetAddedSet() { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mAdded) : 0; } -const iFCOSet* cFCOReportSpecIter::GetRemovedSet() const +const iFCOSet* cFCOReportSpecIter::GetRemovedSet() const { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mRemoved) : 0; } iFCOSet* cFCOReportSpecIter::GetRemovedSet() { - ASSERT(! Done()); + ASSERT(!Done()); return mpData ? (&mpData->mIter->mRemoved) : 0; } @@ -503,8 +498,8 @@ iFCOSet* cFCOReportSpecIter::GetRemovedSet() class cFCOReportChangeIter_i { public: - std::list* mpList; - std::list::iterator mIter; + std::list* mpList; + std::list::iterator mIter; }; cFCOReportChangeIter::cFCOReportChangeIter(const cFCOReportSpecIter& specIter) @@ -514,17 +509,10 @@ cFCOReportChangeIter::cFCOReportChangeIter(const cFCOReportSpecIter& specIter) SetSpecIter(specIter); } -cFCOReportChangeIter::cFCOReportChangeIter() -{ - mpData = new cFCOReportChangeIter_i; - mpData->mpList = 0; - mpData->mIter = mpData->mpList->begin(); -} - cFCOReportChangeIter::cFCOReportChangeIter(const cFCOReportChangeIter& rhs) { mpData = new cFCOReportChangeIter_i; - *this = rhs; + *this = rhs; } cFCOReportChangeIter::~cFCOReportChangeIter() @@ -532,17 +520,19 @@ cFCOReportChangeIter::~cFCOReportChangeIter() delete mpData; } -void cFCOReportChangeIter::operator=(const cFCOReportChangeIter& rhs) +cFCOReportChangeIter& cFCOReportChangeIter::operator=(const cFCOReportChangeIter& rhs) { - mpData->mpList = rhs.mpData->mpList; - mpData->mIter = rhs.mpData->mIter; + mpData->mpList = rhs.mpData->mpList; + mpData->mIter = rhs.mpData->mIter; + + return *this; } void cFCOReportChangeIter::SetSpecIter(const cFCOReportSpecIter& specIter) { - ASSERT(! specIter.Done()); + ASSERT(!specIter.Done()); mpData->mpList = &specIter.mpData->mIter->mChanged; - mpData->mIter = mpData->mpList->begin(); + mpData->mIter = mpData->mpList->begin(); } /////////////////////////////////////////////////////////////////////////////// @@ -550,12 +540,12 @@ void cFCOReportChangeIter::SetSpecIter(const cFCOReportSpecIter& specIter) /////////////////////////////////////////////////////////////////////////////// void cFCOReportChangeIter::Remove() { - ASSERT(! Done()); + ASSERT(!Done()); mpData->mIter->Clear(); mpData->mIter = mpData->mpList->erase(mpData->mIter); } -void cFCOReportChangeIter::SeekBegin() const +void cFCOReportChangeIter::SeekBegin() const { ASSERT(mpData->mpList != 0); mpData->mIter = mpData->mpList->begin(); @@ -564,34 +554,34 @@ void cFCOReportChangeIter::SeekBegin() const void cFCOReportChangeIter::Next() const { ASSERT(mpData->mpList != 0); - mpData->mIter++; + ++(mpData->mIter); } bool cFCOReportChangeIter::Done() const { ASSERT(mpData->mpList != 0); - if(! mpData->mpList) + if (!mpData->mpList) return true; return (mpData->mIter == mpData->mpList->end()); } const iFCO* cFCOReportChangeIter::GetOld() const { - ASSERT(! Done()); + ASSERT(!Done()); return (mpData->mIter->mpOldFCO); } const iFCO* cFCOReportChangeIter::GetNew() const { - ASSERT(! Done()); + ASSERT(!Done()); return (mpData->mIter->mpNewFCO); } -const cFCOPropVector& cFCOReportChangeIter::GetChangeVector() const +const cFCOPropVector& cFCOReportChangeIter::GetChangeVector() const { - ASSERT(! Done()); + ASSERT(!Done()); return (mpData->mIter->mChangeVector); } @@ -630,7 +620,7 @@ const cErrorQueue* cFCOReport::GetErrorQueue() const int cFCOReport::GetNumSpecs(cGenre::Genre genre) const { cFCOReport_i::GenreSpecList::iterator genreIter; - for (genreIter = mpData->mGenreList.begin(); ; ++genreIter) + for (genreIter = mpData->mGenreList.begin();; ++genreIter) { if (genreIter == mpData->mGenreList.end()) { @@ -655,17 +645,20 @@ void cFCOReport::ClearReport() /////////////////////////////////////////////////////////////////////////////// // AddSpec /////////////////////////////////////////////////////////////////////////////// -void cFCOReport::AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOSpecAttr* pAttr, cFCOReportSpecIter* pIter) +void cFCOReport::AddSpec(cGenre::Genre genre, + const iFCOSpec* pSpec, + const cFCOSpecAttr* pAttr, + cFCOReportSpecIter* pIter) { // look up the genre cFCOReport_i::GenreSpecList::iterator genreIter; - for (genreIter = mpData->mGenreList.begin(); ; ++genreIter) + for (genreIter = mpData->mGenreList.begin();; ++genreIter) { if (genreIter == mpData->mGenreList.end()) { cFCOReport_i::cGenreNode newGenre; newGenre.mGenre = genre; - + mpData->mGenreList.push_back(newGenre); genreIter = mpData->mGenreList.end(); @@ -686,10 +679,10 @@ void cFCOReport::AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOS // make sure this spec doesn't overlap any others cFCOReport_i::SpecList::iterator specIter; - for(specIter = genreIter->mSpecList.begin(); specIter != genreIter->mSpecList.end(); ++specIter) + for (specIter = genreIter->mSpecList.begin(); specIter != genreIter->mSpecList.end(); ++specIter) { // TODO -- what is the right action to take? - if(iFCOSpecUtil::SpecsOverlap(pSpec, specIter->mpSpec)) + if (iFCOSpecUtil::SpecsOverlap(pSpec, specIter->mpSpec)) { ASSERT(false); THROW_INTERNAL("fcoreport.cpp"); @@ -698,8 +691,8 @@ void cFCOReport::AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOS genreIter->mSpecList.push_back(cFCOReport_i::cNode()); cFCOReport_i::cNode& node = genreIter->mSpecList.back(); - node.mpSpec = pSpec->Clone(); - node.mpSpecAttr = pAttr; + node.mpSpec = pSpec->Clone(); + node.mpSpecAttr = pAttr; pAttr->AddRef(); node.mAdded.SetSpec(node.mpSpec); node.mRemoved.SetSpec(node.mpSpec); @@ -708,7 +701,7 @@ void cFCOReport::AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOS if (pIter && pIter->mpData && pIter->mpData->mpList == &genreIter->mSpecList) { pIter->mpData->mIter = genreIter->mSpecList.end(); - pIter->mpData->mIter--; + --(pIter->mpData->mIter); ASSERT(pIter->GetSpec() == node.mpSpec); } } @@ -717,29 +710,32 @@ void cFCOReport::AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOS /////////////////////////////////////////////////////////////////////////////// // AddChangedFCO /////////////////////////////////////////////////////////////////////////////// -void cFCOReport::AddChangedFCO(const cFCOReportSpecIter& iter, const iFCO* pOldFCO, const iFCO* pNewFCO, const cFCOPropVector& changedProps) +void cFCOReport::AddChangedFCO(const cFCOReportSpecIter& iter, + const iFCO* pOldFCO, + const iFCO* pNewFCO, + const cFCOPropVector& changedProps) { cDebug d("cFCOReport::AddChangedFCO"); // make some assertions about the iterator - #ifdef _DEBUG +#ifdef DEBUG // make sure iter points to one of our spec lists cFCOReport_i::GenreSpecList::iterator genreIter; - for (genreIter = mpData->mGenreList.begin(); ; ++genreIter) + for (genreIter = mpData->mGenreList.begin();; ++genreIter) { if (genreIter == mpData->mGenreList.end()) { ASSERT(false); - THROW_INTERNAL("fcoreport.cpp"); + THROW_INTERNAL("fcoreport.cpp"); } if (&genreIter->mSpecList == iter.mpData->mpList) break; } - #endif +#endif - ASSERT(! iter.Done()); // make sure it points to something valid + ASSERT(!iter.Done()); // make sure it points to something valid // some sanity checking for the fco names... ASSERT(pOldFCO->GetName().IsEqual(pNewFCO->GetName())); @@ -747,9 +743,9 @@ void cFCOReport::AddChangedFCO(const cFCOReportSpecIter& iter, const iFCO* pOldF iter.mpData->mIter->mChanged.push_back(cFCOReport_i::cChangeNode()); cFCOReport_i::cChangeNode& changeNode = iter.mpData->mIter->mChanged.back(); - changeNode.mpOldFCO = pOldFCO; - changeNode.mpNewFCO = pNewFCO; - changeNode.mChangeVector = changedProps; + changeNode.mpOldFCO = pOldFCO; + changeNode.mpNewFCO = pNewFCO; + changeNode.mChangeVector = changedProps; pOldFCO->AddRef(); pNewFCO->AddRef(); } @@ -766,7 +762,7 @@ void cFCOReport::Read(iSerializer* pSerializer, int32 version) // read in main error queue pSerializer->ReadObject(&mpData->mErrorQueue); - + // read in the genres int32 genreIter, genreCount; int32 specIter, specCount; @@ -775,13 +771,13 @@ void cFCOReport::Read(iSerializer* pSerializer, int32 version) for (genreIter = 0; genreIter < genreCount; genreIter++) { cFCOReport_i::cGenreNode newGenre; - int32 genre; + int32 genre; // TODO:BAM -- this used to be int16, so take care of backwards compatability pSerializer->ReadInt32(genre); newGenre.mGenre = (cGenre::Genre)genre; - - pSerializer->ReadObject( &newGenre.mGenreHeader ); + + pSerializer->ReadObject(&newGenre.mGenreHeader); pSerializer->ReadInt32(specCount); for (specIter = 0; specIter < specCount; specIter++) @@ -789,26 +785,26 @@ void cFCOReport::Read(iSerializer* pSerializer, int32 version) newGenre.mSpecList.push_back(cFCOReport_i::cNode()); cFCOReport_i::cNode& node = newGenre.mSpecList.back(); - node.mpSpec = static_cast (pSerializer->ReadObjectDynCreate()); + node.mpSpec = static_cast(pSerializer->ReadObjectDynCreate()); node.mpSpecAttr = static_cast(pSerializer->ReadObjectDynCreate()); pSerializer->ReadObject(&node.mErrorQueue); pSerializer->ReadObject(&node.mAdded); pSerializer->ReadObject(&node.mRemoved); - pSerializer->ReadInt32( node.mnObjectsScanned ); + pSerializer->ReadInt32(node.mnObjectsScanned); node.mAdded.SetSpec(node.mpSpec); node.mRemoved.SetSpec(node.mpSpec); - + int32 changeSize; pSerializer->ReadInt32(changeSize); - for(int j=0; j(pSerializer->ReadObjectDynCreate()); - cnode.mpNewFCO = static_cast(pSerializer->ReadObjectDynCreate()); - cnode.mChangeVector.Read(pSerializer); + cnode.mpOldFCO = static_cast(pSerializer->ReadObjectDynCreate()); + cnode.mpNewFCO = static_cast(pSerializer->ReadObjectDynCreate()); + cnode.mChangeVector.Read(pSerializer); } } @@ -822,7 +818,7 @@ void cFCOReport::Read(iSerializer* pSerializer, int32 version) void cFCOReport::Write(iSerializer* pSerializer) const { cFCOReport_i::GenreSpecList::iterator genreIter; - cFCOReport_i::SpecList::iterator specIter; + cFCOReport_i::SpecList::iterator specIter; // write out the main error queue pSerializer->WriteObject(&mpData->mErrorQueue); @@ -834,8 +830,8 @@ void cFCOReport::Write(iSerializer* pSerializer) const { // TODO:BAM -- this used to be int16, so take care of backwards compatability pSerializer->WriteInt32(genreIter->mGenre); - pSerializer->WriteObject( &genreIter->mGenreHeader ); - + pSerializer->WriteObject(&genreIter->mGenreHeader); + // write each node out... pSerializer->WriteInt32(genreIter->mSpecList.size()); @@ -847,11 +843,11 @@ void cFCOReport::Write(iSerializer* pSerializer) const pSerializer->WriteObject(&specIter->mErrorQueue); pSerializer->WriteObject(&specIter->mAdded); pSerializer->WriteObject(&specIter->mRemoved); - pSerializer->WriteInt32( specIter->mnObjectsScanned ); + pSerializer->WriteInt32(specIter->mnObjectsScanned); std::list::iterator changedIter; pSerializer->WriteInt32(specIter->mChanged.size()); - for(changedIter = specIter->mChanged.begin(); changedIter != specIter->mChanged.end(); ++changedIter) + for (changedIter = specIter->mChanged.begin(); changedIter != specIter->mChanged.end(); ++changedIter) { pSerializer->WriteObjectDynCreate(changedIter->mpOldFCO); pSerializer->WriteObjectDynCreate(changedIter->mpNewFCO); @@ -865,11 +861,18 @@ void cFCOReport::Write(iSerializer* pSerializer) const // GetFileHeaderID() /////////////////////////////////////////////////////////////////////////////// -struct cFCOReportFHID { +struct cFCOReportFHID +{ cFileHeaderID* ReportID; - cFCOReportFHID() { ReportID = 0; } - ~cFCOReportFHID() { delete ReportID; } + cFCOReportFHID() + { + ReportID = 0; + } + ~cFCOReportFHID() + { + delete ReportID; + } } gFCOReportFHID; const cFileHeaderID& cFCOReport::GetFileHeaderID() @@ -886,16 +889,16 @@ const cFileHeaderID& cFCOReport::GetFileHeaderID() void cFCOReport::TraceContents(int dl) const { - if(dl < 0) + if (dl < 0) dl = cDebug::D_DEBUG; cDebug d("cFCOReport:"); d.TraceDebug("Global Error Queue:\n"); mpData->mErrorQueue.TraceContents(dl); - + cFCOReport_i::GenreSpecList::iterator genreIter; - cFCOReport_i::SpecList::iterator specIter; + cFCOReport_i::SpecList::iterator specIter; for (genreIter = mpData->mGenreList.begin(); genreIter != mpData->mGenreList.end(); ++genreIter) { @@ -919,8 +922,9 @@ void cFCOReport::TraceContents(int dl) const // trace out changed files d.TraceDebug(">>> Changed Files:\n"); std::list::iterator changedIter; - int changeCounter = 0; - for (changedIter = specIter->mChanged.begin(); changedIter != specIter->mChanged.end(); ++changedIter, ++changeCounter) + int changeCounter = 0; + for (changedIter = specIter->mChanged.begin(); changedIter != specIter->mChanged.end(); + ++changedIter, ++changeCounter) { d.Trace(dl, ">>>>> Changed fco [%d]\n", changeCounter); d.Trace(dl, ">>>>> Old FCO:\n"); @@ -932,5 +936,3 @@ void cFCOReport::TraceContents(int dl) const } } } - - diff --git a/src/tw/fcoreport.h b/src/tw/fcoreport.h index 5c578b6..f7db82f 100644 --- a/src/tw/fcoreport.h +++ b/src/tw/fcoreport.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,14 +40,14 @@ #ifndef __FCOGENRE_H #include "fco/fcogenre.h" #endif - + #ifndef __SERIALIZABLE_H #include "core/serializable.h" #endif /////////////////////////////////////////////////////////////////////////////// // class cFCOReport -- The information from an integrity check. -// +// // This class must encompass all the information from an integrity check: // // * It must report each added, removed or changed FCO. @@ -59,9 +59,9 @@ // OK's a FCO change. // // To store all of this information we organize by the specifier list that -// was used to create the report. During integrity checking each cFCOSpec -// will generate an cFCOSet of added FCO's, an cFCOSet of removed FCO's, -// and a pair of cFCOSet's for each changed FCO (a cFCOSet for the old +// was used to create the report. During integrity checking each cFCOSpec +// will generate an cFCOSet of added FCO's, an cFCOSet of removed FCO's, +// and a pair of cFCOSet's for each changed FCO (a cFCOSet for the old // properties of the FCO's and a cFCOSet for new properties of the FCO). // There will also be a cPropertyVector to specify what properties differ // between the old and new FCO for the changed set. @@ -91,50 +91,55 @@ class cFCOReportSpecIter; class cFCOReport : public iTypedSerializable { DECLARE_TYPEDSERIALIZABLE() - friend class cFCOReportSpecIter; + friend class cFCOReportSpecIter; friend class cFCOReportUtil; friend class cFCOReportGenreIter; + public: cFCOReport(); virtual ~cFCOReport(); void ClearReport(); - void AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOSpecAttr* pAttr, cFCOReportSpecIter* pIter = NULL); - // Add a spec to the report. The report will save copies of all three of these - // objects in its internal data structure. - // If pSpec, pAttr, and pIter are all NULL, an empty genre is added to report - // if pIter is passed in, it will be updated to point at the newly added spec. - // if genre is not in this report, it will be added - // if this spec overlaps another spec, an eInternal will be thrown - - void AddChangedFCO(const cFCOReportSpecIter& iter, const iFCO* pOldFCO, const iFCO* pNewFCO, const cFCOPropVector& changedProps); - // For the spec pointed to by the iter, add a changed FCO pair and property vector. - - const cErrorQueue* GetErrorQueue() const; - cErrorQueue* GetErrorQueue(); - // returns a pointer to the report's error queue. The caller is free to iterate over the errors, remove all the - // errors, or chain an error bucket to or from the report's error queue. - + void + AddSpec(cGenre::Genre genre, const iFCOSpec* pSpec, const cFCOSpecAttr* pAttr, cFCOReportSpecIter* pIter = NULL); + // Add a spec to the report. The report will save copies of all three of these + // objects in its internal data structure. + // If pSpec, pAttr, and pIter are all NULL, an empty genre is added to report + // if pIter is passed in, it will be updated to point at the newly added spec. + // if genre is not in this report, it will be added + // if this spec overlaps another spec, an eInternal will be thrown + + void AddChangedFCO(const cFCOReportSpecIter& iter, + const iFCO* pOldFCO, + const iFCO* pNewFCO, + const cFCOPropVector& changedProps); + // For the spec pointed to by the iter, add a changed FCO pair and property vector. + + const cErrorQueue* GetErrorQueue() const; + cErrorQueue* GetErrorQueue(); + // returns a pointer to the report's error queue. The caller is free to iterate over the errors, remove all the + // errors, or chain an error bucket to or from the report's error queue. + int GetNumSpecs(cGenre::Genre genre) const; - // returns the number of specs in the report; these can be iterated over using the iterators below. - // returns 0 if genre is not in report + // returns the number of specs in the report; these can be iterated over using the iterators below. + // returns 0 if genre is not in report - void TraceContents(int dl = -1) const; + void TraceContents(int dl = -1) const; // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) - + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + static const cFileHeaderID& GetFileHeaderID(); - // Return a cFileHeaderID for all databases + // Return a cFileHeaderID for all databases protected: - cFCOReport_i* mpData; + cFCOReport_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// -// iterator classes -- iterates over all the specs in the report and returns +// iterator classes -- iterates over all the specs in the report and returns // refrences to all the spec's related data /////////////////////////////////////////////////////////////////////////////// class cFCOReportGenreIter @@ -142,29 +147,30 @@ class cFCOReportGenreIter friend class cFCOReport; friend class cFCOReportSpecIter; friend class cFCOReportChangeIter; + public: explicit cFCOReportGenreIter(const cFCOReport& report); cFCOReportGenreIter(const cFCOReportGenreIter& rhs); ~cFCOReportGenreIter(); - void operator=(const cFCOReportGenreIter& rhs); + cFCOReportGenreIter& operator=(const cFCOReportGenreIter& rhs); // iteration methods - void SeekBegin() const; - void Next() const; - bool Done() const; - + void SeekBegin() const; + void Next() const; + bool Done() const; + bool SeekToGenre(cGenre::Genre genre); - // seeks to specific genre. Returns false if genre does not exist in report + // seeks to specific genre. Returns false if genre does not exist in report + + void Remove(); + // removes the entire genre from report - void Remove(); - // removes the entire genre from report - // access to data - cGenre::Genre GetGenre() const; - // Get current genre - cFCOReportGenreHeader& GetGenreHeader() const; - + cGenre::Genre GetGenre() const; + // Get current genre + cFCOReportGenreHeader& GetGenreHeader() const; + private: cFCOReportGenreIter_i* mpData; }; @@ -173,49 +179,50 @@ class cFCOReportSpecIter { friend class cFCOReport; friend class cFCOReportChangeIter; + public: cFCOReportSpecIter(const cFCOReport& report, cGenre::Genre genre); - // if genre does not exist in the report, an eInternal error will be thrown. + // if genre does not exist in the report, an eInternal error will be thrown. cFCOReportSpecIter(cFCOReport& report, cGenre::Genre genre); - // if genre does not exist in the report, it will be added to the report with - // and empty spec list. - cFCOReportSpecIter(const cFCOReportGenreIter& genreIter); - // thorws eInternal if genreIter is not at a valid genre or is Done() + // if genre does not exist in the report, it will be added to the report with + // and empty spec list. + explicit cFCOReportSpecIter(const cFCOReportGenreIter& genreIter); + // thorws eInternal if genreIter is not at a valid genre or is Done() cFCOReportSpecIter(const cFCOReportSpecIter& rhs); ~cFCOReportSpecIter(); - void operator=(const cFCOReportSpecIter& rhs); + cFCOReportSpecIter& operator=(const cFCOReportSpecIter& rhs); // iteration methods - void SeekBegin() const; - void Next() const; - bool Done() const; + void SeekBegin() const; + void Next() const; + bool Done() const; bool SeekToSpec(const iFCOSpec* pSpec); - // seeks to the first spec that equals the passed in one; returns false - // and seeks to end if not found. + // seeks to the first spec that equals the passed in one; returns false + // and seeks to end if not found. + + void Remove(); + // removes the spec and all fcos associated wit hit. Behavior is undefined if (Done() == true). + // after the erase, the iterator points to the next element in the list - void Remove(); - // removes the spec and all fcos associated wit hit. Behavior is undefined if (Done() == true). - // after the erase, the iterator points to the next element in the list - // access to data - const iFCOSpec* GetSpec() const; - const cFCOSpecAttr* GetAttr() const; - const cErrorQueue* GetErrorQueue() const; - cErrorQueue* GetErrorQueue(); - const iFCOSet* GetAddedSet() const; - iFCOSet* GetAddedSet(); - const iFCOSet* GetRemovedSet() const; - iFCOSet* GetRemovedSet(); - - int GetNumChanged() const; - // returns the number of fcos in the changed list. - // you access the members of the list by using the iterator below... - - void SetObjectsScanned( int nObjectsScanned ); - int GetObjectsScanned() const; + const iFCOSpec* GetSpec() const; + const cFCOSpecAttr* GetAttr() const; + const cErrorQueue* GetErrorQueue() const; + cErrorQueue* GetErrorQueue(); + const iFCOSet* GetAddedSet() const; + iFCOSet* GetAddedSet(); + const iFCOSet* GetRemovedSet() const; + iFCOSet* GetRemovedSet(); + + int GetNumChanged() const; + // returns the number of fcos in the changed list. + // you access the members of the list by using the iterator below... + + void SetObjectsScanned(int nObjectsScanned); + int GetObjectsScanned() const; private: cFCOReportSpecIter_i* mpData; @@ -226,35 +233,37 @@ class cFCOReportSpecIter class cFCOReportChangeIter { public: - cFCOReportChangeIter(const cFCOReportSpecIter& specIter); - cFCOReportChangeIter(); + explicit cFCOReportChangeIter(const cFCOReportSpecIter& specIter); cFCOReportChangeIter(const cFCOReportChangeIter& rhs); ~cFCOReportChangeIter(); - void operator=(const cFCOReportChangeIter& rhs); - void SetSpecIter(const cFCOReportSpecIter& specIter); - // assocaite this iterator with a different spec. We will assert - // that specIter.Done() is not true. + cFCOReportChangeIter& operator=(const cFCOReportChangeIter& rhs); + void SetSpecIter(const cFCOReportSpecIter& specIter); + // assocaite this iterator with a different spec. We will assert + // that specIter.Done() is not true. + + void Remove(); + // removes the the change entry pointed at by this iter. Behavior is undefined if (Done() == true). + // after the erase, the iterator points to the next element in the list - void Remove(); - // removes the the change entry pointed at by this iter. Behavior is undefined if (Done() == true). - // after the erase, the iterator points to the next element in the list - // iteration methods - void SeekBegin() const; - void Next() const; - bool Done() const; + void SeekBegin() const; + void Next() const; + bool Done() const; // access to data... - const iFCO* GetOld() const; - const iFCO* GetNew() const; - const cFCOPropVector& GetChangeVector() const; + const iFCO* GetOld() const; + const iFCO* GetNew() const; + const cFCOPropVector& GetChangeVector() const; private: + cFCOReportChangeIter() + { + } + cFCOReportChangeIter_i* mpData; // TODO -- if it turns out that we are creating a lot of these, we should consider // making a pool of them. }; #endif //__FCOREPORT_H - diff --git a/src/tw/fcoreportutil.cpp b/src/tw/fcoreportutil.cpp index 076f524..aed4765 100644 --- a/src/tw/fcoreportutil.cpp +++ b/src/tw/fcoreportutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,20 +53,18 @@ #include "fco/twfactory.h" #include "fco/fcopropdisplayer.h" #include "twutil.h" - + //============================================================================= // class cFCOReportUtil //============================================================================= -void cFCOReportUtil::CalculateHeaderInfo( - cFCOReportHeader& reportHeader, - const TSTRING& policyFilename, - const TSTRING& configFilename, - const TSTRING& dbFilename, - const TSTRING& commandLineParams, - int64 createTime, - int64 lastDBUpdateTime - ) +void cFCOReportUtil::CalculateHeaderInfo(cFCOReportHeader& reportHeader, + const TSTRING& policyFilename, + const TSTRING& configFilename, + const TSTRING& dbFilename, + const TSTRING& commandLineParams, + int64 createTime, + int64 lastDBUpdateTime) { reportHeader.SetPolicyFilename(policyFilename); reportHeader.SetConfigFilename(configFilename); @@ -80,78 +78,76 @@ void cFCOReportUtil::CalculateHeaderInfo( reportHeader.SetLastDBUpdateTime(lastDBUpdateTime); } -void cFCOReportUtil::FinalizeReport( cFCOReport& rr ) +void cFCOReportUtil::FinalizeReport(cFCOReport& rr) { - cFCOReportGenreIter genreIter( rr ); + cFCOReportGenreIter genreIter(rr); for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { - InitPropDisplayer( genreIter ); - } + InitPropDisplayer(genreIter); + } } -void cFCOReportUtil::InitPropDisplayer( cFCOReportGenreIter& gi ) +void cFCOReportUtil::InitPropDisplayer(cFCOReportGenreIter& gi) { - if(gi.GetGenreHeader().GetPropDisplayer() == NULL) + if (gi.GetGenreHeader().GetPropDisplayer() == NULL) gi.GetGenreHeader().SetPropDisplayer(iTWFactory::GetInstance()->CreatePropDisplayer()); - + iFCOPropDisplayer* pPropDisplayer = gi.GetGenreHeader().GetPropDisplayer(); - ASSERT( pPropDisplayer != 0); + ASSERT(pPropDisplayer != 0); // cycle through all FCOs in report - // TODO: make a FCO iter class in fcoreport.cpp - cFCOReportSpecIter ri( gi ); - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) - { + // TODO: make a FCO iter class in fcoreport.cpp + cFCOReportSpecIter ri(gi); + for (ri.SeekBegin(); !ri.Done(); ri.Next()) + { // // added // // get added set const iFCOSet* pAddedSet = ri.GetAddedSet(); - ASSERT( pAddedSet != 0); + ASSERT(pAddedSet != 0); // get fco iterator + proxy iter const cIterProxy pSetIterAdded = pAddedSet->GetIter(); - ASSERT( pSetIterAdded != 0); + ASSERT(pSetIterAdded != 0); // iterate over all fcos - for( pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next() ) - { - pPropDisplayer->InitForFCO( pSetIterAdded->FCO() ); + for (pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next()) + { + pPropDisplayer->InitForFCO(pSetIterAdded->FCO()); } - + // // removed // // get removed set const iFCOSet* pRemovedSet = ri.GetRemovedSet(); - ASSERT( pRemovedSet != 0); + ASSERT(pRemovedSet != 0); // get fco iterator + proxy iter const cIterProxy pSetIterRemoved = pRemovedSet->GetIter(); - ASSERT( pSetIterRemoved != 0); + ASSERT(pSetIterRemoved != 0); // iterate over all fcos - for( pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next() ) + for (pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next()) { - pPropDisplayer->InitForFCO( pSetIterRemoved->FCO() ); + pPropDisplayer->InitForFCO(pSetIterRemoved->FCO()); } - + // // changed // // get changed set iterator (don't need pointer to changed set, just need spec iter) - cFCOReportChangeIter changedIter( ri ); + cFCOReportChangeIter changedIter(ri); - // iterate over all changed fcos - for( changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next() ) + // iterate over all changed fcos + for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) { // we've already have old FCO info from db - pPropDisplayer->InitForFCO( changedIter.GetNew() ); - } + pPropDisplayer->InitForFCO(changedIter.GetNew()); + } } } - - diff --git a/src/tw/fcoreportutil.h b/src/tw/fcoreportutil.h index b4e2510..a20797b 100644 --- a/src/tw/fcoreportutil.h +++ b/src/tw/fcoreportutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,24 +53,21 @@ class cFCOReportGenreIter; class cFCOReportUtil { public: - static void CalculateHeaderInfo( - cFCOReportHeader& reportHeader, - const TSTRING& policyFilename, - const TSTRING& configFilename, - const TSTRING& dbFilename, - const TSTRING& commandLineParams, - int64 createTime, - int64 lastDBUpdateTime - ); + static void CalculateHeaderInfo(cFCOReportHeader& reportHeader, + const TSTRING& policyFilename, + const TSTRING& configFilename, + const TSTRING& dbFilename, + const TSTRING& commandLineParams, + int64 createTime, + int64 lastDBUpdateTime); - static void FinalizeReport( cFCOReport& rr ); - // call this when you're done adding to the report. - // adds any info propDisplayer needs, and adds info to header + static void FinalizeReport(cFCOReport& rr); + // call this when you're done adding to the report. + // adds any info propDisplayer needs, and adds info to header private: - static void InitPropDisplayer( cFCOReportGenreIter& gi ); - // call this to gather any info from machine that the report will need for displaying FCOs + static void InitPropDisplayer(cFCOReportGenreIter& gi); + // call this to gather any info from machine that the report will need for displaying FCOs }; #endif //__FCOREPORTUTIL_H - diff --git a/src/tw/filemanipulator.cpp b/src/tw/filemanipulator.cpp index 4ab1283..5c501f2 100644 --- a/src/tw/filemanipulator.cpp +++ b/src/tw/filemanipulator.cpp @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // filemanipulator.cpp -- Provides functionality to examine tripwire file headers -// for file type and encryption type. Also provides a mechanism for +// for file type and encryption type. Also provides a mechanism for // changing encryption keys or removing encryption. // @@ -56,13 +56,12 @@ cFileManipulator::cFileManipulator(const TCHAR* filename) { - mbInit = false; + mbInit = false; mFileName = filename; } cFileManipulator::cFileManipulator(const cFileManipulator& rhs) -: mFileName(rhs.mFileName), - mFileHeader(rhs.mFileHeader) + : mbInit(false), mFileName(rhs.mFileName), mFileHeader(rhs.mFileHeader) { } @@ -75,15 +74,15 @@ void cFileManipulator::Init() if (cFileUtil::FileExists(mFileName)) { cFileArchive arch; - try + try { try - { - arch.OpenRead( mFileName.c_str() ); + { + arch.OpenRead(mFileName.c_str()); } catch (eArchive&) { - throw eFileManipFileRead( mFileName ); + throw eFileManipFileRead(mFileName); } cSerializerImpl s(arch, cSerializerImpl::S_READ); @@ -91,26 +90,26 @@ void cFileManipulator::Init() } catch (eArchive&) { - throw eFileManipHeaderNotFound( mFileName ); + throw eFileManipHeaderNotFound(mFileName); } catch (eSerializer&) { - throw eFileManipHeaderNotFound( mFileName ); + throw eFileManipHeaderNotFound(mFileName); } - } + } else { - throw eFileManipFileNotFound( mFileName ); + throw eFileManipFileNotFound(mFileName); } mbInit = true; } -const cFileHeaderID* cFileManipulator::GetHeaderID() +const cFileHeaderID* cFileManipulator::GetHeaderID() { - ASSERT( mbInit ); + ASSERT(mbInit); if (!mbInit) { -// return NULL; + // return NULL; Init(); } return &mFileHeader.GetID(); @@ -118,10 +117,10 @@ const cFileHeaderID* cFileManipulator::GetHeaderID() uint32 cFileManipulator::GetFileVersion() { - ASSERT( mbInit ); + ASSERT(mbInit); if (!mbInit) { -// return 0; + // return 0; Init(); } return mFileHeader.GetVersion(); @@ -129,71 +128,71 @@ uint32 cFileManipulator::GetFileVersion() cFileHeader::Encoding cFileManipulator::GetEncoding() { - ASSERT( mbInit ); + ASSERT(mbInit); if (!mbInit) { -// return (cFileHeader::Encoding)0; + // return (cFileHeader::Encoding)0; Init(); - } + } return mFileHeader.GetEncoding(); } // Try to decrypt the file using the given key. If thorough is true then -// the entire file is read into memory. Returns true if decryption was +// the entire file is read into memory. Returns true if decryption was // successful. bool cFileManipulator::TestDecryption(const cElGamalSigPublicKey& key, bool thorough) { // TODO: pay attention to thorough flag. For now we will just always act thoroughly. - ASSERT( mbInit ); + ASSERT(mbInit); if (!mbInit) { return false; } bool fError = false; - + // "turn down" the verbosity of iUserNotify to V_NORMAL it it is V_VERBOSE to make output a little cleaner bool fChangedVerbosity = false; - int savedVerbosity = iUserNotify::GetInstance()->GetVerboseLevel(); - if( savedVerbosity == iUserNotify::V_VERBOSE ) + int savedVerbosity = iUserNotify::GetInstance()->GetVerboseLevel(); + if (savedVerbosity == iUserNotify::V_VERBOSE) { - iUserNotify::GetInstance()->SetVerboseLevel( iUserNotify::V_NORMAL ); + iUserNotify::GetInstance()->SetVerboseLevel(iUserNotify::V_NORMAL); fChangedVerbosity = true; } - try + try { if (mFileHeader.GetID() == cFCODatabaseFile::GetFileHeaderID()) { cFCODatabaseFile db; - bool encrypted; + bool encrypted; cTWUtil::ReadDatabase(mFileName.c_str(), db, &key, encrypted); } else if (mFileHeader.GetID() == cFCOReport::GetFileHeaderID()) { - cFCOReport rep; + cFCOReport rep; cFCOReportHeader reph; - bool encrypted; + bool encrypted; cTWUtil::ReadReport(mFileName.c_str(), reph, rep, &key, true, encrypted); } else if (mFileHeader.GetID() == cConfigFile::GetFileHeaderID()) { - // read the embedded key from config file and see if it is the same + // read the embedded key from config file and see if it is the same // as the public key passed in. - cMemoryArchive memArch; - TSTRING configText; //not used - cTWUtil::ReadConfigText( mFileName.c_str(), configText, &memArch ); - memArch.Seek( 0, cBidirArchive::BEGINNING ); + cMemoryArchive memArch; + TSTRING configText; //not used + cTWUtil::ReadConfigText(mFileName.c_str(), configText, &memArch); + memArch.Seek(0, cBidirArchive::BEGINNING); // only do the test if there is baggage (indicating the cfg file is encrypted) - if( memArch.Length() > 0 ) + if (memArch.Length() > 0) { // create the two public keys... - cElGamalSigPublicKey pubKey( memArch.GetMemory() ); + cElGamalSigPublicKey pubKey(memArch.GetMemory()); // compare the two .... - if( ! pubKey.IsEqual( key ) ) + if (!pubKey.IsEqual(key)) throw ePoly(); } } @@ -202,19 +201,19 @@ bool cFileManipulator::TestDecryption(const cElGamalSigPublicKey& key, bool thor std::string policyText; cTWUtil::ReadPolicyText(mFileName.c_str(), policyText, &key); } - else + else throw ePoly(); } catch (eError&) - { + { fError = true; } - + // reset verbosity - if( fChangedVerbosity ) - iUserNotify::GetInstance()->SetVerboseLevel( savedVerbosity ); + if (fChangedVerbosity) + iUserNotify::GetInstance()->SetVerboseLevel(savedVerbosity); - return( fError == false ); + return (fError == false); } // Change the encryption on a file. @@ -227,9 +226,11 @@ bool cFileManipulator::TestDecryption(const cElGamalSigPublicKey& key, bool thor // currently encrypted, the function will not do anything and will just // return. // Returns on successful encryption change. -void cFileManipulator::ChangeEncryption(const cElGamalSigPublicKey* pOldKey, const cElGamalSigPrivateKey* pNewKey, bool backup) +void cFileManipulator::ChangeEncryption(const cElGamalSigPublicKey* pOldKey, + const cElGamalSigPrivateKey* pNewKey, + bool backup) { - ASSERT( mbInit ); + ASSERT(mbInit); if (!mbInit) { Init(); @@ -239,84 +240,85 @@ void cFileManipulator::ChangeEncryption(const cElGamalSigPublicKey* pOldKey, co if (mFileHeader.GetEncoding() != cFileHeader::ASYM_ENCRYPTION) { if (pOldKey != NULL) - throw eFileManipNotEncrypted( mFileName ); + throw eFileManipNotEncrypted(mFileName); if (pNewKey == NULL) - return; // NOOP + return; // NOOP } else if (pOldKey == NULL) throw eFileManipMissingKey(); if (!cFileUtil::FileWritable(mFileName)) - throw eFileManipNotWritable( mFileName ); + throw eFileManipNotWritable(mFileName); if (mFileHeader.GetID() == cFCODatabaseFile::GetFileHeaderID()) { - cFCODatabaseFile db; - bool encrypted; + cFCODatabaseFile db; + bool encrypted; - cTWUtil::ReadDatabase(mFileName.c_str(), db, pOldKey, encrypted); - if (backup) - { - TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); - iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); - } + cTWUtil::ReadDatabase(mFileName.c_str(), db, pOldKey, encrypted); + if (backup) + { + TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); + iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); + } - cTWUtil::WriteDatabase(mFileName.c_str(), db, pNewKey != NULL, pNewKey); - return; + cTWUtil::WriteDatabase(mFileName.c_str(), db, pNewKey != NULL, pNewKey); + return; } else if (mFileHeader.GetID() == cFCOReport::GetFileHeaderID()) { - cFCOReport rep; - cFCOReportHeader reph; - bool encrypted; - cTWUtil::ReadReport(mFileName.c_str(), reph, rep, pOldKey, false, encrypted); - if (backup) - { - TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); - iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); - } - cTWUtil::WriteReport(mFileName.c_str(), reph, rep, pNewKey != NULL, pNewKey); - return; + cFCOReport rep; + cFCOReportHeader reph; + bool encrypted; + cTWUtil::ReadReport(mFileName.c_str(), reph, rep, pOldKey, false, encrypted); + if (backup) + { + TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); + iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); + } + cTWUtil::WriteReport(mFileName.c_str(), reph, rep, pNewKey != NULL, pNewKey); + return; } else if (mFileHeader.GetID() == cConfigFile::GetFileHeaderID()) { - TSTRING configText; + TSTRING configText; - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), - cDisplayEncoder::EncodeInline( mFileName ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), + cDisplayEncoder::EncodeInline(mFileName).c_str()); - cTWUtil::ReadConfigText(mFileName.c_str(), configText); - if (backup) - { - TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); - iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); - } + cTWUtil::ReadConfigText(mFileName.c_str(), configText); + if (backup) + { + TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); + iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); + } - cTWUtil::WriteConfigText(mFileName.c_str(), configText, pNewKey != NULL, pNewKey); + cTWUtil::WriteConfigText(mFileName.c_str(), configText, pNewKey != NULL, pNewKey); - return; + return; } else if (mFileHeader.GetID() == cPolicyFile::GetFileHeaderID()) { - std::string policyText; + std::string policyText; - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_POLICY_FILE).c_str(), - cDisplayEncoder::EncodeInline( mFileName ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_POLICY_FILE).c_str(), + cDisplayEncoder::EncodeInline(mFileName).c_str()); - cTWUtil::ReadPolicyText(mFileName.c_str(), policyText, pOldKey); - if (backup) - { - TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); - iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); - } + cTWUtil::ReadPolicyText(mFileName.c_str(), policyText, pOldKey); + if (backup) + { + TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension(); + iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str()); + } - cTWUtil::WritePolicyText(mFileName.c_str(), policyText, pNewKey != NULL, pNewKey); + cTWUtil::WritePolicyText(mFileName.c_str(), policyText, pNewKey != NULL, pNewKey); - return; + return; } - } // method for getting a list of manipulators @@ -328,7 +330,7 @@ int cFileManipulator::LoadFiles(std::list& ret, TSTRING mask) // TODO: we need to be able to deal with masks for the NT version. // Right now *.* will not work in NT. We should not get a '*' for unix. - try + try { ret.push_back(cFileManipulator(mask.c_str())); } @@ -343,15 +345,11 @@ int cFileManipulator::LoadFiles(std::list& ret, TSTRING mask) bool cFileManipulator::UseSiteKey(const cFileHeaderID& headerID) { - if (headerID == cFCODatabaseFile::GetFileHeaderID() || - headerID == cFCOReport::GetFileHeaderID()) + if (headerID == cFCODatabaseFile::GetFileHeaderID() || headerID == cFCOReport::GetFileHeaderID()) return false; - else - if (headerID == cConfigFile::GetFileHeaderID() || - headerID == cPolicyFile::GetFileHeaderID()) + else if (headerID == cConfigFile::GetFileHeaderID() || headerID == cPolicyFile::GetFileHeaderID()) return true; ASSERT(false); // what could it be? be careful not to en/decrypt keyfiles. return false; } - diff --git a/src/tw/filemanipulator.h b/src/tw/filemanipulator.h index 59f53a9..b668684 100644 --- a/src/tw/filemanipulator.h +++ b/src/tw/filemanipulator.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // filemanipulator.h -- Provides functionality to examine tripwire file headers -// for file type and encryption type. Also provides a mechanism for +// for file type and encryption type. Also provides a mechanism for // changing encryption keys or removing encryption. // @@ -75,15 +75,15 @@ class eFileManipulator : public eError //============================================================================= // eFileManip //============================================================================= -TSS_FILE_EXCEPTION( eFileManip, eFileError ) -TSS_FILE_EXCEPTION( eFileManipInvalidFile, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipFileRead, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipHeaderNotFound,eFileManip ) -TSS_FILE_EXCEPTION( eFileManipFileNotFound, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipNotEncrypted, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipMissingKey, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipNotWritable, eFileManip ) -TSS_FILE_EXCEPTION( eFileManipUnrecognizedFileType, eFileManip ) +TSS_FILE_EXCEPTION(eFileManip, eFileError) +TSS_FILE_EXCEPTION(eFileManipInvalidFile, eFileManip) +TSS_FILE_EXCEPTION(eFileManipFileRead, eFileManip) +TSS_FILE_EXCEPTION(eFileManipHeaderNotFound, eFileManip) +TSS_FILE_EXCEPTION(eFileManipFileNotFound, eFileManip) +TSS_FILE_EXCEPTION(eFileManipNotEncrypted, eFileManip) +TSS_FILE_EXCEPTION(eFileManipMissingKey, eFileManip) +TSS_FILE_EXCEPTION(eFileManipNotWritable, eFileManip) +TSS_FILE_EXCEPTION(eFileManipUnrecognizedFileType, eFileManip) //============================================================================= // cFileManipulator @@ -91,42 +91,42 @@ TSS_FILE_EXCEPTION( eFileManipUnrecognizedFileType, eFileManip ) class cFileManipulator { public: - cFileManipulator(const TCHAR* filename); - // throws eArchive if file does not exist + explicit cFileManipulator(const TCHAR* filename); + // throws eArchive if file does not exist cFileManipulator(const cFileManipulator& rhs); ~cFileManipulator(); void Init(); // information for this file - TSTRING GetFileName() const; - const cFileHeaderID* GetHeaderID() ; // returns NULL if error code is non-zero - uint32 GetFileVersion() ; // throws eFileManipulator if error code is non-zero - cFileHeader::Encoding GetEncoding() ; // throws eFileManipulator if error code is non-zero + TSTRING GetFileName() const; + const cFileHeaderID* GetHeaderID(); // returns NULL if error code is non-zero + uint32 GetFileVersion(); // throws eFileManipulator if error code is non-zero + cFileHeader::Encoding GetEncoding(); // throws eFileManipulator if error code is non-zero // things you can do to this file - bool TestDecryption(const cElGamalSigPublicKey& key, bool thorough) ; - // Try to decrypt the file using the given key. If thorough is true then - // the entire file is read into memory. Returns true if decryption was - // successful. - // throws eFileManipulator if error code is non-zero + bool TestDecryption(const cElGamalSigPublicKey& key, bool thorough); + // Try to decrypt the file using the given key. If thorough is true then + // the entire file is read into memory. Returns true if decryption was + // successful. + // throws eFileManipulator if error code is non-zero void ChangeEncryption(const cElGamalSigPublicKey* pOldKey, const cElGamalSigPrivateKey* pNewKey, bool backup); - // Change the encryption on a file. - // If pNewKey is NULL, then encryption on the file will be removed. - // If pOldKey is NULL and the file is currently encrypted, then the - // function will throw an exception; - // If pOldKey is not NULL and the file is encrypted, then the fuction - // will throw an exception; - // If pOldKey is NULL and pNewKey is NULL and the file is not - // currently encrypted, the function will not do anything and will just - // return. + // Change the encryption on a file. + // If pNewKey is NULL, then encryption on the file will be removed. + // If pOldKey is NULL and the file is currently encrypted, then the + // function will throw an exception; + // If pOldKey is not NULL and the file is encrypted, then the fuction + // will throw an exception; + // If pOldKey is NULL and pNewKey is NULL and the file is not + // currently encrypted, the function will not do anything and will just + // return. // utility functions static int LoadFiles(std::list& ret, TSTRING mask); - // method for getting a list of manipulators - // returns number of files matched, or zero if no files matched mask passed + // method for getting a list of manipulators + // returns number of files matched, or zero if no files matched mask passed static bool UseSiteKey(const cFileHeaderID& headerID); - // convenience function that returns true if header is a config file or policy file - // and returns false if it is a database or report. + // convenience function that returns true if header is a config file or policy file + // and returns false if it is a database or report. private: bool mbInit; @@ -139,4 +139,3 @@ inline TSTRING cFileManipulator::GetFileName() const return mFileName; } #endif - diff --git a/src/tw/headerinfo.cpp b/src/tw/headerinfo.cpp index 3f843be..3e6b298 100644 --- a/src/tw/headerinfo.cpp +++ b/src/tw/headerinfo.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,14 +40,13 @@ #include "fco/fcopropdisplayer.h" #include "core/errorutil.h" -IMPLEMENT_TYPEDSERIALIZABLE( cHeaderInfo, _T("cHeaderInfo"), 0, 1 ); -IMPLEMENT_TYPEDSERIALIZABLE( cFCODbHeader, _T("cFCODbHeader"), 0, 1 ); -IMPLEMENT_TYPEDSERIALIZABLE( cFCOReportHeader, _T("cFCOReportHeader"), 0, 1 ); - -IMPLEMENT_TYPEDSERIALIZABLE( cGenreHeaderInfo, _T("cGenreHeaderInfo"), 0, 1 ); -IMPLEMENT_TYPEDSERIALIZABLE( cFCODbGenreHeader, _T("cFCODbGenreHeader"), 0, 1 ); -IMPLEMENT_TYPEDSERIALIZABLE( cFCOReportGenreHeader, _T("cFCOReportGenreHeader"),0, 1 ); +IMPLEMENT_TYPEDSERIALIZABLE(cHeaderInfo, _T("cHeaderInfo"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cFCODbHeader, _T("cFCODbHeader"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cFCOReportHeader, _T("cFCOReportHeader"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cGenreHeaderInfo, _T("cGenreHeaderInfo"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cFCODbGenreHeader, _T("cFCODbGenreHeader"), 0, 1); +IMPLEMENT_TYPEDSERIALIZABLE(cFCOReportGenreHeader, _T("cFCOReportGenreHeader"), 0, 1); ////////////////////////////////////////////////////////////////////////////// @@ -64,58 +63,55 @@ cHeaderInfo::~cHeaderInfo() void cHeaderInfo::Clear() { - tstr_SystemName = _T(""); - tstr_PolicyFilename= _T(""); - tstr_ConfigFilename= _T(""); - tstr_DBFilename= _T(""); - tstr_CommandLineParams= _T(""); - tstr_CreatedBy= _T(""); - tstr_IPAddress= _T(""); - tstr_HostID = _T(""); - i64_CreationTime = 0; - i64_LastDBUpdateTime = 0; + tstr_SystemName = _T(""); + tstr_PolicyFilename = _T(""); + tstr_ConfigFilename = _T(""); + tstr_DBFilename = _T(""); + tstr_CommandLineParams = _T(""); + tstr_CreatedBy = _T(""); + tstr_IPAddress = _T(""); + tstr_HostID = _T(""); + i64_CreationTime = 0; + i64_LastDBUpdateTime = 0; } -void cHeaderInfo::Read ( iSerializer* pSerializer, int32 version ) // throw (eSerializer, eArchive) +void cHeaderInfo::Read(iSerializer* pSerializer, int32 version) // throw (eSerializer, eArchive) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("cHeaderInfo Read"))); - pSerializer->ReadString( tstr_SystemName ); - pSerializer->ReadString( tstr_PolicyFilename ); - pSerializer->ReadString( tstr_ConfigFilename ); - pSerializer->ReadString( tstr_DBFilename ); - pSerializer->ReadString( tstr_CommandLineParams ); - pSerializer->ReadString( tstr_CreatedBy ); - pSerializer->ReadString( tstr_IPAddress ); - pSerializer->ReadString( tstr_HostID ); - pSerializer->ReadInt64( i64_CreationTime ); - pSerializer->ReadInt64( i64_LastDBUpdateTime ); + pSerializer->ReadString(tstr_SystemName); + pSerializer->ReadString(tstr_PolicyFilename); + pSerializer->ReadString(tstr_ConfigFilename); + pSerializer->ReadString(tstr_DBFilename); + pSerializer->ReadString(tstr_CommandLineParams); + pSerializer->ReadString(tstr_CreatedBy); + pSerializer->ReadString(tstr_IPAddress); + pSerializer->ReadString(tstr_HostID); + pSerializer->ReadInt64(i64_CreationTime); + pSerializer->ReadInt64(i64_LastDBUpdateTime); } void cHeaderInfo::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) { - pSerializer->WriteString( tstr_SystemName ); - pSerializer->WriteString( tstr_PolicyFilename ); - pSerializer->WriteString( tstr_ConfigFilename ); - pSerializer->WriteString( tstr_DBFilename ); - pSerializer->WriteString( tstr_CommandLineParams ); - pSerializer->WriteString( tstr_CreatedBy ); - pSerializer->WriteString( tstr_IPAddress ); - pSerializer->WriteString( tstr_HostID ); - pSerializer->WriteInt64( i64_CreationTime ); - pSerializer->WriteInt64( i64_LastDBUpdateTime ); + pSerializer->WriteString(tstr_SystemName); + pSerializer->WriteString(tstr_PolicyFilename); + pSerializer->WriteString(tstr_ConfigFilename); + pSerializer->WriteString(tstr_DBFilename); + pSerializer->WriteString(tstr_CommandLineParams); + pSerializer->WriteString(tstr_CreatedBy); + pSerializer->WriteString(tstr_IPAddress); + pSerializer->WriteString(tstr_HostID); + pSerializer->WriteInt64(i64_CreationTime); + pSerializer->WriteInt64(i64_LastDBUpdateTime); } - ////////////////////////////////////////////////////////////////////////////// // Ctor, Dtor: Ctor intializes the Header data to zero or a NULL equivalent. -cGenreHeaderInfo::cGenreHeaderInfo() - : mpPropDisplayer( 0 ), - i32_ObjectsScanned( 0 ) +cGenreHeaderInfo::cGenreHeaderInfo() : mpPropDisplayer(0), i32_ObjectsScanned(0) { } @@ -124,13 +120,12 @@ cGenreHeaderInfo::~cGenreHeaderInfo() delete mpPropDisplayer; } -cGenreHeaderInfo::cGenreHeaderInfo( const cGenreHeaderInfo& rhs ) - : mpPropDisplayer(0) +cGenreHeaderInfo::cGenreHeaderInfo(const cGenreHeaderInfo& rhs) : mpPropDisplayer(0) { - if( this == &rhs ) + if (this == &rhs) return; - if( rhs.mpPropDisplayer ) + if (rhs.mpPropDisplayer) mpPropDisplayer = rhs.GetPropDisplayer()->Clone(); i32_ObjectsScanned = rhs.GetObjectsScanned(); @@ -139,41 +134,38 @@ cGenreHeaderInfo::cGenreHeaderInfo( const cGenreHeaderInfo& rhs ) void cGenreHeaderInfo::Clear() { delete mpPropDisplayer; - mpPropDisplayer = 0; + mpPropDisplayer = 0; i32_ObjectsScanned = 0; } -void cGenreHeaderInfo::Read ( iSerializer* pSerializer, int32 version ) // throw (eSerializer, eArchive) +void cGenreHeaderInfo::Read(iSerializer* pSerializer, int32 version) // throw (eSerializer, eArchive) { if (version > Version()) ThrowAndAssert(eSerializerVersionMismatch(_T("cHeaderInfo Read"))); // read the prop displayer - ASSERT( mpPropDisplayer == 0); + ASSERT(mpPropDisplayer == 0); int32 fMakePD; - pSerializer->ReadInt32( fMakePD ); + pSerializer->ReadInt32(fMakePD); + + if (fMakePD == 1) + mpPropDisplayer = static_cast(pSerializer->ReadObjectDynCreate()); - if( fMakePD == 1 ) - mpPropDisplayer = static_cast( pSerializer->ReadObjectDynCreate() ); - - pSerializer->ReadInt32( i32_ObjectsScanned ); + pSerializer->ReadInt32(i32_ObjectsScanned); } -void cGenreHeaderInfo::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) +void cGenreHeaderInfo::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) { // write out the prop displayer - if( mpPropDisplayer ) + if (mpPropDisplayer) { pSerializer->WriteInt32(1); - pSerializer->WriteObjectDynCreate( mpPropDisplayer ); + pSerializer->WriteObjectDynCreate(mpPropDisplayer); } else pSerializer->WriteInt32(0); - pSerializer->WriteInt32( i32_ObjectsScanned ); + pSerializer->WriteInt32(i32_ObjectsScanned); } - - - diff --git a/src/tw/headerinfo.h b/src/tw/headerinfo.h index 96ad016..e9d5735 100644 --- a/src/tw/headerinfo.h +++ b/src/tw/headerinfo.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -56,49 +56,49 @@ class cHeaderInfo : public iTypedSerializable cHeaderInfo(); virtual ~cHeaderInfo(); virtual void Clear(); - //Clears all data in a header to 0 or NULL equivalents. + //Clears all data in a header to 0 or NULL equivalents. //Functions for getting & setting header values: - const TSTRING& GetPolicyFilename() const; - const TSTRING& GetConfigFilename() const; - const TSTRING& GetDBFilename() const; - const TSTRING& GetSystemName() const; - const TSTRING& GetCommandLineParams() const; - const TSTRING& GetIPAddress() const; - const TSTRING& GetCreator() const; - const TSTRING& GetHostID() const; - int64 GetCreationTime() const; - int64 GetLastDBUpdateTime() const; + const TSTRING& GetPolicyFilename() const; + const TSTRING& GetConfigFilename() const; + const TSTRING& GetDBFilename() const; + const TSTRING& GetSystemName() const; + const TSTRING& GetCommandLineParams() const; + const TSTRING& GetIPAddress() const; + const TSTRING& GetCreator() const; + const TSTRING& GetHostID() const; + int64 GetCreationTime() const; + int64 GetLastDBUpdateTime() const; //Set: - void SetPolicyFilename( const TSTRING& ); - void SetConfigFilename( const TSTRING& ); - void SetDBFilename( const TSTRING& ); - void SetSystemName( const TSTRING& ); - void SetCommandLineParams( const TSTRING& ); - void SetIPAddress( const TSTRING& ); - void SetCreator( const TSTRING& ); - void SetHostID( const TSTRING& ); - void SetCreationTime( int64 ); - void SetLastDBUpdateTime( int64 ); - + void SetPolicyFilename(const TSTRING&); + void SetConfigFilename(const TSTRING&); + void SetDBFilename(const TSTRING&); + void SetSystemName(const TSTRING&); + void SetCommandLineParams(const TSTRING&); + void SetIPAddress(const TSTRING&); + void SetCreator(const TSTRING&); + void SetHostID(const TSTRING&); + void SetCreationTime(int64); + void SetLastDBUpdateTime(int64); + // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) private: - cHeaderInfo& operator=( cHeaderInfo& ); + cHeaderInfo& operator=(cHeaderInfo&); //Header Data: - TSTRING tstr_PolicyFilename; - TSTRING tstr_ConfigFilename; - TSTRING tstr_DBFilename; - TSTRING tstr_SystemName; - TSTRING tstr_CommandLineParams; - TSTRING tstr_IPAddress; - TSTRING tstr_CreatedBy; - TSTRING tstr_HostID; - int64 i64_CreationTime; - mutable int64 i64_LastDBUpdateTime; + TSTRING tstr_PolicyFilename; + TSTRING tstr_ConfigFilename; + TSTRING tstr_DBFilename; + TSTRING tstr_SystemName; + TSTRING tstr_CommandLineParams; + TSTRING tstr_IPAddress; + TSTRING tstr_CreatedBy; + TSTRING tstr_HostID; + int64 i64_CreationTime; + mutable int64 i64_LastDBUpdateTime; }; /////////////////////////////////////////////////////////////////////////////// @@ -108,29 +108,29 @@ class cGenreHeaderInfo : public iTypedSerializable { DECLARE_TYPEDSERIALIZABLE() -public: +public: cGenreHeaderInfo(); - cGenreHeaderInfo( const cGenreHeaderInfo& ); + cGenreHeaderInfo(const cGenreHeaderInfo&); virtual ~cGenreHeaderInfo(); void Clear(); // the prop displayer ... once this is set, this object owns the destruction of it. - void SetPropDisplayer(iFCOPropDisplayer* pPropDisplayer); - iFCOPropDisplayer* GetPropDisplayer(); - const iFCOPropDisplayer* GetPropDisplayer() const; + void SetPropDisplayer(iFCOPropDisplayer* pPropDisplayer); + iFCOPropDisplayer* GetPropDisplayer(); + const iFCOPropDisplayer* GetPropDisplayer() const; - void SetObjectsScanned( int32 ); - int32 GetObjectsScanned() const; + void SetObjectsScanned(int32); + int32 GetObjectsScanned() const; // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) private: - cGenreHeaderInfo& operator=( cGenreHeaderInfo& ); + cGenreHeaderInfo& operator=(cGenreHeaderInfo&); - iFCOPropDisplayer* mpPropDisplayer; - int32 i32_ObjectsScanned; + iFCOPropDisplayer* mpPropDisplayer; + int32 i32_ObjectsScanned; }; /////////////////////////////////////////////////////////////////////////////// @@ -141,10 +141,11 @@ class cFCODbGenreHeader : public cGenreHeaderInfo { DECLARE_TYPEDSERIALIZABLE() public: - cFCODbGenreHeader() {}; - cFCODbGenreHeader( const cFCODbGenreHeader& rhs ) : cGenreHeaderInfo( rhs ) {}; + cFCODbGenreHeader(){}; + cFCODbGenreHeader(const cFCODbGenreHeader& rhs) : cGenreHeaderInfo(rhs){}; + private: - cFCODbGenreHeader& operator=( cFCODbGenreHeader& ); + cFCODbGenreHeader& operator=(cFCODbGenreHeader&); }; /////////////////////////////////////////////////////////////////////////////// @@ -154,15 +155,14 @@ class cFCODbGenreHeader : public cGenreHeaderInfo class cFCOReportGenreHeader : public cGenreHeaderInfo { public: - cFCOReportGenreHeader() {}; - cFCOReportGenreHeader( const cFCOReportGenreHeader& rhs ) : cGenreHeaderInfo( rhs ) {}; + cFCOReportGenreHeader(){}; + cFCOReportGenreHeader(const cFCOReportGenreHeader& rhs) : cGenreHeaderInfo(rhs){}; DECLARE_TYPEDSERIALIZABLE() private: - cFCOReportGenreHeader& operator=( cFCOReportGenreHeader& ); + cFCOReportGenreHeader& operator=(cFCOReportGenreHeader&); }; - /////////////////////////////////////////////////////////////////////////////// // cFCODbHeader -- specialization of header info for databases // TODO -- once this actually has data, move it to a seperate file @@ -172,8 +172,9 @@ class cFCODbHeader : public cHeaderInfo DECLARE_TYPEDSERIALIZABLE() public: typedef cHeaderInfo inherited; + private: - cFCODbHeader& operator=( cFCODbHeader& ); + cFCODbHeader& operator=(cFCODbHeader&); }; /////////////////////////////////////////////////////////////////////////////// @@ -185,7 +186,7 @@ class cFCOReportHeader : public cHeaderInfo typedef cHeaderInfo inherited; DECLARE_TYPEDSERIALIZABLE() private: - cFCOReportHeader& operator=( cFCOReportHeader& ); + cFCOReportHeader& operator=(cFCOReportHeader&); }; @@ -193,34 +194,108 @@ class cFCOReportHeader : public cHeaderInfo // inline implementation //----------------------------------------------------------------------------- -inline const TSTRING& cHeaderInfo::GetPolicyFilename() const { return tstr_PolicyFilename; }; -inline const TSTRING& cHeaderInfo::GetConfigFilename() const { return tstr_ConfigFilename; }; -inline const TSTRING& cHeaderInfo::GetDBFilename() const { return tstr_DBFilename; }; -inline const TSTRING& cHeaderInfo::GetSystemName() const { return tstr_SystemName; }; -inline const TSTRING& cHeaderInfo::GetCommandLineParams() const { return tstr_CommandLineParams; }; -inline const TSTRING& cHeaderInfo::GetCreator() const { return tstr_CreatedBy; }; -inline const TSTRING& cHeaderInfo::GetIPAddress() const { return tstr_IPAddress; }; -inline const TSTRING& cHeaderInfo::GetHostID() const { return tstr_HostID; }; -inline int64 cHeaderInfo::GetCreationTime() const { return i64_CreationTime; }; -inline int64 cHeaderInfo::GetLastDBUpdateTime() const { return i64_LastDBUpdateTime; }; - -inline void cHeaderInfo::SetPolicyFilename( const TSTRING& tstr ) { tstr_PolicyFilename = tstr; }; -inline void cHeaderInfo::SetConfigFilename( const TSTRING& tstr ) { tstr_ConfigFilename = tstr; }; -inline void cHeaderInfo::SetDBFilename( const TSTRING& tstr ) { tstr_DBFilename = tstr; }; -inline void cHeaderInfo::SetSystemName( const TSTRING& name ) { tstr_SystemName = name; }; -inline void cHeaderInfo::SetCommandLineParams( const TSTRING& tstr ) { tstr_CommandLineParams = tstr; }; -inline void cHeaderInfo::SetCreator( const TSTRING& tstr ) { tstr_CreatedBy = tstr; }; -inline void cHeaderInfo::SetHostID( const TSTRING& tstr ) { tstr_HostID = tstr; }; -inline void cHeaderInfo::SetIPAddress( const TSTRING& tstr ) { tstr_IPAddress = tstr; }; -inline void cHeaderInfo::SetCreationTime( int64 i ) { i64_CreationTime = i; }; -inline void cHeaderInfo::SetLastDBUpdateTime( int64 i ) { i64_LastDBUpdateTime = i; }; - -inline void cGenreHeaderInfo::SetPropDisplayer(iFCOPropDisplayer* pPropDisplayer) { mpPropDisplayer = pPropDisplayer; } -inline iFCOPropDisplayer* cGenreHeaderInfo::GetPropDisplayer() { return mpPropDisplayer; } -inline const iFCOPropDisplayer* cGenreHeaderInfo::GetPropDisplayer() const { return mpPropDisplayer; } -inline void cGenreHeaderInfo::SetObjectsScanned( int32 i ) { i32_ObjectsScanned = i; }; -inline int32 cGenreHeaderInfo::GetObjectsScanned() const { return i32_ObjectsScanned; }; +inline const TSTRING& cHeaderInfo::GetPolicyFilename() const +{ + return tstr_PolicyFilename; +}; +inline const TSTRING& cHeaderInfo::GetConfigFilename() const +{ + return tstr_ConfigFilename; +}; +inline const TSTRING& cHeaderInfo::GetDBFilename() const +{ + return tstr_DBFilename; +}; +inline const TSTRING& cHeaderInfo::GetSystemName() const +{ + return tstr_SystemName; +}; +inline const TSTRING& cHeaderInfo::GetCommandLineParams() const +{ + return tstr_CommandLineParams; +}; +inline const TSTRING& cHeaderInfo::GetCreator() const +{ + return tstr_CreatedBy; +}; +inline const TSTRING& cHeaderInfo::GetIPAddress() const +{ + return tstr_IPAddress; +}; +inline const TSTRING& cHeaderInfo::GetHostID() const +{ + return tstr_HostID; +}; +inline int64 cHeaderInfo::GetCreationTime() const +{ + return i64_CreationTime; +}; +inline int64 cHeaderInfo::GetLastDBUpdateTime() const +{ + return i64_LastDBUpdateTime; +}; + +inline void cHeaderInfo::SetPolicyFilename(const TSTRING& tstr) +{ + tstr_PolicyFilename = tstr; +}; +inline void cHeaderInfo::SetConfigFilename(const TSTRING& tstr) +{ + tstr_ConfigFilename = tstr; +}; +inline void cHeaderInfo::SetDBFilename(const TSTRING& tstr) +{ + tstr_DBFilename = tstr; +}; +inline void cHeaderInfo::SetSystemName(const TSTRING& name) +{ + tstr_SystemName = name; +}; +inline void cHeaderInfo::SetCommandLineParams(const TSTRING& tstr) +{ + tstr_CommandLineParams = tstr; +}; +inline void cHeaderInfo::SetCreator(const TSTRING& tstr) +{ + tstr_CreatedBy = tstr; +}; +inline void cHeaderInfo::SetHostID(const TSTRING& tstr) +{ + tstr_HostID = tstr; +}; +inline void cHeaderInfo::SetIPAddress(const TSTRING& tstr) +{ + tstr_IPAddress = tstr; +}; +inline void cHeaderInfo::SetCreationTime(int64 i) +{ + i64_CreationTime = i; +}; +inline void cHeaderInfo::SetLastDBUpdateTime(int64 i) +{ + i64_LastDBUpdateTime = i; +}; + +inline void cGenreHeaderInfo::SetPropDisplayer(iFCOPropDisplayer* pPropDisplayer) +{ + mpPropDisplayer = pPropDisplayer; +} +inline iFCOPropDisplayer* cGenreHeaderInfo::GetPropDisplayer() +{ + return mpPropDisplayer; +} +inline const iFCOPropDisplayer* cGenreHeaderInfo::GetPropDisplayer() const +{ + return mpPropDisplayer; +} +inline void cGenreHeaderInfo::SetObjectsScanned(int32 i) +{ + i32_ObjectsScanned = i; +}; +inline int32 cGenreHeaderInfo::GetObjectsScanned() const +{ + return i32_ObjectsScanned; +}; #endif //__HEADERINFO_H - diff --git a/src/tw/policyfile.cpp b/src/tw/policyfile.cpp index 9fc16c8..0009dc9 100644 --- a/src/tw/policyfile.cpp +++ b/src/tw/policyfile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,11 +42,18 @@ // GetFileHeaderID() /////////////////////////////////////////////////////////////////////////////// -struct cPolicyFileFHID { +struct cPolicyFileFHID +{ cFileHeaderID* policyID; - cPolicyFileFHID() { policyID = 0; } - ~cPolicyFileFHID() { delete policyID; } + cPolicyFileFHID() + { + policyID = 0; + } + ~cPolicyFileFHID() + { + delete policyID; + } } gPolicyFileFHID; const cFileHeaderID& cPolicyFile::GetFileHeaderID() @@ -59,5 +66,3 @@ const cFileHeaderID& cPolicyFile::GetFileHeaderID() return *gPolicyFileFHID.policyID; } - - diff --git a/src/tw/policyfile.h b/src/tw/policyfile.h index a24378d..b036c01 100644 --- a/src/tw/policyfile.h +++ b/src/tw/policyfile.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -53,5 +53,4 @@ class cPolicyFile //: public iTyped private: }; -#endif - +#endif diff --git a/src/tw/stdtw.cpp b/src/tw/stdtw.cpp index 7111d82..b24d0f8 100644 --- a/src/tw/stdtw.cpp +++ b/src/tw/stdtw.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // // #include "stdtw.h" - -// eof: stdtw.cpp diff --git a/src/tw/stdtw.h b/src/tw/stdtw.h index e7a5a92..162b421 100644 --- a/src/tw/stdtw.h +++ b/src/tw/stdtw.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/tw/systeminfo.cpp b/src/tw/systeminfo.cpp index a71b7d1..48c1700 100644 --- a/src/tw/systeminfo.cpp +++ b/src/tw/systeminfo.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,4 +41,3 @@ bool cSystemInfo::mbExePathSet(false); TSTRING cSystemInfo::mExeDir(_T("")); bool cSystemInfo::mbExeDirSet(false); int64 cSystemInfo::mExecuteStartTime(0); - diff --git a/src/tw/systeminfo.h b/src/tw/systeminfo.h index 67e9f58..3903c5e 100644 --- a/src/tw/systeminfo.h +++ b/src/tw/systeminfo.h @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // systeminfo.h // -// cSystemInfo -- a storage place for run time system information +// cSystemInfo -- a storage place for run time system information #ifndef __SYSTEMINFO_H #define __SYSTEMINFO_H @@ -50,26 +50,26 @@ class cSystemInfo cSystemInfo(); ~cSystemInfo(); - static TSTRING GetExePath(); - static void SetExePath(const TSTRING& path); - // Get the full path to this executable + static TSTRING GetExePath(); + static void SetExePath(const TSTRING& path); + // Get the full path to this executable - static TSTRING GetExeDir(); - static void SetExeDir(const TSTRING& dir); - // these methods get and set the executable's working directory ... it is asserted - // that SetExeDir() has been called when GetExeDir() is called. + static TSTRING GetExeDir(); + static void SetExeDir(const TSTRING& dir); + // these methods get and set the executable's working directory ... it is asserted + // that SetExeDir() has been called when GetExeDir() is called. - static int64 GetExeStartTime(); - static void SetExeStartTime(const int64& time); - // Get and set the approximate time (time_t format) which the excecutable was started. - // This will be used for all times having to do with this run of the executable. + static int64 GetExeStartTime(); + static void SetExeStartTime(const int64& time); + // Get and set the approximate time (time_t format) which the excecutable was started. + // This will be used for all times having to do with this run of the executable. private: - static TSTRING mExePath; - static bool mbExePathSet; - static TSTRING mExeDir; - static bool mbExeDirSet; - static int64 mExecuteStartTime; + static TSTRING mExePath; + static bool mbExePathSet; + static TSTRING mExeDir; + static bool mbExeDirSet; + static int64 mExecuteStartTime; }; //----------------------------------------------------------------------------- @@ -83,29 +83,29 @@ inline cSystemInfo::~cSystemInfo() { } -inline TSTRING cSystemInfo::GetExePath() +inline TSTRING cSystemInfo::GetExePath() { - ASSERT( mbExePathSet ); + ASSERT(mbExePathSet); return mExePath; } inline void cSystemInfo::SetExePath(const TSTRING& path) { - ASSERT( ! path.empty() ); + ASSERT(!path.empty()); mbExePathSet = true; mExePath = path; } -inline TSTRING cSystemInfo::GetExeDir() +inline TSTRING cSystemInfo::GetExeDir() { - ASSERT( mbExeDirSet ); + ASSERT(mbExeDirSet); return mExeDir; } inline void cSystemInfo::SetExeDir(const TSTRING& dir) { - ASSERT( ! dir.empty() ); + ASSERT(!dir.empty()); mbExeDirSet = true; mExeDir = dir; @@ -113,7 +113,7 @@ inline void cSystemInfo::SetExeDir(const TSTRING& dir) inline int64 cSystemInfo::GetExeStartTime() { - ASSERT( mExecuteStartTime != 0 ); + ASSERT(mExecuteStartTime != 0); return mExecuteStartTime; } @@ -123,4 +123,3 @@ inline void cSystemInfo::SetExeStartTime(const int64& time) } #endif //__SYSTEMINFO_H - diff --git a/src/tw/textdbviewer.cpp b/src/tw/textdbviewer.cpp index 6006843..e009125 100644 --- a/src/tw/textdbviewer.cpp +++ b/src/tw/textdbviewer.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -79,42 +79,54 @@ using namespace std; // GLOBALS //========================================================================= -static const TCHAR* g_sz79Dashes = _T("-------------------------------------------------------------------------------"); -static const TCHAR* g_sz79Equals = _T("==============================================================================="); +static const TCHAR* g_sz79Dashes = + _T("-------------------------------------------------------------------------------"); +static const TCHAR* g_sz79Equals = + _T("==============================================================================="); //========================================================================= // UTIL FUNCTION PROTOTYES //========================================================================= -static void InitOStream( TOSTREAM* pOut ); -static void DisplayFCOProps( const iFCO* const pFCO, const iFCOPropDisplayer* pPD, TOSTREAM* pOut ); +static void InitOStream(TOSTREAM* pOut); +static void DisplayFCOProps(const iFCO* const pFCO, const iFCOPropDisplayer* pPD, TOSTREAM* pOut); -static void OutputDatabaseHeader ( const cFCODbHeader& dbHeader, TOSTREAM* pOut ); +static void OutputDatabaseHeader(const cFCODbHeader& dbHeader, TOSTREAM* pOut); // Currently we don't have a rule summary. See function definition below //static void OutputRulesSummary ( const cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut ); -static void OutputSectionDelimiter( int nString, TOSTREAM* pOut ); -static void OutputGenreDelimiter( cGenre::Genre g, TOSTREAM* pOut ); +static void OutputSectionDelimiter(int nString, TOSTREAM* pOut); +static void OutputGenreDelimiter(cGenre::Genre g, TOSTREAM* pOut); -static void OutputObjectSummary( cFCODatabaseFile& rd, TOSTREAM* pOut, int margin ); -static void OutputObjectDetail( cFCODatabaseFile& rd, TOSTREAM* pOut ); +static void OutputObjectSummary(cFCODatabaseFile& rd, TOSTREAM* pOut, int margin); +static void OutputObjectDetail(cFCODatabaseFile& rd, TOSTREAM* pOut); -static void OutputObjectSummary( cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin ); -static void OutputObjectDetail( cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut ); +static void + OutputObjectSummary(cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin); +static void OutputObjectDetail(cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut); -static void OutputIterChildren ( cDbDataSourceIter dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails ); -static void OutputIterPeers ( cDbDataSourceIter dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails ); +static void OutputIterChildren(cDbDataSourceIter dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails); +static void OutputIterPeers(cDbDataSourceIter dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails); //static void OutputIter ( cDbDataSourceIter& dbIter, const iFCOPropDisplayer* pPD, TOSTREAM* pOut, bool fDetails ); -static void PrintFCOShort ( const iFCO* pFCO, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin ); +static void PrintFCOShort( + const iFCO* pFCO, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin); //static void OutputSpecHeader( const cFCODbSpecIter& dbi, TOSTREAM* pOut ); //static void OutputDetailHeader( const cFCODbSpecIter& dbi, int nObjects, TOSTREAM* pOut ); -static TSTRING util_Encode( const TSTRING& sIn ) +static TSTRING util_Encode(const TSTRING& sIn) { static cDisplayEncoder e; - TSTRING sOut = sIn; - e.Encode( sOut ); + TSTRING sOut = sIn; + e.Encode(sOut); return sOut; } @@ -122,57 +134,59 @@ static TSTRING util_Encode( const TSTRING& sIn ) // METHOD CODE //========================================================================= -void cTextDBViewer::PrintDB( cFCODatabaseFile& rd, const TSTRING& strFilename ) +void cTextDBViewer::PrintDB(cFCODatabaseFile& rd, const TSTRING& strFilename, DbVerbosity verbosity) { TOSTREAM* pOut; TOFSTREAM fileOut; - bool fIsFile = false; + bool fIsFile = false; - if( strFilename == _T("-") ) + if (strFilename == _T("-")) { pOut = &TCOUT; } else { //Gonna have to insert a lame hack here, since ostr.open DEMANDS a const char*!! -#ifdef _UNICODE - char ncBuf[ iFSServices::TW_MAX_PATH ]; - wcstombs( ncBuf, strFilename.c_str(), sizeof(char)); - fileOut.open( ncBuf ); -#else //narrow character mode - fileOut.open( strFilename.c_str() ); -#endif + fileOut.open(strFilename.c_str()); - if( fileOut.is_open() ) + if (fileOut.is_open()) { - pOut = &fileOut; + pOut = &fileOut; fIsFile = true; } else { - ASSERT( false ); - throw eArchiveOpen( strFilename, iFSServices::GetInstance()->GetErrString() ); + ASSERT(false); + throw eArchiveOpen(strFilename, iFSServices::GetInstance()->GetErrString()); } } - InitOStream( pOut ); - + InitOStream(pOut); + // // output header, just like it sez.... // - OutputDatabaseHeader( rd.GetHeader(), pOut ); + OutputDatabaseHeader(rd.GetHeader(), pOut); - OutputObjectSummary( rd, pOut, DETAILS_MARGIN ); - OutputObjectDetail( rd, pOut ); + if (verbosity > SUMMARY) + { + //TODO: OutputRulesSummary() would go here + + OutputObjectSummary(rd, pOut, DETAILS_MARGIN); + + if (verbosity == VERBOSE) + { + OutputObjectDetail(rd, pOut); + } + } - // we're done (*pOut) << g_sz79Dashes << endl; - (*pOut) << TSS_GetString( cTW, tw::STR_END_OF_DB ) << endl << endl; - (*pOut) << TSS_GetString( cTW, tw::STR_COPYRIGHT ) << endl; + (*pOut) << TSS_GetString(cTW, tw::STR_END_OF_DB) << endl << endl; + (*pOut) << TSS_GetString(cTW, tw::STR_COPYRIGHT) << endl; - if( fIsFile ) + if (fIsFile) static_cast(pOut)->close(); return; @@ -182,22 +196,28 @@ void cTextDBViewer::PrintDB( cFCODatabaseFile& rd, const TSTRING& strFilename ) /////////////////////////////////////////////////////////////////////////////// // OutputFCO /////////////////////////////////////////////////////////////////////////////// -void cTextDBViewer::OutputFCO( cDbDataSourceIter& dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails ) -{ - InitOStream( pOut ); +void cTextDBViewer::OutputFCO(cDbDataSourceIter& dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails) +{ + InitOStream(pOut); - if( dbIter.HasFCOData() ) + if (dbIter.HasFCOData()) { iFCO* pFCO = dbIter.CreateFCO(); - - if( fDetails ) + + if (fDetails) { - (*pOut) << TSS_GetString( cTW, tw::STR_OBJECT_NAME ) << _T(" ") << pNT->ToStringDisplay( pFCO->GetName() ).c_str() << endl << endl; - DisplayFCOProps( pFCO, pPD, pOut ); + (*pOut) << TSS_GetString(cTW, tw::STR_OBJECT_NAME) << _T(" ") + << pNT->ToStringDisplay(pFCO->GetName()).c_str() << endl + << endl; + DisplayFCOProps(pFCO, pPD, pOut); (*pOut) << endl << endl; } else - PrintFCOShort( pFCO, pPD, pNT, pOut, DETAILS_MARGIN ); + PrintFCOShort(pFCO, pPD, pNT, pOut, DETAILS_MARGIN); pFCO->Release(); } @@ -208,117 +228,117 @@ void cTextDBViewer::OutputFCO( cDbDataSourceIter& dbIter, const iFCOPropDisplaye // UTIL FUNCTION CODE //========================================================================= -void InitOStream( TOSTREAM* pOut ) +void InitOStream(TOSTREAM* pOut) { // align left - (*pOut).flags( ( (*pOut).flags() & ~std::ios::adjustfield ) | std::ios::left ); + (*pOut).flags(((*pOut).flags() & ~std::ios::adjustfield) | std::ios::left); } /////////////////////////////////////////////////////////////////////////////// // PrintFCOShort /////////////////////////////////////////////////////////////////////////////// -static void PrintFCOShort( const iFCO* pFCO, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin ) +static void +PrintFCOShort(const iFCO* pFCO, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin) { - ASSERT( pOut != 0); + ASSERT(pOut != 0); TSTRING strDetails; - // + // // output ""\n\t
" // (*pOut) << _T(" "); - (*pOut) << pNT->ToStringDisplay( pFCO->GetName() ).c_str(); + (*pOut) << pNT->ToStringDisplay(pFCO->GetName()).c_str(); (*pOut) << endl; - (*pOut) << setw( margin ) << _T(""); - pPD->GetDetails( pFCO, strDetails ); + (*pOut) << setw(margin) << _T(""); + pPD->GetDetails(pFCO, strDetails); (*pOut) << strDetails; (*pOut) << _T("\n"); } -static void OutputIterChildren( cDbDataSourceIter dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails ) +static void OutputIterChildren(cDbDataSourceIter dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails) { dbIter.Descend(); - OutputIterPeers( dbIter, pPD, pNT, pOut, fDetails ); + OutputIterPeers(dbIter, pPD, pNT, pOut, fDetails); } -static void OutputIterPeers( cDbDataSourceIter dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails ) +static void OutputIterPeers(cDbDataSourceIter dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails) { - for ( dbIter.SeekBegin(); ! dbIter.Done(); dbIter.Next() ) + for (dbIter.SeekBegin(); !dbIter.Done(); dbIter.Next()) { // TODO: this obviously needs to be expanded upon. - cTextDBViewer::OutputFCO( dbIter, pPD, pNT, pOut, fDetails ); + cTextDBViewer::OutputFCO(dbIter, pPD, pNT, pOut, fDetails); - if( dbIter.CanDescend() ) - OutputIterChildren( dbIter, pPD, pNT, pOut, fDetails ); + if (dbIter.CanDescend()) + OutputIterChildren(dbIter, pPD, pNT, pOut, fDetails); } } -static void OutputDatabaseHeader( const cFCODbHeader& dbHeader, TOSTREAM* pOut ) +static void OutputDatabaseHeader(const cFCODbHeader& dbHeader, TOSTREAM* pOut) { const int headerColumnWidth = 30; - (*pOut) << TSS_GetString( cTW, tw::STR_DBPRINT_TITLE ) << endl << endl; - + (*pOut) << TSS_GetString(cTW, tw::STR_DBPRINT_TITLE) << endl << endl; + (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_DB_GENERATED_BY ) << util_Encode( dbHeader.GetCreator() ) << endl; - + (*pOut) << TSS_GetString(cTW, tw::STR_DB_GENERATED_BY) << util_Encode(dbHeader.GetCreator()) << endl; + TSTRING tstrDummy; - int64 i64CreateTime = dbHeader.GetCreationTime(); + int64 i64CreateTime = dbHeader.GetCreationTime(); (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_DB_CREATED_ON ) << cTWLocale::FormatTime( i64CreateTime, tstrDummy ).c_str() << endl; - + (*pOut) << TSS_GetString(cTW, tw::STR_DB_CREATED_ON) << cTWLocale::FormatTime(i64CreateTime, tstrDummy).c_str() + << endl; + (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_DB_LAST_UPDATE ); + (*pOut) << TSS_GetString(cTW, tw::STR_DB_LAST_UPDATE); int64 i64LastDBUTime = dbHeader.GetLastDBUpdateTime(); - if( i64LastDBUTime == 0 ) - { - (*pOut) << TSS_GetString( cTW, tw::STR_NEVER ) << endl << endl; + if (i64LastDBUTime == 0) + { + (*pOut) << TSS_GetString(cTW, tw::STR_NEVER) << endl << endl; } else - { - (*pOut) << cTWLocale::FormatTime( i64LastDBUTime, tstrDummy ).c_str() << endl << endl; + { + (*pOut) << cTWLocale::FormatTime(i64LastDBUTime, tstrDummy).c_str() << endl << endl; } - OutputSectionDelimiter( tw::STR_DB_SUMMARY, pOut ); + OutputSectionDelimiter(tw::STR_DB_SUMMARY, pOut); (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_HOST_NAME ) << dbHeader.GetSystemName().c_str() << endl; + (*pOut) << TSS_GetString(cTW, tw::STR_HOST_NAME) << dbHeader.GetSystemName().c_str() << endl; (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_HOST_IP ) << dbHeader.GetIPAddress() << endl; + (*pOut) << TSS_GetString(cTW, tw::STR_HOST_IP) << dbHeader.GetIPAddress() << endl; - -// only output host ID on UNIX systems -#if IS_UNIX - (*pOut).width(headerColumnWidth); - (*pOut) << TSS_GetString( cTW, tw::STR_HOST_ID ); - if(! dbHeader.GetHostID().empty() ) + (*pOut).width(headerColumnWidth); + (*pOut) << TSS_GetString(cTW, tw::STR_HOST_ID); + + if (!dbHeader.GetHostID().empty()) (*pOut) << dbHeader.GetHostID() << endl; else - (*pOut) << TSS_GetString( cTW, tw::STR_NONE ) << endl; -#endif + (*pOut) << TSS_GetString(cTW, tw::STR_NONE) << endl; - (*pOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_POLICY_FILE_USED ) - << util_Encode( dbHeader.GetPolicyFilename() ) - << endl; - (*pOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_CONFIG_FILE_USED ) - << util_Encode( dbHeader.GetConfigFilename() ) - << endl; + (*pOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_POLICY_FILE_USED) + << util_Encode(dbHeader.GetPolicyFilename()) << endl; - (*pOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_DB_FILE_USED ) - << util_Encode( dbHeader.GetDBFilename() ) - << endl; + (*pOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_CONFIG_FILE_USED) + << util_Encode(dbHeader.GetConfigFilename()) << endl; - (*pOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_CMD_LINE_USED ) - << util_Encode( dbHeader.GetCommandLineParams() ) - << endl + (*pOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_DB_FILE_USED) + << util_Encode(dbHeader.GetDBFilename()) << endl; + + (*pOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_CMD_LINE_USED) + << util_Encode(dbHeader.GetCommandLineParams()) << endl << endl; } @@ -385,78 +405,77 @@ static void OutputRulesSummary(const cFCODatabaseFileIter& genreIter, const iFCO #endif - -void OutputSectionDelimiter( int nString, TOSTREAM* pOut ) +void OutputSectionDelimiter(int nString, TOSTREAM* pOut) { (*pOut) << g_sz79Equals << endl; - (*pOut) << TSS_GetString( cTW, nString ) << endl; + (*pOut) << TSS_GetString(cTW, nString) << endl; (*pOut) << g_sz79Equals << endl << endl; } -void OutputGenreDelimiter( cGenre::Genre g, TOSTREAM* pOut ) +void OutputGenreDelimiter(cGenre::Genre g, TOSTREAM* pOut) { (*pOut) << g_sz79Dashes << endl; - (*pOut) << _T("# ") << TSS_GetString( cTW, tw::STR_SECTION ); - (*pOut) << _T(": ") << cGenreSwitcher::GetInstance()->GenreToString( g, true ) << endl; + (*pOut) << _T("# ") << TSS_GetString(cTW, tw::STR_SECTION); + (*pOut) << _T(": ") << cGenreSwitcher::GetInstance()->GenreToString(g, true) << endl; (*pOut) << g_sz79Dashes << endl << endl; } -void OutputObjectSummary( cFCODatabaseFile& rd, TOSTREAM* pOut, int margin ) -{ - OutputSectionDelimiter( tw::STR_OBJECT_SUMMARY, pOut ); +void OutputObjectSummary(cFCODatabaseFile& rd, TOSTREAM* pOut, int margin) +{ + OutputSectionDelimiter(tw::STR_OBJECT_SUMMARY, pOut); cFCODatabaseFileIter genreIter(rd); for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { - cGenreSwitcher::GetInstance()->SelectGenre( (cGenre::Genre) genreIter.GetGenre() ); - + cGenreSwitcher::GetInstance()->SelectGenre((cGenre::Genre)genreIter.GetGenre()); + iFCONameTranslator* pNT = iTWFactory::GetInstance()->GetNameTranslator(); - - OutputGenreDelimiter( (cGenre::Genre) genreIter.GetGenre(), pOut ); + + OutputGenreDelimiter((cGenre::Genre)genreIter.GetGenre(), pOut); // Currently we don't have a rule summary. See function definition below //OutputRulesSummary( genreIter, pNT, pOut); - OutputObjectSummary( genreIter, pNT, pOut, margin ); + OutputObjectSummary(genreIter, pNT, pOut, margin); } } -void OutputObjectSummary( cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin ) +void OutputObjectSummary(cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut, int margin) { - const cDbDataSourceIter dbIter( &genreIter.GetDb() ); + const cDbDataSourceIter dbIter(&genreIter.GetDb()); ASSERT(dbIter.AtRoot()); - (*pOut) << setw( margin ) << _T(""); + (*pOut) << setw(margin) << _T(""); TSTRING strBuf; - (*pOut) << genreIter.GetGenreHeader().GetPropDisplayer()->GetDetailsHeader( strBuf, margin ).c_str() << endl; + (*pOut) << genreIter.GetGenreHeader().GetPropDisplayer()->GetDetailsHeader(strBuf, margin).c_str() << endl; - OutputIterPeers( dbIter, genreIter.GetGenreHeader().GetPropDisplayer(), pNT, pOut, false ); + OutputIterPeers(dbIter, genreIter.GetGenreHeader().GetPropDisplayer(), pNT, pOut, false); (*pOut) << endl; } -void OutputObjectDetail( cFCODatabaseFile& rd, TOSTREAM* pOut ) +void OutputObjectDetail(cFCODatabaseFile& rd, TOSTREAM* pOut) { - OutputSectionDelimiter( tw::STR_OBJECT_DETAIL, pOut ); + OutputSectionDelimiter(tw::STR_OBJECT_DETAIL, pOut); cFCODatabaseFileIter genreIter(rd); for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { - cGenreSwitcher::GetInstance()->SelectGenre( (cGenre::Genre) genreIter.GetGenre() ); + cGenreSwitcher::GetInstance()->SelectGenre((cGenre::Genre)genreIter.GetGenre()); iFCONameTranslator* pNT = iTWFactory::GetInstance()->GetNameTranslator(); - - OutputGenreDelimiter( (cGenre::Genre) genreIter.GetGenre(), pOut ); - OutputObjectDetail( genreIter, pNT, pOut ); + OutputGenreDelimiter((cGenre::Genre)genreIter.GetGenre(), pOut); + + OutputObjectDetail(genreIter, pNT, pOut); } } -void OutputObjectDetail( cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut ) +void OutputObjectDetail(cFCODatabaseFileIter& genreIter, const iFCONameTranslator* pNT, TOSTREAM* pOut) { const cDbDataSourceIter dbIterDetails(&genreIter.GetDb()); - - OutputIterPeers( dbIterDetails, genreIter.GetGenreHeader().GetPropDisplayer(), pNT, pOut, true); + + OutputIterPeers(dbIterDetails, genreIter.GetGenreHeader().GetPropDisplayer(), pNT, pOut, true); (*pOut) << endl; } @@ -493,47 +512,43 @@ static void OutputSpecHeader( const cFCODbSpecIter &dbi, TOSTREAM* pOut ) */ -void DisplayFCOProps( const iFCO* const pFCO, const iFCOPropDisplayer* pPD, TOSTREAM* pOut ) +void DisplayFCOProps(const iFCO* const pFCO, const iFCOPropDisplayer* pPD, TOSTREAM* pOut) { - ASSERT( pOut != 0); - ASSERT( pFCO != 0); - - const int attrNameWidth = 24; + ASSERT(pOut != 0); + ASSERT(pFCO != 0); + + const int attrNameWidth = 24; const int attrValueWidth = 28; // output header // TODO: make these constants into enums - (*pOut).width( attrNameWidth ); - (*pOut) << TSS_GetString( cTW, tw::STR_ATTRIBUTES ); - (*pOut).width( attrValueWidth ); - (*pOut) << TSS_GetString( cTW, tw::STR_ATTR_VALUE ); + (*pOut).width(attrNameWidth); + (*pOut) << TSS_GetString(cTW, tw::STR_ATTRIBUTES); + (*pOut).width(attrValueWidth); + (*pOut) << TSS_GetString(cTW, tw::STR_ATTR_VALUE); (*pOut) << endl; - - (*pOut).width( attrNameWidth ); + + (*pOut).width(attrNameWidth); (*pOut) << _T("-------------"); - (*pOut).width( attrValueWidth ); + (*pOut).width(attrValueWidth); (*pOut) << _T("-----------"); (*pOut) << endl; int iNumProps = pFCO->GetPropSet()->GetNumProps(); - for( int j = 0; j < iNumProps; j++ ) + for (int j = 0; j < iNumProps; j++) { // output if prop is in FCO, and prop is not cFCOUndefinedProp - if( - pFCO->GetPropSet()->GetValidVector().ContainsItem( j ) - && - pFCO->GetPropSet()->GetPropAt( j )->GetType() != cFCOUndefinedProp::GetInstance()->GetType() - ) + if (pFCO->GetPropSet()->GetValidVector().ContainsItem(j) && + pFCO->GetPropSet()->GetPropAt(j)->GetType() != cFCOUndefinedProp::GetInstance()->GetType()) { TSTRING strProp; // output property name - (*pOut).width( attrNameWidth ); + (*pOut).width(attrNameWidth); (*pOut) << pFCO->GetPropSet()->GetPropName(j); - (*pOut).width( attrValueWidth ); - (*pOut) << pPD->PropAsString( pFCO, j, attrNameWidth, 0 ); + (*pOut).width(attrValueWidth); + (*pOut) << pPD->PropAsString(pFCO, j, attrNameWidth, 0); (*pOut) << _T("\n"); } } } - diff --git a/src/tw/textdbviewer.h b/src/tw/textdbviewer.h index b81e800..2e8fba6 100644 --- a/src/tw/textdbviewer.h +++ b/src/tw/textdbviewer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -50,12 +50,25 @@ class iFCONameTranslator; class cTextDBViewer { public: - - static void PrintDB( cFCODatabaseFile& rd, const TSTRING& strFilename ); // throw - static void OutputFCO( cDbDataSourceIter& dbIter, const iFCOPropDisplayer* pPD, const iFCONameTranslator* pNT, TOSTREAM* pOut, bool fDetails = true ); - // prints to the given ostream a text representation of the FCO pointed at by the iter. Silently - // does nothing if(dbIter.Done()). + enum DbVerbosity + { + INVALID, + SUMMARY, + CONCISE, + VERBOSE + }; + + static void PrintDB(cFCODatabaseFile& rd, const TSTRING& strFilename, DbVerbosity=VERBOSE); // throw + + static void OutputFCO(cDbDataSourceIter& dbIter, + const iFCOPropDisplayer* pPD, + const iFCONameTranslator* pNT, + TOSTREAM* pOut, + bool fDetails = true); + // prints to the given ostream a text representation of the FCO pointed at by the iter. Silently + // does nothing if(dbIter.Done()). + private: // // private enums @@ -67,5 +80,3 @@ class cTextDBViewer }; #endif // __TEXTDBVIEWER_H - - diff --git a/src/tw/textreportviewer.cpp b/src/tw/textreportviewer.cpp index a43de25..2d24b5b 100644 --- a/src/tw/textreportviewer.cpp +++ b/src/tw/textreportviewer.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -86,10 +86,10 @@ #include #include #ifdef HAVE_WCHAR_H -# include +#include #endif #ifdef HAVE_UNISTD_H -# include +#include #endif //========================================================================= @@ -102,67 +102,72 @@ using namespace std; // GLOBALS //========================================================================= -static const TCHAR* g_sz79Dashes = _T("-------------------------------------------------------------------------------"); +static const TCHAR* g_sz79Dashes = + _T("-------------------------------------------------------------------------------"); static const TCHAR* g_sz40Dashes = _T("----------------------------------------"); -static const TCHAR* g_sz79Equals = _T("==============================================================================="); +static const TCHAR* g_sz79Equals = + _T("==============================================================================="); //========================================================================= // UTIL FUNCTION PROTOTYES //========================================================================= -static void OpenOutputFile( fixed_basic_ofstream& out, const TSTRING& strFile ); // throw( eTextReportViewer ) -static void OpenInputFile ( std::ifstream& out, const TSTRING& strFile ); // throw( eTextReportViewer ) -static bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ); +static void OpenOutputFile(fixed_basic_ofstream& out, const TSTRING& strFile); // throw( eTextReportViewer ) +static void OpenInputFile(std::ifstream& out, const TSTRING& strFile); // throw( eTextReportViewer ) +static bool PrintableProp(const iFCO* pfcoOld, const iFCO* pfcoNew, int j); -static bool SpecEmpty( const cFCOReportSpecIter& ri ); +static bool SpecEmpty(const cFCOReportSpecIter& ri); -static TSTRING util_Encode( const TSTRING& sIn ) +static TSTRING util_Encode(const TSTRING& sIn) { static cDisplayEncoder e; - TSTRING sOut = sIn; - e.Encode( sOut ); + TSTRING sOut = sIn; + e.Encode(sOut); return sOut; } //========================================================================= // METHOD CODE //========================================================================= -cTextReportViewer::cTextReportViewer( const cFCOReportHeader& h, const cFCOReport& r ) +cTextReportViewer::cTextReportViewer(const cFCOReportHeader& h, const cFCOReport& r) { - Init( h, const_cast(r) ); // TODO:BAM -- hack to allow creation - // for updating (non-const report) and non-updating - // (const report) in one constructor format + Init(h, const_cast(r)); // TODO:BAM -- hack to allow creation + // for updating (non-const report) and non-updating + // (const report) in one constructor format } -cTextReportViewer::cTextReportViewer( const cFCOReportHeader& h, cFCOReport& r ) +cTextReportViewer::cTextReportViewer(const cFCOReportHeader& h, cFCOReport& r) { - Init( h, r ); + Init(h, r); } -int cTextReportViewer::Init( const cFCOReportHeader& h, cFCOReport& r ) +int cTextReportViewer::Init(const cFCOReportHeader& h, cFCOReport& r) { - mpHeader = &h; - mpReport = &r; - mpOut = NULL; - mpCurPD = NULL; - mpCurNT = NULL; - mfUpdate = false; + mpHeader = &h; + mpReport = &r; + mpOut = NULL; + mpIn = NULL; + mpCurPD = NULL; + mpCurNT = NULL; + mfUpdate = false; mMaxSeverityViolated = 0; - mNumberViolations = 0; - mErrorNum = 1; - mReportingLevel = FULL_REPORT; - mfGotNumbers = false; - mCurrentCharSize = 0; + mNumberViolations = 0; + mErrorNum = 1; + mReportingLevel = FULL_REPORT; + mfGotNumbers = false; + mCurrentChar[0] = '\0'; + mCurrentCharSize = 0; + mFilterFCOs = false; return 0; } cTextReportViewer::~cTextReportViewer() { - if( mfUpdate ) + if (mfUpdate) { - for( GenreList::iterator i = mFCOsRemoveFromReport.begin(); i != mFCOsRemoveFromReport.end(); i++ ) + for (GenreList::iterator i = mFCOsRemoveFromReport.begin(); i != mFCOsRemoveFromReport.end(); ++i) { - ASSERT( i->second != 0 ); + ASSERT(i->second != 0); i->second->clear(); delete i->second; } @@ -172,7 +177,7 @@ cTextReportViewer::~cTextReportViewer() int cTextReportViewer::GetMaxSeverityViolated() { - if( ! mfGotNumbers ) + if (!mfGotNumbers) GetReportNumbers(); return mMaxSeverityViolated; @@ -180,7 +185,7 @@ int cTextReportViewer::GetMaxSeverityViolated() int cTextReportViewer::GetNumberViolations() { - if( ! mfGotNumbers ) + if (!mfGotNumbers) GetReportNumbers(); return mNumberViolations; @@ -189,10 +194,11 @@ int cTextReportViewer::GetNumberViolations() void cTextReportViewer::InitOStream() { // align left - (*mpOut).flags( ( (*mpOut).flags() & ~std::ios::adjustfield ) | std::ios::left ); + (*mpOut).flags(((*mpOut).flags() & ~std::ios::adjustfield) | std::ios::left); } -void cTextReportViewer::DisplayReportAndHaveUserUpdateIt( const TSTRING& edName, ReportingLevel level ) //throw (eFSServices) +void cTextReportViewer::DisplayReportAndHaveUserUpdateIt(const TSTRING& edName, + ReportingLevel level) //throw (eFSServices) { if (!CanUpdate()) { @@ -200,57 +206,57 @@ void cTextReportViewer::DisplayReportAndHaveUserUpdateIt( const TSTRING& edName, THROW_INTERNAL("textreportviewer.cpp"); } - ASSERT( ! edName.empty() ); + ASSERT(!edName.empty()); // // get temp filename in which to store user-readable report // - TSTRING strTempFile; + TSTRING strTempFile; iFSServices* pFSServices = iFSServices::GetInstance(); - ASSERT( pFSServices != 0 ); + ASSERT(pFSServices != 0); - pFSServices->GetTempDirName( strTempFile ); + pFSServices->GetTempDirName(strTempFile); strTempFile += _T("twtempXXXXXX"); - pFSServices->MakeTempFilename( strTempFile ); + pFSServices->MakeTempFilename(strTempFile); // this try/catch ensures the temp file was removed... try { // we are updating... - mfUpdate = true; + mfUpdate = true; // // write report to the temp file. put checks beside each FCO entry. - // - PrintTextReport( strTempFile, level ); - + // + PrintTextReport(strTempFile, level); + // // find an appropriate editor and launch it on the temp file. the user // can uncheck any item she doesn't want put back into the database. // - LaunchEditorOnFile( strTempFile, edName ); + LaunchEditorOnFile(strTempFile, edName); // // read report back in from the temp file and remove any unchecked entries from // the report // - ReadTextReport( strTempFile ); + ReadTextReport(strTempFile); // // remove unchecked elements from remove - // + // RemoveFCOsFromReport(); } - catch(...) + catch (...) { // delete the temp file, then rethrow - pFSServices->FileDelete( strTempFile ); + pFSServices->FileDelete(strTempFile); throw; } // // delete temp file // - pFSServices->FileDelete( strTempFile ); + pFSServices->FileDelete(strTempFile); } /////////////////////////////////////////////////////////////////////////////// @@ -260,11 +266,11 @@ void cTextReportViewer::DisplayReportAndHaveUserUpdateIt( const TSTRING& edName, // version that takes a file name is just a convenience function that calls the // ostream version. '-' can be passed to signify stdout. /////////////////////////////////////////////////////////////////////////////// -void cTextReportViewer::PrintTextReport( const TSTRING& strFilename, ReportingLevel level ) //throw (eTextReportViewer); +void cTextReportViewer::PrintTextReport(const TSTRING& strFilename, ReportingLevel level) //throw (eTextReportViewer); { mReportingLevel = level; - if( strFilename.compare(_T("-")) == 0 ) + if (strFilename.compare(_T("-")) == 0) { mpOut = &TCOUT; OutputTextReport(); @@ -272,7 +278,7 @@ void cTextReportViewer::PrintTextReport( const TSTRING& strFilename, ReportingLe else { fixed_basic_ofstream out; - OpenOutputFile( out, strFilename ); + OpenOutputFile(out, strFilename); mpOut = &out; OutputTextReport(); out.close(); @@ -282,47 +288,47 @@ void cTextReportViewer::PrintTextReport( const TSTRING& strFilename, ReportingLe /////////////////////////////////////////////////////////////////////////////// // PrintTextReport /////////////////////////////////////////////////////////////////////////////// -void cTextReportViewer::PrintTextReport( TOSTREAM& ostr, ReportingLevel level ) +void cTextReportViewer::PrintTextReport(TOSTREAM& ostr, ReportingLevel level) { mReportingLevel = level; - mpOut = &ostr; + mpOut = &ostr; OutputTextReport(); } void cTextReportViewer::GetReportNumbers() { - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) - { + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { // We need to at least get the max severity in this function - cFCOReportSpecIter ri( genreIter ); - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) - { - if( !IgnoreThisSpec( ri.GetAttr() ) ) + cFCOReportSpecIter ri(genreIter); + for (ri.SeekBegin(); !ri.Done(); ri.Next()) + { + if (!IgnoreThisSpec(ri.GetAttr())) { int nAdded = ri.GetAddedSet()->Size(); int nRemoved = ri.GetRemovedSet()->Size(); int nChanged = ri.GetNumChanged(); - if( nAdded || nRemoved || nChanged ) + if (nAdded || nRemoved || nChanged) { // update the max severity - if( mMaxSeverityViolated < ri.GetAttr()->GetSeverity() ) + if (mMaxSeverityViolated < ri.GetAttr()->GetSeverity()) mMaxSeverityViolated = ri.GetAttr()->GetSeverity(); - mNumberViolations += ( nAdded + nRemoved + nChanged ); + mNumberViolations += (nAdded + nRemoved + nChanged); } } } - } + } mfGotNumbers = true; } void cTextReportViewer::OutputTextReport() //throw (eTextReportViewer); { - ASSERT( mpOut != 0 ); + ASSERT(mpOut != 0); InitOStream(); @@ -334,21 +340,21 @@ void cTextReportViewer::OutputTextReport() //throw (eTextReportViewer); // // TODO: move this // - if( SINGLE_LINE == mReportingLevel ) + if (SINGLE_LINE == mReportingLevel) { (*mpOut) << SingleLineReport() << endl; } - else if( PARSEABLE == mReportingLevel ) - { + else if (PARSEABLE == mReportingLevel) + { OutputParseableReport(); } - else if( SUMMARY_ONLY <= mReportingLevel ) - { + else if (SUMMARY_ONLY <= mReportingLevel) + { // // output header, just like it sez.... // OutputReportHeader(); - + // // output summary info // @@ -359,23 +365,23 @@ void cTextReportViewer::OutputTextReport() //throw (eTextReportViewer); // // don't print out object summary if in CONCISE_REPORT because // the detailed report will look a lot like the summary. - // - if( CONCISE_REPORT != mReportingLevel ) - { + // + if (CONCISE_REPORT != mReportingLevel) + { OutputObjectSummary(); } - if( CONCISE_REPORT <= mReportingLevel ) - { + if (CONCISE_REPORT <= mReportingLevel) + { // // print details of rule-breakers // OutputObjectDetails(); - } - + } + // // output any errors - // + // PrintErrors(); // @@ -385,13 +391,13 @@ void cTextReportViewer::OutputTextReport() //throw (eTextReportViewer); } } -void cTextReportViewer::SetUpForNewGenre( const cFCOReportGenreIter& genreIter ) +void cTextReportViewer::SetUpForNewGenre(const cFCOReportGenreIter& genreIter) { // // set up prop displayer and name translator // mpCurPD = genreIter.GetGenreHeader().GetPropDisplayer(); - mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre( genreIter.GetGenre() )->GetNameTranslator(); + mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre(genreIter.GetGenre())->GetNameTranslator(); } void cTextReportViewer::PrintErrors() @@ -399,204 +405,204 @@ void cTextReportViewer::PrintErrors() // // output header // - OutputSectionDelimiter( tw::STR_ERROR_REPORT ); + OutputSectionDelimiter(tw::STR_ERROR_REPORT); // // output any errors from the report's general error queue - // - bool fAtLeastOneGeneralError = false; - cErrorQueueIter eqIter( *( mpReport->GetErrorQueue() ) ); - for( eqIter.SeekBegin(); !eqIter.Done(); eqIter.Next() ) + // + bool fAtLeastOneGeneralError = false; + cErrorQueueIter eqIter(*(mpReport->GetErrorQueue())); + for (eqIter.SeekBegin(); !eqIter.Done(); eqIter.Next()) { - ReportError( eqIter ); + ReportError(eqIter); fAtLeastOneGeneralError = true; } // separate general errors from genre errors - if( fAtLeastOneGeneralError ) + if (fAtLeastOneGeneralError) (*mpOut) << endl; // // cycle through genres - // - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) + // + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { // // set up prop displayer and name translator // - SetUpForNewGenre( genreIter ); + SetUpForNewGenre(genreIter); // // report errors for genre - // - bool fFirstErrorInGenre = true; - cFCOReportSpecIter rsi( genreIter ); - for( rsi.SeekBegin(); !rsi.Done(); rsi.Next() ) + // + bool fFirstErrorInGenre = true; + cFCOReportSpecIter rsi(genreIter); + for (rsi.SeekBegin(); !rsi.Done(); rsi.Next()) { - cErrorQueueIter eqIter( *( rsi.GetErrorQueue() ) ); - for( eqIter.SeekBegin(); !eqIter.Done(); eqIter.Next() ) - { - if( fFirstErrorInGenre ) + cErrorQueueIter eqIter2(*(rsi.GetErrorQueue())); + for (eqIter2.SeekBegin(); !eqIter2.Done(); eqIter2.Next()) + { + if (fFirstErrorInGenre) { - OutputGenreDelimiter( genreIter.GetGenre() ); + OutputGenreDelimiter(genreIter.GetGenre()); fFirstErrorInGenre = false; } - ReportError( eqIter ); - } + ReportError(eqIter2); + } } // separate genre errors - if( ! fFirstErrorInGenre ) + if (!fFirstErrorInGenre) (*mpOut) << endl; } // // if there were no errors, tell user - // - if( 1 == mErrorNum ) + // + if (1 == mErrorNum) { - (*mpOut) << TSS_GetString( cTW, tw::STR_REPORT_NO_ERRORS ) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_REPORT_NO_ERRORS) << endl << endl; } } -void cTextReportViewer::OutputSectionDelimiter( int nString ) +void cTextReportViewer::OutputSectionDelimiter(int nString) { (*mpOut) << g_sz79Equals << endl; - (*mpOut) << TSS_GetString( cTW, nString ) << endl; + (*mpOut) << TSS_GetString(cTW, nString) << endl; (*mpOut) << g_sz79Equals << endl << endl; } -void cTextReportViewer::OutputGenreDelimiter( cGenre::Genre g, bool fDenoteBallotSection ) +void cTextReportViewer::OutputGenreDelimiter(cGenre::Genre g, bool fDenoteBallotSection) { (*mpOut) << g_sz79Dashes << endl; // a # denotes the ballot section - if( fDenoteBallotSection ) + if (fDenoteBallotSection) (*mpOut) << _T("# "); else (*mpOut) << _T(" "); - (*mpOut) << TSS_GetString( cTW, tw::STR_SECTION ); - (*mpOut) << _T(": ") << cGenreSwitcher::GetInstance()->GenreToString( g, true ) << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_SECTION); + (*mpOut) << _T(": ") << cGenreSwitcher::GetInstance()->GenreToString(g, true) << endl; (*mpOut) << g_sz79Dashes << endl << endl; } -void cTextReportViewer::OutputNumDetails( int nString, int nObjects ) +void cTextReportViewer::OutputNumDetails(int nString, int nObjects) { (*mpOut) << _T(" ") << g_sz40Dashes << endl; - (*mpOut) << _T(" ") << TSS_GetString( cTW, nString ) << nObjects << endl; + (*mpOut) << _T(" ") << TSS_GetString(cTW, nString) << nObjects << endl; (*mpOut) << _T(" ") << g_sz40Dashes << endl << endl; } void cTextReportViewer::OutputObjectSummary() -{ +{ // // check if we should output summary - // + // if (!WantOutputObjectSummary()) return; // // output summary header // - OutputSectionDelimiter( tw::STR_OBJECT_SUMMARY ); + OutputSectionDelimiter(tw::STR_OBJECT_SUMMARY); // // cycle through genres // - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) - { + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { // // set up prop displayer and name translator // - SetUpForNewGenre( genreIter ); + SetUpForNewGenre(genreIter); // // output genre delimiter - // - OutputGenreDelimiter( genreIter.GetGenre(), true ); + // + OutputGenreDelimiter(genreIter.GetGenre(), true); // // output object summary - // - OutputObjectSummary( genreIter ); + // + OutputObjectSummary(genreIter); } } -void cTextReportViewer::OutputObjectSummary( const cFCOReportGenreIter& genreIter ) +void cTextReportViewer::OutputObjectSummary(const cFCOReportGenreIter& genreIter) { // iterate over all report elements (keyed by a spec), and save // references to all added, removed, and changed FCOs. We do this // because we want to group the FCOs by added, removed, and changed, // not by spec. - + // // if we're updating, we need to save a list of names // - FCOList* pFCONameList = NULL; - if( mfUpdate ) + FCOList* pFCONameList = NULL; + if (mfUpdate) pFCONameList = new FCOList; - cFCOReportSpecIter ri( genreIter ); - bool violationReported = false; - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) - { + cFCOReportSpecIter ri(genreIter); + bool violationReported = false; + for (ri.SeekBegin(); !ri.Done(); ri.Next()) + { // skip this spec if it's not one we care about for this report if (IgnoreThisSpec(ri.GetAttr())) continue; - + // // output a spec header if it was violated // - if( ! SpecEmpty( ri ) ) + if (!SpecEmpty(ri)) { violationReported = true; - OutputSpecHeader( ri ); + OutputSpecHeader(ri); (*mpOut) << endl; - - if( mfUpdate ) + + if (mfUpdate) { - (*mpOut) << TSS_GetString( cTW, tw::STR_ADD_X ) << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_ADD_X) << endl; (*mpOut) << endl; } // // output added set // - OutputAddedSummary( ri, pFCONameList ); - + OutputAddedSummary(ri, pFCONameList); + // // output removed set // - OutputRemovedSummary( ri, pFCONameList ); - + OutputRemovedSummary(ri, pFCONameList); + // // output changed set // - OutputChangedSummary( ri, pFCONameList ); + OutputChangedSummary(ri, pFCONameList); } } if (violationReported == false) { // There are no violations for this section - (*mpOut) << TSS_GetString( cTW, tw::STR_NO_VIOLATIONS_IN_SECTION ) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_NO_VIOLATIONS_IN_SECTION) << endl << endl; } // // insert FCO list into master list // - if( mfUpdate ) - mFCOsRemoveFromReport.insert( cTextReportViewer::GenreList::value_type( genreIter.GetGenre(), pFCONameList ) ); + if (mfUpdate) + mFCOsRemoveFromReport.insert(cTextReportViewer::GenreList::value_type(genreIter.GetGenre(), pFCONameList)); } void cTextReportViewer::OutputObjectDetails() -{ +{ // // check if we should output details // @@ -606,163 +612,163 @@ void cTextReportViewer::OutputObjectDetails() // // output detail header // - OutputSectionDelimiter( tw::STR_OBJECT_DETAIL ); - + OutputSectionDelimiter(tw::STR_OBJECT_DETAIL); + // // cycle through genres // - cFCOReportGenreIter genreIter( *mpReport ); - for(genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) - { + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { // // set up prop displayer and name translator // - SetUpForNewGenre( genreIter ); + SetUpForNewGenre(genreIter); // // output genre delimiter - // - OutputGenreDelimiter( genreIter.GetGenre() ); + // + OutputGenreDelimiter(genreIter.GetGenre()); // // output details - // - OutputObjectDetails( genreIter ); + // + OutputObjectDetails(genreIter); } } -void cTextReportViewer::OutputObjectDetails( const cFCOReportGenreIter& genreIter ) -{ +void cTextReportViewer::OutputObjectDetails(const cFCOReportGenreIter& genreIter) +{ // // Now enumerate all changes // - cFCOReportSpecIter ri( genreIter ); - bool violationReported = false; + cFCOReportSpecIter ri(genreIter); + bool violationReported = false; - for(ri.SeekBegin() ; !ri.Done(); ri.Next() ) - { + for (ri.SeekBegin(); !ri.Done(); ri.Next()) + { // skip this spec if it's not one we care about for this report if (IgnoreThisSpec(ri.GetAttr())) continue; - + // // output spec section header if there are changes // - if( ! SpecEmpty( ri ) ) + if (!SpecEmpty(ri)) { violationReported = true; - OutputSpecHeader( ri ); + OutputSpecHeader(ri); // // output added set // - OutputAddedDetails( ri ); - + OutputAddedDetails(ri); + // // output removed set // - OutputRemovedDetails( ri ); + OutputRemovedDetails(ri); // // output changed set // - OutputChangedDetails( ri ); + OutputChangedDetails(ri); } } // enum change details if (violationReported == false) { // There are no violations for this section - (*mpOut) << TSS_GetString( cTW, tw::STR_NO_VIOLATIONS_IN_SECTION ) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_NO_VIOLATIONS_IN_SECTION) << endl << endl; } } void cTextReportViewer::OutputFooter() { (*mpOut) << g_sz79Dashes << endl; - (*mpOut) << TSS_GetString( cTW, tw::STR_END_OF_REPORT ) << endl << endl; - (*mpOut) << TSS_GetString( cTW, tw::STR_COPYRIGHT ) << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_END_OF_REPORT) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_COPYRIGHT) << endl; } -bool cTextReportViewer::LaunchEditorOnFile( const TSTRING& strFilename, const TSTRING& edName ) //throw (eTextReportViewer) +bool cTextReportViewer::LaunchEditorOnFile(const TSTRING& strFilename, + const TSTRING& edName) //throw (eTextReportViewer) { - bool fRanViewer = false; - TSTRING editor = edName; + bool fRanViewer = false; + TSTRING editor = edName; // make sure we can read from this file - cFileUtil::TestFileReadable( strFilename ); - -#if IS_UNIX - + cFileUtil::TestFileReadable(strFilename); +#if USES_MSYSTEM // editor is going to need terminal type, so tell msystem to include // it in environment when it makes its system call. le_set("TERM"); - le_set("DISPLAY"); // DISPLAY and HOME needed so we can launch X apps. X apps apparently check - le_set("HOME"); // a .xpermissions file in the users home dir - le_set("LANG"); // LANG allowed through in case any apps need - int systemRet = msystem( (char*) ( ( editor+ _T(' ') + strFilename ).c_str() ) ); + le_set("DISPLAY"); // DISPLAY and HOME needed so we can launch X apps. X apps apparently check + le_set("HOME"); // a .xpermissions file in the users home dir + le_set("LANG"); // LANG allowed through in case any apps need + int systemRet = msystem((char*)((editor + _T(' ') + strFilename).c_str())); le_unset("LANG"); le_unset("HOME"); le_unset("DISPLAY"); le_unset("TERM"); +#else + int systemRet = system((char*)((editor + _T(' ') + strFilename).c_str())); +#endif - if( 0 == systemRet ) + if (0 == systemRet) { fRanViewer = true; } else { //ASSERT( false ); - throw eTextReportViewerEditorLaunch( edName ); + throw eTextReportViewerEditorLaunch(edName); } -#endif //if IS_WIN32 - - return( fRanViewer ); + return (fRanViewer); } -void cTextReportViewer::ReportError( const cErrorQueueIter& eqIter ) +void cTextReportViewer::ReportError(const cErrorQueueIter& eqIter) { const int nWidth = 5; // output error number TOSTRINGSTREAM ostr; ostr << mErrorNum << _T("."); - (*mpOut).width( nWidth ); + (*mpOut).width(nWidth); (*mpOut) << ostr.str(); - // output general error - (*mpOut) << cErrorTable::GetInstance()->Get( eqIter.GetError().GetID() )<< endl; + // output general error + (*mpOut) << cErrorTable::GetInstance()->Get(eqIter.GetError().GetID()) << endl; - // output specific error - (*mpOut).width( nWidth ); + // output specific error + (*mpOut).width(nWidth); (*mpOut) << _T(""); // this is here so the next output is 10 chars over - (*mpOut) << cDisplayUtil::FormatMultiLineString( - cDisplayEncoder::EncodeInlineAllowWS( - eqIter.GetError().GetMsg() ), nWidth, 0 ) << endl; + (*mpOut) << cDisplayUtil::FormatMultiLineString( + cDisplayEncoder::EncodeInlineAllowWS(eqIter.GetError().GetMsg()), nWidth, 0) + << endl; mErrorNum++; } -void cTextReportViewer::PrintBallotLine( const iFCO& FCO ) +void cTextReportViewer::PrintBallotLine(const iFCO& FCO) { - ASSERT( mpOut != 0 ); + ASSERT(mpOut != 0); - // + // // output "[X] " // - if( mfUpdate ) //only have Xs for updating + if (mfUpdate) //only have Xs for updating { (*mpOut) << _T("[x] "); // TODO: should this be in resources? } - TSTRING strEncoded = mpCurNT->ToStringDisplay( FCO.GetName(), true ); + TSTRING strEncoded = mpCurNT->ToStringDisplay(FCO.GetName(), true); (*mpOut) << strEncoded.c_str(); (*mpOut) << endl; @@ -771,62 +777,62 @@ void cTextReportViewer::PrintBallotLine( const iFCO& FCO ) // looks for "\n[" and leaves the file pointer at the next character // could be a problem if the ballot box is the first line in the file, then "\n[" -// wouldn't be encountered, only "[", so make sure that the ballots aren't +// wouldn't be encountered, only "[", so make sure that the ballots aren't // on the first line // returns false if finds "\n#" -- start of new genre int cTextReportViewer::FindNextLineToken() { // loop over chars until (1) EOF is hit, or (2) we find "\n[" or '\n#' - for( GetChar(); !mpIn->eof(); GetChar() ) + for (GetChar(); !mpIn->eof(); GetChar()) { - if( mCurrentChar[0] == '\n' ) + if (mCurrentChar[0] == '\n') { // we'll only compare to single byte chars // so it's ok to use PeekChar() instead of our GetChar() - if( PeekChar() == '[' ) + if (PeekChar() == '[') { return TOKEN_BALLOT_BOX; } - else if( PeekChar() == '#' ) // start of new genre + else if (PeekChar() == '#') // start of new genre { return TOKEN_GENRE; } } } - return( TOKEN_EOF ); + return (TOKEN_EOF); } -void cTextReportViewer::ReadTextReport( const TSTRING& strFilename ) //throw (eTextReportViewer) +void cTextReportViewer::ReadTextReport(const TSTRING& strFilename) //throw (eTextReportViewer) { std::ifstream in; - OpenInputFile( in, strFilename ); + OpenInputFile(in, strFilename); mpIn = ∈ // // for each genre and ballot box in text report file // - bool fMoreTokens = true; - FCOList* pCurList = NULL; - while( fMoreTokens ) + bool fMoreTokens = true; + FCOList* pCurList = NULL; + while (fMoreTokens) { - switch( FindNextLineToken() ) + switch (FindNextLineToken()) { - case TOKEN_GENRE: - GetGenreInfo( &pCurList ); + case TOKEN_GENRE: + GetGenreInfo(&pCurList); break; - case TOKEN_BALLOT_BOX: - GetBallotInfo( pCurList ); + case TOKEN_BALLOT_BOX: + GetBallotInfo(pCurList); break; - case TOKEN_EOF: - fMoreTokens = false; + case TOKEN_EOF: + fMoreTokens = false; break; - default: - ASSERT( false ); + default: + ASSERT(false); break; } } - + // // close the file // @@ -834,61 +840,61 @@ void cTextReportViewer::ReadTextReport( const TSTRING& strFilename ) //throw (eT } -void cTextReportViewer::GetGenreInfo( FCOList** ppCurList ) +void cTextReportViewer::GetGenreInfo(FCOList** ppCurList) { // // identify genre // TSTRING strGenre = GetGenre(); - ASSERT( ! strGenre.empty() ); - cGenre::Genre g = cGenreSwitcher::GetInstance()->StringToGenre( strGenre.c_str() ); - if( cGenre::GENRE_INVALID == g) + ASSERT(!strGenre.empty()); + cGenre::Genre g = cGenreSwitcher::GetInstance()->StringToGenre(strGenre.c_str()); + if (cGenre::GENRE_INVALID == g) { - throw eTextReportViewerReportCorrupt(); // TODO: ERR_UKNOWN_GENRE + throw eTextReportViewerReportCorrupt("Invalid Genre"); // TODO: ERR_UKNOWN_GENRE } - cGenreSwitcher::GetInstance()->SelectGenre( g ); + cGenreSwitcher::GetInstance()->SelectGenre(g); // // get list of fcos in report for this genre // - GenreList::iterator curIter = mFCOsRemoveFromReport.find( g ); - if( curIter == mFCOsRemoveFromReport.end() ) - throw eTextReportViewerReportCorrupt(); // TODO: ERR_UKNOWN_GENRE + GenreList::iterator curIter = mFCOsRemoveFromReport.find(g); + if (curIter == mFCOsRemoveFromReport.end()) + throw eTextReportViewerReportCorrupt("No files found in report"); // TODO: ERR_UKNOWN_GENRE *ppCurList = curIter->second; // // get the prop displayer // - mpCurPD = cGenreSwitcher::GetInstance()->GetFactoryForGenre( g )->CreatePropDisplayer(); - mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre( g )->GetNameTranslator(); + mpCurPD = cGenreSwitcher::GetInstance()->GetFactoryForGenre(g)->CreatePropDisplayer(); + mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre(g)->GetNameTranslator(); } -void cTextReportViewer::GetBallotInfo( FCOList* pCurList ) +void cTextReportViewer::GetBallotInfo(FCOList* pCurList) { - if( ! pCurList ) - throw eTextReportViewerReportCorrupt(); + if (!pCurList) + throw eTextReportViewerReportCorrupt("No ballot list found"); // if the box is checked, then the user elected to leave the item // in the report, so we do nothing. If the box isn't checked, then // we must remove the item from the report. - if( IsChecked() ) + if (IsChecked()) { // // look at the ballot line and get the name of the FCO // cFCOName fcoName; - GetFCONameFromBallotLine( fcoName ); + GetFCONameFromBallotLine(fcoName); /////////////////////////////////////// // remove this FCO from list cTextReportViewer::FCOList::const_iterator iter; - iter = pCurList->find( fcoName ); - if( iter == pCurList->end() ) + iter = pCurList->find(fcoName); + if (iter == pCurList->end()) { - throw eTextReportViewerReportCorrupt();// TODO: ERR_UKNOWN_NAME + throw eTextReportViewerReportCorrupt("Unknown file name in report"); // TODO: ERR_UKNOWN_NAME } - pCurList->erase( fcoName ); + pCurList->erase(fcoName); /////////////////////////////////////// } } @@ -900,26 +906,24 @@ TSTRING cTextReportViewer::GetGenre() EatSection(); - while( true ) + while (true) { char chFirst = PeekChar(); - if( PeekIsEOF() || - chFirst == '\r' || - chFirst == '\n' ) + if (PeekIsEOF() || chFirst == '\r' || chFirst == '\n') break; // eat up char GetChar(); - AppendChar( strGenre ); + AppendChar(strGenre); } - return cStringUtil::StrToTstr( strGenre ); + return cStringUtil::StrToTstr(strGenre); } bool cTextReportViewer::PeekIsEOF() { - return( mpIn->peek() == char_traits::eof() ); + return (mpIn->peek() == char_traits::eof()); } // if the next character in the stream is ('X' or 'x'), it eats the x, else it returns false @@ -929,57 +933,53 @@ bool cTextReportViewer::IsChecked() bool fIsChecked = false; char chFirst; - GetChar(); // eat up '[' + GetChar(); // eat up '[' chFirst = PeekChar(); // look for 'X' - if( ( ! PeekIsEOF() ) && - ( chFirst == 'X' || chFirst == 'x' ) ) // TODO: X in resources? + if ((!PeekIsEOF()) && (chFirst == 'X' || chFirst == 'x')) // TODO: X in resources? { - mpIn->get( chFirst ); // eat up X + mpIn->get(chFirst); // eat up X char chSecond = PeekChar(); - if( ( ! PeekIsEOF() ) && - ( chSecond == ']' ) ) + if ((!PeekIsEOF()) && (chSecond == ']')) { fIsChecked = true; - mpIn->get( chSecond ); // eat up ']' + mpIn->get(chSecond); // eat up ']' } } - return( fIsChecked ); + return (fIsChecked); } // FCO names are '\"' delimited and begin after the first '\"' after the ballot box // NOTE: will not eat up a return character -void cTextReportViewer::GetFCONameFromBallotLine( cFCOName& fcoName ) //throw (eTextReportViewer) +void cTextReportViewer::GetFCONameFromBallotLine(cFCOName& fcoName) //throw (eTextReportViewer) { - char chIn; + char chIn; std::string strFCOName; - #define TW_IS_QUOTE( ch ) ( ch == '\"' ) - #define TW_IS_EOL( ch ) ( ch == '\n' || ch == '\r' ) - #define TW_IS_BACKSLASH( ch ) ( ch == '\\' ) +#define TW_IS_QUOTE(ch) (ch == '\"') +#define TW_IS_EOL(ch) (ch == '\n' || ch == '\r') +#define TW_IS_BACKSLASH(ch) (ch == '\\') // // go past any character that's not '\"' or EOL // if we hit EOL, then there was no fconame present, so error // - for( chIn = PeekChar(); - ! PeekIsEOF(); - chIn = PeekChar() ) // while not EOF + for (chIn = PeekChar(); !PeekIsEOF(); chIn = PeekChar()) // while not EOF { - if( TW_IS_QUOTE( chIn ) ) + if (TW_IS_QUOTE(chIn)) { - mpIn->get( chIn ); // eat up all chars but EOL - strFCOName += chIn; // add quote to string - + mpIn->get(chIn); // eat up all chars but EOL + strFCOName += chIn; // add quote to string + // we've found our quote, break and get name break; } - else if( TW_IS_EOL( chIn ) ) + else if (TW_IS_EOL(chIn)) { // if EOL, there was no name! - throw eTextReportViewerReportCorrupt(); + throw eTextReportViewerReportCorrupt("Ballot item without a name"); } else { @@ -989,44 +989,40 @@ void cTextReportViewer::GetFCONameFromBallotLine( cFCOName& fcoName ) //throw (e // // get FCO name (chars up until the next '') - // - for( chIn = PeekChar(); - ! PeekIsEOF(); - chIn = PeekChar() ) // while not EOF + // + for (chIn = PeekChar(); !PeekIsEOF(); chIn = PeekChar()) // while not EOF { - if( TW_IS_EOL( chIn ) ) // if EOL, there was no ending quote! + if (TW_IS_EOL(chIn)) // if EOL, there was no ending quote! { // found end of fconame break; - } + } else - { + { // add char to fco name GetChar(); - AppendChar( strFCOName ); + AppendChar(strFCOName); } } // make sure we've got a name - if( strFCOName.empty() - || - ! mpCurNT->DisplayStringToFCOName( - cStringUtil::StrToTstr( strFCOName ), - fcoName ) ) + if (strFCOName.empty() || !mpCurNT->DisplayStringToFCOName(cStringUtil::StrToTstr(strFCOName), fcoName)) { - throw eTextReportViewerReportCorrupt(); // TODO -- it might be nice to be able to specify what line of the report got corrupted + std::string msg = "Invalid object name: " + strFCOName; + throw eTextReportViewerReportCorrupt( + msg); // TODO -- it might be nice to be able to specify what line of the report got corrupted } } void cTextReportViewer::RemoveFCOsFromReport() //throw (eTextReportViewer) -{ +{ // TODO: remove fconames from fcosToRemove when we find them in report, // so we don't compare that fconame again. Watch out for messing // with iters in the for, loops, though! That's why I didn't do // it yet... (and I figure most users would only un-X a few items, // in which case it is currently faster anyways...) - + // // iterate over all specs in report, then in each of the added, // removed, and changed sets, lookup the FCOName and, if found, @@ -1034,49 +1030,49 @@ void cTextReportViewer::RemoveFCOsFromReport() //throw (eTextReportViewer) // int nFCOsRemoved = 0; - cFCOReportGenreIter rgi( *mpReport ); - for( rgi.SeekBegin(); !rgi.Done(); rgi.Next() ) + cFCOReportGenreIter rgi(*mpReport); + for (rgi.SeekBegin(); !rgi.Done(); rgi.Next()) { - cTextReportViewer::GenreList::iterator currentList = mFCOsRemoveFromReport.find( rgi.GetGenre() ); - ASSERT( currentList != mFCOsRemoveFromReport.end() ); + cTextReportViewer::GenreList::iterator currentList = mFCOsRemoveFromReport.find(rgi.GetGenre()); + ASSERT(currentList != mFCOsRemoveFromReport.end()); cTextReportViewer::FCOList* pFCOList = currentList->second; - cFCOReportSpecIter rsi( rgi ); - for( rsi.SeekBegin(); !rsi.Done(); rsi.Next() ) + cFCOReportSpecIter rsi(rgi); + for (rsi.SeekBegin(); !rsi.Done(); rsi.Next()) { // search added const iFCOSet* pAddedSet = rsi.GetAddedSet(); - ASSERT( pAddedSet != 0 ); + ASSERT(pAddedSet != 0); - const iFCOIter* fcoIter = NULL; + const iFCOIter* fcoIter = NULL; cTextReportViewer::FCOList::iterator iter; // // see if any FCOs to remove are in this set - // - for( iter = pFCOList->begin(); iter != pFCOList->end(); iter++ ) + // + for (iter = pFCOList->begin(); iter != pFCOList->end(); ++iter) { - fcoIter = pAddedSet->Lookup( *iter ); - if( fcoIter ) + fcoIter = pAddedSet->Lookup(*iter); + if (fcoIter) { fcoIter->Remove(); nFCOsRemoved++; fcoIter->DestroyIter(); } - } - + } + // search removed // get removed set const iFCOSet* pRemovedSet = rsi.GetRemovedSet(); - ASSERT( pRemovedSet != 0 ); + ASSERT(pRemovedSet != 0); // // see if any FCOs to remove are in this set - // - for( iter = pFCOList->begin(); iter != pFCOList->end(); iter++ ) + // + for (iter = pFCOList->begin(); iter != pFCOList->end(); ++iter) { - fcoIter = pRemovedSet->Lookup( *iter ); - if( fcoIter ) + fcoIter = pRemovedSet->Lookup(*iter); + if (fcoIter) { fcoIter->Remove(); nFCOsRemoved++; @@ -1085,40 +1081,40 @@ void cTextReportViewer::RemoveFCOsFromReport() //throw (eTextReportViewer) } } - - for( iter = pFCOList->begin(); iter != pFCOList->end(); iter++ ) + + for (iter = pFCOList->begin(); iter != pFCOList->end(); ++iter) { // search changed // get changed set iterator - cFCOReportChangeIter changedIter( rsi ); + cFCOReportChangeIter changedIter(rsi); - // iterate over all changed fcos - for( changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next() ) + // iterate over all changed fcos + for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) { cFCOName name = changedIter.GetOld()->GetName(); - - if( name.IsEqual( *iter ) ) + + if (name.IsEqual(*iter)) { - changedIter.Remove(); + changedIter.Remove(); nFCOsRemoved++; } } } } } - + // // count FCOs to remove // - int nFCOsToRemove = 0; - cTextReportViewer::GenreList::const_iterator iter = mFCOsRemoveFromReport.begin(); - for( ; iter != mFCOsRemoveFromReport.end(); iter++ ) + int nFCOsToRemove = 0; + cTextReportViewer::GenreList::const_iterator iter = mFCOsRemoveFromReport.begin(); + for (; iter != mFCOsRemoveFromReport.end(); ++iter) nFCOsToRemove += iter->second->size(); - if( nFCOsToRemove != nFCOsRemoved ) + if (nFCOsToRemove != nFCOsRemoved) { // TODO -- maybe have a different enumeration for this? - throw eTextReportViewerReportCorrupt(); + throw eTextReportViewerReportCorrupt("Mismatch in objects to remove"); } } @@ -1129,214 +1125,201 @@ void cTextReportViewer::OutputReportHeader() const int headerColumnWidth = 30; - (*mpOut) << TSS_GetString( cTW, tw::STR_REPORT_TITLE ) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_REPORT_TITLE) << endl << endl; + + + (*mpOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_R_GENERATED_BY) + << util_Encode(mpHeader->GetCreator()) << endl; - - (*mpOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_R_GENERATED_BY ) - << util_Encode( mpHeader->GetCreator() ) - << endl; - // TODO: ( start / end / elapsed ) time TSTRING tstrDummy; - int64 i64CreateTime = mpHeader->GetCreationTime(); + int64 i64CreateTime = mpHeader->GetCreationTime(); (*mpOut).width(headerColumnWidth); - (*mpOut) << TSS_GetString( cTW, tw::STR_R_CREATED_ON ) << cTWLocale::FormatTime( i64CreateTime, tstrDummy ).c_str() << endl; - + (*mpOut) << TSS_GetString(cTW, tw::STR_R_CREATED_ON) << cTWLocale::FormatTime(i64CreateTime, tstrDummy).c_str() + << endl; + (*mpOut).width(headerColumnWidth); - (*mpOut) << TSS_GetString( cTW, tw::STR_DB_LAST_UPDATE ); + (*mpOut) << TSS_GetString(cTW, tw::STR_DB_LAST_UPDATE); int64 i64LastDBUTime = mpHeader->GetLastDBUpdateTime(); - if( i64LastDBUTime == 0 ) - { - (*mpOut) << TSS_GetString( cTW, tw::STR_NEVER ) << endl << endl; + if (i64LastDBUTime == 0) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_NEVER) << endl << endl; } else - { - (*mpOut) << cTWLocale::FormatTime( i64LastDBUTime, tstrDummy ).c_str() << endl << endl; + { + (*mpOut) << cTWLocale::FormatTime(i64LastDBUTime, tstrDummy).c_str() << endl << endl; } - OutputSectionDelimiter( tw::STR_R_SUMMARY ); + OutputSectionDelimiter(tw::STR_R_SUMMARY); (*mpOut).width(headerColumnWidth); - (*mpOut) << TSS_GetString( cTW, tw::STR_HOST_NAME ) << mpHeader->GetSystemName().c_str() << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_HOST_NAME) << mpHeader->GetSystemName().c_str() << endl; (*mpOut).width(headerColumnWidth); - (*mpOut) << TSS_GetString( cTW, tw::STR_HOST_IP ) << mpHeader->GetIPAddress() << endl; - -// only output host ID on UNIX systems -#if IS_UNIX + (*mpOut) << TSS_GetString(cTW, tw::STR_HOST_IP) << mpHeader->GetIPAddress() << endl; + (*mpOut).width(headerColumnWidth); - (*mpOut) << TSS_GetString( cTW, tw::STR_HOST_ID ); + (*mpOut) << TSS_GetString(cTW, tw::STR_HOST_ID); - if(! mpHeader->GetHostID().empty() ) + if (!mpHeader->GetHostID().empty()) (*mpOut) << mpHeader->GetHostID() << endl; else - (*mpOut) << TSS_GetString( cTW, tw::STR_NONE ) << endl; -#endif + (*mpOut) << TSS_GetString(cTW, tw::STR_NONE) << endl; + + (*mpOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_POLICY_FILE_USED) + << util_Encode(mpHeader->GetPolicyFilename()) << endl; + + (*mpOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_CONFIG_FILE_USED) + << util_Encode(mpHeader->GetConfigFilename()) << endl; - - (*mpOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_POLICY_FILE_USED ) - << util_Encode( mpHeader->GetPolicyFilename() ) - << endl; - - (*mpOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_CONFIG_FILE_USED ) - << util_Encode( mpHeader->GetConfigFilename() ) - << endl; - - (*mpOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_DB_FILE_USED ) - << util_Encode( mpHeader->GetDBFilename() ) - << endl; - - (*mpOut) << setw(headerColumnWidth) - << TSS_GetString( cTW, tw::STR_CMD_LINE_USED ) - << util_Encode( mpHeader->GetCommandLineParams() ) - << endl - << endl; + (*mpOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_DB_FILE_USED) + << util_Encode(mpHeader->GetDBFilename()) << endl; + + (*mpOut) << setw(headerColumnWidth) << TSS_GetString(cTW, tw::STR_CMD_LINE_USED) + << util_Encode(mpHeader->GetCommandLineParams()) << endl + << endl; } void cTextReportViewer::OutputRulesSummary() { // // check if we should output summary - // - if( !WantOutputRulesSummary() ) + // + if (!WantOutputRulesSummary()) return; // // output summary header // - OutputSectionDelimiter( tw::STR_RULE_SUMMARY ); + OutputSectionDelimiter(tw::STR_RULE_SUMMARY); // // cycle through genres // - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) - { + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { // // set up prop displayer and name translator - // - SetUpForNewGenre( genreIter ); + // + SetUpForNewGenre(genreIter); // // output genre delimiter - // - OutputGenreDelimiter( genreIter.GetGenre() ); + // + OutputGenreDelimiter(genreIter.GetGenre()); // // output rules summary - // - OutputRulesSummary( genreIter ); + // + OutputRulesSummary(genreIter); } } -void cTextReportViewer::OutputRulesSummary( const cFCOReportGenreIter& genreIter ) +void cTextReportViewer::OutputRulesSummary(const cFCOReportGenreIter& genreIter) { // output spec stats header // 2 + specNameWidth + severityWidth + 3*numObjectsWidth should be < 80 - const int specNameWidth = 32; - const int severityWidth = 18; + const int specNameWidth = 32; + const int severityWidth = 18; const int numObjectsWidth = 9; (*mpOut) << _T(" "); // indent - (*mpOut).width( specNameWidth ); - (*mpOut) << TSS_GetString( cTW, tw::STR_RULE_NAME ); - (*mpOut).width( severityWidth ); - (*mpOut) << TSS_GetString( cTW, tw::STR_SEVERITY_LEVEL ); - (*mpOut).width( numObjectsWidth ); - (*mpOut) << TSS_GetString( cTW, tw::STR_ADDED ); - (*mpOut).width( numObjectsWidth ); - (*mpOut) << TSS_GetString( cTW, tw::STR_REMOVED ); - (*mpOut).width( numObjectsWidth ); - (*mpOut) << TSS_GetString( cTW, tw::STR_CHANGED ); + (*mpOut).width(specNameWidth); + (*mpOut) << TSS_GetString(cTW, tw::STR_RULE_NAME); + (*mpOut).width(severityWidth); + (*mpOut) << TSS_GetString(cTW, tw::STR_SEVERITY_LEVEL); + (*mpOut).width(numObjectsWidth); + (*mpOut) << TSS_GetString(cTW, tw::STR_ADDED); + (*mpOut).width(numObjectsWidth); + (*mpOut) << TSS_GetString(cTW, tw::STR_REMOVED); + (*mpOut).width(numObjectsWidth); + (*mpOut) << TSS_GetString(cTW, tw::STR_CHANGED); (*mpOut) << endl; (*mpOut) << _T(" "); - (*mpOut) << setw( specNameWidth ) << _T("---------"); - (*mpOut) << setw( severityWidth ) << _T("--------------"); - (*mpOut) << setw( numObjectsWidth ) << _T("-----"); - (*mpOut) << setw( numObjectsWidth ) << _T("-------"); - (*mpOut) << setw( numObjectsWidth ) << _T("--------"); + (*mpOut) << setw(specNameWidth) << _T("---------"); + (*mpOut) << setw(severityWidth) << _T("--------------"); + (*mpOut) << setw(numObjectsWidth) << _T("-----"); + (*mpOut) << setw(numObjectsWidth) << _T("-------"); + (*mpOut) << setw(numObjectsWidth) << _T("--------"); (*mpOut) << endl; // merge rules of duplicate names and severities ObjectSummaryList summaryList; - CollateRulesSummary( genreIter, summaryList ); + CollateRulesSummary(genreIter, summaryList); // Output the information in the list - int nTotalObjectsChanged = 0; + int nTotalObjectsChanged = 0; ObjectSummaryList::iterator si; for (si = summaryList.begin(); si != summaryList.end(); ++si) { // highlight violated rules - if( si->mAddedObjects + si->mRemovedObjects + si->mChangedObjects > 0 ) + if (si->mAddedObjects + si->mRemovedObjects + si->mChangedObjects > 0) (*mpOut) << _T("* "); else (*mpOut) << _T(" "); // indent - TSTRING strSpecName = util_Encode( si->mSpecName ); - (*mpOut) << setw( specNameWidth ) - << strSpecName; + TSTRING strSpecName = util_Encode(si->mSpecName); + (*mpOut) << setw(specNameWidth) << strSpecName; // if the name is too long, put it on its own line - if( strSpecName.length() >= (unsigned int)specNameWidth ) + if (strSpecName.length() >= (unsigned int)specNameWidth) { - (*mpOut) << endl; + (*mpOut) << endl; (*mpOut) << _T(" "); // indent - (*mpOut).width( specNameWidth ); + (*mpOut).width(specNameWidth); (*mpOut) << _T(""); // output space holder } - - (*mpOut).width( severityWidth ); + + (*mpOut).width(severityWidth); (*mpOut) << si->mSeverity; - (*mpOut).width( numObjectsWidth ); + (*mpOut).width(numObjectsWidth); (*mpOut) << si->mAddedObjects; - (*mpOut).width( numObjectsWidth ); + (*mpOut).width(numObjectsWidth); (*mpOut) << si->mRemovedObjects; - (*mpOut).width( numObjectsWidth ); + (*mpOut).width(numObjectsWidth); (*mpOut) << si->mChangedObjects; - (*mpOut) << endl; + (*mpOut) << endl; // output start point on next line // TODO: I am not sure if I like this in the new collated reports, dmb Sept 16 1999 if (!si->mStartPoint.empty()) (*mpOut) << _T(" (") << si->mStartPoint << _T(")") << endl; - + nTotalObjectsChanged += si->mAddedObjects + si->mRemovedObjects + si->mChangedObjects; } (*mpOut) << endl; - (*mpOut) << TSS_GetString( cTW, tw::STR_OBJECTS_SCANNED ) << _T(" ") << genreIter.GetGenreHeader().GetObjectsScanned() << endl; - (*mpOut) << TSS_GetString( cTW, tw::STR_TOTAL_VIOLATIONS ) << _T(" ") << nTotalObjectsChanged << endl; - (*mpOut) << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_OBJECTS_SCANNED) << _T(" ") << genreIter.GetGenreHeader().GetObjectsScanned() + << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_TOTAL_VIOLATIONS) << _T(" ") << nTotalObjectsChanged << endl; + (*mpOut) << endl; } -void cTextReportViewer::CollateRulesSummary( const cFCOReportGenreIter& genreIter, ObjectSummaryList& summaryList ) +void cTextReportViewer::CollateRulesSummary(const cFCOReportGenreIter& genreIter, ObjectSummaryList& summaryList) { summaryList.clear(); - cFCOReportSpecIter ri( genreIter ); - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) + cFCOReportSpecIter ri(genreIter); + for (ri.SeekBegin(); !ri.Done(); ri.Next()) { // skip this spec if it's not one we care about for this report if (IgnoreThisSpec(ri.GetAttr())) continue; RuleSummaryLine newLine; - - newLine.mSpecName = util_Encode( ri.GetSpec()->GetName() ); - newLine.mSeverity = ri.GetAttr()->GetSeverity(); - newLine.mAddedObjects = ri.GetAddedSet()->Size(); + + newLine.mSpecName = util_Encode(ri.GetSpec()->GetName()); + newLine.mSeverity = ri.GetAttr()->GetSeverity(); + newLine.mAddedObjects = ri.GetAddedSet()->Size(); newLine.mRemovedObjects = ri.GetRemovedSet()->Size(); newLine.mChangedObjects = ri.GetNumChanged(); - newLine.mStartPoint = mpCurNT->ToStringDisplay( ri.GetSpec()->GetStartPoint() ); + newLine.mStartPoint = mpCurNT->ToStringDisplay(ri.GetSpec()->GetStartPoint()); // If there is already a summary line for this rule with equivalent severity, merge this one into it ObjectSummaryList::iterator si; - for (si = summaryList.begin(); ; ++si) + for (si = summaryList.begin();; ++si) { if (si == summaryList.end()) { @@ -1344,8 +1327,7 @@ void cTextReportViewer::CollateRulesSummary( const cFCOReportGenreIter& genreIte break; } - if (si->mSpecName.compare(newLine.mSpecName) == 0 && - si->mSeverity == newLine.mSeverity) + if (si->mSpecName.compare(newLine.mSpecName) == 0 && si->mSeverity == newLine.mSeverity) { si->mAddedObjects += newLine.mAddedObjects; si->mRemovedObjects += newLine.mRemovedObjects; @@ -1358,84 +1340,85 @@ void cTextReportViewer::CollateRulesSummary( const cFCOReportGenreIter& genreIte si->mStartPoint = newLine.mStartPoint; else si->mStartPoint.erase(); + else if (si->mStartPoint.compare(0, si->mStartPoint.length(), newLine.mStartPoint) == 0) + ; else - if (si->mStartPoint.compare(0, si->mStartPoint.length(), newLine.mStartPoint) == 0) - ; - else - si->mStartPoint.erase(); + si->mStartPoint.erase(); break; } } } } - -void cTextReportViewer::OutputSpecHeader( const cFCOReportSpecIter &ri ) + +void cTextReportViewer::OutputSpecHeader(const cFCOReportSpecIter& ri) { if (!WantOutputSpecHeader()) return; (*mpOut) << g_sz79Dashes << endl; - - (*mpOut) << TSS_GetString( cTW, tw::STR_RULE_NAME ) << _T(": ") << util_Encode( ri.GetSpec()->GetName() ); - (*mpOut) << _T( " (" ) << mpCurNT->ToStringDisplay( ri.GetSpec()->GetStartPoint() ) << _T( ")" ) << endl; - (*mpOut) << TSS_GetString( cTW, tw::STR_SEVERITY_LEVEL ) << _T(": ") << ri.GetAttr()->GetSeverity() << endl; + + (*mpOut) << TSS_GetString(cTW, tw::STR_RULE_NAME) << _T(": ") << util_Encode(ri.GetSpec()->GetName()); + (*mpOut) << _T( " (" ) << mpCurNT->ToStringDisplay(ri.GetSpec()->GetStartPoint()) << _T( ")" ) << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_SEVERITY_LEVEL) << _T(": ") << ri.GetAttr()->GetSeverity() << endl; (*mpOut) << g_sz79Dashes << endl; } -void cTextReportViewer::DisplayChangedProps( const iFCO* const pfcoOld, const iFCO* const pfcoNew, const cFCOPropVector* pv ) +void cTextReportViewer::DisplayChangedProps(const iFCO* const pfcoOld, + const iFCO* const pfcoNew, + const cFCOPropVector* pv) { - ASSERT( mpOut != 0 ); - ASSERT( pfcoOld || pfcoNew); // have to have at least one to display + ASSERT(mpOut != 0); + ASSERT(pfcoOld || pfcoNew); // have to have at least one to display + + const iFCO* pfcoValid = pfcoOld ? pfcoOld : pfcoNew; // we need to use one of the pfco's for some Get functions - const iFCO* pfcoValid = pfcoOld ? pfcoOld : pfcoNew; // we need to use one of the pfco's for some Get functions - // marginWidth + attrNameWidth + ( 2 * attrValueWidth ) should be < 80 - const int attrNameWidth = 21; + const int attrNameWidth = 21; const int attrValueWidth = 28; - const int marginWidth = 2; // for " " or "* " - ASSERT( ( attrNameWidth + ( 2 * attrValueWidth ) + marginWidth ) < 80 ); - + const int marginWidth = 2; // for " " or "* " + ASSERT((attrNameWidth + (2 * attrValueWidth) + marginWidth) < 80); + // output header - (*mpOut) << setw( marginWidth ) << _T(""); - (*mpOut) << setw( attrNameWidth ) << TSS_GetString( cTW, tw::STR_ATTRIBUTES ); - (*mpOut) << setw( attrValueWidth ) << TSS_GetString( cTW, tw::STR_EXPECTED ); - (*mpOut) << setw( attrValueWidth ) << TSS_GetString( cTW, tw::STR_OBSERVED ); + (*mpOut) << setw(marginWidth) << _T(""); + (*mpOut) << setw(attrNameWidth) << TSS_GetString(cTW, tw::STR_ATTRIBUTES); + (*mpOut) << setw(attrValueWidth) << TSS_GetString(cTW, tw::STR_EXPECTED); + (*mpOut) << setw(attrValueWidth) << TSS_GetString(cTW, tw::STR_OBSERVED); (*mpOut) << endl; - (*mpOut) << setw( marginWidth ) << _T(""); - (*mpOut) << setw( attrNameWidth ) << _T("-------------"); - (*mpOut) << setw( attrValueWidth ) << _T("-----------"); - (*mpOut) << setw( attrValueWidth ) << _T("-----------"); + (*mpOut) << setw(marginWidth) << _T(""); + (*mpOut) << setw(attrNameWidth) << _T("-------------"); + (*mpOut) << setw(attrValueWidth) << _T("-----------"); + (*mpOut) << setw(attrValueWidth) << _T("-----------"); (*mpOut) << endl; int iNumProps = pfcoValid->GetPropSet()->GetNumProps(); // TODO: what if new + old have different props - for( int j = 0; j < iNumProps; j++ ) + for (int j = 0; j < iNumProps; j++) { // if not a full report, only print properties that have changed - if( FULL_REPORT != mReportingLevel ) + if (FULL_REPORT != mReportingLevel) { - if( !pv || !pv->ContainsItem( j ) ) + if (!pv || !pv->ContainsItem(j)) continue; } // ignore certain combinations of undef and non-existent props - if( ! PrintableProp( pfcoOld, pfcoNew, j ) ) + if (!PrintableProp(pfcoOld, pfcoNew, j)) continue; // highlight changes and set width for prop name - if( ! mpCurPD->IsMultiLineProp( j ) ) + if (!mpCurPD->IsMultiLineProp(j)) { - if( !pv || pv->ContainsItem( j ) ) - (*mpOut) << setw( marginWidth ) << _T("*"); + if (!pv || pv->ContainsItem(j)) + (*mpOut) << setw(marginWidth) << _T("*"); else - (*mpOut) << setw( marginWidth ) << _T(""); + (*mpOut) << setw(marginWidth) << _T(""); } else // for multiline props we will highlight the observed prop if it has changed { - (*mpOut) << setw( marginWidth ) << _T(""); + (*mpOut) << setw(marginWidth) << _T(""); } @@ -1446,259 +1429,335 @@ void cTextReportViewer::DisplayChangedProps( const iFCO* const pfcoOld, const iF TSTRING strNewName; strNewName = pfcoValid->GetPropSet()->GetPropName(j); - if( mpCurPD->IsMultiLineProp( j ) ) + if (mpCurPD->IsMultiLineProp(j)) { - strNewName += _T(" ") ; - strNewName += TSS_GetString( cTW, tw::STR_EXPECTED ); + strNewName += _T(" "); + strNewName += TSS_GetString(cTW, tw::STR_EXPECTED); } //strNewName += _T(':') ; - (*mpOut) << setw( attrNameWidth ) << strNewName; + (*mpOut) << setw(attrNameWidth) << strNewName; } // // output old value // TSTRING strOldValue; - (*mpOut).width( attrValueWidth ); - if( pfcoOld && pfcoOld->GetPropSet()->GetValidVector().ContainsItem( j ) ) - strOldValue = mpCurPD->PropAsString( pfcoOld, j, ( marginWidth + attrNameWidth ), 0 ).c_str(); + (*mpOut).width(attrValueWidth); + if (pfcoOld && pfcoOld->GetPropSet()->GetValidVector().ContainsItem(j)) + strOldValue = mpCurPD->PropAsString(pfcoOld, j, (marginWidth + attrNameWidth), 0).c_str(); else strOldValue = _T("---"); (*mpOut) << strOldValue; - + // // output name again, if necessary (if multiline prop) // - if( mpCurPD->IsMultiLineProp( j ) ) + if (mpCurPD->IsMultiLineProp(j)) { TSTRING strNewName; strNewName = pfcoValid->GetPropSet()->GetPropName(j); - strNewName += _T(" ") ; - strNewName += TSS_GetString( cTW, tw::STR_OBSERVED ); + strNewName += _T(" "); + strNewName += TSS_GetString(cTW, tw::STR_OBSERVED); //strNewName += _T(':') ; (*mpOut) << endl; - if( !pv || pv->ContainsItem( j ) ) - (*mpOut) << setw( marginWidth ) << _T("*"); + if (!pv || pv->ContainsItem(j)) + (*mpOut) << setw(marginWidth) << _T("*"); else - (*mpOut) << setw( marginWidth ) << _T(""); + (*mpOut) << setw(marginWidth) << _T(""); - (*mpOut) << setw( attrNameWidth ) << strNewName; + (*mpOut) << setw(attrNameWidth) << strNewName; } else - { + { // if old value would run into this value, we need to put this value // on the next line (but in the same column). don't output // value but position "cursor" in the correct place - if( strOldValue.length() >= (unsigned int)attrValueWidth ) + if (strOldValue.length() >= (unsigned int)attrValueWidth) { (*mpOut) << endl; - (*mpOut) << setw( marginWidth ) << _T(""); - (*mpOut) << setw( attrNameWidth ) << _T(""); - (*mpOut) << setw( attrValueWidth ) << _T(""); + (*mpOut) << setw(marginWidth) << _T(""); + (*mpOut) << setw(attrNameWidth) << _T(""); + (*mpOut) << setw(attrValueWidth) << _T(""); } } // // output new value // - (*mpOut).width( attrValueWidth ); - if( pfcoNew && pfcoNew->GetPropSet()->GetValidVector().ContainsItem( j ) ) - (*mpOut) << mpCurPD->PropAsString( pfcoNew, j, ( marginWidth + attrNameWidth ), 0 ).c_str(); + (*mpOut).width(attrValueWidth); + if (pfcoNew && pfcoNew->GetPropSet()->GetValidVector().ContainsItem(j)) + (*mpOut) << mpCurPD->PropAsString(pfcoNew, j, (marginWidth + attrNameWidth), 0).c_str(); else (*mpOut) << _T("---"); (*mpOut) << endl; } } - -void cTextReportViewer::OutputAddedSummary( const cFCOReportSpecIter& ri, FCOList* pFCONameList ) + +void cTextReportViewer::OutputAddedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList) { - if( ! ri.GetAddedSet()->IsEmpty() ) + if (!ri.GetAddedSet()->IsEmpty()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_ADDED ) << _T(":") << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_ADDED) << _T(":") << endl; // iterate over all fcos const cIterProxy pSetIterAdded = ri.GetAddedSet()->GetIter(); - for( pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next() ) + for (pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next()) { - PrintBallotLine( *pSetIterAdded->FCO() ); + const iFCO* fco = pSetIterAdded->FCO(); + if (!IgnoreThisFCO(fco)) + { + PrintBallotLine(*fco); - // if we're updating, save a list of FCO names - if( mfUpdate ) - pFCONameList->insert( pSetIterAdded->FCO()->GetName() ); + // if we're updating, save a list of FCO names + if (mfUpdate && pFCONameList) + pFCONameList->insert(fco->GetName()); + } } (*mpOut) << endl; } } -void cTextReportViewer::OutputRemovedSummary( const cFCOReportSpecIter& ri, FCOList* pFCONameList) -{ - if( ! ri.GetRemovedSet()->IsEmpty() ) +void cTextReportViewer::OutputRemovedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList) +{ + if (!ri.GetRemovedSet()->IsEmpty()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_REMOVED ) << _T(":") << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_REMOVED) << _T(":") << endl; - // iterate over all fcos + // iterate over all fcos const cIterProxy pSetIterRemoved = ri.GetRemovedSet()->GetIter(); - for( pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next() ) + for (pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next()) { - PrintBallotLine( *pSetIterRemoved->FCO() ); - - // if we're updating, save a list of FCO names - if( mfUpdate ) - pFCONameList->insert( pSetIterRemoved->FCO()->GetName() ); + const iFCO* fco = pSetIterRemoved->FCO(); + if (!IgnoreThisFCO(fco)) + { + PrintBallotLine(*fco); + + // if we're updating, save a list of FCO names + if (mfUpdate && pFCONameList) + pFCONameList->insert(fco->GetName()); + } } (*mpOut) << endl; } } -void cTextReportViewer::OutputChangedSummary( const cFCOReportSpecIter& ri, FCOList* pFCONameList ) -{ - if( ri.GetNumChanged() > 0 ) +void cTextReportViewer::OutputChangedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList) +{ + if (ri.GetNumChanged() > 0) { - (*mpOut) << TSS_GetString( cTW, tw::STR_CHANGED ) << _T(":") << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_CHANGED) << _T(":") << endl; - // iterate over all changed fcos - cFCOReportChangeIter changedIter( ri ); - for( changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next() ) + // iterate over all changed fcos + cFCOReportChangeIter changedIter(ri); + for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) { - PrintBallotLine( *changedIter.GetNew() ); + const iFCO* fco = changedIter.GetNew(); + if (!IgnoreThisFCO(fco)) + { + PrintBallotLine(*fco); - // if we're updating, save a list of FCO names - if( mfUpdate ) - pFCONameList->insert( changedIter.GetNew()->GetName() ); + // if we're updating, save a list of FCO names + if (mfUpdate && pFCONameList) + pFCONameList->insert(fco->GetName()); + } } (*mpOut) << endl; - } + } } -void cTextReportViewer::OutputAddedDetails( const cFCOReportSpecIter& ri ) +void cTextReportViewer::OutputAddedDetails(const cFCOReportSpecIter& ri) { - if( ! ri.GetAddedSet()->IsEmpty() ) + if (!ri.GetAddedSet()->IsEmpty()) { - OutputNumDetails( tw::STR_ADDED_FILES, ri.GetAddedSet()->Size() ); + OutputNumDetails(tw::STR_ADDED_FILES, ri.GetAddedSet()->Size()); // iterate over all fcos - const cIterProxy pSetIterAdded = ri.GetAddedSet()->GetIter(); ASSERT( pSetIterAdded != 0 ); - for( pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next() ) + const cIterProxy pSetIterAdded = ri.GetAddedSet()->GetIter(); + ASSERT(pSetIterAdded != 0); + for (pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_ADDED_FILE_NAME ) << _T(" ") << mpCurNT->ToStringDisplay( pSetIterAdded->FCO()->GetName() ).c_str() << endl; - - if( FULL_REPORT == mReportingLevel ) - { - (*mpOut) << endl; - DisplayChangedProps( NULL, pSetIterAdded->FCO(), NULL ); - (*mpOut) << endl << endl; + const iFCO* fco = pSetIterAdded->FCO(); + if (!IgnoreThisFCO(fco)) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_ADDED_FILE_NAME) << _T(" ") + << mpCurNT->ToStringDisplay(fco->GetName()).c_str() << endl; + + if (FULL_REPORT == mReportingLevel) + { + (*mpOut) << endl; + DisplayChangedProps(NULL, fco, NULL); + (*mpOut) << endl << endl; + } } } - + (*mpOut) << endl; } } -void cTextReportViewer::OutputRemovedDetails( const cFCOReportSpecIter& ri ) -{ - if( ! ri.GetRemovedSet()->IsEmpty() ) +void cTextReportViewer::OutputRemovedDetails(const cFCOReportSpecIter& ri) +{ + if (!ri.GetRemovedSet()->IsEmpty()) { - OutputNumDetails( tw::STR_REMOVED_FILES, ri.GetRemovedSet()->Size() ); + OutputNumDetails(tw::STR_REMOVED_FILES, ri.GetRemovedSet()->Size()); // iterate over all fcos - const cIterProxy pSetIterRemoved = ri.GetRemovedSet()->GetIter(); ASSERT( pSetIterRemoved != 0 ); - for( pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next() ) - { - (*mpOut) << TSS_GetString( cTW, tw::STR_REMOVED_FILE_NAME ) << _T(" ") << mpCurNT->ToStringDisplay( pSetIterRemoved->FCO()->GetName() ).c_str() << endl; - - if( FULL_REPORT == mReportingLevel ) + const cIterProxy pSetIterRemoved = ri.GetRemovedSet()->GetIter(); + ASSERT(pSetIterRemoved != 0); + for (pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next()) + { + const iFCO* fco = pSetIterRemoved->FCO(); + if (!IgnoreThisFCO(fco)) { - (*mpOut) << endl; - DisplayChangedProps( pSetIterRemoved->FCO(), NULL, NULL ); - (*mpOut) << endl << endl; + (*mpOut) << TSS_GetString(cTW, tw::STR_REMOVED_FILE_NAME) << _T(" ") + << mpCurNT->ToStringDisplay(fco->GetName()).c_str() << endl; + + if (FULL_REPORT == mReportingLevel) + { + (*mpOut) << endl; + DisplayChangedProps(fco, NULL, NULL); + (*mpOut) << endl << endl; + } } - } + } (*mpOut) << endl; } } -void cTextReportViewer::OutputChangedDetails( const cFCOReportSpecIter& ri ) -{ - if( ri.GetNumChanged() > 0 ) - { - OutputNumDetails( tw::STR_CHANGED_FILES, ri.GetNumChanged() ); +void cTextReportViewer::OutputChangedDetails(const cFCOReportSpecIter& ri) +{ + if (ri.GetNumChanged() > 0) + { + OutputNumDetails(tw::STR_CHANGED_FILES, ri.GetNumChanged()); - // iterate over all changed fcos - cFCOReportChangeIter changedIter( ri ); - for( changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next() ) + // iterate over all changed fcos + cFCOReportChangeIter changedIter(ri); + for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_CHANGED_FILE_NAME ) << _T(" ") << mpCurNT->ToStringDisplay( changedIter.GetOld()->GetName() ).c_str() << endl << endl; - DisplayChangedProps( changedIter.GetOld(), changedIter.GetNew(), &changedIter.GetChangeVector() ); - (*mpOut) << endl << endl; + const iFCO* fco = changedIter.GetOld(); + if (!IgnoreThisFCO(fco)) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_CHANGED_FILE_NAME) << _T(" ") + << mpCurNT->ToStringDisplay(fco->GetName()).c_str() << endl + << endl; + DisplayChangedProps(fco, changedIter.GetNew(), &changedIter.GetChangeVector()); + (*mpOut) << endl << endl; + } } (*mpOut) << endl; } } +void cTextReportViewer::SetObjects(const std::set& objects) +{ + if (!objects.empty()) + { + mObjects = objects; + mFilterFCOs = true; + } +} + // overridables: // These function allows derived classes to tailor reports -bool cTextReportViewer::IgnoreThisSpec(const cFCOSpecAttr *attr) { return false; } -bool cTextReportViewer::WantOutputReportHeader() { return true; } -bool cTextReportViewer::WantOutputRulesSummary() { return true; } -bool cTextReportViewer::WantOutputSpecHeader() { return true; } -bool cTextReportViewer::WantOutputObjectSummary() { return true; } -bool cTextReportViewer::WantOutputObjectDetails() { return true; } -bool cTextReportViewer::CanUpdate() { return true; } +bool cTextReportViewer::IgnoreThisSpec(const cFCOSpecAttr* attr) +{ + return false; +} + +bool cTextReportViewer::IgnoreThisFCO(const iFCO* fco) +{ + if (!mFilterFCOs) + { + return false; + } + return (mObjects.find(fco->GetName().AsString()) == mObjects.end()); +} + +bool cTextReportViewer::WantOutputReportHeader() +{ + return true; +} + +bool cTextReportViewer::WantOutputRulesSummary() +{ + return true; +} + +bool cTextReportViewer::WantOutputSpecHeader() +{ + return true; +} + +bool cTextReportViewer::WantOutputObjectSummary() +{ + return true; +} + +bool cTextReportViewer::WantOutputObjectDetails() +{ + return true; +} + +bool cTextReportViewer::CanUpdate() +{ + return true; +} //========================================================================= // UTIL FUNCTION CODE //========================================================================= -void OpenInputFile( std::ifstream& in, const TSTRING& strFile ) // throw( eTextReportViewer ) +void OpenInputFile(std::ifstream& in, const TSTRING& strFile) // throw( eTextReportViewer ) { - in.open( cStringUtil::TstrToStr( strFile ).c_str() ); - - if(! in.is_open()) + in.open(cStringUtil::TstrToStr(strFile).c_str()); + + if (!in.is_open()) { - throw eTextReportViewerFileOpen( strFile ); + throw eTextReportViewerFileOpen(strFile); } } -void OpenOutputFile( fixed_basic_ofstream& out, const TSTRING& strFile ) // throw( eTextReportViewer ) +void OpenOutputFile(fixed_basic_ofstream& out, const TSTRING& strFile) // throw( eTextReportViewer ) { - std::string narrowFilename = cStringUtil::TstrToStr( strFile ); + std::string narrowFilename = cStringUtil::TstrToStr(strFile); - // we explicitly create the file so that we control the + // we explicitly create the file so that we control the // permissions on the new file. unlink(narrowFilename.c_str()); - int fd = open(narrowFilename.c_str(), O_RDWR|O_CREAT|O_TRUNC|O_EXCL, 00600); - if (fd == -1 || close(fd) != 0) { - throw eTextReportViewerFileOpen( strFile ); + int fd = open(narrowFilename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 00600); + if (fd == -1 || close(fd) != 0) + { + throw eTextReportViewerFileOpen(strFile); } - out.open( narrowFilename.c_str() ); - - if(! out.is_open()) - throw eTextReportViewerFileOpen( strFile ); + out.open(narrowFilename.c_str()); + + if (!out.is_open()) + throw eTextReportViewerFileOpen(strFile); } -bool SpecEmpty( const cFCOReportSpecIter& ri ) +bool SpecEmpty(const cFCOReportSpecIter& ri) { - return( ri.GetAddedSet()->IsEmpty() && ri.GetRemovedSet()->IsEmpty() && 0 == ri.GetNumChanged() ); + return (ri.GetAddedSet()->IsEmpty() && ri.GetRemovedSet()->IsEmpty() && 0 == ri.GetNumChanged()); } -bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ) -{ - bool fOldExists = pfcoOld && pfcoOld->GetPropSet()->GetValidVector().ContainsItem( j ); - bool fNewExists = pfcoNew && pfcoNew->GetPropSet()->GetValidVector().ContainsItem( j ); +bool PrintableProp(const iFCO* pfcoOld, const iFCO* pfcoNew, int j) +{ + bool fOldExists = pfcoOld && pfcoOld->GetPropSet()->GetValidVector().ContainsItem(j); + bool fNewExists = pfcoNew && pfcoNew->GetPropSet()->GetValidVector().ContainsItem(j); // // don't output line if neither FCO has the prop // - if( ! fOldExists && ! fNewExists ) + if (!fOldExists && !fNewExists) { return false; } @@ -1706,11 +1765,9 @@ bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ) // // don't output anything if both props are undefined // - if ( fOldExists && fNewExists && - pfcoOld->GetPropSet()->GetPropAt( j )->GetType() - == cFCOUndefinedProp::GetInstance()->GetType() && - pfcoNew->GetPropSet()->GetPropAt( j )->GetType() - == cFCOUndefinedProp::GetInstance()->GetType() ) + if (fOldExists && fNewExists && + pfcoOld->GetPropSet()->GetPropAt(j)->GetType() == cFCOUndefinedProp::GetInstance()->GetType() && + pfcoNew->GetPropSet()->GetPropAt(j)->GetType() == cFCOUndefinedProp::GetInstance()->GetType()) { return false; } @@ -1718,13 +1775,8 @@ bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ) // // don't output anything if old is undef and new doesn't exist // - if( - fOldExists - && - ! fNewExists - && - pfcoOld->GetPropSet()->GetPropAt( j )->GetType() == cFCOUndefinedProp::GetInstance()->GetType() - ) + if (fOldExists && !fNewExists && + pfcoOld->GetPropSet()->GetPropAt(j)->GetType() == cFCOUndefinedProp::GetInstance()->GetType()) { return false; } @@ -1732,13 +1784,8 @@ bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ) // // don't output anything if new is undef and old doesn't exist // - if( - ! fOldExists - && - fNewExists - && - pfcoNew->GetPropSet()->GetPropAt( j )->GetType() == cFCOUndefinedProp::GetInstance()->GetType() - ) + if (!fOldExists && fNewExists && + pfcoNew->GetPropSet()->GetPropAt(j)->GetType() == cFCOUndefinedProp::GetInstance()->GetType()) { return false; } @@ -1747,19 +1794,16 @@ bool PrintableProp( const iFCO* pfcoOld, const iFCO* pfcoNew, int j ) } void cTextReportViewer::EatSection() -{ +{ GetChar(); // get '#' // eat up " section: " - int nb = - cStringUtil::TstrToStr( - TSS_GetString( cTW, tw::STR_SECTION ) - ).length(); + int nb = cStringUtil::TstrToStr(TSS_GetString(cTW, tw::STR_SECTION)).length(); nb += 3; // one for each space surrounding section, and one for colon // eat up nb bytes - for( int i = 0; !mpIn->eof() && i < nb; i++ ) + for (int i = 0; !mpIn->eof() && i < nb; i++) mpIn->get(); } @@ -1769,14 +1813,16 @@ void cTextReportViewer::EatSection() // //========================================================================= -cEmailReportViewer::cEmailReportViewer( const cFCOReportHeader& h, const cFCOReport& r, - const TSTRING &address, bool bForceFullReport /*= false */) - : cTextReportViewer( h, r ), mbForceFullReport(bForceFullReport) +cEmailReportViewer::cEmailReportViewer(const cFCOReportHeader& h, + const cFCOReport& r, + const TSTRING& address, + bool bForceFullReport /*= false */) + : cTextReportViewer(h, r), mbForceFullReport(bForceFullReport) { mAddress = address; } -bool cEmailReportViewer::IgnoreThisSpec(const cFCOSpecAttr *attr) +bool cEmailReportViewer::IgnoreThisSpec(const cFCOSpecAttr* attr) { // IgnoreThisSpec - returns false if the email address is specified // for the given spec attributes. @@ -1786,7 +1832,7 @@ bool cEmailReportViewer::IgnoreThisSpec(const cFCOSpecAttr *attr) // loop through all email addresses for this spec cFCOSpecAttrEmailIter emailIter(*attr); - for(emailIter.SeekBegin(); ! emailIter.Done(); emailIter.Next()) + for (emailIter.SeekBegin(); !emailIter.Done(); emailIter.Next()) { if (emailIter.EmailAddress() == mAddress) return false; // Don't ignore it. It applies to me. @@ -1802,83 +1848,81 @@ bool cEmailReportViewer::WantOutputObjectSummary() return false; } -bool cEmailReportViewer::CanUpdate() +bool cEmailReportViewer::CanUpdate() { // this derived class does not allow "DisplayReportAndHaveUserUpdateIt()" return false; } - - //========================================================================= // 6/16/99 -- new reporting stuff //========================================================================= TSTRING cTextReportViewer::SingleLineReport() { TOSTRINGSTREAM sstrReport; - ASSERT( mpReport != 0 ); - ASSERT( mpHeader != 0 ); - + ASSERT(mpReport != 0); + ASSERT(mpHeader != 0); + // // get current time // - tm* ptm = cTimeUtil::TimeToDateLocal( mpHeader->GetCreationTime() ); - if( NULL == ptm ) - ThrowAndAssert( ePoly() ); + tm* ptm = cTimeUtil::TimeToDateLocal(mpHeader->GetCreationTime()); + if (NULL == ptm) + ThrowAndAssert(ePoly()); // // format time: YYYYMMDDHHMMSS // TCHAR szDate[256]; - _tcsftime( szDate, countof( szDate ), _T("%Y%m%d%H%M%S"), ptm ); + _tcsftime(szDate, countof(szDate), _T("%Y%m%d%H%M%S"), ptm); - sstrReport << TSS_GetString( cTW, tw::STR_TRIPWIRE_REPORT_SHORT ); + sstrReport << TSS_GetString(cTW, tw::STR_TRIPWIRE_REPORT_SHORT); sstrReport << _T(" "); - sstrReport << mpHeader->GetSystemName(); + sstrReport << mpHeader->GetSystemName(); sstrReport << _T(" "); sstrReport << szDate; // // get report stats - // - int nAddedTotal = 0; - int nRemovedTotal = 0; - int nChangedTotal = 0; - int nViolations = 0; + // + int nAddedTotal = 0; + int nRemovedTotal = 0; + int nChangedTotal = 0; + int nViolations = 0; int maxSeverityViolated = 0; - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { // We need to at least get the max severity in this function - cFCOReportSpecIter ri( genreIter ); - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) + cFCOReportSpecIter ri(genreIter); + for (ri.SeekBegin(); !ri.Done(); ri.Next()) { int nAdded = ri.GetAddedSet()->Size(); int nRemoved = ri.GetRemovedSet()->Size(); int nChanged = ri.GetNumChanged(); - nAddedTotal += nAdded; + nAddedTotal += nAdded; nRemovedTotal += nRemoved; nChangedTotal += nChanged; - if( nAdded || nRemoved || nChanged ) + if (nAdded || nRemoved || nChanged) { // update the max severity - if( maxSeverityViolated < ri.GetAttr()->GetSeverity() ) + if (maxSeverityViolated < ri.GetAttr()->GetSeverity()) maxSeverityViolated = ri.GetAttr()->GetSeverity(); - nViolations += ( nAdded + nRemoved + nChanged ); + nViolations += (nAdded + nRemoved + nChanged); } } } - sstrReport << _T(" ") << TSS_GetString( cTW, tw::STR_VIOLATIONS_SHORT ) << _T(":") << nViolations; - sstrReport << _T(" ") << TSS_GetString( cTW, tw::STR_MAX_SEV_SHORT ) << _T(":") << maxSeverityViolated; - sstrReport << _T(" ") << TSS_GetString( cTW, tw::STR_ADDED_SHORT ) << _T(":") << nAddedTotal; - sstrReport << _T(" ") << TSS_GetString( cTW, tw::STR_REMOVED_SHORT ) << _T(":") << nRemovedTotal; - sstrReport << _T(" ") << TSS_GetString( cTW, tw::STR_CHANGED_SHORT ) << _T(":") << nChangedTotal; + sstrReport << _T(" ") << TSS_GetString(cTW, tw::STR_VIOLATIONS_SHORT) << _T(":") << nViolations; + sstrReport << _T(" ") << TSS_GetString(cTW, tw::STR_MAX_SEV_SHORT) << _T(":") << maxSeverityViolated; + sstrReport << _T(" ") << TSS_GetString(cTW, tw::STR_ADDED_SHORT) << _T(":") << nAddedTotal; + sstrReport << _T(" ") << TSS_GetString(cTW, tw::STR_REMOVED_SHORT) << _T(":") << nRemovedTotal; + sstrReport << _T(" ") << TSS_GetString(cTW, tw::STR_CHANGED_SHORT) << _T(":") << nChangedTotal; return sstrReport.str(); } @@ -1887,108 +1931,113 @@ TSTRING cTextReportViewer::SingleLineReport() void cTextReportViewer::OutputParseableReport() { // iterate over all genres in a report - cFCOReportGenreIter genreIter( *mpReport ); - for( genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next() ) - { - SetUpForNewGenre( genreIter ); + cFCOReportGenreIter genreIter(*mpReport); + for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) + { + SetUpForNewGenre(genreIter); // iterate over all specs in a genre - cFCOReportSpecIter ri( genreIter ); - for( ri.SeekBegin(); !ri.Done(); ri.Next() ) - { - // iterate over all removed fcos + cFCOReportSpecIter ri(genreIter); + for (ri.SeekBegin(); !ri.Done(); ri.Next()) + { + // iterate over all added fcos const cIterProxy pSetIterAdded = ri.GetAddedSet()->GetIter(); - for( pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next() ) - { - (*mpOut) << TSS_GetString( cTW, tw::STR_ADDED ) << _T(":\t"); - (*mpOut) << mpCurNT->ToStringDisplay( pSetIterAdded->FCO()->GetName(), true ) << endl; + for (pSetIterAdded->SeekBegin(); !pSetIterAdded->Done(); pSetIterAdded->Next()) + { + if (!IgnoreThisFCO(pSetIterAdded->FCO())) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_ADDED) << _T(":\t"); + (*mpOut) << mpCurNT->ToStringDisplay(pSetIterAdded->FCO()->GetName(), true) << endl; + } } - - // iterate over all removed fcos + + // iterate over all removed fcos const cIterProxy pSetIterRemoved = ri.GetRemovedSet()->GetIter(); - for( pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next() ) + for (pSetIterRemoved->SeekBegin(); !pSetIterRemoved->Done(); pSetIterRemoved->Next()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_REMOVED ) << _T(":\t"); - (*mpOut) << mpCurNT->ToStringDisplay( pSetIterRemoved->FCO()->GetName(), true ) << endl; + if (!IgnoreThisFCO(pSetIterRemoved->FCO())) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_REMOVED) << _T(":\t"); + (*mpOut) << mpCurNT->ToStringDisplay(pSetIterRemoved->FCO()->GetName(), true) << endl; + } } - - // iterate over all changed fcos - cFCOReportChangeIter changedIter( ri ); - for( changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next() ) + + // iterate over all changed fcos + cFCOReportChangeIter changedIter(ri); + for (changedIter.SeekBegin(); !changedIter.Done(); changedIter.Next()) { - (*mpOut) << TSS_GetString( cTW, tw::STR_CHANGED ) << _T(":\t"); - (*mpOut) << mpCurNT->ToStringDisplay( changedIter.GetNew()->GetName(), true ) << endl; + if (!IgnoreThisFCO(changedIter.GetNew())) + { + (*mpOut) << TSS_GetString(cTW, tw::STR_CHANGED) << _T(":\t"); + (*mpOut) << mpCurNT->ToStringDisplay(changedIter.GetNew()->GetName(), true) << endl; + } } } } } char cTextReportViewer::PeekChar() -{ - return char_traits:: - to_char_type( - mpIn->peek() ); +{ + return char_traits::to_char_type(mpIn->peek()); } // TODO:BAM -- man is this function sloppy!!! -// The only reason that this function would fail would be that the text report +// The only reason that this function would fail would be that the text report // was corrupted, like um, binarily corrupted. (that is, anything a text editor // would put in here would be readable) void cTextReportViewer::GetChar() { cDebug d("cTextReportViewer::GetChar"); - ASSERT( sizeof( mCurrentChar ) >= MB_CUR_MAX ); // mCurrentChar holds a mb character for current locale + ASSERT(sizeof(mCurrentChar) >= MB_CUR_MAX); // mCurrentChar holds a mb character for current locale // initialize mCurrentChar mCurrentCharSize = 0; - for( int i = 0; i < (int)sizeof( mCurrentChar ); i++ ) + for (uint32 i = 0; i < sizeof(mCurrentChar); i++) mCurrentChar[i] = 0; - static const std::istream::char_type eof = - std::char_traits< char >::to_char_type( - std::char_traits< char >::eof() ); + static const std::istream::char_type eof = std::char_traits::to_char_type(std::char_traits::eof()); + + std::streampos pos = mpIn->tellg(); - for( size_t nch = 0; nch < (size_t)MB_CUR_MAX; nch++ ) + for (size_t nch = 0; nch < (size_t)MB_CUR_MAX; nch++) { - if( mpIn->eof() || PeekIsEOF() ) + if (mpIn->eof() || PeekIsEOF()) { // should be first byte we read - if( nch != 0 ) - throw eTextReportViewerReportCorrupt(); + if (nch != 0) + throw eTextReportViewerReportCorrupt("Expected EOF"); - if( PeekIsEOF() ) + if (PeekIsEOF()) { // get the eof char so that mpIn->eof() will return true mpIn->get(); } - d.TraceDebug( _T("Found EOF\n") ); + d.TraceDebug(_T("Found EOF\n")); - mCurrentChar[0] = eof; + mCurrentChar[0] = eof; mCurrentCharSize = 1; - + return; } else { - if( ! mpIn->good() ) + if (!mpIn->good()) { - d.TraceDebug( _T("Input stream error.\n") ); - throw eTextReportViewerReportCorrupt(); + d.TraceDebug(_T("Input stream error.\n")); + throw eTextReportViewerReportCorrupt("Input stream error"); } - + // get character from input stream - std::istream::char_type ch = - std::char_traits::to_char_type( - mpIn->get() ); + std::istream::char_type ch = std::char_traits::to_char_type(mpIn->get()); // add character to mb buffer mCurrentChar[nch] = ch; mCurrentCharSize++; // have we found a complete mb character yet? - if( 0 <= mbtowc( NULL, mCurrentChar, mCurrentCharSize ) ) + if (0 <= mbtowc(NULL, mCurrentChar, mCurrentCharSize)) { // completed a valid mb charactter return; @@ -2000,20 +2049,29 @@ void cTextReportViewer::GetChar() } } + mpIn->seekg(pos); + std::istream::char_type c = std::char_traits::to_char_type(mpIn->get()); + if ((unsigned char)c > 0x7f) + { + mCurrentChar[0] = c; + mCurrentChar[1] = 0; + mCurrentCharSize = 1; + return; + } + // sequence was not a valid mb character // (searched MB_CUR_MAX chars and didn't find a complete mb character) - d.TraceDebug( _T("Invalid mb char found!\n") ); -#ifdef _DEBUG - for( int j = 0; j < MB_CUR_MAX; j++ ) - d.TraceDebug( _T("%u\n"), (size_t)(unsigned char)mCurrentChar[j] ); + d.TraceDebug(_T("Invalid mb char found!\n")); +#ifdef DEBUG + for (int j = 0; j < MB_CUR_MAX; j++) + d.TraceDebug(_T("%u\n"), (size_t)(unsigned char)mCurrentChar[j]); #endif - ASSERT( false ); - throw eTextReportViewerReportCorrupt(); + ASSERT(false); + throw eTextReportViewerReportCorrupt("Invalid multibyte sequence"); } -void cTextReportViewer::AppendChar( std::string& str ) +void cTextReportViewer::AppendChar(std::string& str) { - for( size_t s = 0; s < mCurrentCharSize; s++ ) + for (size_t s = 0; s < mCurrentCharSize; s++) str += mCurrentChar[s]; } - diff --git a/src/tw/textreportviewer.h b/src/tw/textreportviewer.h index b5321f6..5c94614 100644 --- a/src/tw/textreportviewer.h +++ b/src/tw/textreportviewer.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -69,10 +69,10 @@ class cErrorQueueIter; // DECLARATION OF CLASSES //========================================================================= -TSS_EXCEPTION( eTextReportViewer, eError ); -TSS_EXCEPTION( eTextReportViewerFileOpen, eTextReportViewer ); -TSS_EXCEPTION( eTextReportViewerEditorLaunch, eTextReportViewer ); -TSS_EXCEPTION( eTextReportViewerReportCorrupt, eTextReportViewer ); +TSS_EXCEPTION(eTextReportViewer, eError); +TSS_EXCEPTION(eTextReportViewerFileOpen, eTextReportViewer); +TSS_EXCEPTION(eTextReportViewerEditorLaunch, eTextReportViewer); +TSS_EXCEPTION(eTextReportViewerReportCorrupt, eTextReportViewer); /////////////////////////////////////////////////////////////////////////////// @@ -80,15 +80,15 @@ TSS_EXCEPTION( eTextReportViewerReportCorrupt, eTextReportViewer ); // class cTextReportViewer { -public: +public: // // ctors and dtors // - cTextReportViewer( const cFCOReportHeader& h, cFCOReport& r ); - cTextReportViewer( const cFCOReportHeader& h, const cFCOReport& r ); + cTextReportViewer(const cFCOReportHeader& h, cFCOReport& r); + cTextReportViewer(const cFCOReportHeader& h, const cFCOReport& r); virtual ~cTextReportViewer(); - int Init( const cFCOReportHeader& h, cFCOReport& r ); - + int Init(const cFCOReportHeader& h, cFCOReport& r); + enum ReportingLevel { SINGLE_LINE, @@ -101,30 +101,34 @@ class cTextReportViewer // // basic functionality // - void DisplayReportAndHaveUserUpdateIt( const TSTRING& edName, ReportingLevel level = FULL_REPORT ); //throw (eFSServices, eTextReportViewer, eInternal); - // outputs the given report to a temp file, opens an editor, has - // the user view changes to the database, and, by selecting FCO entries, - // chooses which changes to write to the database. Unchecked entries - // are removed from the report - // edName is the name of the editor to use to update the report - - virtual void PrintTextReport( const TSTRING& strFilename, ReportingLevel level = FULL_REPORT ); //throw (eTextReportViewer); - // if strFilename is "-", will print to TCOUT - virtual void PrintTextReport( TOSTREAM& ostr, ReportingLevel level = FULL_REPORT ); //throw (eTextReportViewer); + void DisplayReportAndHaveUserUpdateIt( + const TSTRING& edName, ReportingLevel level = FULL_REPORT); //throw (eFSServices, eTextReportViewer, eInternal); + // outputs the given report to a temp file, opens an editor, has + // the user view changes to the database, and, by selecting FCO entries, + // chooses which changes to write to the database. Unchecked entries + // are removed from the report + // edName is the name of the editor to use to update the report + + virtual void PrintTextReport(const TSTRING& strFilename, + ReportingLevel level = FULL_REPORT); //throw (eTextReportViewer); + // if strFilename is "-", will print to TCOUT + virtual void PrintTextReport(TOSTREAM& ostr, ReportingLevel level = FULL_REPORT); //throw (eTextReportViewer); // prints the report to the specified ostream TSTRING SingleLineReport(); - + int GetMaxSeverityViolated(); int GetNumberViolations(); + void SetObjects(const std::set& objects); + protected: // // don't let C++ create these functions // cTextReportViewer(); - cTextReportViewer( const cTextReportViewer& ); - cTextReportViewer& operator=( const cTextReportViewer& ); + cTextReportViewer(const cTextReportViewer&); + cTextReportViewer& operator=(const cTextReportViewer&); // // private enums @@ -133,7 +137,7 @@ class cTextReportViewer { DETAILS_MARGIN = 4 }; - + enum { TOKEN_GENRE, @@ -141,7 +145,7 @@ class cTextReportViewer TOKEN_EOF }; - // + // // private structures // struct RuleSummaryLine @@ -153,81 +157,89 @@ class cTextReportViewer int mChangedObjects; TSTRING mStartPoint; - RuleSummaryLine() {} - RuleSummaryLine(const RuleSummaryLine& rhs) { *this = rhs; } - void operator = (const RuleSummaryLine& rhs) - { - mSpecName = rhs.mSpecName; - mSeverity = rhs.mSeverity; - mAddedObjects = rhs.mAddedObjects; + RuleSummaryLine() : mSeverity(0), mAddedObjects(0), mRemovedObjects(0), mChangedObjects(0) + { + } + RuleSummaryLine(const RuleSummaryLine& rhs) + { + *this = rhs; + } + RuleSummaryLine& operator=(const RuleSummaryLine& rhs) + { + mSpecName = rhs.mSpecName; + mSeverity = rhs.mSeverity; + mAddedObjects = rhs.mAddedObjects; mRemovedObjects = rhs.mRemovedObjects; mChangedObjects = rhs.mChangedObjects; - mStartPoint = rhs.mStartPoint; + mStartPoint = rhs.mStartPoint; + + return *this; } }; // // private typedefs // - typedef std::set< cFCOName > FCOList; - typedef std::map< cGenre::Genre, FCOList* > GenreList; - typedef std::list< RuleSummaryLine > ObjectSummaryList; - + typedef std::set FCOList; + typedef std::map GenreList; + typedef std::list ObjectSummaryList; + // // private util functions // - bool LaunchEditorOnFile( const TSTRING& strFilename, const TSTRING& edName ); //throw (eFSServices, eTextReportViewer); - void OutputTextReport(); //throw (eTextReportViewer); - - void PrintGenre( const cFCOReportGenreIter& genreIter ); //throw (eTextReportViewer); - void OutputGenreDelimiter( cGenre::Genre g, bool fDenoteBallotSection = false ); - void OutputSectionDelimiter( int nString ); - void OutputNumDetails( int nString, int nObjects ); - - void PrintBallotLine( const iFCO& FCO ); - void DisplayChangedProps( const iFCO* const pfcoOld, const iFCO* const pfcoNew, const cFCOPropVector* pv ); - void SetUpForNewGenre( const cFCOReportGenreIter& genreIter ); // call this after changing genres - + bool LaunchEditorOnFile(const TSTRING& strFilename, + const TSTRING& edName); //throw (eFSServices, eTextReportViewer); + void OutputTextReport(); //throw (eTextReportViewer); + + void PrintGenre(const cFCOReportGenreIter& genreIter); //throw (eTextReportViewer); + void OutputGenreDelimiter(cGenre::Genre g, bool fDenoteBallotSection = false); + void OutputSectionDelimiter(int nString); + void OutputNumDetails(int nString, int nObjects); + + void PrintBallotLine(const iFCO& FCO); + void DisplayChangedProps(const iFCO* const pfcoOld, const iFCO* const pfcoNew, const cFCOPropVector* pv); + void SetUpForNewGenre(const cFCOReportGenreIter& genreIter); // call this after changing genres + void OutputReportHeader(); void OutputRulesSummary(); - void OutputRulesSummary( const cFCOReportGenreIter& genreIter ); - void CollateRulesSummary( const cFCOReportGenreIter& genreIter, ObjectSummaryList& summaryList ); - void OutputSpecHeader( const cFCOReportSpecIter &ri ); + void OutputRulesSummary(const cFCOReportGenreIter& genreIter); + void CollateRulesSummary(const cFCOReportGenreIter& genreIter, ObjectSummaryList& summaryList); + void OutputSpecHeader(const cFCOReportSpecIter& ri); void OutputFooter(); - + void PrintErrors(); - void ReportError( const cErrorQueueIter& eqIter ); - - void OutputObjectSummary (); - void OutputObjectSummary ( const cFCOReportGenreIter& genreIter ); - void OutputAddedSummary ( const cFCOReportSpecIter& ri, FCOList* pFCONameList ); - void OutputRemovedSummary( const cFCOReportSpecIter& ri, FCOList* pFCONameList ); - void OutputChangedSummary( const cFCOReportSpecIter& ri, FCOList* pFCONameList ); - - void OutputObjectDetails (); - void OutputObjectDetails ( const cFCOReportGenreIter& genreIter ); - void OutputAddedDetails ( const cFCOReportSpecIter& ri ); - void OutputRemovedDetails( const cFCOReportSpecIter& ri ); - void OutputChangedDetails( const cFCOReportSpecIter& ri ); - - bool IsChecked(); + void ReportError(const cErrorQueueIter& eqIter); + + void OutputObjectSummary(); + void OutputObjectSummary(const cFCOReportGenreIter& genreIter); + void OutputAddedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList); + void OutputRemovedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList); + void OutputChangedSummary(const cFCOReportSpecIter& ri, FCOList* pFCONameList); + + void OutputObjectDetails(); + void OutputObjectDetails(const cFCOReportGenreIter& genreIter); + void OutputAddedDetails(const cFCOReportSpecIter& ri); + void OutputRemovedDetails(const cFCOReportSpecIter& ri); + void OutputChangedDetails(const cFCOReportSpecIter& ri); + + bool IsChecked(); TSTRING GetGenre(); - void InitOStream(); - void GetReportNumbers(); + void InitOStream(); + void GetReportNumbers(); - void ReadTextReport( const TSTRING& strFilename ); + void ReadTextReport(const TSTRING& strFilename); void GetChar(); char PeekChar(); bool PeekIsEOF(); - void AppendChar( std::string& str ); - + void AppendChar(std::string& str); + void EatSection(); int FindNextLineToken(); - void GetGenreInfo( FCOList** ppCurList ); - void GetBallotInfo( FCOList* pCurList ); - void GetFCONameFromBallotLine( cFCOName& fcoName ); //throw (eTextReportViewer) - void RemoveFCOsFromReport();//throw (eTextReportViewer) + void GetGenreInfo(FCOList** ppCurList); + void GetBallotInfo(FCOList* pCurList); + void GetFCONameFromBallotLine(cFCOName& fcoName); //throw (eTextReportViewer) + void RemoveFCOsFromReport(); //throw (eTextReportViewer) void OutputParseableReport(); @@ -235,16 +247,17 @@ class cTextReportViewer // overridables: // - virtual bool IgnoreThisSpec(const cFCOSpecAttr *attr); + virtual bool IgnoreThisSpec(const cFCOSpecAttr* attr); + virtual bool IgnoreThisFCO(const iFCO* fco); virtual bool WantOutputReportHeader(); virtual bool WantOutputRulesSummary(); virtual bool WantOutputSpecHeader(); virtual bool WantOutputObjectSummary(); virtual bool WantOutputObjectDetails(); - // These function allows derived classes to tailor the report's apearance + // These function allows derived classes to tailor the report's apearance virtual bool CanUpdate(); - // override this to return false if DisplayReportAndHaveUserUpdateIt should not be allowed + // override this to return false if DisplayReportAndHaveUserUpdateIt should not be allowed // // data members @@ -264,6 +277,8 @@ class cTextReportViewer bool mfGotNumbers; char mCurrentChar[6]; size_t mCurrentCharSize; + bool mFilterFCOs; + std::set mObjects; }; @@ -278,24 +293,22 @@ class cEmailReportViewer : public cTextReportViewer { public: // constructor must be provided an email recipient's address - cEmailReportViewer( const cFCOReportHeader& h, const cFCOReport& r, - const TSTRING &address, - bool bForceFullReport = false); + cEmailReportViewer(const cFCOReportHeader& h, + const cFCOReport& r, + const TSTRING& address, + bool bForceFullReport = false); protected: // overrides - virtual bool IgnoreThisSpec(const cFCOSpecAttr *attr); + virtual bool IgnoreThisSpec(const cFCOSpecAttr* attr); virtual bool WantOutputObjectSummary(); virtual bool CanUpdate(); // data members TSTRING mAddress; - bool mbForceFullReport; - + bool mbForceFullReport; }; #endif // __TEXTREPORTVIEWER_H - - diff --git a/src/tw/tw.cpp b/src/tw/tw.cpp index dcb0d66..e03031e 100644 --- a/src/tw/tw.cpp +++ b/src/tw/tw.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,19 +52,16 @@ /////////////////////////////////////////////////////////////////////////////// // cTW /////////////////////////////////////////////////////////////////////////////// -TSS_ImplementPackage( cTW ) +TSS_ImplementPackage(cTW) cTW::cTW() { - TSS_Dependency( cCore ); - TSS_Dependency( cDb ); - TSS_Dependency( cTWCrypto ); - TSS_Dependency( cFCO ); - TSS_Dependency( cUtil ); - TSS_Dependency( cFS ); - - TSS_REGISTER_PKG_ERRORS( tw ) -} - -// eof: tw.cpp + TSS_Dependency(cCore); + TSS_Dependency(cDb); + TSS_Dependency(cTWCrypto); + TSS_Dependency(cFCO); + TSS_Dependency(cUtil); + TSS_Dependency(cFS); + TSS_REGISTER_PKG_ERRORS(tw) +} diff --git a/src/tw/tw.h b/src/tw/tw.h index 547bfe7..fbdfd27 100644 --- a/src/tw/tw.h +++ b/src/tw/tw.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,20 +40,19 @@ #ifndef __TW_H #define __TW_H -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #include "core/package.h" -TSS_BeginPackage( cTW ) +TSS_BeginPackage(cTW) TSS_DECLARE_STRINGTABLE; public: - cTW(); - -TSS_EndPackage( cTW ) +cTW(); +TSS_EndPackage(cTW) -#endif//__TW_H +#endif //__TW_H diff --git a/src/tw/twerrors.cpp b/src/tw/twerrors.cpp index cf9be69..dd538c6 100644 --- a/src/tw/twerrors.cpp +++ b/src/tw/twerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,76 +43,75 @@ #include "filemanipulator.h" #include "fcodatabasefile.h" -TSS_BEGIN_ERROR_REGISTRATION( tw ) +TSS_BEGIN_ERROR_REGISTRATION(tw) // // General // -TSS_REGISTER_ERROR( eTWDbNotEncrypted(), _T("Database is not encrypted.") ); -TSS_REGISTER_ERROR( eTWDbDoesntHaveGenre(), _T("Section not found in database.") ); -TSS_REGISTER_ERROR( eTWDbHasNoGenres(), _T("Database file contains no sections!") ); -TSS_REGISTER_ERROR( eTWBadPropsToIgnore(), _T("Invalid property mask specified on command line:") ); -TSS_REGISTER_ERROR( eTWUnknownSectionName(), _T("Unknown section name specified on command line:") ); -TSS_REGISTER_ERROR( eTWBadSeverityName(), _T("Unknown severity name (valid values are [low, medium, high]).") ); -TSS_REGISTER_ERROR( eTWCfgUnencrypted(), _T("Config file is unencrypted.") ); -TSS_REGISTER_ERROR( eTWPolUnencrypted(), _T("Policy file is unencrypted.") ); -TSS_REGISTER_ERROR( eTWSyslog(), _T("Syslog reporting failure.") ); +TSS_REGISTER_ERROR(eTWDbNotEncrypted(), _T("Database is not encrypted.")); +TSS_REGISTER_ERROR(eTWDbDoesntHaveGenre(), _T("Section not found in database.")); +TSS_REGISTER_ERROR(eTWDbHasNoGenres(), _T("Database file contains no sections!")); +TSS_REGISTER_ERROR(eTWBadPropsToIgnore(), _T("Invalid property mask specified on command line:")); +TSS_REGISTER_ERROR(eTWUnknownSectionName(), _T("Unknown section name specified on command line:")); +TSS_REGISTER_ERROR(eTWBadSeverityName(), _T("Unknown severity name (valid values are [low, medium, high]).")); +TSS_REGISTER_ERROR(eTWCfgUnencrypted(), _T("Config file is unencrypted.")); +TSS_REGISTER_ERROR(eTWPolUnencrypted(), _T("Policy file is unencrypted.")); +TSS_REGISTER_ERROR(eTWSyslog(), _T("Syslog reporting failure.")); // // Config File // -TSS_REGISTER_ERROR( eConfigFile(), _T("Configuration file error.") ) -TSS_REGISTER_ERROR( eConfigFileNoEq(), _T("Configuration file contains a line with no \"=\".") ) -TSS_REGISTER_ERROR( eConfigFileNoKey(), _T("Configuration file contains a line with no variable.") ) -TSS_REGISTER_ERROR( eConfigFileAssignToPredefVar(), _T("Configuration file assigns a value to a read only variable.") ) -TSS_REGISTER_ERROR( eConfigFileUseUndefVar(), _T("Configuration file uses an undefined variable.") ) -TSS_REGISTER_ERROR( eConfigFileMissReqKey(), _T("Configuration file does not define mandatory variable(s).") ) -TSS_REGISTER_ERROR( eConfigFileEmptyVariable(), _T("Configuration file assigns an empty value to a variable.") ) -TSS_REGISTER_ERROR( eConfigFileMissingRightParen(), _T("Configuration file variable has no right parenthesis.") ) +TSS_REGISTER_ERROR(eConfigFile(), _T("Configuration file error.")) +TSS_REGISTER_ERROR(eConfigFileNoEq(), _T("Configuration file contains a line with no \"=\".")) +TSS_REGISTER_ERROR(eConfigFileNoKey(), _T("Configuration file contains a line with no variable.")) +TSS_REGISTER_ERROR(eConfigFileAssignToPredefVar(), _T("Configuration file assigns a value to a read only variable.")) +TSS_REGISTER_ERROR(eConfigFileUseUndefVar(), _T("Configuration file uses an undefined variable.")) +TSS_REGISTER_ERROR(eConfigFileMissReqKey(), _T("Configuration file does not define mandatory variable(s).")) +TSS_REGISTER_ERROR(eConfigFileEmptyVariable(), _T("Configuration file assigns an empty value to a variable.")) +TSS_REGISTER_ERROR(eConfigFileMissingRightParen(), _T("Configuration file variable has no right parenthesis.")) // // TW Util // -TSS_REGISTER_ERROR( eTWUtil(), _T("Tripwire error.") ) -TSS_REGISTER_ERROR( eTWUtilNotFullPath(), _T("Object name is not fully qualified; skipping.") ) -TSS_REGISTER_ERROR( eTWUtilCfgKeyMismatch(), _T("Config file site key mismatch.") ) -TSS_REGISTER_ERROR( eTWUtilCorruptedFile(), _T("File is corrupted.") ) -TSS_REGISTER_ERROR( eTWUtilBadPassLocal(), _T("Incorrect local passphrase.") ) -TSS_REGISTER_ERROR( eTWUtilBadPassSite(), _T("Incorrect site passphrase.") ) -TSS_REGISTER_ERROR( eTWUtilEchoModeSet(), _T("Could not set console to no echo mode.") ) -TSS_REGISTER_ERROR( eTWUtilPolUnencrypted(), _T("Policy file is unencrypted.") ) -TSS_REGISTER_ERROR( eTWUtilObjNotInDb(), _T("Object not found in the database.") ) +TSS_REGISTER_ERROR(eTWUtil(), _T("Tripwire error.")) +TSS_REGISTER_ERROR(eTWUtilNotFullPath(), _T("Object name is not fully qualified; skipping.")) +TSS_REGISTER_ERROR(eTWUtilCfgKeyMismatch(), _T("Config file site key mismatch.")) +TSS_REGISTER_ERROR(eTWUtilCorruptedFile(), _T("File is corrupted.")) +TSS_REGISTER_ERROR(eTWUtilBadPassLocal(), _T("Incorrect local passphrase.")) +TSS_REGISTER_ERROR(eTWUtilBadPassSite(), _T("Incorrect site passphrase.")) +TSS_REGISTER_ERROR(eTWUtilEchoModeSet(), _T("Could not set console to no echo mode.")) +TSS_REGISTER_ERROR(eTWUtilPolUnencrypted(), _T("Policy file is unencrypted.")) +TSS_REGISTER_ERROR(eTWUtilObjNotInDb(), _T("Object not found in the database.")) // // Text Report Viewer // -TSS_REGISTER_ERROR( eTextReportViewer(), _T("Text report viewer error.") ) -TSS_REGISTER_ERROR( eTextReportViewerFileOpen(), _T("File could not be opened.") ) -TSS_REGISTER_ERROR( eTextReportViewerEditorLaunch(), _T("Editor could not be launched.") ) -TSS_REGISTER_ERROR( eTextReportViewerReportCorrupt(), _T("Report file could not be parsed. Report may be corrupt.") ) +TSS_REGISTER_ERROR(eTextReportViewer(), _T("Text report viewer error.")) +TSS_REGISTER_ERROR(eTextReportViewerFileOpen(), _T("File could not be opened.")) +TSS_REGISTER_ERROR(eTextReportViewerEditorLaunch(), _T("Editor could not be launched.")) +TSS_REGISTER_ERROR(eTextReportViewerReportCorrupt(), _T("Report file could not be parsed. Report may be corrupt.")) // // File Manipulator // -TSS_REGISTER_ERROR( eFileManip(), _T("File manipulation error.") ) -TSS_REGISTER_ERROR( eFileManipInvalidFile(), _T("Could not manipulate invalid file.") ) -TSS_REGISTER_ERROR( eFileManipFileRead(), _T("File could not be read.") ) -TSS_REGISTER_ERROR( eFileManipHeaderNotFound(), _T("File is not a Tripwire data file.") ) -TSS_REGISTER_ERROR( eFileManipFileNotFound(), _T("File could not be found.") ) -TSS_REGISTER_ERROR( eFileManipNotEncrypted(), _T("File is not encrypted.") ) -TSS_REGISTER_ERROR( eFileManipMissingKey(), _T("Key not supplied.") ) -TSS_REGISTER_ERROR( eFileManipNotWritable(), _T("File is not writable.") ) -TSS_REGISTER_ERROR( eFileManipUnrecognizedFileType(), _T("Unrecognized file type.") ) - // TODO:mdb -- why was this commented out of twstrings and the error table? +TSS_REGISTER_ERROR(eFileManip(), _T("File manipulation error.")) +TSS_REGISTER_ERROR(eFileManipInvalidFile(), _T("Could not manipulate invalid file.")) +TSS_REGISTER_ERROR(eFileManipFileRead(), _T("File could not be read.")) +TSS_REGISTER_ERROR(eFileManipHeaderNotFound(), _T("File is not a Tripwire data file.")) +TSS_REGISTER_ERROR(eFileManipFileNotFound(), _T("File could not be found.")) +TSS_REGISTER_ERROR(eFileManipNotEncrypted(), _T("File is not encrypted.")) +TSS_REGISTER_ERROR(eFileManipMissingKey(), _T("Key not supplied.")) +TSS_REGISTER_ERROR(eFileManipNotWritable(), _T("File is not writable.")) +TSS_REGISTER_ERROR(eFileManipUnrecognizedFileType(), _T("Unrecognized file type.")) +// TODO:mdb -- why was this commented out of twstrings and the error table? // // Database File // -TSS_REGISTER_ERROR( eFCODbFile(), _T("Database file error.") ); -TSS_REGISTER_ERROR( eFCODbFileTooBig(), _T("Database file too large.") ); +TSS_REGISTER_ERROR(eFCODbFile(), _T("Database file error.")); +TSS_REGISTER_ERROR(eFCODbFileTooBig(), _T("Database file too large.")); TSS_END_ERROR_REGISTRATION() - diff --git a/src/tw/twerrors.h b/src/tw/twerrors.h index df2613c..da1a900 100644 --- a/src/tw/twerrors.h +++ b/src/tw/twerrors.h @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// twerror.h -- +// twerror.h -- // #ifndef __TWERROR_H @@ -40,16 +40,16 @@ // TODO:mdb !!!! These do _not_ belong here!!! Did I do this???? // #include "core/error.h" -TSS_EXCEPTION( eTW, eError ); -TSS_EXCEPTION( eTWDbNotEncrypted, eTW ); -TSS_EXCEPTION( eTWDbDoesntHaveGenre, eTW ); -TSS_EXCEPTION( eTWDbHasNoGenres, eTW ); -TSS_EXCEPTION( eTWBadPropsToIgnore, eTW ); -TSS_EXCEPTION( eTWUnknownSectionName, eTW ); -TSS_EXCEPTION( eTWBadSeverityName, eTW ); -TSS_EXCEPTION( eTWCfgUnencrypted, eTW ); -TSS_EXCEPTION( eTWPolUnencrypted, eTW ); -TSS_EXCEPTION( eTWSyslog, eTW ); +TSS_EXCEPTION(eTW, eError); +TSS_EXCEPTION(eTWDbNotEncrypted, eTW); +TSS_EXCEPTION(eTWDbDoesntHaveGenre, eTW); +TSS_EXCEPTION(eTWDbHasNoGenres, eTW); +TSS_EXCEPTION(eTWBadPropsToIgnore, eTW); +TSS_EXCEPTION(eTWUnknownSectionName, eTW); +TSS_EXCEPTION(eTWBadSeverityName, eTW); +TSS_EXCEPTION(eTWCfgUnencrypted, eTW); +TSS_EXCEPTION(eTWPolUnencrypted, eTW); +TSS_EXCEPTION(eTWSyslog, eTW); // // end (stuff that should move @@ -57,7 +57,6 @@ TSS_EXCEPTION( eTWSyslog, eTW ); #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( tw ) +TSS_DECLARE_ERROR_REGISTRATION(tw) #endif //#ifndef __TWERROR_H - diff --git a/src/tw/twinit.cpp b/src/tw/twinit.cpp index 58ce031..d733808 100644 --- a/src/tw/twinit.cpp +++ b/src/tw/twinit.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -74,12 +74,11 @@ #include "fco/fconame.h" #include "fs/fs.h" // object initialization -#if IS_UNIX #include "core/unixfsservices.h" -#include "core/tw_signal.h" // to ignore SIGPIPE -#endif +#include "core/tw_signal.h" // to ignore SIGPIPE -#ifdef __AROS__ +#if IS_AROS +#include #include #include #include @@ -94,22 +93,21 @@ class cTWInit_i { public: cTWInit_i(); - ~cTWInit_i(); - // both shouldn't throw exceptions + ~cTWInit_i(); + // both shouldn't throw exceptions - iFSServices* pFSServices; - cUserNotifyStdout unStdout; - cErrorTracer et; - cErrorReporter er; + iFSServices* pFSServices; + cUserNotifyStdout unStdout; + cErrorTracer et; + cErrorReporter er; }; -cTWInit_i::cTWInit_i() - : pFSServices( NULL ) -{ +cTWInit_i::cTWInit_i() : pFSServices(NULL) +{ // package initialization - // + // - TSS_Dependency( cFS ); + TSS_Dependency(cFS); } cTWInit_i::~cTWInit_i() @@ -118,58 +116,60 @@ cTWInit_i::~cTWInit_i() } /////////////////////////////////////////////////////////////////////////////// -// RegisterAllSerializable() -- Register all serializable objects +// RegisterAllSerializable() -- Register all serializable objects /////////////////////////////////////////////////////////////////////////////// static void RegisterAllSerializable() { // Reference count objects - cSerializerImpl::RegisterSerializableRefCt (CLASS_TYPE(cFSObject), cFSObject::Create); - cSerializerImpl::RegisterSerializableRefCt (CLASS_TYPE(cFCOSpecImpl), cFCOSpecImpl::Create); - cSerializerImpl::RegisterSerializableRefCt (CLASS_TYPE(cFCOSpecAttr), cFCOSpecAttr::Create); + cSerializerImpl::RegisterSerializableRefCt(CLASS_TYPE(cFSObject), cFSObject::Create); + cSerializerImpl::RegisterSerializableRefCt(CLASS_TYPE(cFCOSpecImpl), cFCOSpecImpl::Create); + cSerializerImpl::RegisterSerializableRefCt(CLASS_TYPE(cFCOSpecAttr), cFCOSpecAttr::Create); // Non-reference count objects - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCODatabaseFile), cFCODatabaseFile::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cErrorQueue), cErrorQueue::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOName), cFCOName::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOReport), cFCOReport::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOSetImpl), cFCOSetImpl::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOSpecStopPointSet), cFCOSpecStopPointSet::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOSpecNoChildren), cFCOSpecNoChildren::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cSerializableNString), cSerializableNString::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cSerializableWString), cSerializableWString::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cHeaderInfo), cHeaderInfo::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCODbHeader), cFCODbHeader::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFCOReportHeader), cFCOReportHeader::Create); - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFSPropSet), cFSPropSet::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCODatabaseFile), cFCODatabaseFile::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cErrorQueue), cErrorQueue::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOName), cFCOName::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOReport), cFCOReport::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOSetImpl), cFCOSetImpl::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOSpecStopPointSet), cFCOSpecStopPointSet::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOSpecNoChildren), cFCOSpecNoChildren::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cSerializableNString), cSerializableNString::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cSerializableWString), cSerializableWString::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cHeaderInfo), cHeaderInfo::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCODbHeader), cFCODbHeader::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFCOReportHeader), cFCOReportHeader::Create); + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFSPropSet), cFSPropSet::Create); // prop displayers - cSerializerImpl::RegisterSerializable (CLASS_TYPE(cFSPropDisplayer), cFSPropDisplayer::Create); - + cSerializerImpl::RegisterSerializable(CLASS_TYPE(cFSPropDisplayer), cFSPropDisplayer::Create); } /////////////////////////////////////////////////////////////////////////////// // SetExeDir /////////////////////////////////////////////////////////////////////////////// -static bool SetExeDir( const TSTRING& strArgv0 ) +static bool SetExeDir(const TSTRING& strArgv0) { - ASSERT( ! strArgv0.empty() ); + ASSERT(!strArgv0.empty()); // record executable directory TSTRING strFullPath; - if( iFSServices::GetInstance()->GetExecutableFilename( strFullPath, strArgv0 ) && !strFullPath.empty() ) + if (iFSServices::GetInstance()->GetExecutableFilename(strFullPath, strArgv0) && !strFullPath.empty()) { +#if USES_DEVICE_PATH + strFullPath = cDevicePath::AsPosix(strFullPath); +#endif cSystemInfo::SetExePath(strFullPath); - TSTRING::size_type s = strFullPath.find_last_of( _T('/') ); + TSTRING::size_type s = strFullPath.find_last_of(_T('/')); // paths will always come back from GetExecutableFilename delimited with a forward slash - ASSERT( TSTRING::npos != s ); - if( TSTRING::npos != s ) - strFullPath.resize( s ); + ASSERT(TSTRING::npos != s); + if (TSTRING::npos != s) + strFullPath.resize(s); cSystemInfo::SetExeDir(strFullPath); } else // error { - ASSERT( false ); + ASSERT(false); cSystemInfo::SetExeDir(_T("")); return false; } @@ -194,41 +194,40 @@ cTWInit::~cTWInit() delete mpData; // - // clear out the fco name tbl + // clear out the fco name tbl // this helps the mem leak quest... // cFCOName::ClearNameTable(); - } /////////////////////////////////////////////////////////////////////////////// // Init /////////////////////////////////////////////////////////////////////////////// -void cTWInit::Init( const TSTRING& strArgv0 ) +void cTWInit::Init(const TSTRING& strArgv0) { // package initialization... // - TSS_Dependency( cTW ); // initialize all packages on program startup (exes - // should call this function (cTWInit::Init) on startup + TSS_Dependency(cTW); // initialize all packages on program startup (exes + // should call this function (cTWInit::Init) on startup // we require 8-bit bytes for some functionality - ASSERT( sizeof( byte ) == sizeof( uint8 ) ); + ASSERT(sizeof(byte) == sizeof(uint8)); // - // set debug level + // set debug level // NOTE:BAM -- this is also being set in cCore::cCore() because // things in that constructor need to have a debug output as well. // so this code here is redundant. // - cDebug::SetDebugLevel( cDebug::D_DEBUG ); - cDebug::AddOutTarget( cDebug::OUT_STDOUT ); + cDebug::SetDebugLevel(cDebug::D_DEBUG); + cDebug::AddOutTarget(cDebug::OUT_STDOUT); // ------------------------------------------------------------ // BEG:RAD -- Does not belong here, moved to cCore::cCore! // ------------------------------------------------------------ // // initialize locale - // + // // cTWLocale::InitGlobalLocale(); // ------------------------------------------------------------ // END:RAD @@ -245,97 +244,98 @@ void cTWInit::Init( const TSTRING& strArgv0 ) // END:RAD // ------------------------------------------------------------ -#ifdef __AROS__ +#if IS_AROS aros_socketbase_init(); #endif // - // set up the file system services + // set up the file system services // -#if IS_UNIX mpData->pFSServices = new cUnixFSServices; -#endif - ASSERT( mpData->pFSServices != 0 ); - iFSServices::SetInstance( mpData->pFSServices ); - + ASSERT(mpData->pFSServices != 0); + iFSServices::SetInstance(mpData->pFSServices); + // // save directory in which this executable resides // - SetExeDir( strArgv0 ); + SetExeDir(strArgv0); // // save current time // - cSystemInfo::SetExeStartTime( cTimeUtil::GetTime() ); + cSystemInfo::SetExeStartTime(cTimeUtil::GetTime()); // assure that a default genre has been set and... - ASSERT( cGenre::GENRE_INVALID != cGenreSwitcher::GetInstance()->GetDefaultGenre() ); + ASSERT(cGenre::GENRE_INVALID != cGenreSwitcher::GetInstance()->GetDefaultGenre()); // ...switch to it - cGenreSwitcher::GetInstance()->SelectGenre( cGenreSwitcher::GetInstance()->GetDefaultGenre() ); + cGenreSwitcher::GetInstance()->SelectGenre(cGenreSwitcher::GetInstance()->GetDefaultGenre()); // initialize iUserNotify - iUserNotify::SetInstance( &mpData->unStdout ); + iUserNotify::SetInstance(&mpData->unStdout); iUserNotify::GetInstance()->SetVerboseLevel(iUserNotify::V_NORMAL); // register serializable objects RegisterAllSerializable(); // set up an error bucket that will spit things to stderr - mpData->et.SetChild( &mpData->er ); - errorQueue.SetChild( &mpData->et ); + mpData->et.SetChild(&mpData->er); + errorQueue.SetChild(&mpData->et); -#if IS_UNIX +#if SUPPORTS_POSIX_SIGNALS // ignore SIGPIPE tw_sigign(SIGPIPE); //TODO: somebody add comment here! // We'll install handlers for each signal that would cause a core dump. // the disposition will still be to exit, just without producing a core file. - // I'll emit an error statement that indicates the interrupt before the exit + // I'll emit an error statement that indicates the interrupt before the exit // call. - tw_HandleSignal( SIGBUS ); // Handle Bus error signals without dumping core... - tw_HandleSignal( SIGSEGV ); // Segmentation fault - tw_HandleSignal( SIGQUIT ); // Quit signal - issued from terminal (CTRL-\) - tw_HandleSignal( SIGILL ); // Illegal instruction - probably won't be an issue. -#ifndef _DEBUG - tw_HandleSignal( SIGTRAP ); // We don't want to mess up the debugger in debug builds... -#endif - tw_HandleSignal( SIGABRT ); // Supposedly we can only get this signal by calling abort() - // ourselves, but to be on the safe side... -#ifdef SIGEMT - tw_HandleSignal( SIGEMT ); // Emulator trap. -#endif -#ifdef SIGSYS - tw_HandleSignal( SIGSYS ); // Bad system call. -#endif - tw_HandleSignal( SIGFPE ); // Floating point exception. - tw_HandleSignal( SIGXCPU ); // CPU time exceeded. Might very well be an issue for us. - tw_HandleSignal( SIGXFSZ ); // File size limit exceeded. + tw_HandleSignal(SIGBUS); // Handle Bus error signals without dumping core... + tw_HandleSignal(SIGSEGV); // Segmentation fault + tw_HandleSignal(SIGQUIT); // Quit signal - issued from terminal (CTRL-\) + tw_HandleSignal(SIGILL); // Illegal instruction - probably won't be an issue. +# ifndef DEBUG + tw_HandleSignal(SIGTRAP); // We don't want to mess up the debugger in debug builds... +# endif + tw_HandleSignal(SIGABRT); // Supposedly we can only get this signal by calling abort() + // ourselves, but to be on the safe side... +# ifdef SIGEMT + tw_HandleSignal(SIGEMT); // Emulator trap. +# endif +# ifdef SIGSYS + tw_HandleSignal(SIGSYS); // Bad system call. +# endif + tw_HandleSignal(SIGFPE); // Floating point exception. + +# ifdef SIGXCPU + tw_HandleSignal(SIGXCPU); // CPU time exceeded. Might very well be an issue for us. +# endif + +# ifdef SIGXFSZ + tw_HandleSignal(SIGXFSZ); // File size limit exceeded. +# endif #endif - - } -#ifdef __AROS__ -struct Library* SocketBase=0; +#if IS_AROS +struct Library* SocketBase = 0; bool aros_socketbase_init() { - if (!(SocketBase = OpenLibrary("bsdsocket.library", 4))) - { - printf("Failed to load socket library"); - return 0; - } - - if (SocketBaseTags( - SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (IPTR)&errno, - SBTM_SETVAL(SBTC_HERRNOLONGPTR), (IPTR)&errno, - TAG_DONE)) - { - printf("Failed to init socket library"); - return 0; - } - return 1; + if (!(SocketBase = OpenLibrary("bsdsocket.library", 4))) + { + printf("Failed to load socket library"); + return 0; + } + + if (SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), + (IPTR)&errno, + SBTM_SETVAL(SBTC_HERRNOLONGPTR), + (IPTR)&errno, + TAG_DONE)) + { + printf("Failed to init socket library"); + return 0; + } + return 1; } #endif - - diff --git a/src/tw/twinit.h b/src/tw/twinit.h index 7179627..128b799 100644 --- a/src/tw/twinit.h +++ b/src/tw/twinit.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,17 +43,16 @@ class cTWInit_i; class cTWInit { public: - cTWInit(); // throw() // used to record exe dir - // will not throw exceptions - ~cTWInit(); // throw() + cTWInit(); // throw() // used to record exe dir + // will not throw exceptions + ~cTWInit(); // throw() // will not throw exceptions - void Init( const TSTRING& strArgv0 ); - // may throw exceptions - - cErrorQueue errorQueue; -private: + void Init(const TSTRING& strArgv0); + // may throw exceptions - cTWInit_i* mpData; -}; + cErrorQueue errorQueue; +private: + cTWInit_i* mpData; +}; diff --git a/src/tw/twstrings.cpp b/src/tw/twstrings.cpp index 9f52e5c..f112e8e 100644 --- a/src/tw/twstrings.cpp +++ b/src/tw/twstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,35 +40,27 @@ #include "twstrings.h" #include "buildnum.h" -#ifdef _UNICODE -# ifdef _DEBUG // lets leave out the "u" for non-debug -# define UNICODE_STR _T("u") -# else -# define UNICODE_STR _T("") -# endif -#else -# define UNICODE_STR _T("") -#endif +#define UNICODE_STR _T("") -#ifdef _DEBUG -# define DEBUG_STR _T("d") +#ifdef DEBUG +# define DEBUG_STR _T("d") #else -# define DEBUG_STR _T("") +# define DEBUG_STR _T("") #endif -#define TSS_PRODUCT_NAME _T("Open Source Tripwire(R) 2.4.3.1.") +#define TSS_PRODUCT_NAME _T("Open Source Tripwire(R) " PACKAGE_VERSION ".") #define TSS_COPYRIGHT_NOTICE \ -_T("Open Source Tripwire 2.4 Portions copyright 2000 Tripwire, Inc. Tripwire is a registered\n\ + _T("Open Source Tripwire 2.4 Portions copyright 2000-2018 Tripwire, Inc. Tripwire is a registered\n\ trademark of Tripwire, Inc. This software comes with ABSOLUTELY NO WARRANTY;\n\ for details use --version. This is free software which may be redistributed\n\ or modified only under certain conditions; see COPYING for details.\n\ All rights reserved.") -#define TSS_COPYRIGHT_NOTICE_LONG \ -_T("The developer of the original code and/or files is Tripwire, Inc. Portions \n\ -created by Tripwire, Inc. are copyright 2000 Tripwire, Inc. Tripwire is a \n\ +#define TSS_COPYRIGHT_NOTICE_LONG \ + _T("The developer of the original code and/or files is Tripwire, Inc. Portions \n\ +created by Tripwire, Inc. are copyright 2000-2018 Tripwire, Inc. Tripwire is a \n\ registered trademark of Tripwire, Inc. All rights reserved.\n\ \n\ This program is free software. The contents of this file are subject to the \n\ @@ -94,169 +86,157 @@ If you have any questions, please contact Tripwire, Inc. at either \n\ info@tripwire.org or www.tripwire.org.") -TSS_BeginStringtable( cTW ) +TSS_BeginStringtable(cTW) - TSS_StringEntry( tw::STR_ERR_MISSING_LOCAL_KEY, _T("No local key specified.")), - TSS_StringEntry( tw::STR_ERR_MISSING_SITE_KEY, _T("No site key specified.")), - TSS_StringEntry( tw::STR_ERR_MISSING_POLICY, _T("No policy file specified.")), - TSS_StringEntry( tw::STR_ERR_MISSING_DB, _T("No database file specified.")), - TSS_StringEntry( tw::STR_ERR_MISSING_REPORT, _T("No report file specified.")), - TSS_StringEntry( tw::STR_ERR_MISSING_EDITOR, _T("No text editor specified in configuration file,\n") - _T("command line, or in VISUAL or EDITOR environment variables.")), + TSS_StringEntry(tw::STR_ERR_MISSING_LOCAL_KEY, _T("No local key specified.")), + TSS_StringEntry(tw::STR_ERR_MISSING_SITE_KEY, _T("No site key specified.")), + TSS_StringEntry(tw::STR_ERR_MISSING_POLICY, _T("No policy file specified.")), + TSS_StringEntry(tw::STR_ERR_MISSING_DB, _T("No database file specified.")), + TSS_StringEntry(tw::STR_ERR_MISSING_REPORT, _T("No report file specified.")), + TSS_StringEntry(tw::STR_ERR_MISSING_EDITOR, + _T("No text editor specified in configuration file,\n") + _T("command line, or in VISUAL or EDITOR environment variables.")), - TSS_StringEntry( tw::STR_ERR_WRONG_PASSPHRASE_SITE, _T("Incorrect site passphrase.") ), - TSS_StringEntry( tw::STR_ERR_WRONG_PASSPHRASE_LOCAL, _T("Incorrect local passphrase.") ), + TSS_StringEntry(tw::STR_ERR_WRONG_PASSPHRASE_SITE, _T("Incorrect site passphrase.")), + TSS_StringEntry(tw::STR_ERR_WRONG_PASSPHRASE_LOCAL, _T("Incorrect local passphrase.")), #if defined(CONFIG_DIR) // NOTE:mdb if we are following the FHS, then the config file lives in /etc/tripwire and not in // the current working directory - TSS_StringEntry( tw::STR_DEF_CFG_FILENAME, _T(CONFIG_DIR"/tw.cfg")), + TSS_StringEntry(tw::STR_DEF_CFG_FILENAME, _T(CONFIG_DIR "/tw.cfg")), #else - TSS_StringEntry( tw::STR_DEF_CFG_FILENAME, _T("/etc/tw.cfg")), + TSS_StringEntry(tw::STR_DEF_CFG_FILENAME, _T("/etc/tw.cfg")), #endif - TSS_StringEntry( tw::STR_WIN_NT_ONLY, _T("Open Source Tripwire(R) runs only on Windows NT.")), - TSS_StringEntry( tw::STR_GET_HELP, _T("Use --help to get help.")), - TSS_StringEntry( tw::STR_NEWLINE, _T("\n")), - TSS_StringEntry( tw::STR_ERR_TWCFG_CANT_READ, _T("Configuration file could not be read.")), - TSS_StringEntry( tw::STR_ERR_NO_MODE, _T("No mode specified.")), - TSS_StringEntry( tw::STR_UNKOWN_MODE_SPECIFIED, _T("Unknown mode specified: ")), - TSS_StringEntry( tw::STR_ERR2_BAD_MODE_SWITCH, _T("Unrecognized mode: ")), - - TSS_StringEntry( tw::STR_OPEN_POLICY_FILE, _T("Opening policy file: ")), - TSS_StringEntry( tw::STR_PARSING_POLICY, _T("Parsing policy file: ")), - TSS_StringEntry( tw::STR_ERR_REPORT_READ, _T("Report file could not be read.")), - TSS_StringEntry( tw::STR_REPORT_NOT_ENCRYPTED, _T("Note: Report is not encrypted.\n")), - TSS_StringEntry( tw::STR_ERR_DB_READ, _T("Database file could not be read.")), - - TSS_StringEntry( tw::STR_CUR_LINE, _T("Line number ") ), - - TSS_StringEntry( tw::STR_ENTER_LOCAL_PASSPHRASE, _T("Please enter your local passphrase: ") ), - TSS_StringEntry( tw::STR_ENTER_SITE_PASSPHRASE, _T("Please enter your site passphrase: ") ), - TSS_StringEntry( tw::STR_ENTER_PROVIDED_PASSPHRASE, _T("Please enter passphrase: ") ), - - TSS_StringEntry( tw::STR_DB_NOT_UPDATED, _T("The database was not updated. ") ), - TSS_StringEntry( tw::STR_IGNORE_PROPS, _T("Ignoring properties: ") ), - TSS_StringEntry( tw::STR_NOT_IMPLEMENTED, _T("Feature not implemented yet: ") ), - TSS_StringEntry( tw::STR_REPORT_EMPTY, _T("The report contains no new data, the database will not be updated.\n") ), - - TSS_StringEntry( tw::STR_GENERATING_DB, _T("Generating the database...\n") ), - TSS_StringEntry( tw::STR_INIT_SUCCESS, _T("The database was successfully generated.\n") ), - TSS_StringEntry( tw::STR_FILE_WRITTEN, _T("File written: ") ), - TSS_StringEntry( tw::STR_FILE_OPEN, _T("Opening file: ") ), - TSS_StringEntry( tw::STR_FILE_ENCRYPTED, _T("This file is encrypted.\n") ), - TSS_StringEntry( tw::STR_OPEN_KEYFILE, _T("Opening key file: ") ), - TSS_StringEntry( tw::STR_OPEN_CONFIG_FILE, _T("Opening configuration file: ") ), - TSS_StringEntry( tw::STR_OPEN_DB_FILE, _T("Opening database file: ") ), - TSS_StringEntry( tw::STR_OPEN_REPORT_FILE, _T("Opening report file: ") ), - - TSS_StringEntry( tw::STR_REPORTEVENT_FAILED, _T("Unable to add event to Event Log. The Event Log may be full.") ), - TSS_StringEntry( tw::STR_SYSLOG_FAILED, _T("Unable to add event to Syslog.") ), - - TSS_StringEntry( tw::STR_WRITE_POLICY_FILE, _T("Wrote policy file: ") ), - TSS_StringEntry( tw::STR_WRITE_DB_FILE, _T("Wrote database file: ") ), - TSS_StringEntry( tw::STR_WRITE_REPORT_FILE, _T("Wrote report file: ") ), - TSS_StringEntry( tw::STR_WRITE_CONFIG_FILE, _T("Wrote configuration file: ") ), - - TSS_StringEntry( tw::STR_REPORT_TITLE, _T("Open Source Tripwire(R) 2.4.3.1 Integrity Check Report") ), - TSS_StringEntry( tw::STR_R_GENERATED_BY, _T("Report generated by: ") ), - TSS_StringEntry( tw::STR_R_CREATED_ON, _T("Report created on: ") ), - TSS_StringEntry( tw::STR_DB_CREATED_ON, _T("Database generated on: ") ), - TSS_StringEntry( tw::STR_DB_LAST_UPDATE, _T("Database last updated on: ") ), - TSS_StringEntry( tw::STR_R_SUMMARY, _T("Report Summary:") ), - TSS_StringEntry( tw::STR_HOST_NAME, _T("Host name:") ), - TSS_StringEntry( tw::STR_HOST_IP, _T("Host IP address:") ), - TSS_StringEntry( tw::STR_HOST_ID, _T("Host ID:") ), - TSS_StringEntry( tw::STR_POLICY_FILE_USED, _T("Policy file used: ") ), - TSS_StringEntry( tw::STR_CONFIG_FILE_USED, _T("Configuration file used: ") ), - TSS_StringEntry( tw::STR_DB_FILE_USED, _T("Database file used: ") ), - TSS_StringEntry( tw::STR_CMD_LINE_USED, _T("Command line used: ") ), - TSS_StringEntry( tw::STR_SEVERITY_LEVEL, _T("Severity Level") ), - TSS_StringEntry( tw::STR_TOTAL_VIOLATIONS, _T("Total violations found: ") ), - TSS_StringEntry( tw::STR_OBJECTS_SCANNED, _T("Total objects scanned: ") ), - TSS_StringEntry( tw::STR_SECTION, _T("Section") ), - - - TSS_StringEntry( tw::STR_ATTRIBUTES, _T("Property: ") ), - TSS_StringEntry( tw::STR_OBSERVED, _T("Observed") ), - TSS_StringEntry( tw::STR_EXPECTED, _T("Expected") ), - TSS_StringEntry( tw::STR_DB_UPDATE, _T("Database Update: ") ), - TSS_StringEntry( tw::STR_RULE_SUMMARY, _T("Rule Summary: ") ), - TSS_StringEntry( tw::STR_OBJECT_SUMMARY, _T("Object Summary: ") ), - TSS_StringEntry( tw::STR_OBJECT_DETAIL, _T("Object Detail: ") ), - TSS_StringEntry( tw::STR_RULE_NAME, _T("Rule Name") ), - TSS_StringEntry( tw::STR_ALL_RULE_NAMES, _T("Rules Used: ") ), - TSS_StringEntry( tw::STR_TOTAL_NUM_RULES, _T("Total number of rules used: ") ), - TSS_StringEntry( tw::STR_START_POINT, _T("Start Point: ") ), - TSS_StringEntry( tw::STR_ADDED, _T("Added") ), - TSS_StringEntry( tw::STR_REMOVED, _T("Removed") ), - TSS_StringEntry( tw::STR_CHANGED, _T("Modified") ), - TSS_StringEntry( tw::STR_ADDED_FILES, _T("Added Objects: ") ), - TSS_StringEntry( tw::STR_REMOVED_FILES, _T("Removed Objects: ") ), - TSS_StringEntry( tw::STR_CHANGED_FILES, _T("Modified Objects: ") ), - TSS_StringEntry( tw::STR_TOTAL_NUM_ADDED_FILES, _T("Total number of added objects: ") ), - TSS_StringEntry( tw::STR_TOTAL_NUM_REMOVED_FILES, _T("Total number of removed objects: ") ), - TSS_StringEntry( tw::STR_TOTAL_NUM_CHANGED_FILES, _T("Total number of modified objects: ") ), - TSS_StringEntry( tw::STR_OBJECT_NAME, _T("Object name: ") ), - TSS_StringEntry( tw::STR_ADDED_FILE_NAME, _T("Added object name: ") ), - TSS_StringEntry( tw::STR_REMOVED_FILE_NAME, _T("Removed object name: ") ), - TSS_StringEntry( tw::STR_CHANGED_FILE_NAME, _T("Modified object name: ") ), - TSS_StringEntry( tw::STR_ERROR_REPORT, _T("Error Report: ") ), - TSS_StringEntry( tw::STR_REPORT_NO_ERRORS, _T("No Errors") ), - TSS_StringEntry( tw::STR_NO_VIOLATIONS_IN_SECTION,_T("No violations.") ), - - TSS_StringEntry( tw::STR_ADD_X, _T("Remove the \"x\" from the adjacent box to prevent updating the database\nwith the new values for this object.") ), - TSS_StringEntry( tw::STR_UPDATE_ALL, _T("Update database with all modifications for rule: ") ), - - TSS_StringEntry( tw::STR_END_OF_REPORT, _T("*** End of report ***") ), - TSS_StringEntry( tw::STR_NONE, _T("None") ), - TSS_StringEntry( tw::STR_NEVER, _T("Never") ), - TSS_StringEntry( tw::STR_OBJECTS, _T("Objects") ), - TSS_StringEntry( tw::STR_TRIPWIRE_REPORT_SHORT, _T("TWReport") ), - TSS_StringEntry( tw::STR_VIOLATIONS_SHORT, _T("V") ), - TSS_StringEntry( tw::STR_MAX_SEV_SHORT, _T("S") ), - TSS_StringEntry( tw::STR_ADDED_SHORT, _T("A") ), - TSS_StringEntry( tw::STR_REMOVED_SHORT, _T("R") ), - TSS_StringEntry( tw::STR_CHANGED_SHORT, _T("C") ), - - TSS_StringEntry( tw::STR_DBPRINT_TITLE, _T("Open Source Tripwire(R) 2.4.3.1 Database") ), - TSS_StringEntry( tw::STR_DB_GENERATED_BY, _T("Database generated by: ") ), - TSS_StringEntry( tw::STR_TOTAL_NUM_FILES, _T("Total number of objects: ") ), - TSS_StringEntry( tw::STR_END_OF_DB, _T("*** End of database ***") ), - TSS_StringEntry( tw::STR_DB_SUMMARY, _T("Database Summary: ") ), - TSS_StringEntry( tw::STR_ATTR_VALUE, _T("Value: ") ), + TSS_StringEntry(tw::STR_GET_HELP, _T("Use --help to get help.")), TSS_StringEntry(tw::STR_NEWLINE, _T("\n")), + TSS_StringEntry(tw::STR_ERR_TWCFG_CANT_READ, _T("Configuration file could not be read.")), + TSS_StringEntry(tw::STR_ERR_NO_MODE, _T("No mode specified.")), + TSS_StringEntry(tw::STR_UNKNOWN_MODE_SPECIFIED, _T("Unknown mode specified: ")), + TSS_StringEntry(tw::STR_ERR2_BAD_MODE_SWITCH, _T("Unrecognized mode: ")), + + TSS_StringEntry(tw::STR_OPEN_POLICY_FILE, _T("Opening policy file: ")), + TSS_StringEntry(tw::STR_PARSING_POLICY, _T("Parsing policy file: ")), + TSS_StringEntry(tw::STR_ERR_REPORT_READ, _T("Report file could not be read.")), + TSS_StringEntry(tw::STR_REPORT_NOT_ENCRYPTED, _T("Note: Report is not encrypted.\n")), + TSS_StringEntry(tw::STR_ERR_DB_READ, _T("Database file could not be read.")), + + TSS_StringEntry(tw::STR_CUR_LINE, _T("Line number ")), + + TSS_StringEntry(tw::STR_ENTER_LOCAL_PASSPHRASE, _T("Please enter your local passphrase: ")), + TSS_StringEntry(tw::STR_ENTER_SITE_PASSPHRASE, _T("Please enter your site passphrase: ")), + TSS_StringEntry(tw::STR_ENTER_PROVIDED_PASSPHRASE, _T("Please enter passphrase: ")), + + TSS_StringEntry(tw::STR_DB_NOT_UPDATED, _T("The database was not updated. ")), + TSS_StringEntry(tw::STR_IGNORE_PROPS, _T("Ignoring properties: ")), + TSS_StringEntry(tw::STR_NOT_IMPLEMENTED, _T("Feature not implemented yet: ")), + TSS_StringEntry(tw::STR_REPORT_EMPTY, _T("The report contains no new data, the database will not be updated.\n")), + + TSS_StringEntry(tw::STR_GENERATING_DB, _T("Generating the database...\n")), + TSS_StringEntry(tw::STR_INIT_SUCCESS, _T("The database was successfully generated.\n")), + TSS_StringEntry(tw::STR_FILE_WRITTEN, _T("File written: ")), + TSS_StringEntry(tw::STR_FILE_OPEN, _T("Opening file: ")), + TSS_StringEntry(tw::STR_FILE_ENCRYPTED, _T("This file is encrypted.\n")), + TSS_StringEntry(tw::STR_OPEN_KEYFILE, _T("Opening key file: ")), + TSS_StringEntry(tw::STR_OPEN_CONFIG_FILE, _T("Opening configuration file: ")), + TSS_StringEntry(tw::STR_OPEN_DB_FILE, _T("Opening database file: ")), + TSS_StringEntry(tw::STR_OPEN_REPORT_FILE, _T("Opening report file: ")), + + TSS_StringEntry(tw::STR_REPORTEVENT_FAILED, _T("Unable to add event to Event Log. The Event Log may be full.")), + TSS_StringEntry(tw::STR_SYSLOG_FAILED, _T("Unable to add event to Syslog.")), + + TSS_StringEntry(tw::STR_WRITE_POLICY_FILE, _T("Wrote policy file: ")), + TSS_StringEntry(tw::STR_WRITE_DB_FILE, _T("Wrote database file: ")), + TSS_StringEntry(tw::STR_WRITE_REPORT_FILE, _T("Wrote report file: ")), + TSS_StringEntry(tw::STR_WRITE_CONFIG_FILE, _T("Wrote configuration file: ")), + + TSS_StringEntry(tw::STR_REPORT_TITLE, _T("Open Source Tripwire(R) " PACKAGE_VERSION " Integrity Check Report")), + TSS_StringEntry(tw::STR_R_GENERATED_BY, _T("Report generated by: ")), + TSS_StringEntry(tw::STR_R_CREATED_ON, _T("Report created on: ")), + TSS_StringEntry(tw::STR_DB_CREATED_ON, _T("Database generated on: ")), + TSS_StringEntry(tw::STR_DB_LAST_UPDATE, _T("Database last updated on: ")), + TSS_StringEntry(tw::STR_R_SUMMARY, _T("Report Summary:")), TSS_StringEntry(tw::STR_HOST_NAME, _T("Host name:")), + TSS_StringEntry(tw::STR_HOST_IP, _T("Host IP address:")), TSS_StringEntry(tw::STR_HOST_ID, _T("Host ID:")), + TSS_StringEntry(tw::STR_POLICY_FILE_USED, _T("Policy file used: ")), + TSS_StringEntry(tw::STR_CONFIG_FILE_USED, _T("Configuration file used: ")), + TSS_StringEntry(tw::STR_DB_FILE_USED, _T("Database file used: ")), + TSS_StringEntry(tw::STR_CMD_LINE_USED, _T("Command line used: ")), + TSS_StringEntry(tw::STR_SEVERITY_LEVEL, _T("Severity Level")), + TSS_StringEntry(tw::STR_TOTAL_VIOLATIONS, _T("Total violations found: ")), + TSS_StringEntry(tw::STR_OBJECTS_SCANNED, _T("Total objects scanned: ")), + TSS_StringEntry(tw::STR_SECTION, _T("Section")), + + + TSS_StringEntry(tw::STR_ATTRIBUTES, _T("Property: ")), TSS_StringEntry(tw::STR_OBSERVED, _T("Observed")), + TSS_StringEntry(tw::STR_EXPECTED, _T("Expected")), TSS_StringEntry(tw::STR_DB_UPDATE, _T("Database Update: ")), + TSS_StringEntry(tw::STR_RULE_SUMMARY, _T("Rule Summary: ")), + TSS_StringEntry(tw::STR_OBJECT_SUMMARY, _T("Object Summary: ")), + TSS_StringEntry(tw::STR_OBJECT_DETAIL, _T("Object Detail: ")), TSS_StringEntry(tw::STR_RULE_NAME, _T("Rule Name")), + TSS_StringEntry(tw::STR_ALL_RULE_NAMES, _T("Rules Used: ")), + TSS_StringEntry(tw::STR_TOTAL_NUM_RULES, _T("Total number of rules used: ")), + TSS_StringEntry(tw::STR_START_POINT, _T("Start Point: ")), TSS_StringEntry(tw::STR_ADDED, _T("Added")), + TSS_StringEntry(tw::STR_REMOVED, _T("Removed")), TSS_StringEntry(tw::STR_CHANGED, _T("Modified")), + TSS_StringEntry(tw::STR_ADDED_FILES, _T("Added Objects: ")), + TSS_StringEntry(tw::STR_REMOVED_FILES, _T("Removed Objects: ")), + TSS_StringEntry(tw::STR_CHANGED_FILES, _T("Modified Objects: ")), + TSS_StringEntry(tw::STR_TOTAL_NUM_ADDED_FILES, _T("Total number of added objects: ")), + TSS_StringEntry(tw::STR_TOTAL_NUM_REMOVED_FILES, _T("Total number of removed objects: ")), + TSS_StringEntry(tw::STR_TOTAL_NUM_CHANGED_FILES, _T("Total number of modified objects: ")), + TSS_StringEntry(tw::STR_OBJECT_NAME, _T("Object name: ")), + TSS_StringEntry(tw::STR_ADDED_FILE_NAME, _T("Added object name: ")), + TSS_StringEntry(tw::STR_REMOVED_FILE_NAME, _T("Removed object name: ")), + TSS_StringEntry(tw::STR_CHANGED_FILE_NAME, _T("Modified object name: ")), + TSS_StringEntry(tw::STR_ERROR_REPORT, _T("Error Report: ")), + TSS_StringEntry(tw::STR_REPORT_NO_ERRORS, _T("No Errors")), + TSS_StringEntry(tw::STR_NO_VIOLATIONS_IN_SECTION, _T("No violations.")), + + TSS_StringEntry(tw::STR_ADD_X, + _T("Remove the \"x\" from the adjacent box to prevent updating the database\nwith the new values ") + _T("for this object.")), + TSS_StringEntry(tw::STR_UPDATE_ALL, _T("Update database with all modifications for rule: ")), + + TSS_StringEntry(tw::STR_END_OF_REPORT, _T("*** End of report ***")), TSS_StringEntry(tw::STR_NONE, _T("None")), + TSS_StringEntry(tw::STR_NEVER, _T("Never")), TSS_StringEntry(tw::STR_OBJECTS, _T("Objects")), + TSS_StringEntry(tw::STR_TRIPWIRE_REPORT_SHORT, _T("TWReport")), TSS_StringEntry(tw::STR_VIOLATIONS_SHORT, _T("V")), + TSS_StringEntry(tw::STR_MAX_SEV_SHORT, _T("S")), TSS_StringEntry(tw::STR_ADDED_SHORT, _T("A")), + TSS_StringEntry(tw::STR_REMOVED_SHORT, _T("R")), TSS_StringEntry(tw::STR_CHANGED_SHORT, _T("C")), + + TSS_StringEntry(tw::STR_DBPRINT_TITLE, _T("Open Source Tripwire(R) " PACKAGE_VERSION " Database")), + TSS_StringEntry(tw::STR_DB_GENERATED_BY, _T("Database generated by: ")), + TSS_StringEntry(tw::STR_TOTAL_NUM_FILES, _T("Total number of objects: ")), + TSS_StringEntry(tw::STR_END_OF_DB, _T("*** End of database ***")), + TSS_StringEntry(tw::STR_DB_SUMMARY, _T("Database Summary: ")), TSS_StringEntry(tw::STR_ATTR_VALUE, _T("Value: ")), // twutil - TSS_StringEntry( tw::STR_IP_UNKNOWN, _T("Unknown IP") ), + TSS_StringEntry(tw::STR_IP_UNKNOWN, _T("Unknown IP")), // twutil - TSS_StringEntry( tw::STR_ERR_NOT_FULL_PATH, _T("Object name is not fully qualified; skipping.") ), - TSS_StringEntry( tw::STR_ERR_OBJ_NOT_IN_DB, _T("Object not found in the database.") ), - TSS_StringEntry( tw::STR_ERR_DB_DOESNT_CONTAIN_GENRE, _T("Section not found in database.") ), - TSS_StringEntry( tw::STR_ERR2_CFG_KEY_MISMATCH1, _T("The config file \"") ), - TSS_StringEntry( tw::STR_ERR2_CFG_KEY_MISMATCH2, _T("\" is not encrypted with the current keyfile \"") ), - TSS_StringEntry( tw::STR_ERR2_CFG_KEY_MISMATCH3, _T("\".") ), - TSS_StringEntry( tw::STR_ERR_CFG_UNENCRYPTED, _T("Config file is unencrypted.") ), - TSS_StringEntry( tw::STR_ERR_POL_UNENCRYPTED, _T("Policy file is unencrypted.") ), - TSS_StringEntry( tw::STR_ERR_BACKUP_FAILED, _T("File Backup Failed.") ), - TSS_StringEntry( tw::STR_ERR2_BACKUP_FAILED1, _T("Error backing up \"") ), - TSS_StringEntry( tw::STR_ERR2_BACKUP_FAILED2, _T("\" to \"") ), - TSS_StringEntry( tw::STR_ERR2_BACKUP_FAILED3, _T("\".") ), + TSS_StringEntry(tw::STR_ERR_NOT_FULL_PATH, _T("Object name is not fully qualified; skipping.")), + TSS_StringEntry(tw::STR_ERR_OBJ_NOT_IN_DB, _T("Object not found in the database.")), + TSS_StringEntry(tw::STR_ERR_DB_DOESNT_CONTAIN_GENRE, _T("Section not found in database.")), + TSS_StringEntry(tw::STR_ERR2_CFG_KEY_MISMATCH1, _T("The config file \"")), + TSS_StringEntry(tw::STR_ERR2_CFG_KEY_MISMATCH2, _T("\" is not encrypted with the current keyfile \"")), + TSS_StringEntry(tw::STR_ERR2_CFG_KEY_MISMATCH3, _T("\".")), + TSS_StringEntry(tw::STR_ERR_CFG_UNENCRYPTED, _T("Config file is unencrypted.")), + TSS_StringEntry(tw::STR_ERR_POL_UNENCRYPTED, _T("Policy file is unencrypted.")), + TSS_StringEntry(tw::STR_ERR_BACKUP_FAILED, _T("File Backup Failed.")), + TSS_StringEntry(tw::STR_ERR2_BACKUP_FAILED1, _T("Error backing up \"")), + TSS_StringEntry(tw::STR_ERR2_BACKUP_FAILED2, _T("\" to \"")), + TSS_StringEntry(tw::STR_ERR2_BACKUP_FAILED3, _T("\".")), // used for reporting errors when linked with console.exe or reportviewer.exe - TSS_StringEntry( tw::STR_MEMORY_MAPPED_FILENAME, _T("Memory Mapped File") ), + TSS_StringEntry(tw::STR_MEMORY_MAPPED_FILENAME, _T("Memory Mapped File")), // // Version // - TSS_StringEntry( tw::STR_COPYRIGHT, TSS_COPYRIGHT_NOTICE ), - TSS_StringEntry( tw::STR_TSS_PRODUCT_NAME, TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR ), - - TSS_StringEntry( tw::STR_VERSION, TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR _T(" built for "TARGET_OS"\n\n") TSS_COPYRIGHT_NOTICE ), - TSS_StringEntry( tw::STR_VERSION_LONG, TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR _T(" built for "TARGET_OS"\n\n") TSS_COPYRIGHT_NOTICE_LONG ), - -TSS_EndStringtable( cTW ) - + TSS_StringEntry(tw::STR_COPYRIGHT, TSS_COPYRIGHT_NOTICE), + TSS_StringEntry(tw::STR_TSS_PRODUCT_NAME, TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR), -// eof: twstrings.cpp + TSS_StringEntry(tw::STR_VERSION, + TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR _T(" built for " TARGET_OS "\n\n") + TSS_COPYRIGHT_NOTICE), + TSS_StringEntry(tw::STR_VERSION_LONG, + TSS_PRODUCT_NAME BUILD_NUM UNICODE_STR DEBUG_STR _T(" built for " TARGET_OS "\n\n") + TSS_COPYRIGHT_NOTICE_LONG), + TSS_EndStringtable(cTW) diff --git a/src/tw/twstrings.h b/src/tw/twstrings.h index bb406d1..edeeeed 100644 --- a/src/tw/twstrings.h +++ b/src/tw/twstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,136 +41,41 @@ #include "tw.h" -TSS_BeginStringIds( tw ) - STR_ERR_MISSING_LOCAL_KEY, - STR_ERR_MISSING_SITE_KEY, - STR_ERR_MISSING_POLICY, - STR_ERR_MISSING_DB, - STR_ERR_MISSING_REPORT, - STR_ERR_MISSING_EDITOR, - STR_GENERATING_DB, - STR_ERR_WRONG_PASSPHRASE_LOCAL, - STR_ERR_WRONG_PASSPHRASE_SITE, - STR_DEF_CFG_FILENAME, - STR_WIN_NT_ONLY, - STR_GET_HELP, - STR_VERSION, - STR_VERSION_LONG, - STR_NEWLINE, - STR_ERR_TWCFG_CANT_READ, - STR_ERR_NO_MODE, - STR_UNKOWN_MODE_SPECIFIED, - STR_ERR2_BAD_MODE_SWITCH, - STR_PARSING_POLICY, - STR_ERR_REPORT_READ, - STR_REPORT_NOT_ENCRYPTED, - STR_ERR_DB_READ, - STR_CUR_LINE, - STR_INIT_SUCCESS, - STR_REPORTEVENT_FAILED, - STR_SYSLOG_FAILED, +TSS_BeginStringIds(tw) STR_ERR_MISSING_LOCAL_KEY, STR_ERR_MISSING_SITE_KEY, STR_ERR_MISSING_POLICY, STR_ERR_MISSING_DB, + STR_ERR_MISSING_REPORT, STR_ERR_MISSING_EDITOR, STR_GENERATING_DB, STR_ERR_WRONG_PASSPHRASE_LOCAL, + STR_ERR_WRONG_PASSPHRASE_SITE, STR_DEF_CFG_FILENAME, STR_GET_HELP, STR_VERSION, STR_VERSION_LONG, STR_NEWLINE, + STR_ERR_TWCFG_CANT_READ, STR_ERR_NO_MODE, STR_UNKNOWN_MODE_SPECIFIED, STR_ERR2_BAD_MODE_SWITCH, STR_PARSING_POLICY, + STR_ERR_REPORT_READ, STR_REPORT_NOT_ENCRYPTED, STR_ERR_DB_READ, STR_CUR_LINE, STR_INIT_SUCCESS, + STR_REPORTEVENT_FAILED, STR_SYSLOG_FAILED, - STR_ENTER_LOCAL_PASSPHRASE, - STR_ENTER_SITE_PASSPHRASE, - STR_ENTER_PROVIDED_PASSPHRASE, - STR_DB_NOT_UPDATED, // db update not performed due to anal mode - STR_IGNORE_PROPS, // ignoring properties - STR_NOT_IMPLEMENTED, - STR_REPORT_EMPTY, - STR_FILE_WRITTEN, - STR_FILE_OPEN, - STR_FILE_ENCRYPTED, - STR_OPEN_KEYFILE, - STR_OPEN_CONFIG_FILE, - STR_OPEN_DB_FILE, - STR_OPEN_REPORT_FILE, - STR_OPEN_POLICY_FILE, - STR_WRITE_POLICY_FILE, - STR_WRITE_DB_FILE, - STR_WRITE_REPORT_FILE, - STR_WRITE_CONFIG_FILE, + STR_ENTER_LOCAL_PASSPHRASE, STR_ENTER_SITE_PASSPHRASE, STR_ENTER_PROVIDED_PASSPHRASE, + STR_DB_NOT_UPDATED, // db update not performed due to secure mode + STR_IGNORE_PROPS, // ignoring properties + STR_NOT_IMPLEMENTED, STR_REPORT_EMPTY, STR_FILE_WRITTEN, STR_FILE_OPEN, STR_FILE_ENCRYPTED, STR_OPEN_KEYFILE, + STR_OPEN_CONFIG_FILE, STR_OPEN_DB_FILE, STR_OPEN_REPORT_FILE, STR_OPEN_POLICY_FILE, STR_WRITE_POLICY_FILE, + STR_WRITE_DB_FILE, STR_WRITE_REPORT_FILE, STR_WRITE_CONFIG_FILE, - STR_REPORT_TITLE, - STR_R_GENERATED_BY, - STR_R_CREATED_ON, - STR_DB_CREATED_ON, - STR_DB_LAST_UPDATE, - STR_R_SUMMARY, - STR_HOST_NAME, - STR_HOST_IP, - STR_HOST_ID, - STR_POLICY_FILE_USED, - STR_CONFIG_FILE_USED, - STR_DB_FILE_USED, - STR_CMD_LINE_USED, - STR_SEVERITY_LEVEL, - STR_RULE_NAME, - STR_ALL_RULE_NAMES, - STR_TOTAL_NUM_RULES, - STR_START_POINT, - STR_TOTAL_VIOLATIONS, - STR_OBJECTS_SCANNED, - STR_SECTION, - STR_ATTRIBUTES, - STR_OBSERVED, - STR_EXPECTED, - STR_DB_UPDATE, - STR_RULE_SUMMARY, - STR_OBJECT_SUMMARY, - STR_OBJECT_DETAIL, - STR_ADDED, - STR_REMOVED, - STR_CHANGED, - STR_ADDED_FILES, - STR_REMOVED_FILES, - STR_CHANGED_FILES, - STR_TOTAL_NUM_ADDED_FILES, - STR_TOTAL_NUM_REMOVED_FILES, - STR_TOTAL_NUM_CHANGED_FILES, - STR_OBJECT_NAME, - STR_ADDED_FILE_NAME, - STR_REMOVED_FILE_NAME, - STR_CHANGED_FILE_NAME, - STR_ERROR_REPORT, - STR_REPORT_NO_ERRORS, - STR_NO_VIOLATIONS_IN_SECTION, - STR_ADD_X, - STR_UPDATE_ALL, - STR_END_OF_REPORT, - STR_NONE, - STR_NEVER, - STR_OBJECTS, - STR_TRIPWIRE_REPORT_SHORT, - STR_VIOLATIONS_SHORT, - STR_MAX_SEV_SHORT, - STR_ADDED_SHORT, - STR_REMOVED_SHORT, - STR_CHANGED_SHORT, + STR_REPORT_TITLE, STR_R_GENERATED_BY, STR_R_CREATED_ON, STR_DB_CREATED_ON, STR_DB_LAST_UPDATE, STR_R_SUMMARY, + STR_HOST_NAME, STR_HOST_IP, STR_HOST_ID, STR_POLICY_FILE_USED, STR_CONFIG_FILE_USED, STR_DB_FILE_USED, + STR_CMD_LINE_USED, STR_SEVERITY_LEVEL, STR_RULE_NAME, STR_ALL_RULE_NAMES, STR_TOTAL_NUM_RULES, STR_START_POINT, + STR_TOTAL_VIOLATIONS, STR_OBJECTS_SCANNED, STR_SECTION, STR_ATTRIBUTES, STR_OBSERVED, STR_EXPECTED, STR_DB_UPDATE, + STR_RULE_SUMMARY, STR_OBJECT_SUMMARY, STR_OBJECT_DETAIL, STR_ADDED, STR_REMOVED, STR_CHANGED, STR_ADDED_FILES, + STR_REMOVED_FILES, STR_CHANGED_FILES, STR_TOTAL_NUM_ADDED_FILES, STR_TOTAL_NUM_REMOVED_FILES, + STR_TOTAL_NUM_CHANGED_FILES, STR_OBJECT_NAME, STR_ADDED_FILE_NAME, STR_REMOVED_FILE_NAME, STR_CHANGED_FILE_NAME, + STR_ERROR_REPORT, STR_REPORT_NO_ERRORS, STR_NO_VIOLATIONS_IN_SECTION, STR_ADD_X, STR_UPDATE_ALL, + STR_END_OF_REPORT, STR_NONE, STR_NEVER, STR_OBJECTS, STR_TRIPWIRE_REPORT_SHORT, STR_VIOLATIONS_SHORT, + STR_MAX_SEV_SHORT, STR_ADDED_SHORT, STR_REMOVED_SHORT, STR_CHANGED_SHORT, // database strings - STR_DBPRINT_TITLE, - STR_DB_GENERATED_BY, - STR_TOTAL_NUM_FILES, - STR_END_OF_DB, - STR_DB_SUMMARY, - STR_ATTR_VALUE, + STR_DBPRINT_TITLE, STR_DB_GENERATED_BY, STR_TOTAL_NUM_FILES, STR_END_OF_DB, STR_DB_SUMMARY, STR_ATTR_VALUE, // twutil STR_IP_UNKNOWN, // twutil - STR_ERR_NOT_FULL_PATH, - STR_ERR_OBJ_NOT_IN_DB, - STR_ERR_DB_DOESNT_CONTAIN_GENRE, - STR_ERR2_CFG_KEY_MISMATCH1, - STR_ERR2_CFG_KEY_MISMATCH2, - STR_ERR2_CFG_KEY_MISMATCH3, - STR_ERR_CFG_UNENCRYPTED, - STR_ERR_POL_UNENCRYPTED, - STR_ERR_BACKUP_FAILED, - STR_ERR2_BACKUP_FAILED1, - STR_ERR2_BACKUP_FAILED2, - STR_ERR2_BACKUP_FAILED3, + STR_ERR_NOT_FULL_PATH, STR_ERR_OBJ_NOT_IN_DB, STR_ERR_DB_DOESNT_CONTAIN_GENRE, STR_ERR2_CFG_KEY_MISMATCH1, + STR_ERR2_CFG_KEY_MISMATCH2, STR_ERR2_CFG_KEY_MISMATCH3, STR_ERR_CFG_UNENCRYPTED, STR_ERR_POL_UNENCRYPTED, + STR_ERR_BACKUP_FAILED, STR_ERR2_BACKUP_FAILED1, STR_ERR2_BACKUP_FAILED2, STR_ERR2_BACKUP_FAILED3, // used for reporting errors when linked with console.exe or reportviewer.exe STR_MEMORY_MAPPED_FILENAME, @@ -178,10 +83,9 @@ TSS_BeginStringIds( tw ) STR_COPYRIGHT, STR_TSS_PRODUCT_NAME -TSS_EndStringIds( tw ) + TSS_EndStringIds(tw) // Get strings like this: // TSS_GetString( cTW, tw::STR_NOTIFY_GEN_SIG ).c_str(), -#endif//__TWSTRINGS_H - +#endif //__TWSTRINGS_H diff --git a/src/tw/twutil.cpp b/src/tw/twutil.cpp index 2e4f9a3..4bee800 100644 --- a/src/tw/twutil.cpp +++ b/src/tw/twutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -64,38 +64,37 @@ #include "tw/twerrors.h" #include "core/ntmbs.h" #include "core/displayencoder.h" +#include "core/tw_signal.h" #ifdef TW_PROFILE #include "core/tasktimer.h" #endif -#include "core/fsservices.h" // for the util_IsDir() stuff - -#if IS_UNIX #include #include +#if SUPPORTS_TERMIOS #include #include -#include "core/tw_signal.h" int _getch(void); #endif -#ifdef _UNICODE // right now we only need this for unicode -#include -#endif // constants -static const char* POLICY_FILE_MAGIC_8BYTE = "#POLTXT\n"; -static const char* CONFIG_FILE_MAGIC_8BYTE = "#CFGTXT\n"; -static const uint32 CURRENT_FIXED_VERSION = 0x02020000; +static const char* POLICY_FILE_MAGIC_8BYTE = "#POLTXT\n"; +static const char* CONFIG_FILE_MAGIC_8BYTE = "#CFGTXT\n"; +static const uint32 CURRENT_FIXED_VERSION = 0x02020000; /////////////////////////////////////////////////////////////////////////////// // WriteObjectToArchive -- called from WriteObject, does most of the work /////////////////////////////////////////////////////////////////////////////// -static void WriteObjectToArchive(cArchive &arch, const TCHAR* filename, // filename is used only for issuing error messages - const iTypedSerializable* pObjHeader, const iTypedSerializable& obj, - cFileHeader& fileHeader, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +static void WriteObjectToArchive(cArchive& arch, + const TCHAR* filename, // filename is used only for issuing error messages + const iTypedSerializable* pObjHeader, + const iTypedSerializable& obj, + cFileHeader& fileHeader, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { try { @@ -117,7 +116,7 @@ static void WriteObjectToArchive(cArchive &arch, const TCHAR* filename, // filen cryptoArchive.SetWrite(&arch, pPrivateKey); cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_WRITE, filename); ser.Init(); - if(pObjHeader) + if (pObjHeader) ser.WriteObject(pObjHeader); ser.WriteObject(&obj); ser.Finit(); @@ -130,55 +129,55 @@ static void WriteObjectToArchive(cArchive &arch, const TCHAR* filename, // filen cryptoArchive.Start(&arch); cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_WRITE, filename); ser.Init(); - if(pObjHeader) + if (pObjHeader) ser.WriteObject(pObjHeader); ser.WriteObject(&obj); ser.Finit(); cryptoArchive.Finish(); } - } catch (eError& e) { - throw ePoly( - e.GetID(), - cErrorUtil::MakeFileError( e.GetMsg(), filename ), - e.GetFlags() ); + throw ePoly(e.GetID(), cErrorUtil::MakeFileError(e.GetMsg(), filename), e.GetFlags()); } } /////////////////////////////////////////////////////////////////////////////// -// WriteObject -- template class that writes an object to disk (ie -- report, -// db, etc) either encrypted or unencrypted. +// WriteObject -- template class that writes an object to disk (ie -- report, +// db, etc) either encrypted or unencrypted. // The only requrement on the object is that it is typed serializable. // errorMsg is a number that can be passed to iUserString to indicate an // appropriate error message if the object fails to load // -// 10/30 -- this function has been expanded to take two objects -- a header and -// an object. Both are typed serializable, but the header can be NULL if -// none is desired. +// 10/30 -- this function has been expanded to take two objects -- a header and +// an object. Both are typed serializable, but the header can be NULL if +// none is desired. /////////////////////////////////////////////////////////////////////////////// -static void WriteObject(const TCHAR* filename, const iTypedSerializable* pObjHeader, const iTypedSerializable& obj, - cFileHeader& fileHeader, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +static void WriteObject(const TCHAR* filename, + const iTypedSerializable* pObjHeader, + const iTypedSerializable& obj, + cFileHeader& fileHeader, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cDebug d("WriteObject"); d.TraceDebug(_T("Writing %s to file %s\n"), obj.GetType().AsString(), filename); - ASSERT(pPrivateKey || (! bEncrypt)); + ASSERT(pPrivateKey || (!bEncrypt)); cFileArchive arch; if (!cFileUtil::IsRegularFile(filename) && cFileUtil::FileExists(filename)) - throw eArchiveNotRegularFile( filename ); + throw eArchiveNotRegularFile(filename); try { - arch.OpenReadWrite( filename ); + arch.OpenReadWrite(filename); } catch (eArchive&) { // probably better to rethrow this as a write failed exception - throw eArchiveWrite( filename, iFSServices::GetInstance()->GetErrString() ) ; + throw eArchiveWrite(filename, iFSServices::GetInstance()->GetErrString()); } WriteObjectToArchive(arch, filename, pObjHeader, obj, fileHeader, bEncrypt, pPrivateKey); @@ -190,7 +189,13 @@ static void WriteObject(const TCHAR* filename, const iTypedSerializable* pObjHea /////////////////////////////////////////////////////////////////////////////// // WriteObjectToArchive -- called from WriteObject, does most of the work /////////////////////////////////////////////////////////////////////////////// -static void ReadObjectFromArchive(cArchive &arch, const TCHAR* objFileName, iTypedSerializable* pObjHeader, iTypedSerializable& obj, const cFileHeaderID& fhid, const cElGamalSigPublicKey* pPublicKey, bool& bEncrypted) +static void ReadObjectFromArchive(cArchive& arch, + const TCHAR* objFileName, + iTypedSerializable* pObjHeader, + iTypedSerializable& obj, + const cFileHeaderID& fhid, + const cElGamalSigPublicKey* pPublicKey, + bool& bEncrypted) { cFileHeader fileHeader; @@ -209,13 +214,14 @@ static void ReadObjectFromArchive(cArchive &arch, const TCHAR* objFileName, iTyp if (fileHeader.GetVersion() != CURRENT_FIXED_VERSION) ThrowAndAssert(eSerializerVersionMismatch(_T(""), objFileName, eSerializer::TY_FILE)); - try + try { // switch on the type of encoding... - if(fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) + if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { // tell the user the db is encrypted - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString( cTW, tw::STR_FILE_ENCRYPTED).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str()); bEncrypted = true; if (pPublicKey == 0) @@ -224,14 +230,14 @@ static void ReadObjectFromArchive(cArchive &arch, const TCHAR* objFileName, iTyp cElGamalSigArchive cryptoArchive; cryptoArchive.SetRead(&arch, pPublicKey); - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName); + cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName); ser.Init(); - if(pObjHeader) + if (pObjHeader) ser.ReadObject(pObjHeader); ser.ReadObject(&obj); ser.Finit(); } - else if(fileHeader.GetEncoding() == cFileHeader::COMPRESSED) + else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED) { //not encrypted db... bEncrypted = false; @@ -239,9 +245,9 @@ static void ReadObjectFromArchive(cArchive &arch, const TCHAR* objFileName, iTyp cNullCryptoArchive cryptoArchive; cryptoArchive.Start(&arch); - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName); + cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ, objFileName); ser.Init(); - if(pObjHeader) + if (pObjHeader) ser.ReadObject(pObjHeader); ser.ReadObject(&obj); ser.Finit(); @@ -253,44 +259,45 @@ static void ReadObjectFromArchive(cArchive &arch, const TCHAR* objFileName, iTyp catch (eError& e) { // include filename in error msg - throw ePoly( - e.GetID(), - cErrorUtil::MakeFileError( e.GetMsg(), objFileName ), - e.GetFlags() ); + throw ePoly(e.GetID(), cErrorUtil::MakeFileError(e.GetMsg(), objFileName), e.GetFlags()); } } /////////////////////////////////////////////////////////////////////////////// // ReadObject -- writes an object from disk, either encrypted or not, that was -// written using WriteObject above. +// written using WriteObject above. /////////////////////////////////////////////////////////////////////////////// -static void ReadObject(const TCHAR* objFileName, iTypedSerializable* pObjHeader, iTypedSerializable& obj, const cFileHeaderID& fhid, const cElGamalSigPublicKey* pPublicKey, bool& bEncrypted) +static void ReadObject(const TCHAR* objFileName, + iTypedSerializable* pObjHeader, + iTypedSerializable& obj, + const cFileHeaderID& fhid, + const cElGamalSigPublicKey* pPublicKey, + bool& bEncrypted) { cDebug d("ReadObject"); d.TraceDebug(_T("Reading %s from file %s\n"), obj.GetType().AsString(), objFileName); - + cFileArchive arch; - arch.OpenRead( objFileName ); + arch.OpenRead(objFileName); ReadObjectFromArchive(arch, objFileName, pObjHeader, obj, fhid, pPublicKey, bEncrypted); - } /////////////////////////////////////////////////////////////////////////////// // IsObjectEncrypted /////////////////////////////////////////////////////////////////////////////// -bool cTWUtil::IsObjectEncrypted( const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg ) +bool cTWUtil::IsObjectEncrypted(const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg) { - bool fEncrypted = false; + bool fEncrypted = false; cDebug d("IsObjectEncrypted"); d.TraceDebug(_T("Reading from file %s\n"), objFileName); - + try { cFileArchive arch; - arch.OpenRead( objFileName ); + arch.OpenRead(objFileName); - cFileHeader fileHeader; + cFileHeader fileHeader; cSerializerImpl fhSer(arch, cSerializerImpl::S_READ, objFileName); fileHeader.Read(&fhSer); @@ -299,11 +306,11 @@ bool cTWUtil::IsObjectEncrypted( const TCHAR* objFileName, const cFileHeaderID& ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE)); // switch on the type of encoding... - if(fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) + if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { fEncrypted = true; } - else if(fileHeader.GetEncoding() == cFileHeader::COMPRESSED) + else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED) { fEncrypted = false; } @@ -311,126 +318,79 @@ bool cTWUtil::IsObjectEncrypted( const TCHAR* objFileName, const cFileHeaderID& // unknown encoding... ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE)); } - catch(eArchive& e) - { - // Note: Output to TCERR is O.K. here, it is documented that this is what this function does - TSTRING msg = e.GetMsg(); - if( ! msg.empty() ) - msg += _T("\n"); - msg += errorMsg; - - cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags() )); - ThrowAndAssert(ePoly()); - } - catch(eSerializer& e) - { - // Note: Output to TCERR is O.K. here, it is documented that this is what this function does - TSTRING msg = e.GetMsg(); - if( ! msg.empty() ) - msg += _T("\n"); - msg += errorMsg; - - cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags() )); - ThrowAndAssert(ePoly()); - } - - return( fEncrypted ); -} - -bool cTWUtil::IsObjectEncrypted( cArchive &arch, const cFileHeaderID& fhid, const TSTRING& errorMsg ) -{ - bool fEncrypted = false; - cDebug d("IsObjectEncrypted"); - d.TraceDebug(_T("Reading from archive\n")); - - try - { - cFileHeader fileHeader; - cSerializerImpl fhSer(arch, cSerializerImpl::S_READ, TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME).c_str()); - fileHeader.Read(&fhSer); - - // check for a mismatched header - if (fileHeader.GetID() != fhid) - ThrowAndAssert(eSerializerInputStreamFmt(_T(""), TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME).c_str(), eSerializer::TY_FILE)); - - // switch on the type of encoding... - if(fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) - { - fEncrypted = true; - } - else if(fileHeader.GetEncoding() == cFileHeader::COMPRESSED) - { - fEncrypted = false; - } - else - // unknown encoding... - ThrowAndAssert(eSerializerInputStreamFmt(_T(""), TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME).c_str(), eSerializer::TY_FILE)); - } - catch(eArchive& e) + catch (eArchive& e) { // Note: Output to TCERR is O.K. here, it is documented that this is what this function does TSTRING msg = e.GetMsg(); - if( ! msg.empty() ) + if (!msg.empty()) msg += _T("\n"); msg += errorMsg; - cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags() )); + cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags())); ThrowAndAssert(ePoly()); } - catch(eSerializer& e) + catch (eSerializer& e) { // Note: Output to TCERR is O.K. here, it is documented that this is what this function does TSTRING msg = e.GetMsg(); - if( ! msg.empty() ) + if (!msg.empty()) msg += _T("\n"); msg += errorMsg; - cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags() )); + cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags())); ThrowAndAssert(ePoly()); } - return( fEncrypted ); + return (fEncrypted); } /////////////////////////////////////////////////////////////////////////////// // WriteDatabase /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::WriteDatabase(const TCHAR* filename, cFCODatabaseFile& db, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +void cTWUtil::WriteDatabase(const TCHAR* filename, + cFCODatabaseFile& db, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cFileHeader fileHeader; fileHeader.SetID(db.GetFileHeaderID()); - + // I am almost positive that this does nothing, WriteObject() sets the version in the cFileHeader - Jun 8, 1999 - dmb //fileHeader.SetVersion(1); #ifdef TW_PROFILE - cWin32TaskTimer timer(_T("Write Database")); + cTaskTimer timer(_T("Write Database")); timer.Start(); #endif - + WriteObject(filename, 0, db, fileHeader, bEncrypt, pPrivateKey); #ifdef TW_PROFILE timer.Stop(); #endif - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_DB_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_WRITE_DB_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); } /////////////////////////////////////////////////////////////////////////////// // ReadDatabase /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::ReadDatabase(const TCHAR* filename, cFCODatabaseFile& db, const cElGamalSigPublicKey* pPublicKey, bool& bEncrypted) +void cTWUtil::ReadDatabase(const TCHAR* filename, + cFCODatabaseFile& db, + const cElGamalSigPublicKey* pPublicKey, + bool& bEncrypted) { - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_DB_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_DB_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); #ifdef TW_PROFILE - cWin32TaskTimer timer("cTWUtil::ReadDatabase"); + cTaskTimer timer("cTWUtil::ReadDatabase"); timer.Start(); #endif @@ -444,60 +404,50 @@ void cTWUtil::ReadDatabase(const TCHAR* filename, cFCODatabaseFile& db, const cE /////////////////////////////////////////////////////////////////////////////// // WriteReport /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::WriteReport(const TCHAR* filename, const cFCOReportHeader& reportHeader, const cFCOReport& r, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +void cTWUtil::WriteReport(const TCHAR* filename, + const cFCOReportHeader& reportHeader, + const cFCOReport& r, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cFileHeader fileHeader; fileHeader.SetID(cFCOReport::GetFileHeaderID()); WriteObject(filename, &reportHeader, r, fileHeader, bEncrypt, pPrivateKey); - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_REPORT_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_WRITE_REPORT_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); } -void cTWUtil::WriteReport(cArchive &archive, const cFCOReportHeader& reportHeader, const cFCOReport& r, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) -{ - cFileHeader fileHeader; - fileHeader.SetID(cFCOReport::GetFileHeaderID()); - - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - - WriteObjectToArchive(archive, filename.c_str(), &reportHeader, r, fileHeader, bEncrypt, pPrivateKey); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_REPORT_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); -} - /////////////////////////////////////////////////////////////////////////////// // ReadReport /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::ReadReport(const TCHAR* reportFileName, cFCOReportHeader& reportHeader, cFCOReport& r, const cElGamalSigPublicKey* pPublicKey, bool silent, bool& bEncrypted) +void cTWUtil::ReadReport(const TCHAR* reportFileName, + cFCOReportHeader& reportHeader, + cFCOReport& r, + const cElGamalSigPublicKey* pPublicKey, + bool silent, + bool& bEncrypted) { - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_REPORT_FILE).c_str(), - cDisplayEncoder::EncodeInline( reportFileName ).c_str() ); - + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_REPORT_FILE).c_str(), + cDisplayEncoder::EncodeInline(reportFileName).c_str()); + ReadObject(reportFileName, &reportHeader, r, cFCOReport::GetFileHeaderID(), pPublicKey, bEncrypted); } -void cTWUtil::ReadReport(cArchive &archive, cFCOReportHeader& reportHeader, cFCOReport& r, const cElGamalSigPublicKey* pPublicKey, bool silent, bool& bEncrypted) -{ - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_REPORT_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str()); - - ReadObjectFromArchive(archive, filename.c_str(), &reportHeader, r, cFCOReport::GetFileHeaderID(), pPublicKey, bEncrypted); -} /////////////////////////////////////////////////////////////////////////////// // UpdatePolicyFile /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::UpdatePolicyFile(const TCHAR* destFileName, const TCHAR* srcFileName, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +void cTWUtil::UpdatePolicyFile(const TCHAR* destFileName, + const TCHAR* srcFileName, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cFileArchive src; src.OpenRead(srcFileName); // note: eArchive may float up @@ -508,64 +458,65 @@ void cTWUtil::UpdatePolicyFile(const TCHAR* destFileName, const TCHAR* srcFileNa src.ReadBlob((void*)policyText.data(), src.Length()); // NOTE -- this method will emit a message to stdout when the file has been written - cTWUtil::WritePolicyText(destFileName, policyText, bEncrypt, pPrivateKey); + cTWUtil::WritePolicyText(destFileName, policyText, bEncrypt, pPrivateKey); } TSTRING cTWUtil::GetCfgFilePath(const cCmdLineParser& cmdLine, int cfgFileID) { - TSTRING cfgFilePath; - bool fConfigOnCmdLine = false; + TSTRING cfgFilePath; + bool fConfigOnCmdLine = false; - // let's see if this was specified on the command line... - cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + // let's see if this was specified on the command line... + cCmdLineIter iter(cmdLine); + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - if(iter.ArgId() == cfgFileID) + if (iter.ArgId() == cfgFileID) { - ASSERT(iter.NumParams() > 0); - cfgFilePath = iter.ParamAt(0); - fConfigOnCmdLine = true; + ASSERT(iter.NumParams() > 0); + cfgFilePath = iter.ParamAt(0); + fConfigOnCmdLine = true; } } - - // OK, now we need to figure out where to find the config file. - // If the location was specified on the command line, get the full path to it. - // otherwise, the location is the dir that this exe is in. - if( fConfigOnCmdLine ) + + // OK, now we need to figure out where to find the config file. + // If the location was specified on the command line, get the full path to it. + // otherwise, the location is the dir that this exe is in. + if (fConfigOnCmdLine) { TSTRING pathOut; - iFSServices::GetInstance()->FullPath( pathOut, cfgFilePath ) ; + iFSServices::GetInstance()->FullPath(pathOut, cfgFilePath); cfgFilePath = pathOut; } - else + else { - iFSServices::GetInstance()->FullPath( cfgFilePath, TSS_GetString(cTW, tw::STR_DEF_CFG_FILENAME), - cSystemInfo::GetExeDir() ) ; + iFSServices::GetInstance()->FullPath( + cfgFilePath, TSS_GetString(cTW, tw::STR_DEF_CFG_FILENAME), cSystemInfo::GetExeDir()); } - - cFileUtil::TestFileExists(cfgFilePath); - - - return (cfgFilePath); + + cFileUtil::TestFileExists(cfgFilePath); + + + return (cfgFilePath); } /////////////////////////////////////////////////////////////////////////////// -// OpenConfigFile -- opens the config file, either from a known location or +// OpenConfigFile -- opens the config file, either from a known location or // from the location specified on the command line. Returns false if it fails. // cfgFileID is the ID of the config file switch // TODO -- should this guy spit the error to cerr or fill up an error bucket? ///////////////////////////////////////////////////////////////////////////////// -void cTWUtil::OpenConfigFile(cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFileID, cErrorBucket& errorBucket, TSTRING& configFileOut) +void cTWUtil::OpenConfigFile( + cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFileID, cErrorBucket& errorBucket, TSTRING& configFileOut) { - configFileOut = GetCfgFilePath(cmdLine, cfgFileID); + configFileOut = GetCfgFilePath(cmdLine, cfgFileID); - // ok, now let's load it! - TSTRING configText; - cTWUtil::ReadConfigText(configFileOut.c_str(), configText); - cf.ReadString( configText ); + // ok, now let's load it! + TSTRING configText; + cTWUtil::ReadConfigText(configFileOut.c_str(), configText); + cf.ReadString(configText); } /////////////////////////////////////////////////////////////////////////////// @@ -573,51 +524,22 @@ void cTWUtil::OpenConfigFile(cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFi // eArchive is thrown if filename can not be opened // eSerializer is thrown if reading or writing fails -void cTWUtil::WriteConfigText(const TCHAR* filename, const TSTRING configText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +void cTWUtil::WriteConfigText(const TCHAR* filename, + const TSTRING configText, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cSerializableNString nstring; nstring.mString = CONFIG_FILE_MAGIC_8BYTE; std::string ns; - cStringUtil::Convert( ns, configText ); + cStringUtil::Convert(ns, configText); nstring.mString += ns; cFileHeader fileHeader; fileHeader.SetID(cConfigFile::GetFileHeaderID()); - - fileHeader.SetVersion(CURRENT_FIXED_VERSION); - - if (bEncrypt) - { - ASSERT(pPrivateKey != 0); - cElGamalSigPublicKey publicKey(*pPrivateKey); - fileHeader.GetBaggage().MapArchive(0, publicKey.GetWriteLen()); - publicKey.Write(fileHeader.GetBaggage().GetMap()); - } - - WriteObject(filename, NULL, nstring, fileHeader, bEncrypt, pPrivateKey); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_CONFIG_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); -} - -void cTWUtil::WriteConfigText(cArchive &archive, const TSTRING configText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) -{ - cSerializableNString nstring; - - nstring.mString = CONFIG_FILE_MAGIC_8BYTE; - - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - std::string ns; - cStringUtil::Convert( ns, configText ); - nstring.mString += ns; - - cFileHeader fileHeader; - fileHeader.SetID(cConfigFile::GetFileHeaderID()); - fileHeader.SetVersion(CURRENT_FIXED_VERSION); if (bEncrypt) @@ -628,11 +550,12 @@ void cTWUtil::WriteConfigText(cArchive &archive, const TSTRING configText, bool publicKey.Write(fileHeader.GetBaggage().GetMap()); } - WriteObjectToArchive(archive, filename.c_str(), NULL, nstring, fileHeader, bEncrypt, pPrivateKey); + WriteObject(filename, NULL, nstring, fileHeader, bEncrypt, pPrivateKey); - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_CONFIG_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_WRITE_CONFIG_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); } @@ -644,7 +567,7 @@ void cTWUtil::WriteConfigText(cArchive &archive, const TSTRING configText, bool void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchive* pBaggage) { -// TODO -- neat up this function; try to use LoadObject() above... + // TODO -- neat up this function; try to use LoadObject() above... cSerializableNString nstring; @@ -652,13 +575,14 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv // file header to obtain the public key, thus the special casing. cDebug d("ReadConfigText"); d.TraceDebug(_T("Reading %s from file %s\n"), nstring.GetType().AsString(), filename); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); + + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); cFileArchive arch; - arch.OpenRead( filename ); + arch.OpenRead(filename); cFileHeader fileHeader; @@ -672,7 +596,7 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE); } -#if 0 // XXX: This is broken, what the h*ll are they trying to write here? -PH +#if 0 // XXX: This is broken, what the h*ll are they trying to write here? -PH d.TraceDebug("Found a file header of type %d.\n", fileHeader.GetEncoding()); #endif @@ -685,13 +609,13 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv throw eSerializerVersionMismatch(_T(""), filename, eSerializer::TY_FILE); // switch on the type of encoding... - if(fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) + if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { d.TraceDebug("Config file is compressed, public key len %d.\n", fileHeader.GetBaggage().Length()); // tell the user the db is encrypted - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str()); - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); ASSERT(fileHeader.GetBaggage().Length() > 0); if (fileHeader.GetBaggage().Length() <= 0) @@ -704,7 +628,7 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv cElGamalSigArchive cryptoArchive; cryptoArchive.SetRead(&arch, &publicKey); - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); + cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); ser.Init(); ser.ReadObject(&nstring); ser.Finit(); @@ -713,13 +637,13 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv // Note: We rely in VerifySiteKey that we only fill out pBaggage if // the config file is encrypted. // - if( pBaggage ) + if (pBaggage) { - fileHeader.GetBaggage().Seek( 0, cBidirArchive::BEGINNING ); - pBaggage->Copy( &fileHeader.GetBaggage(), fileHeader.GetBaggage().Length() ); + fileHeader.GetBaggage().Seek(0, cBidirArchive::BEGINNING); + pBaggage->Copy(&fileHeader.GetBaggage(), fileHeader.GetBaggage().Length()); } } - else if(fileHeader.GetEncoding() == cFileHeader::COMPRESSED) + else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED) { d.TraceDebug("Config file is not compressed.\n"); @@ -727,7 +651,7 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv cNullCryptoArchive cryptoArchive; cryptoArchive.Start(&arch); - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); + cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); ser.Init(); ser.ReadObject(&nstring); ser.Finit(); @@ -737,127 +661,25 @@ void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchiv throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE); // check 8 byte header - if (nstring.mString.compare(0, 8*sizeof(byte), CONFIG_FILE_MAGIC_8BYTE) != 0) + if (nstring.mString.compare(0, 8 * sizeof(byte), CONFIG_FILE_MAGIC_8BYTE) != 0) ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE)); // remove 8 byte header nstring.mString.assign(nstring.mString.substr(8)); - cStringUtil::Convert( configText, nstring.mString ); -} - - -void cTWUtil::ReadConfigText(cArchive &arch, TSTRING& configText, cArchive* pBaggage) -{ -// TODO -- neat up this function; try to use LoadObject() above... - - cSerializableNString nstring; - - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - - // This was coppied from ReadObject(). We need to use the baggage of the - // file header to obtain the public key, thus the special casing. - cDebug d("ReadConfigText"); - d.TraceDebug(_T("Reading %s from file %s\n"), nstring.GetType().AsString(), filename.c_str()); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str()); - - - cFileHeader fileHeader; - - try - { - cSerializerImpl fhSer(arch, cSerializerImpl::S_READ); - fileHeader.Read(&fhSer); - } - catch (eError&) - { - throw eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE); - } - -#if 0 // XXX: This is broken, how can you convert a class to an int??? -PH - d.TraceDebug("Found a file header of type %d.\n", fileHeader.GetEncoding()); -#endif - - // check for a mismatched header - if (fileHeader.GetID() != cConfigFile::GetFileHeaderID()) - throw eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE); - - // check the version - if (fileHeader.GetVersion() != CURRENT_FIXED_VERSION) - throw eSerializerVersionMismatch(_T(""), filename.c_str(), eSerializer::TY_FILE); - - // switch on the type of encoding... - if(fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) - { - d.TraceDebug("Config file is compressed, public key len %d.\n", fileHeader.GetBaggage().Length()); - - // tell the user the db is encrypted - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str()); - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); - - ASSERT(fileHeader.GetBaggage().Length() > 0); - if (fileHeader.GetBaggage().Length() <= 0) - ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE)); - - fileHeader.GetBaggage().MapArchive(0, fileHeader.GetBaggage().Length()); - - cElGamalSigPublicKey publicKey(fileHeader.GetBaggage().GetMap()); - - cElGamalSigArchive cryptoArchive; - cryptoArchive.SetRead(&arch, &publicKey); - - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); - ser.Init(); - ser.ReadObject(&nstring); - ser.Finit(); - - // copy the baggage into the archive, if it was passed in - // Note: We rely in VerifySiteKey that we only fill out pBaggage if - // the config file is encrypted. - // - if( pBaggage ) - { - fileHeader.GetBaggage().Seek( 0, cBidirArchive::BEGINNING ); - pBaggage->Copy( &fileHeader.GetBaggage(), fileHeader.GetBaggage().Length() ); - } - } - else if(fileHeader.GetEncoding() == cFileHeader::COMPRESSED) - { - d.TraceDebug("Config file is not compressed.\n"); - - //not encrypted db... - cNullCryptoArchive cryptoArchive; - cryptoArchive.Start(&arch); - - cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); - ser.Init(); - ser.ReadObject(&nstring); - ser.Finit(); - } - else - // unknown encoding... - throw eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE); - - // check 8 byte header - if (nstring.mString.compare(0, 8*sizeof(byte), CONFIG_FILE_MAGIC_8BYTE) != 0) - ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE)); - - // remove 8 byte header - nstring.mString.assign(nstring.mString.substr(8)); - - cStringUtil::Convert( configText, nstring.mString ); + cStringUtil::Convert(configText, nstring.mString); } - + /////////////////////////////////////////////////////////////////////////////// // Given a filename and the text of a policy file, write an encrypted version -// of the policy file text to disk. +// of the policy file text to disk. // Will throw eError on failure. -void cTWUtil::WritePolicyText(const TCHAR* filename, const std::string polText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) +void cTWUtil::WritePolicyText(const TCHAR* filename, + const std::string& polText, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey) { cSerializableNString nstring; @@ -871,35 +693,16 @@ void cTWUtil::WritePolicyText(const TCHAR* filename, const std::string polText, WriteObject(filename, NULL, nstring, fileHeader, bEncrypt, pPrivateKey); - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_POLICY_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_WRITE_POLICY_FILE).c_str(), + cDisplayEncoder::EncodeInline(filename).c_str()); } -void cTWUtil::WritePolicyText(cArchive &archive, const std::string polText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) -{ - cSerializableNString nstring; - - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - - // add a 8 byte header we can use to verify decryption - nstring.mString = POLICY_FILE_MAGIC_8BYTE; - - nstring.mString += polText; - - cFileHeader fileHeader; - fileHeader.SetID(cPolicyFile::GetFileHeaderID()); - - WriteObjectToArchive(archive, filename.c_str(), NULL, nstring, fileHeader, bEncrypt, pPrivateKey); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_WRITE_POLICY_FILE).c_str(), - cDisplayEncoder::EncodeInline( filename ).c_str()); -} /////////////////////////////////////////////////////////////////////////////// // ReadPolicyText -// +// // Read the policy file. Read the text of a policy language into configText // Will throw eError on failure. /////////////////////////////////////////////////////////////////////////////// @@ -913,7 +716,7 @@ void cTWUtil::ReadPolicyText(const TCHAR* filename, std::string& polText, const ReadObject(filename, NULL, nstring, cPolicyFile::GetFileHeaderID(), pPublicKey, bEncrypted); // check 8 byte header - if (nstring.mString.compare(0, 8*sizeof(byte), POLICY_FILE_MAGIC_8BYTE) != 0) + if (nstring.mString.compare(0, 8 * sizeof(byte), POLICY_FILE_MAGIC_8BYTE) != 0) ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE)); // remove 8 byte header @@ -922,24 +725,6 @@ void cTWUtil::ReadPolicyText(const TCHAR* filename, std::string& polText, const polText = nstring.mString; } -void cTWUtil::ReadPolicyText(cArchive &archive, std::string& polText, const cElGamalSigPublicKey* pPublicKey) -{ - cSerializableNString nstring; - - TSTRING filename = TSS_GetString( cTW, tw::STR_MEMORY_MAPPED_FILENAME); - - bool bEncrypted; - ReadObjectFromArchive(archive, filename.c_str(), NULL, nstring, cPolicyFile::GetFileHeaderID(), pPublicKey, bEncrypted); - - // check 8 byte header - if (nstring.mString.compare(0, 8*sizeof(byte), POLICY_FILE_MAGIC_8BYTE) != 0) - ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename.c_str(), eSerializer::TY_FILE)); - - // remove 8 byte header - nstring.mString.assign(nstring.mString.substr(8)); - - polText = nstring.mString; -} /////////////////////////////////////////////////////////////////////////////// // OpenKeyFile @@ -948,10 +733,11 @@ void cTWUtil::OpenKeyFile(cKeyFile& keyFile, TSTRING fileName) { // first, make sure the file exists... cFileUtil::TestFileExists(fileName); - - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString( cTW, tw::STR_OPEN_KEYFILE).c_str(), - cDisplayEncoder::EncodeInline( fileName ).c_str()); + + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_KEYFILE).c_str(), + cDisplayEncoder::EncodeInline(fileName).c_str()); keyFile.ReadFile(fileName.c_str()); } @@ -961,53 +747,54 @@ void cTWUtil::OpenKeyFile(cKeyFile& keyFile, TSTRING fileName) // we will attempt to get the correct passphrase three times before we // give up. /////////////////////////////////////////////////////////////////////////////// -const cElGamalSigPrivateKey* cTWUtil::CreatePrivateKey(cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs) +const cElGamalSigPrivateKey* +cTWUtil::CreatePrivateKey(cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs) { ASSERT(keyType == KEY_SITE || keyType == KEY_LOCAL || keyType == KEY_PROVIDED); const cElGamalSigPrivateKey* pPrivateKey = NULL; - wc16_string passphrase; + wc16_string passphrase; - if ( usePassphrase ) - { + if (usePassphrase) + { // sleep to hinder brute force (dictionary, etc.) attacks - iFSServices::GetInstance()->Sleep( nSecs ); + iFSServices::GetInstance()->Sleep(nSecs); passphrase = usePassphrase; - #ifndef WORDS_BIGENDIAN +#ifndef WORDS_BIGENDIAN passphrase.swapbytes(); - #endif +#endif pPrivateKey = keyFile.GetPrivateKey((int8*)passphrase.data(), passphrase.length() * sizeof(WCHAR16)); - if(pPrivateKey) + if (pPrivateKey) return pPrivateKey; // if we got here, then a passphrase was provided on the command line that // was not correct; this is an error condition. // - if( keyType == KEY_LOCAL ) + if (keyType == KEY_LOCAL) throw eTWUtilBadPassLocal(); else throw eTWUtilBadPassSite(); } int count = 0; - while(count < 3) + while (count < 3) { cTWUtil::NoEcho noEcho; switch (keyType) { case KEY_LOCAL: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_LOCAL_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_LOCAL_PASSPHRASE); break; case KEY_SITE: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_SITE_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_SITE_PASSPHRASE); break; case KEY_PROVIDED: default: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_PROVIDED_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_PROVIDED_PASSPHRASE); break; } @@ -1015,11 +802,11 @@ const cElGamalSigPrivateKey* cTWUtil::CreatePrivateKey(cKeyFile& keyFile, const TCOUT << std::endl; // sleep to hinder brute force (dictionary, etc.) attacks - iFSServices::GetInstance()->Sleep( nSecs ); + iFSServices::GetInstance()->Sleep(nSecs); - #ifndef WORDS_BIGENDIAN +#ifndef WORDS_BIGENDIAN passphrase.swapbytes(); - #endif +#endif pPrivateKey = keyFile.GetPrivateKey((int8*)passphrase.data(), passphrase.length() * sizeof(WCHAR16)); @@ -1027,20 +814,20 @@ const cElGamalSigPrivateKey* cTWUtil::CreatePrivateKey(cKeyFile& keyFile, const break; // tell the user that they entered the wrong passphrase - int strId = (keyType==KEY_LOCAL) ? tw::STR_ERR_WRONG_PASSPHRASE_LOCAL : - tw::STR_ERR_WRONG_PASSPHRASE_SITE; - TCOUT << TSS_GetString( cTW, strId) << std::endl; + int strId = (keyType == KEY_LOCAL) ? tw::STR_ERR_WRONG_PASSPHRASE_LOCAL : tw::STR_ERR_WRONG_PASSPHRASE_SITE; + TCOUT << TSS_GetString(cTW, strId) << std::endl; passphrase.resize(0); count++; } - if(! pPrivateKey) + if (!pPrivateKey) throw ePoly(); return pPrivateKey; } -void cTWUtil::CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs) +void cTWUtil::CreatePrivateKey( + cPrivateKeyProxy& proxy, cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs) { ASSERT(keyType == KEY_SITE || keyType == KEY_LOCAL || keyType == KEY_PROVIDED); @@ -1049,13 +836,13 @@ void cTWUtil::CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const if (usePassphrase != 0) { // sleep to hinder brute force (dictionary, etc.) attacks - iFSServices::GetInstance()->Sleep( nSecs ); + iFSServices::GetInstance()->Sleep(nSecs); passphrase = usePassphrase; - #ifndef WORDS_BIGENDIAN +#ifndef WORDS_BIGENDIAN passphrase.swapbytes(); - #endif +#endif if (proxy.AquireKey(keyFile, (int8*)passphrase.data(), passphrase.length() * sizeof(WCHAR16))) return; @@ -1063,27 +850,27 @@ void cTWUtil::CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const // if we got here, then a passphrase was provided on the command line that // was not correct; this is an error condition. // - if( keyType == KEY_LOCAL ) + if (keyType == KEY_LOCAL) throw eTWUtilBadPassLocal(); else throw eTWUtilBadPassSite(); } int count = 0; - while(count < 3) + while (count < 3) { cTWUtil::NoEcho noEcho; switch (keyType) { case KEY_LOCAL: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_LOCAL_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_LOCAL_PASSPHRASE); break; case KEY_SITE: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_SITE_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_SITE_PASSPHRASE); break; case KEY_PROVIDED: default: - TCOUT << TSS_GetString( cTW, tw::STR_ENTER_PROVIDED_PASSPHRASE); + TCOUT << TSS_GetString(cTW, tw::STR_ENTER_PROVIDED_PASSPHRASE); break; } @@ -1091,21 +878,22 @@ void cTWUtil::CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const TCOUT << std::endl; // sleep to hinder brute force (dictionary, etc.) attacks - iFSServices::GetInstance()->Sleep( nSecs ); + iFSServices::GetInstance()->Sleep(nSecs); - #ifndef WORDS_BIGENDIAN +#ifndef WORDS_BIGENDIAN passphrase.swapbytes(); - #endif +#endif if (proxy.AquireKey(keyFile, (int8*)passphrase.data(), passphrase.length() * sizeof(WCHAR16))) return; // tell the user that they entered the wrong passphrase - int strId = (keyType==KEY_LOCAL) ? tw::STR_ERR_WRONG_PASSPHRASE_LOCAL : - (keyType==KEY_SITE) ? tw::STR_ERR_WRONG_PASSPHRASE_SITE : - tw::STR_ERR_WRONG_PASSPHRASE_LOCAL; // TODO: make this provided + int strId = (keyType == KEY_LOCAL) ? + tw::STR_ERR_WRONG_PASSPHRASE_LOCAL : + (keyType == KEY_SITE) ? tw::STR_ERR_WRONG_PASSPHRASE_SITE : + tw::STR_ERR_WRONG_PASSPHRASE_LOCAL; // TODO: make this provided - TCOUT << TSS_GetString( cTW, strId) << std::endl; + TCOUT << TSS_GetString(cTW, strId) << std::endl; passphrase.resize(0); count++; } @@ -1117,59 +905,74 @@ void cTWUtil::CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const // GetStringNoEcho -- Get a string from the user without echoing it /////////////////////////////////////////////////////////////////////////////// - -#if IS_UNIX static void (*old_SIGINT)(int); static void (*old_SIGQUIT)(int); + +#if SUPPORTS_TERMIOS static struct termios Otty; +#endif + static void RestoreEcho(int sig) { -#ifdef _DEBUG - std::cout << "Caught signal, resetting echo."<< std::endl; +#if SUPPORTS_TERMIOS +# ifdef DEBUG + std::cout << "Caught signal, resetting echo." << std::endl; sleep(2); -#endif +# endif - tcsetattr( 0, TCSAFLUSH, &Otty); + tcsetattr(0, TCSAFLUSH, &Otty); tw_signal(SIGINT, old_SIGINT); tw_signal(SIGQUIT, old_SIGQUIT); - +#endif tw_raise(sig); } void cTWUtil::GetString(wc16_string& ret) { #ifdef _UNICODE -#error We depend on Unix not being Unicode +# error We depend on Unix not being Unicode +#endif + +// tcsetattr doesn't seem to work on AROS, so tweak ANSI terminal settings to hide passphrases. +#if IS_AROS + printf("\e[8m"); // set the 'concealed' flag + fflush(stdout); #endif // get the string const int MAX_STRING = 1024; - char buf[MAX_STRING]; - int len; + char buf[MAX_STRING]; + int len; TCOUT.flush(); - len = read( 0, buf, MAX_STRING ); + len = read(0, buf, MAX_STRING); + +#if IS_AROS + printf("\e[0m"); // reset back to normal text + fflush(stdout); +#endif // TODO:BAM -- mb-enable this! if (len < MAX_STRING - 1) buf[len] = 0; - char* psz = tss::strdec( buf, buf + len ); - if ( *psz == '\n') + char* psz = tss::strdec(buf, buf + len); + if (*psz == '\n') *psz = 0; - ret = cStringUtil::TstrToWstr( buf ); + ret = cStringUtil::TstrToWstr(buf); } cTWUtil::NoEcho::NoEcho() { +#if SUPPORTS_TERMIOS // set the terminal to no echo mode static struct termios Ntty; fflush(stdout); - tcgetattr( 0, &Otty); + tcgetattr(0, &Otty); Ntty = Otty; Ntty.c_lflag &= ~ECHO; @@ -1178,16 +981,20 @@ cTWUtil::NoEcho::NoEcho() old_SIGINT = tw_signal(SIGINT, RestoreEcho); old_SIGQUIT = tw_signal(SIGQUIT, RestoreEcho); - if (tcsetattr( 0, TCSAFLUSH, &Ntty) != 0 && isatty(0)) + if (tcsetattr(0, TCSAFLUSH, &Ntty) != 0 && isatty(0)) { ThrowAndAssert(eTWUtilEchoModeSet()); } +#endif } -cTWUtil::NoEcho::~NoEcho() { - tcsetattr( 0, TCSAFLUSH, &Otty); +cTWUtil::NoEcho::~NoEcho() +{ +#if SUPPORTS_TERMIOS + tcsetattr(0, TCSAFLUSH, &Otty); tw_signal(SIGINT, old_SIGINT); tw_signal(SIGQUIT, old_SIGQUIT); +#endif } void cTWUtil::GetStringNoEcho(wc16_string& ret) @@ -1195,88 +1002,87 @@ void cTWUtil::GetStringNoEcho(wc16_string& ret) NoEcho noEcho; GetString(ret); } -#endif /////////////////////////////////////////////////////////////////////////////// // ParseObjectList /////////////////////////////////////////////////////////////////////////////// -void cTWUtil::ParseObjectList( cTWUtil::GenreObjList& listOut, const cTWUtil::ObjList& listIn ) +void cTWUtil::ParseObjectList(cTWUtil::GenreObjList& listOut, const cTWUtil::ObjList& listIn) { cGenre::Genre curGenre = cGenreSwitcher::GetInstance()->GetDefaultGenre(); - ASSERT( listIn.size() > 0 ); + ASSERT(listIn.size() > 0); listOut.clear(); - GenreObjList::iterator curIter = listOut.end(); - cGenre::Genre iterGenre = cGenre::GENRE_INVALID; + GenreObjList::iterator curIter = listOut.end(); + cGenre::Genre iterGenre = cGenre::GENRE_INVALID; // iterate over all of the input... // - for( ObjList::const_iterator i = listIn.begin(); i != listIn.end(); i++ ) + for (ObjList::const_iterator i = listIn.begin(); i != listIn.end(); ++i) { // first, try to interperate the current string as a genre name... // 17 Mar 99 mdb -- we now only do this if the string ends in a ':' // cGenre::Genre g = cGenre::GENRE_INVALID; - - if( i->at( i->length()-1 ) == _T(':') ) + + if (i->at(i->length() - 1) == _T(':')) { TSTRING genreStr; - genreStr.assign( i->begin(), i->end()-1 ); - g = cGenreSwitcher::GetInstance()->StringToGenre( genreStr.c_str() ); - + genreStr.assign(i->begin(), i->end() - 1); + g = cGenreSwitcher::GetInstance()->StringToGenre(genreStr.c_str()); + // - // if it is not a valid genre name, then test to see if it could + // if it is not a valid genre name, then test to see if it could // be an fconame. If it is not, then it is a badly formed genre. // - if( g == cGenre::GENRE_INVALID ) + if (g == cGenre::GENRE_INVALID) { - std::auto_ptr pParseUtil (iTWFactory::GetInstance()->CreateParserGenreUtil()); - if( ! pParseUtil->IsAbsolutePath( *i ) ) - throw eTWUnknownSectionName( *i ); + TW_UNIQUE_PTR pParseUtil(iTWFactory::GetInstance()->CreateParserGenreUtil()); + if (!pParseUtil->IsAbsolutePath(*i)) + throw eTWUnknownSectionName(*i); } } - if( g == cGenre::GENRE_INVALID ) + if (g == cGenre::GENRE_INVALID) { // assume that we are in the correct genre; this is a fully qualified object name // TODO -- throw here if cGenreParserHelper says it isn't a fully qualified name. // - if( iterGenre != curGenre ) + if (iterGenre != curGenre) { // seek to right list; create it if it is not there... // - for( curIter = listOut.begin(); curIter != listOut.end(); curIter++ ) + for (curIter = listOut.begin(); curIter != listOut.end(); ++curIter) { - if( curIter->first == curGenre ) + if (curIter->first == curGenre) break; } - if( curIter == listOut.end() ) + if (curIter == listOut.end()) { // it doesn't exist; we will have to create a new one. // - listOut.push_back( GenreObjs() ); + listOut.push_back(GenreObjs()); listOut.back().first = curGenre; - curIter = listOut.end() - 1; + curIter = listOut.end() - 1; } iterGenre = curGenre; } - ASSERT( curIter != listOut.end() ); + ASSERT(curIter != listOut.end()); // // add this to the list; assert that it has not been added yet. // ObjList::iterator oi; - for( oi = curIter->second.begin(); oi != curIter->second.end(); oi++ ) + for (oi = curIter->second.begin(); oi != curIter->second.end(); ++oi) { - if( *oi == *i ) + if (*oi == *i) { //TODO -- what should I do here? probably warn and continue... - ASSERT( false ); + ASSERT(false); break; } } - if( oi == curIter->second.end() ) - curIter->second.push_back( *i ); + if (oi == curIter->second.end()) + curIter->second.push_back(*i); } else { @@ -1285,50 +1091,49 @@ void cTWUtil::ParseObjectList( cTWUtil::GenreObjList& listOut, const cTWUtil::Ob curGenre = g; } } - } /////////////////////////////////////////////////////////////////////////////// // ParseObjectName /////////////////////////////////////////////////////////////////////////////// -cFCOName cTWUtil::ParseObjectName( const TSTRING& fcoName ) +cFCOName cTWUtil::ParseObjectName(const TSTRING& fcoName) { - std::auto_ptr pParseUtil (iTWFactory::GetInstance()->CreateParserGenreUtil()); - cFCOName name( iTWFactory::GetInstance()->GetNameInfo() ); + TW_UNIQUE_PTR pParseUtil(iTWFactory::GetInstance()->CreateParserGenreUtil()); + cFCOName name(iTWFactory::GetInstance()->GetNameInfo()); // // make sure the fco name is a full path... // - if( ! pParseUtil->IsAbsolutePath( fcoName ) ) - throw eTWUtilNotFullPath( fcoName ); + if (!pParseUtil->IsAbsolutePath(fcoName)) + throw eTWUtilNotFullPath(fcoName); // // construct the list that InterpretFCOName needs.... - std::list inputNameList; + std::list inputNameList; // // dice up the string into a list // currently, we only slice it up based on "|" (for nt registry entries) // - TSTRING::size_type pos = fcoName.find_first_of( _T('|') ); - if( pos != TSTRING::npos ) + TSTRING::size_type pos = fcoName.find_first_of(_T('|')); + if (pos != TSTRING::npos) { - // if the input string is "foo|bar" then we want the list to + // if the input string is "foo|bar" then we want the list to // look like this: "foo", "|", "bar" (three entries) // TSTRING str; - str.assign( fcoName, 0, pos ); - inputNameList.push_back( str ); - inputNameList.push_back( _T("|") ); - str.assign( fcoName, pos+1, fcoName.length() - pos ); - inputNameList.push_back( str ); + str.assign(fcoName, 0, pos); + inputNameList.push_back(str); + inputNameList.push_back(_T("|")); + str.assign(fcoName, pos + 1, fcoName.length() - pos); + inputNameList.push_back(str); } else { - inputNameList.push_back( fcoName ); + inputNameList.push_back(fcoName); } - pParseUtil->InterpretFCOName( inputNameList, name ) ; - - return name; + pParseUtil->InterpretFCOName(inputNameList, name); + + return name; } @@ -1347,16 +1152,14 @@ TSTRING cTWUtil::GetIPAddress() { uint32 ipaddress; if (iFSServices::GetInstance()->GetIPAddress(ipaddress) == false) - return TSS_GetString( cTW, tw::STR_IP_UNKNOWN); - + return TSS_GetString(cTW, tw::STR_IP_UNKNOWN); + // convert to host byte-order - ipaddress = tw_ntohl( ipaddress ); + ipaddress = tw_ntohl(ipaddress); TOSTRINGSTREAM ret; - ret << (int)(ipaddress >> 24) << _T(".") - << (int)((ipaddress >> 16) & 0xff) << _T(".") - << (int)((ipaddress >> 8) & 0xff) << _T(".") - << (int)(ipaddress & 0xff); + ret << (int)(ipaddress >> 24) << _T(".") << (int)((ipaddress >> 16) & 0xff) << _T(".") + << (int)((ipaddress >> 8) & 0xff) << _T(".") << (int)(ipaddress & 0xff); return ret.str(); } @@ -1380,7 +1183,7 @@ TSTRING cTWUtil::GetHostID() /////////////////////////////////////////////////////////////////////////////// void cTWUtil::PrintErrorMsg(const eError& e, const TSTRING& strExtra) { - ASSERT( e.GetID() != 0 ); // NOTE: BAM 5/9/99 -- there should no longer be an ID of ZERO + ASSERT(e.GetID() != 0); // NOTE: BAM 5/9/99 -- there should no longer be an ID of ZERO /* BAM 5/9/99 -- this is old stuff if((e.GetID() == 0) && (e.GetMsg().empty())) @@ -1404,24 +1207,24 @@ void cTWUtil::PrintErrorMsg(const eError& e, const TSTRING& strExtra) bool cTWUtil::ConfirmYN(const TCHAR* prompt) { wc16_string reply; - TSTRING s; - int x; + TSTRING s; + int x; - while (1) + while (1) { TCOUT << prompt; GetString(reply); - + cStringUtil::Convert(s, reply); - + #ifdef UNICODE - for (x = 0; s[x] && iswctype(s[x], wctype("space") ); x++) + for (x = 0; s[x] && iswctype(s[x], wctype("space")); x++) ; #else - for (x = 0; s[x] && std::isspace( s[x], std::locale() ); x++) + for (x = 0; s[x] && std::isspace(s[x], std::locale()); x++) ; #endif - + if (_totupper(s[x]) == _T('Y')) return true; else if (_totupper(s[x]) == _T('N')) @@ -1432,27 +1235,27 @@ bool cTWUtil::ConfirmYN(const TCHAR* prompt) /////////////////////////////////////////////////////////////////////////////// // VerifySiteKey /////////////////////////////////////////////////////////////////////////////// -bool cTWUtil::VerifyCfgSiteKey( const TSTRING& strConfigFile, const TSTRING& siteKeyPath ) +bool cTWUtil::VerifyCfgSiteKey(const TSTRING& strConfigFile, const TSTRING& siteKeyPath) { // open the config file // - cMemoryArchive memArch; + cMemoryArchive memArch; try { - TSTRING dummyString; - cTWUtil::ReadConfigText( strConfigFile.c_str(), dummyString, &memArch ); + TSTRING dummyString; + cTWUtil::ReadConfigText(strConfigFile.c_str(), dummyString, &memArch); } catch (eArchive& e) { // if the file is corrupted, eArchive may be thrown. // For sanity sake we need to re-throw this as eTWUtil TSTRING estr; - estr.assign(TSS_GetString( cCore, core::STR_ERROR_FILENAME )); + estr.assign(TSS_GetString(cCore, core::STR_ERROR_FILENAME)); estr.append(strConfigFile); - estr.append(TSS_GetString( cCore, core::STR_NEWLINE )); + estr.append(TSS_GetString(cCore, core::STR_NEWLINE)); estr.append(e.GetMsg()); - throw eTWUtilCorruptedFile( estr ); + throw eTWUtilCorruptedFile(estr); } // only do the test if there is baggage (indicating the cfg file is encrypted) @@ -1464,28 +1267,26 @@ bool cTWUtil::VerifyCfgSiteKey( const TSTRING& strConfigFile, const TSTRING& sit // get site public key // cKeyFile siteKeyfile; - cTWUtil::OpenKeyFile( siteKeyfile, siteKeyPath ); + cTWUtil::OpenKeyFile(siteKeyfile, siteKeyPath); // create the two public keys... // - memArch.Seek( 0, cBidirArchive::BEGINNING ); - cElGamalSigPublicKey pubKey( memArch.GetMemory() ); + memArch.Seek(0, cBidirArchive::BEGINNING); + cElGamalSigPublicKey pubKey(memArch.GetMemory()); // compare the two .... // - if( ! pubKey.IsEqual( *siteKeyfile.GetPublicKey() ) ) + if (!pubKey.IsEqual(*siteKeyfile.GetPublicKey())) { TSTRING estr; - estr.assign(TSS_GetString( cTW, tw::STR_ERR2_CFG_KEY_MISMATCH1 )); + estr.assign(TSS_GetString(cTW, tw::STR_ERR2_CFG_KEY_MISMATCH1)); estr.append(strConfigFile); - estr.append(TSS_GetString( cTW, tw::STR_ERR2_CFG_KEY_MISMATCH2 )); + estr.append(TSS_GetString(cTW, tw::STR_ERR2_CFG_KEY_MISMATCH2)); estr.append(siteKeyPath); - estr.append(TSS_GetString( cTW, tw::STR_ERR2_CFG_KEY_MISMATCH3 )); + estr.append(TSS_GetString(cTW, tw::STR_ERR2_CFG_KEY_MISMATCH3)); - throw eTWUtilCfgKeyMismatch( estr ); + throw eTWUtilCfgKeyMismatch(estr); } return true; } - - diff --git a/src/tw/twutil.h b/src/tw/twutil.h index 451f834..1212311 100644 --- a/src/tw/twutil.h +++ b/src/tw/twutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -76,58 +76,79 @@ class cFCODatabaseFile; class cArchive; class cMemoryArchive; -TSS_EXCEPTION( eTWUtil, eError ) -TSS_EXCEPTION( eTWUtilNotFullPath, eTWUtil ) -TSS_EXCEPTION( eTWUtilCfgKeyMismatch, eTWUtil ) -TSS_EXCEPTION( eTWUtilCorruptedFile, eTWUtil ) -TSS_EXCEPTION( eTWUtilBadPassLocal, eTWUtil ) -TSS_EXCEPTION( eTWUtilBadPassSite, eTWUtil ) -TSS_EXCEPTION( eTWUtilEchoModeSet, eTWUtil ) -TSS_EXCEPTION( eTWUtilDbDoesntHaveGenre,eTWUtil ) -TSS_EXCEPTION( eTWUtilPolUnencrypted, eTWUtil ) -TSS_EXCEPTION( eTWUtilObjNotInDb, eTWUtil ) +TSS_EXCEPTION(eTWUtil, eError) +TSS_EXCEPTION(eTWUtilNotFullPath, eTWUtil) +TSS_EXCEPTION(eTWUtilCfgKeyMismatch, eTWUtil) +TSS_EXCEPTION(eTWUtilCorruptedFile, eTWUtil) +TSS_EXCEPTION(eTWUtilBadPassLocal, eTWUtil) +TSS_EXCEPTION(eTWUtilBadPassSite, eTWUtil) +TSS_EXCEPTION(eTWUtilEchoModeSet, eTWUtil) +TSS_EXCEPTION(eTWUtilDbDoesntHaveGenre, eTWUtil) +TSS_EXCEPTION(eTWUtilPolUnencrypted, eTWUtil) +TSS_EXCEPTION(eTWUtilObjNotInDb, eTWUtil) class cTWUtil { public: //------------------------------------------------------------------------- - // Reading and Writing tripwire file objects (database, report, config + // Reading and Writing tripwire file objects (database, report, config // and policy files). //------------------------------------------------------------------------- - static void WriteDatabase(const TCHAR* filename, cFCODatabaseFile& db, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw eError - // writes a database to disk. If an error occurs, a message is spit to stderr and an eError is thrown. - // if bEncrypt is false, then the key pointer may be false, otherwise, it must be non-null - static void ReadDatabase(const TCHAR* filename, cFCODatabaseFile& db, const cElGamalSigPublicKey* pPublicKey, bool& bEncrypted); // throw (eError); - // reads a database from disk. If the db is encrypted, then it will load the named key file into keyFile and - // set bEncrypted to true; otherwise keyFile is not modified and bEncrypted is set to false. - // if keyFile is already open, then the currently loaded keys are used and keyFileName is ignored. - // if an error occurs, this will print the error message to stderr and throw eError. - - static void WriteReport (const TCHAR* filename, const cFCOReportHeader& reportHeader, const cFCOReport& r, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw eError - static void WriteReport (cArchive &archive, const cFCOReportHeader& reportHeader, const cFCOReport& r, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw eError - static void ReadReport (const TCHAR* reportFileName, cFCOReportHeader& reportHeader, cFCOReport& r, const cElGamalSigPublicKey* pPublicKey, bool silent, bool& bEncrypted); // throw eError - static void ReadReport (cArchive &archive, cFCOReportHeader& reportHeader, cFCOReport& r, const cElGamalSigPublicKey* pPublicKey, bool silent, bool& bEncrypted); // throw eError - // same as Read/WriteDatabase above, except it operates on reports - // if an error occurs, this will print the error message to stderr and throw eError. - - static void WriteConfigText(const TCHAR* filename, const TSTRING configText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw (eArchive()) - static void WriteConfigText(cArchive &archive, const TSTRING configText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw (eArchive()) + static void WriteDatabase(const TCHAR* filename, + cFCODatabaseFile& db, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey); // throw eError + // writes a database to disk. If an error occurs, a message is spit to stderr and an eError is thrown. + // if bEncrypt is false, then the key pointer may be false, otherwise, it must be non-null + static void ReadDatabase(const TCHAR* filename, + cFCODatabaseFile& db, + const cElGamalSigPublicKey* pPublicKey, + bool& bEncrypted); // throw (eError); + // reads a database from disk. If the db is encrypted, then it will load the named key file into keyFile and + // set bEncrypted to true; otherwise keyFile is not modified and bEncrypted is set to false. + // if keyFile is already open, then the currently loaded keys are used and keyFileName is ignored. + // if an error occurs, this will print the error message to stderr and throw eError. + + static void WriteReport(const TCHAR* filename, + const cFCOReportHeader& reportHeader, + const cFCOReport& r, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey); // throw eError + + static void ReadReport(const TCHAR* reportFileName, + cFCOReportHeader& reportHeader, + cFCOReport& r, + const cElGamalSigPublicKey* pPublicKey, + bool silent, + bool& bEncrypted); // throw eError + + // same as Read/WriteDatabase above, except it operates on reports + // if an error occurs, this will print the error message to stderr and throw eError. + + static void WriteConfigText(const TCHAR* filename, + const TSTRING configText, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey); // throw (eArchive()) + static void ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchive* pBaggage = 0); - static void ReadConfigText(cArchive &archive, TSTRING& configText, cArchive* pBaggage = 0); - // read and write config file text to and from disk. - // if pBaggage is non-NULL, the contents of the baggage( ie -- the public key ) is copied to the archive. - // eArchive is thrown if filename can not be opened - // eSerializer is thrown if reading or writing fails - // eConfigFile is thrown if config file does not parse correctly during reading - - static void WritePolicyText(const TCHAR* filename, const std::string policyText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); - static void WritePolicyText(cArchive &archive, const std::string policyText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); + + // read and write config file text to and from disk. + // if pBaggage is non-NULL, the contents of the baggage( ie -- the public key ) is copied to the archive. + // eArchive is thrown if filename can not be opened + // eSerializer is thrown if reading or writing fails + // eConfigFile is thrown if config file does not parse correctly during reading + + static void WritePolicyText(const TCHAR* filename, + const std::string& policyText, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey); + static void ReadPolicyText(const TCHAR* filename, std::string& policyText, const cElGamalSigPublicKey* pPublicKey); - static void ReadPolicyText(cArchive &archive, std::string& policyText, const cElGamalSigPublicKey* pPublicKey); - // read and write policy file to and from disk - // eError() will be thrown on error + + // read and write policy file to and from disk + // eError() will be thrown on error //------------------------------------------------------------------------- // Higher level manipulation of Tripwire file objects @@ -137,89 +158,107 @@ class cTWUtil // Get's the path of the config file, either from the commandline, or from // the default location. - static void OpenConfigFile(cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFileID, cErrorBucket& errorBucket, TSTRING& configFileOut ); - // opens the config file, either from a known location or - // from the location specified on the command line. Returns false if it fails - // reads config info into cf - // cfgFileID is the ID of the config file that cCmdLineParser::ArgId() will know about - // if pBaggage is non-NULL, the contents of the baggage( ie -- the public key ) is copied to the archive. - // errors will be reported to errorBucket - // configFileOut returns actual config file used - // returns false on failure - - static void UpdatePolicyFile(const TCHAR* destFileName, const TCHAR* srcFileName, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey); // throw eError - // saves the plain text policy file pointed at by srcFileName encrypted with pPrivateKey in destFileName - // if an error occurs an exception suitable for printing with + static void OpenConfigFile( + cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFileID, cErrorBucket& errorBucket, TSTRING& configFileOut); + // opens the config file, either from a known location or + // from the location specified on the command line. Returns false if it fails + // reads config info into cf + // cfgFileID is the ID of the config file that cCmdLineParser::ArgId() will know about + // if pBaggage is non-NULL, the contents of the baggage( ie -- the public key ) is copied to the archive. + // errors will be reported to errorBucket + // configFileOut returns actual config file used + // returns false on failure + + static void UpdatePolicyFile(const TCHAR* destFileName, + const TCHAR* srcFileName, + bool bEncrypt, + const cElGamalSigPrivateKey* pPrivateKey); // throw eError + // saves the plain text policy file pointed at by srcFileName encrypted with pPrivateKey in destFileName + // if an error occurs an exception suitable for printing with //------------------------------------------------------------------------- // key manipulation utilities //------------------------------------------------------------------------- - static bool VerifyCfgSiteKey( const TSTRING& mstrConfigFile, const TSTRING& siteKeyPath ); //throw (eTWUtil) - // This method verifies that either the config file is unencrypted or the public key in the + static bool VerifyCfgSiteKey(const TSTRING& mstrConfigFile, const TSTRING& siteKeyPath); //throw (eTWUtil) + // This method verifies that either the config file is unencrypted or the public key in the // config file mstrConfigFile matches the public key contained in the file specified by siteKeyPath. // Returns true if the keys match or false if the config file is unencrypted. // Throws eTWUtil if the config file is encrypted but does not match the site key. // Throws eError if the site keyfile can not be opened. - + static void GetString(wc16_string& ret); static void GetStringNoEcho(wc16_string& ret); - // This takes an input string from the user with or without displaying it on the screen. - // To use passphrazes compatible between Unicode and non-Unicode, we return the most portable - // type of string, the wide string. - // This simply calls GetString in the scope of a NoEcho object. + // This takes an input string from the user with or without displaying it on the screen. + // To use passphrazes compatible between Unicode and non-Unicode, we return the most portable + // type of string, the wide string. + // This simply calls GetString in the scope of a NoEcho object. - class NoEcho { + class NoEcho + { public: NoEcho(); ~NoEcho(); }; - // For the lifetime of a cTWUtil::NoEcho object, - // tty echoing on standard input is disabled. - // At construction time, pending input is discarded. - // In order to be friendly to programs like expect, - // whose scripts typically supply input immediately after - // prompting, such prompting should happen after NoEcho - // construction to ensure that such input is not discarded. - - static void OpenKeyFile(cKeyFile& keyFile, TSTRING fileName); // throw (eError) - // this opens the passed in keyfile and associates it with keyFile. + // For the lifetime of a cTWUtil::NoEcho object, + // tty echoing on standard input is disabled. + // At construction time, pending input is discarded. + // In order to be friendly to programs like expect, + // whose scripts typically supply input immediately after + // prompting, such prompting should happen after NoEcho + // construction to ensure that such input is not discarded. + + static void OpenKeyFile(cKeyFile& keyFile, TSTRING fileName); // throw (eError) + // this opens the passed in keyfile and associates it with keyFile. // If an error occurs an exception is thrown with appropriate information. - enum KeyType { KEY_SITE, KEY_LOCAL, KEY_PROVIDED }; - enum SleepPeriodInSecs{ SLEEP_DEFAULT = 2 }; - static const cElGamalSigPrivateKey* CreatePrivateKey(cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs = SLEEP_DEFAULT ); - static void CreatePrivateKey(cPrivateKeyProxy& proxy, cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs = SLEEP_DEFAULT ); - // This will attempt to create the private key from the given key file using the given password. - // If usePassphrase is NULL then the user will be promtped to enter the passphrase. - // If usePassphrase is non-NULL, then it will be used to attempt to opent the private - // key. If this is the wrong password, an error message will be printed and an exception thrown. - // The keyfile must already be open (using OpenKeyFile above). - // The key must be freed using cKeyFile::ReleasePrivateKey(). - // keyType is just used so that an appropriate string can be displayed to the user - // nSecs is the number of to wait before showing user if password was correct. hinders brute - // force (dictionary, etc.) attacks. defaults to 2 seconds. - // NOTE: An eError() exception with an appropriate error message will be thrown on failure. - // TODO: Try to use the second version as we will want to upgrade to this some day - dmb - + enum KeyType + { + KEY_SITE, + KEY_LOCAL, + KEY_PROVIDED + }; + enum SleepPeriodInSecs + { + SLEEP_DEFAULT = 2 + }; + static const cElGamalSigPrivateKey* + CreatePrivateKey(cKeyFile& keyFile, const WCHAR16* usePassphrase, KeyType keyType, int nSecs = SLEEP_DEFAULT); + static void CreatePrivateKey(cPrivateKeyProxy& proxy, + cKeyFile& keyFile, + const WCHAR16* usePassphrase, + KeyType keyType, + int nSecs = SLEEP_DEFAULT); + // This will attempt to create the private key from the given key file using the given password. + // If usePassphrase is NULL then the user will be promtped to enter the passphrase. + // If usePassphrase is non-NULL, then it will be used to attempt to opent the private + // key. If this is the wrong password, an error message will be printed and an exception thrown. + // The keyfile must already be open (using OpenKeyFile above). + // The key must be freed using cKeyFile::ReleasePrivateKey(). + // keyType is just used so that an appropriate string can be displayed to the user + // nSecs is the number of to wait before showing user if password was correct. hinders brute + // force (dictionary, etc.) attacks. defaults to 2 seconds. + // NOTE: An eError() exception with an appropriate error message will be thrown on failure. + // TODO: Try to use the second version as we will want to upgrade to this some day - dmb + //------------------------------------------------------------------------- // Command Line //------------------------------------------------------------------------- - typedef std::vector ObjList; - typedef std::pair GenreObjs; - typedef std::vector GenreObjList; - static void ParseObjectList( GenreObjList& listOut, const ObjList& listIn ); // throw eError() + typedef std::vector ObjList; + typedef std::pair GenreObjs; + typedef std::vector GenreObjList; + static void ParseObjectList(GenreObjList& listOut, const ObjList& listIn); // throw eError() // takes a list of strings (listIn) and turns them into a collection of pairs. // This is used while integrity checking or printing a set of FCOs. This takes the form: [genre|objName]+ // where each object is associated with the most recently mentioned genre. If an object appears - // before any genre identifiers, it is assumed to be in FS on unix or NTFS on NT. + // before any genre identifiers, it is assumed to be in FS on unix or NTFS on NT. // eError will be thrown if an unknown genre is encountered - static cFCOName ParseObjectName( const TSTRING& fcoName ); // throw (eError) + static cFCOName ParseObjectName(const TSTRING& fcoName); // throw (eError) // converts a string representation of an FCO name (that was passed in on the command line for integrity // check or database printing) into a cFCOName. It is assumed that the name is for an object in the current // genre. If the string cannot be converted (ie -- relative path or invalid formatting), eError is thrown. - + //------------------------------------------------------------------------- // Database and report header helpers //------------------------------------------------------------------------- @@ -231,26 +270,25 @@ class cTWUtil static TSTRING GetHostID(); //------------------------------------------------------------------------- - // Micellaneous + // Micellaneous //------------------------------------------------------------------------- - static bool IsObjectEncrypted( const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg ); - static bool IsObjectEncrypted( cArchive &arch, const cFileHeaderID& fhid, const TSTRING& errorMsg ); - // Tests an object serialized to objFileName to see if it's encrypted. fhid ensures that the object in the - // file is of the correct type. - // If an error occurs while reading the file, this WILL PRINT an error message errorMsg, - // then it will throw eError(NULL). + static bool IsObjectEncrypted(const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg); + static bool IsObjectEncrypted(cArchive& arch, const cFileHeaderID& fhid, const TSTRING& errorMsg); + // Tests an object serialized to objFileName to see if it's encrypted. fhid ensures that the object in the + // file is of the correct type. + // If an error occurs while reading the file, this WILL PRINT an error message errorMsg, + // then it will throw eError(NULL). static void PrintErrorMsg(const eError& e, const TSTRING& strExtra = _T("")); - // nicely displays the contents of the exception to stderr. - // currently, it has the format: - // ### Error e.GetErrorNum(): e.GetMsg() : cErrorTable::GetErrorString(e.GetErrorNum()) + // nicely displays the contents of the exception to stderr. + // currently, it has the format: + // ### Error e.GetErrorNum(): e.GetMsg() : cErrorTable::GetErrorString(e.GetErrorNum()) static bool ConfirmYN(const TCHAR* prompt); - // prompt the user with given string and wait for a 'Y' or 'N' response. - // returns true if 'Y' entered. + // prompt the user with given string and wait for a 'Y' or 'N' response. + // returns true if 'Y' entered. }; #endif //__TWUTIL_H - diff --git a/src/twadmin/Makefile.am b/src/twadmin/Makefile.am index 98f514a..538bde7 100644 --- a/src/twadmin/Makefile.am +++ b/src/twadmin/Makefile.am @@ -1,18 +1,23 @@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. LIBS = -ltripwire -lcryptlib @LIBS@ LDFLAGS = @LDFLAGS@ -L../../lib LN_S = @LN@ sbin_PROGRAMS = twadmin +twadmindir=. twadmin_SOURCES = \ keygeneration.cpp stdtwadmin.cpp twadmin.cpp twadmincl.cpp \ twadminerrors.cpp twadminmain.cpp twadminstrings.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../bin/twadmin +twadmin_HEADERS = \ + keygeneration.h resource.h stdtwadmin.h twadmin.h \ + twadmincl.h twadminerrors.h twadminstrings.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = ../../bin/twadmin *.gcno *.gcda all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin diff --git a/src/twadmin/Makefile.in b/src/twadmin/Makefile.in index 4d50108..b3a8e68 100644 --- a/src/twadmin/Makefile.in +++ b/src/twadmin/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(twadmin_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,43 +87,117 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ sbin_PROGRAMS = twadmin$(EXEEXT) subdir = src/twadmin -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(twadmin_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twadmindir)" PROGRAMS = $(sbin_PROGRAMS) am_twadmin_OBJECTS = keygeneration.$(OBJEXT) stdtwadmin.$(OBJEXT) \ twadmin.$(OBJEXT) twadmincl.$(OBJEXT) twadminerrors.$(OBJEXT) \ twadminmain.$(OBJEXT) twadminstrings.$(OBJEXT) twadmin_OBJECTS = $(am_twadmin_OBJECTS) twadmin_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(twadmin_SOURCES) DIST_SOURCES = $(twadmin_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +HEADERS = $(twadmin_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -88,7 +213,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -96,6 +221,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -107,6 +233,7 @@ LN = @LN@ LN_S = @LN@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -123,21 +250,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -167,20 +297,29 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. +twadmindir = . twadmin_SOURCES = \ keygeneration.cpp stdtwadmin.cpp twadmin.cpp twadmincl.cpp \ twadminerrors.cpp twadminmain.cpp twadminstrings.cpp -CLEANFILES = ../../bin/twadmin +twadmin_HEADERS = \ + keygeneration.h resource.h stdtwadmin.h twadmin.h \ + twadmincl.h twadminerrors.h twadminstrings.h + +CLEANFILES = ../../bin/twadmin *.gcno *.gcda all: all-am .SUFFIXES: @@ -189,15 +328,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twadmin/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/twadmin/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twadmin/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/twadmin/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -214,32 +352,53 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): install-sbinPROGRAMS: $(sbin_PROGRAMS) @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(mkdir_p) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(sbindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(sbindir)" || exit 1; \ + fi; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p \ + ; then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' \ + -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || exit $$?; \ + } \ + ; done uninstall-sbinPROGRAMS: @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' \ + `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(sbindir)" && rm -f $$files clean-sbinPROGRAMS: -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -twadmin$(EXEEXT): $(twadmin_OBJECTS) $(twadmin_DEPENDENCIES) + +twadmin$(EXEEXT): $(twadmin_OBJECTS) $(twadmin_DEPENDENCIES) $(EXTRA_twadmin_DEPENDENCIES) @rm -f twadmin$(EXEEXT) - $(CXXLINK) $(twadmin_LDFLAGS) $(twadmin_OBJECTS) $(twadmin_LDADD) $(LIBS) + $(AM_V_CXXLD)$(CXXLINK) $(twadmin_OBJECTS) $(twadmin_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -248,93 +407,120 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-twadminHEADERS: $(twadmin_HEADERS) + @$(NORMAL_INSTALL) + @list='$(twadmin_HEADERS)'; test -n "$(twadmindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(twadmindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(twadmindir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(twadmindir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(twadmindir)" || exit $$?; \ + done + +uninstall-twadminHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(twadmin_HEADERS)'; test -n "$(twadmindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(twadmindir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + for dir in "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twadmindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -346,17 +532,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -376,18 +568,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-twadminHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: install-sbinPROGRAMS +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -406,22 +618,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-sbinPROGRAMS +uninstall-am: uninstall-sbinPROGRAMS uninstall-twadminHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-sbinPROGRAMS ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-sbinPROGRAMS install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-sbinPROGRAMS cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ + install-strip install-twadminHEADERS installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am uninstall-sbinPROGRAMS + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-sbinPROGRAMS uninstall-twadminHEADERS + +.PRECIOUS: Makefile all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/twadmin/keygeneration.cpp b/src/twadmin/keygeneration.cpp index 5edb2a8..a14118a 100644 --- a/src/twadmin/keygeneration.cpp +++ b/src/twadmin/keygeneration.cpp @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// keygeneration.cpp +// keygeneration.cpp // #include "stdtwadmin.h" @@ -42,73 +42,65 @@ #include "twadminstrings.h" #include "core/usernotify.h" - -#ifndef _DEBUG -const cElGamalSig::KeySize TRIPWIRE_PUBLIC_KEYSIZE = cElGamalSig::KEY1024; -#else -const cElGamalSig::KeySize TRIPWIRE_PUBLIC_KEYSIZE = cElGamalSig::KEY1024; -#endif - struct tGK { - bool doneFlag; - int retValue; - int8* passphrase; - int passphraseLen; + bool doneFlag; + int retValue; + int8* passphrase; + int passphraseLen; const TCHAR* keyPath; enum ReturnValue { - OK = 0, - INVALIDPARAM = 1, + OK = 0, + INVALIDPARAM = 1, GENERATION_ERROR = 2, FILE_WRITE_ERROR = 3, LAST }; - tGK() + tGK() { - doneFlag = false; - retValue = 0; - passphrase = 0; + doneFlag = false; + retValue = 0; + passphrase = 0; passphraseLen = 0; - keyPath = 0; + keyPath = 0; } }; -static void GeneratePublicPrivateKeys(void* pParams) +static void GeneratePublicPrivateKeys(void* pParams, const cElGamalSig::KeySize key_size) { tGK* pGK = (tGK*)pParams; - if (pGK->doneFlag != false || - pGK->keyPath == 0 || - _tcslen(pGK->keyPath) == 0) + if (pGK->doneFlag != false || pGK->keyPath == 0 || _tcslen(pGK->keyPath) == 0) { pGK->retValue = tGK::INVALIDPARAM; pGK->doneFlag = true; return; } - try { + try + { cKeyFile keyfile; -#ifdef _DEBUG +#ifdef DEBUG cDebug d("GeneratePublicPrivateKeys"); d.TraceDebug("calling keyfile.GenerateKeys()\n"); #endif - + try { - keyfile.GenerateKeys(TRIPWIRE_PUBLIC_KEYSIZE, pGK->passphrase, pGK->passphraseLen); + keyfile.GenerateKeys(key_size, pGK->passphrase, pGK->passphraseLen); } - catch(eKeyFile&) + catch (eKeyFile&) { pGK->retValue = tGK::GENERATION_ERROR; pGK->doneFlag = true; return; } -#ifdef _DEBUG +#ifdef DEBUG d.TraceDebug(_T("writing to keyfile %s\n"), pGK->keyPath); #endif @@ -116,14 +108,14 @@ static void GeneratePublicPrivateKeys(void* pParams) { keyfile.WriteFile(pGK->keyPath); } - catch(eKeyFile&) + catch (eKeyFile&) { pGK->retValue = tGK::FILE_WRITE_ERROR; pGK->doneFlag = true; return; } } - catch(eError& e) + catch (eError& e) { (void)e; pGK->retValue = tGK::GENERATION_ERROR; @@ -136,41 +128,42 @@ static void GeneratePublicPrivateKeys(void* pParams) return; } -bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase) +bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase, const cElGamalSig::KeySize key_size) { #ifndef WORDS_BIGENDIAN passphrase.swapbytes(); #endif -#ifdef _DEBUG +#ifdef DEBUG // test reading in the keys - wc16_string passphrase_copy = passphrase.c_str(); + wc16_string passphrase_copy = passphrase.c_str(); wc16_string passphrase_copy2 = passphrase.c_str(); #endif - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_GENERATING_KEYS).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_GENERATING_KEYS).c_str()); -#if IS_UNIX fflush(stdout); -#endif tGK gk; - gk.passphrase = (int8*)passphrase.data(); + gk.passphrase = (int8*)passphrase.data(); gk.passphraseLen = passphrase.length() * sizeof(WCHAR16); - gk.keyPath = keyPath; + gk.keyPath = keyPath; -#if IS_UNIX - GeneratePublicPrivateKeys(&gk); -#endif + GeneratePublicPrivateKeys(&gk, key_size); if (gk.retValue != tGK::OK) { switch (gk.retValue) { case tGK::FILE_WRITE_ERROR: - TCERR << std::endl << TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYGEN_FILEWRITE) << gk.keyPath << std::endl; + TCERR << std::endl + << TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYGEN_FILEWRITE) << gk.keyPath << std::endl; + break; + default: - TCERR << std::endl << TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYGEN) << gk.keyPath + TCERR << std::endl + << TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYGEN) << gk.keyPath << TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYGEN2) << std::endl; break; } @@ -178,7 +171,7 @@ bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase) return false; } -#ifdef _DEBUG +#ifdef DEBUG // test reading in the keys cKeyFile keyfile; @@ -190,7 +183,7 @@ bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase) //keyfile.WriteFile(_T("tripwire2.key")); // test memory writing - int8 mem[4000]; + int8 mem[4000]; ASSERT(4000 > keyfile.GetWriteLen()); keyfile.WriteMem(mem); @@ -202,8 +195,8 @@ bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase) k2.ReleasePrivateKey(); #endif - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_GENERATION_COMPLETE).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_GENERATION_COMPLETE).c_str()); return true; } - diff --git a/src/twadmin/keygeneration.h b/src/twadmin/keygeneration.h index d2fe8fc..ca8f10c 100644 --- a/src/twadmin/keygeneration.h +++ b/src/twadmin/keygeneration.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,7 +44,8 @@ #include "core/wchar16.h" #endif -bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase); +#include "twcrypto/crypto.h" -#endif +bool GenerateKey(const TCHAR* keyPath, wc16_string passphrase, const cElGamalSig::KeySize key_size); +#endif diff --git a/src/twadmin/resource.h b/src/twadmin/resource.h index 5510e67..d9d6a03 100644 --- a/src/twadmin/resource.h +++ b/src/twadmin/resource.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,13 +35,12 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 +# ifndef APSTUDIO_READONLY_SYMBOLS +# define _APS_NEXT_RESOURCE_VALUE 102 +# define _APS_NEXT_COMMAND_VALUE 40001 +# define _APS_NEXT_CONTROL_VALUE 1000 +# define _APS_NEXT_SYMED_VALUE 101 +# endif #endif -#endif - diff --git a/src/twadmin/stdtwadmin.cpp b/src/twadmin/stdtwadmin.cpp index 380ac77..99bf872 100644 --- a/src/twadmin/stdtwadmin.cpp +++ b/src/twadmin/stdtwadmin.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdtwadmin.h" - -// eof: stdtwadmin.cpp diff --git a/src/twadmin/stdtwadmin.h b/src/twadmin/stdtwadmin.h index 8d7c961..e9ace88 100644 --- a/src/twadmin/stdtwadmin.h +++ b/src/twadmin/stdtwadmin.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/twadmin/twadmin.cpp b/src/twadmin/twadmin.cpp index 84f0fb1..f402070 100644 --- a/src/twadmin/twadmin.cpp +++ b/src/twadmin/twadmin.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,11 +42,11 @@ #include "stdtwadmin.h" #include "twadmin.h" -#include "tw/tw.h" // for cTW +#include "tw/tw.h" // for cTW #include "twadminerrors.h" -TSS_ImplementPackage( cTWAdmin ) +TSS_ImplementPackage(cTWAdmin) //============================================================================= // cTWAdmin::cTWAdmin() @@ -65,8 +65,6 @@ cTWAdmin::cTWAdmin() // // set up dependencies // - TSS_Dependency( cTW ); - TSS_REGISTER_PKG_ERRORS ( twadmin ); + TSS_Dependency(cTW); + TSS_REGISTER_PKG_ERRORS(twadmin); } - -// eof: twadmin.cpp diff --git a/src/twadmin/twadmin.h b/src/twadmin/twadmin.h index c825f82..13897a0 100644 --- a/src/twadmin/twadmin.h +++ b/src/twadmin/twadmin.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,18 +42,17 @@ //--Requirements -#include "core/package.h" // for: Packaging Abstraction +#include "core/package.h" // for: Packaging Abstraction //--Classes -TSS_BeginPackage( cTWAdmin ) +TSS_BeginPackage(cTWAdmin) TSS_DECLARE_STRINGTABLE; - + public: - cTWAdmin(); +cTWAdmin(); -TSS_EndPackage( cTWAdmin ) +TSS_EndPackage(cTWAdmin) #endif //#ifndef __TWADMIN_H - diff --git a/src/twadmin/twadmincl.cpp b/src/twadmin/twadmincl.cpp index 0dc5012..18f0e40 100644 --- a/src/twadmin/twadmincl.cpp +++ b/src/twadmin/twadmincl.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,17 +34,16 @@ // #include "stdtwadmin.h" -#include - #include "twadmincl.h" #include "twadminstrings.h" #include "keygeneration.h" #include "core/errorgeneral.h" -#include "core/errorbucketimpl.h" // needed for the error table +#include "core/errorbucketimpl.h" // needed for the error table #include "core/archive.h" #include "core/usernotify.h" #include "core/cmdlineparser.h" #include "core/usernotify.h" +#include "core/corestrings.h" #include "fco/fconame.h" #include "tw/configfile.h" #include "tw/twutil.h" @@ -62,51 +61,54 @@ #include "twcrypto/crypto.h" #include "core/displayencoder.h" +#include + //Provide a swab() impl. from glibc, for platforms that don't have one -#if defined(__SYLLABLE__) || defined(__ANDROID_API__) || defined(_SORTIX_SOURCE) -void swab (const void *bfrom, void *bto, ssize_t n) +#if !HAVE_SWAB || NEEDS_SWAB_IMPL +void swab(const void* bfrom, void* bto, ssize_t n) { - const char *from = (const char *) bfrom; - char *to = (char *) bto; + const char* from = (const char*)bfrom; + char* to = (char*)bto; - n &= ~((ssize_t) 1); - while (n > 1) + n &= ~((ssize_t)1); + while (n > 1) { - const char b0 = from[--n], b1 = from[--n]; - to[n] = b0; - to[n + 1] = b1; + const char b0 = from[--n], b1 = from[--n]; + to[n] = b0; + to[n + 1] = b1; } } #endif // forwards static bool NotifyFileType(const cFileHeaderID& id, uint32 version, iUserNotify::VerboseLevel vl); - // Calls UserNotify(V_VERBOSE, ...) to print out type of file specified in cFileHeaderID. - // Returns false if cFileHeaderID not recognized. - // Used in changing and removing encryption algorithms +// Calls UserNotify(V_VERBOSE, ...) to print out type of file specified in cFileHeaderID. +// Returns false if cFileHeaderID not recognized. +// Used in changing and removing encryption algorithms static bool NotifyEncryptionType(cFileHeader::Encoding encoding, iUserNotify::VerboseLevel vl); - // Calls UserNotify(V_VERBOSE, ...) to print out type of file specified in cFileHeaderID. - // Returns false if encoding not recognized. - // Used in changing and removing encryption algorithms +// Calls UserNotify(V_VERBOSE, ...) to print out type of file specified in cFileHeaderID. +// Returns false if encoding not recognized. +// Used in changing and removing encryption algorithms // error implementations -eTWACreateCfgMissingSitekey::eTWACreateCfgMissingSitekey( const TSTRING& msg, uint32 flags ) - : eTWA( TSTRING(), flags ) -{ - mMsg = TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_MISSING_KEYFILE) + msg; -} +eTWACreateCfgMissingSitekey::eTWACreateCfgMissingSitekey(const TSTRING& msg, uint32 flags) : eTWA(TSTRING(), flags) +{ + mMsg = TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_MISSING_KEYFILE) + msg; +} -eTWACreateCfgSitekeyMismatch::eTWACreateCfgSitekeyMismatch( const TSTRING& specifiedKeyfile, const TSTRING& configKeyfile, uint32 flags ) - : eTWA( TSTRING(), flags ) -{ - mMsg = TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1); +eTWACreateCfgSitekeyMismatch::eTWACreateCfgSitekeyMismatch(const TSTRING& specifiedKeyfile, + const TSTRING& configKeyfile, + uint32 flags) + : eTWA(TSTRING(), flags) +{ + mMsg = TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1); mMsg.append(specifiedKeyfile); - mMsg.append(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2)); + mMsg.append(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2)); mMsg.append(configKeyfile); - mMsg.append(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3)); -} + mMsg.append(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3)); +} /////////////////////////////////////////////////////////////////////////////// // cTWAModeCommon -- common modes that all iTWAMode implementations will @@ -115,15 +117,18 @@ eTWACreateCfgSitekeyMismatch::eTWACreateCfgSitekeyMismatch( const TSTRING& speci class cTWAModeCommon : public iTWAMode { protected: - int mVerbosity; // must be 0 <= n <= 2 - TSTRING mPolFile; - TSTRING mSiteKeyFile; - bool mSiteKeyFileProvieded; - TSTRING mLocalKeyFile; - bool mLocalKeyFileProvieded; - bool mLatePassphrase; + int mVerbosity; // must be 0 <= n <= 2 + TSTRING mPolFile; + TSTRING mSiteKeyFile; + bool mSiteKeyFileProvieded; + TSTRING mLocalKeyFile; + bool mLocalKeyFileProvieded; + bool mLatePassphrase; - cTWAModeCommon() : mVerbosity(1), mSiteKeyFileProvieded(false), mLocalKeyFileProvieded(false), mLatePassphrase(false) {} + cTWAModeCommon() + : mVerbosity(1), mSiteKeyFileProvieded(false), mLocalKeyFileProvieded(false), mLatePassphrase(false) + { + } void InitCmdLineCommon(cCmdLineParser& parser); void FillOutConfigInfo(const cConfigFile* cf); @@ -136,13 +141,13 @@ class cTWAModeCommon : public iTWAMode void cTWAModeCommon::InitCmdLineCommon(cCmdLineParser& parser) { - parser.AddArg(cTWAdminCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::POL_FILE, TSTRING(_T("p")), TSTRING(_T("polfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::POL_FILE, TSTRING(_T("p")), TSTRING(_T("polfile")), cCmdLineParser::PARAM_ONE); parser.AddMutEx(cTWAdminCmdLine::VERBOSE, cTWAdminCmdLine::SILENT); } @@ -155,40 +160,41 @@ void cTWAModeCommon::FillOutConfigInfo(const cConfigFile* cf) return; TSTRING str; - if(cf->Lookup(TSTRING(_T("POLFILE")), str)) + if (cf->Lookup(TSTRING(_T("POLFILE")), str)) mPolFile = str; - if(cf->Lookup(TSTRING(_T("SITEKEYFILE")), str)) + if (cf->Lookup(TSTRING(_T("SITEKEYFILE")), str)) mSiteKeyFile = str; - if(cf->Lookup(TSTRING(_T("LOCALKEYFILE")), str)) + if (cf->Lookup(TSTRING(_T("LOCALKEYFILE")), str)) mLocalKeyFile = str; - if(cf->Lookup(TSTRING(_T("LATEPROMPTING")), str)) + if (cf->Lookup(TSTRING(_T("LATEPROMPTING")), str)) { if (_tcsicmp(str.c_str(), _T("true")) == 0) - mLatePassphrase = true; + mLatePassphrase = true; } - // + // // turn all of the file names into full paths (they're relative to the exe dir) - // + // TSTRING fullPath; - if(!mPolFile.empty() && iFSServices::GetInstance()->FullPath( fullPath, mPolFile, cSystemInfo::GetExeDir() )) + if (!mPolFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mPolFile, cSystemInfo::GetExeDir())) mPolFile = fullPath; - if(!mSiteKeyFile.empty() && iFSServices::GetInstance()->FullPath( fullPath, mSiteKeyFile, cSystemInfo::GetExeDir() )) + if (!mSiteKeyFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mSiteKeyFile, cSystemInfo::GetExeDir())) mSiteKeyFile = fullPath; - if(!mLocalKeyFile.empty() && iFSServices::GetInstance()->FullPath( fullPath, mLocalKeyFile, cSystemInfo::GetExeDir() )) + if (!mLocalKeyFile.empty() && + iFSServices::GetInstance()->FullPath(fullPath, mLocalKeyFile, cSystemInfo::GetExeDir())) mLocalKeyFile = fullPath; } /////////////////////////////////////////////////////////////////////////////// -// FillOutCmdLineInfo -- fills out info common to all modes that appears on the +// FillOutCmdLineInfo -- fills out info common to all modes that appears on the // command line. /////////////////////////////////////////////////////////////////////////////// void cTWAModeCommon::FillOutCmdLineInfo(const cCmdLineParser& parser) -{ +{ cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::VERBOSE: mVerbosity = 2; @@ -197,17 +203,17 @@ void cTWAModeCommon::FillOutCmdLineInfo(const cCmdLineParser& parser) mVerbosity = 0; break; case cTWAdminCmdLine::POL_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser mPolFile = iter.ParamAt(0); break; case cTWAdminCmdLine::SITE_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mSiteKeyFile = iter.ParamAt(0); + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mSiteKeyFile = iter.ParamAt(0); mSiteKeyFileProvieded = true; break; case cTWAdminCmdLine::LOCAL_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mLocalKeyFile = iter.ParamAt(0); + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mLocalKeyFile = iter.ParamAt(0); mLocalKeyFileProvieded = true; break; } @@ -217,11 +223,11 @@ void cTWAModeCommon::FillOutCmdLineInfo(const cCmdLineParser& parser) // Note: We depend later on the if one of these files is not specified, the string // is empty. Currently FullPath() expands "" to the CWD. TSTRING fullPath; - if(!mPolFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mPolFile)) + if (!mPolFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mPolFile)) mPolFile = fullPath; - if(!mSiteKeyFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mSiteKeyFile)) + if (!mSiteKeyFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mSiteKeyFile)) mSiteKeyFile = fullPath; - if(!mLocalKeyFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mLocalKeyFile)) + if (!mLocalKeyFile.empty() && iFSServices::GetInstance()->FullPath(fullPath, mLocalKeyFile)) mLocalKeyFile = fullPath; // use the verbosity information @@ -231,38 +237,47 @@ void cTWAModeCommon::FillOutCmdLineInfo(const cCmdLineParser& parser) /////////////////////////////////////////////////////////////////////////////// // TWAdmin modes -// -// No one else should need to see these classes, so we will keep them +// +// No one else should need to see these classes, so we will keep them // localized to this file. // /////////////////////////////////////////////////////////////////////////////// -// cTWAModeCreateCfg +// cTWAModeCreateCfg class cTWAModeCreateCfg : public cTWAModeCommon { public: cTWAModeCreateCfg(); virtual ~cTWAModeCreateCfg(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_CREATE_CONFIG; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_CREATE_CONFIG; + } private: TSTRING mPlaintextConfig; TSTRING mEncryptedConfig; - wc16_string mPassPhrase; // pass phrase for private key + wc16_string mPassPhrase; // pass phrase for private key bool mPassPhraseProvided; bool mNoEncryption; }; cTWAModeCreateCfg::cTWAModeCreateCfg() { - mNoEncryption = false; + mNoEncryption = false; mPassPhraseProvided = false; } @@ -274,11 +289,17 @@ void cTWAModeCreateCfg::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_CREATE_CONFIG, TSTRING(_T("")), TSTRING(_T("create-cfgfile")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::NO_ENCRYPTION, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::MODE_CREATE_CONFIG, + TSTRING(_T("")), + TSTRING(_T("create-cfgfile")), + cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::NO_ENCRYPTION, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); parser.AddMutEx(cTWAdminCmdLine::NO_ENCRYPTION, cTWAdminCmdLine::SITE_KEY_FILE); parser.AddMutEx(cTWAdminCmdLine::NO_ENCRYPTION, cTWAdminCmdLine::PASSPHRASE); } @@ -286,27 +307,27 @@ void cTWAModeCreateCfg::InitCmdLineParser(cCmdLineParser& parser) bool cTWAModeCreateCfg::Init(const cConfigFile* cf, const cCmdLineParser& parser) { TSTRING str; - + FillOutConfigInfo(cf); FillOutCmdLineInfo(parser); - bool fConfigOnCmdLine = false; + bool fConfigOnCmdLine = false; cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::NO_ENCRYPTION: mNoEncryption = true; break; case cTWAdminCmdLine::PASSPHRASE: - { - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mPassPhrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mPassPhraseProvided = true; - } - break; + { + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mPassPhrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mPassPhraseProvided = true; + } + break; case cTWAdminCmdLine::CFG_FILE: if (iter.NumParams() < 1) { @@ -325,24 +346,24 @@ bool cTWAModeCreateCfg::Init(const cConfigFile* cf, const cCmdLineParser& parser } // get full path to files - TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, mPlaintextConfig ) ) - mPlaintextConfig = strFullPath; + TSTRING strPlaintextConfigPath; + if (iFSServices::GetInstance()->FullPath(strPlaintextConfigPath, mPlaintextConfig)) + mPlaintextConfig = strPlaintextConfigPath; // OK, now we need to figure out where to put the new config file. // If the location was specified on the command line, get the full path to it. // otherwise, the location is the dir that this exe is in. - if( fConfigOnCmdLine ) + if (fConfigOnCmdLine) { - TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, mEncryptedConfig ) ) - mEncryptedConfig = strFullPath; + TSTRING strEncryptedConfigPath; + if (iFSServices::GetInstance()->FullPath(strEncryptedConfigPath, mEncryptedConfig)) + mEncryptedConfig = strEncryptedConfigPath; } else { - iFSServices::GetInstance()->FullPath( mEncryptedConfig, TSS_GetString(cTW, tw::STR_DEF_CFG_FILENAME ), - cSystemInfo::GetExeDir() ) ; - } + iFSServices::GetInstance()->FullPath( + mEncryptedConfig, TSS_GetString(cTW, tw::STR_DEF_CFG_FILENAME), cSystemInfo::GetExeDir()); + } return true; } @@ -363,25 +384,26 @@ int cTWAModeCreateCfg::Execute(cErrorQueue* pQueue) if (mSiteKeyFile.empty() && !mNoEncryption) { - cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED))); + cTWUtil::PrintErrorMsg( + eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED))); return 1; } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTWAdmin, twadmin::STR_UPCONFIG_VERBOSE_PT_CONFIG).c_str(), - cDisplayEncoder::EncodeInline( mPlaintextConfig ).c_str()); + cDisplayEncoder::EncodeInline(mPlaintextConfig).c_str()); cFileArchive arch; - arch.OpenRead(mPlaintextConfig.c_str(), cFileArchive::FA_OPEN_TEXT); // Note: eArchive may be thrown - + arch.OpenRead(mPlaintextConfig.c_str(), cFileArchive::FA_OPEN_TEXT); // Note: eArchive may be thrown + // read in config text std::string narrowPlaintext; narrowPlaintext.resize(arch.Length()); // NOTE: archive may write fewer than arch.Length() bytes since // it is converting CR/LF to CR. int cbRead = arch.ReadBlob((void*)narrowPlaintext.data(), arch.Length()); - narrowPlaintext.resize( cbRead ); // may have garbage after plaintext[cbRead] due to text mode conversion + narrowPlaintext.resize(cbRead); // may have garbage after plaintext[cbRead] due to text mode conversion TSTRING plaintext = cStringUtil::StrToTstr(narrowPlaintext); @@ -396,12 +418,11 @@ int cTWAModeCreateCfg::Execute(cErrorQueue* pQueue) cConfigFile cf; cf.ReadString(plaintext); - if ( (plaintextKeyFileLoaded = cf.Lookup(_T("SITEKEYFILE"), plaintextKeyFileName)) == true && - (plaintextKeyFileLoaded = !plaintextKeyFileName.empty()) == true - ) + if ((plaintextKeyFileLoaded = cf.Lookup(_T("SITEKEYFILE"), plaintextKeyFileName)) == true && + (plaintextKeyFileLoaded = !plaintextKeyFileName.empty()) == true) { TSTRING fullPath; - if (iFSServices::GetInstance()->FullPath( fullPath, plaintextKeyFileName, cSystemInfo::GetExeDir() )) + if (iFSServices::GetInstance()->FullPath(fullPath, plaintextKeyFileName, cSystemInfo::GetExeDir())) plaintextKeyFileName = fullPath; cTWUtil::OpenKeyFile(plaintextKeyFile, plaintextKeyFileName); @@ -410,11 +431,11 @@ int cTWAModeCreateCfg::Execute(cErrorQueue* pQueue) } catch (eConfigFile& e) { - pQueue->AddError( e ); + pQueue->AddError(e); return 1; } - cKeyFile specifiedKeyFile; + cKeyFile specifiedKeyFile; const cElGamalSigPrivateKey* pPrivateKey; if (!mNoEncryption) @@ -424,18 +445,19 @@ int cTWAModeCreateCfg::Execute(cErrorQueue* pQueue) { // User wishes to create a config file using a key, but has not specified the key in the config file. // For safty and sanity reasons we do not let them do this. - pQueue->AddError( eTWACreateCfgMissingSitekey(TSTRING()) ); + pQueue->AddError(eTWACreateCfgMissingSitekey(TSTRING())); return false; } else if (!specifiedKeyFile.GetPublicKey()->IsEqual(*plaintextKeyFile.GetPublicKey())) { // The site key specified in this config file does not match the sitekey they are encrypting the // config file with. This is likely to lead to problems so we try to catch it here. - pQueue->AddError( eTWACreateCfgSitekeyMismatch(mSiteKeyFile, plaintextKeyFileName) ); + pQueue->AddError(eTWACreateCfgSitekeyMismatch(mSiteKeyFile, plaintextKeyFileName)); return false; } - pPrivateKey = cTWUtil::CreatePrivateKey(specifiedKeyFile, mPassPhraseProvided ? mPassPhrase.c_str() : NULL, cTWUtil::KEY_SITE); + pPrivateKey = cTWUtil::CreatePrivateKey( + specifiedKeyFile, mPassPhraseProvided ? mPassPhrase.c_str() : NULL, cTWUtil::KEY_SITE); } else pPrivateKey = 0; @@ -465,24 +487,33 @@ class cTWAModeCreatePol : public cTWAModeCommon public: cTWAModeCreatePol(); virtual ~cTWAModeCreatePol(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_CREATE_POLICY; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_CREATE_POLICY; + } private: TSTRING mPlaintextPolicy; - wc16_string mPassPhrase; // pass phrase for private key + wc16_string mPassPhrase; // pass phrase for private key bool mPassPhraseProvided; bool mNoEncryption; }; cTWAModeCreatePol::cTWAModeCreatePol() { - mNoEncryption = false; + mNoEncryption = false; mPassPhraseProvided = false; } @@ -494,11 +525,17 @@ void cTWAModeCreatePol::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_CREATE_POLICY, TSTRING(_T("")), TSTRING(_T("create-polfile")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::NO_ENCRYPTION, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::MODE_CREATE_POLICY, + TSTRING(_T("")), + TSTRING(_T("create-polfile")), + cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::PASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::NO_ENCRYPTION, TSTRING(_T("e")), TSTRING(_T("no-encryption")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); parser.AddMutEx(cTWAdminCmdLine::NO_ENCRYPTION, cTWAdminCmdLine::SITE_KEY_FILE); parser.AddMutEx(cTWAdminCmdLine::NO_ENCRYPTION, cTWAdminCmdLine::PASSPHRASE); } @@ -506,25 +543,25 @@ void cTWAModeCreatePol::InitCmdLineParser(cCmdLineParser& parser) bool cTWAModeCreatePol::Init(const cConfigFile* cf, const cCmdLineParser& parser) { TSTRING str; - + FillOutConfigInfo(cf); FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::NO_ENCRYPTION: mNoEncryption = true; break; case cTWAdminCmdLine::PASSPHRASE: - { - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mPassPhrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mPassPhraseProvided = true; - } - break; + { + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mPassPhrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mPassPhraseProvided = true; + } + break; case cTWAdminCmdLine::PARAMS: ASSERT(iter.NumParams() == 1); mPlaintextPolicy = iter.ParamAt(0); @@ -534,9 +571,9 @@ bool cTWAModeCreatePol::Init(const cConfigFile* cf, const cCmdLineParser& parser // get full path to files TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, mSiteKeyFile ) ) + if (iFSServices::GetInstance()->FullPath(strFullPath, mSiteKeyFile)) mSiteKeyFile = strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, mPlaintextPolicy ) ) + if (iFSServices::GetInstance()->FullPath(strFullPath, mPlaintextPolicy)) mPlaintextPolicy = strFullPath; if (mPlaintextPolicy.empty()) @@ -547,13 +584,13 @@ bool cTWAModeCreatePol::Init(const cConfigFile* cf, const cCmdLineParser& parser // check that the config file and site key file are in sync... // - if( ! mCfgFilePath.empty() ) - try + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -566,8 +603,8 @@ int cTWAModeCreatePol::Execute(cErrorQueue* pQueue) { if (mPlaintextPolicy.empty()) { - cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_NO_PT_POLICY))); - return 1; + cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_NO_PT_POLICY))); + return 1; } if (mPolFile.empty()) @@ -578,41 +615,42 @@ int cTWAModeCreatePol::Execute(cErrorQueue* pQueue) if (mSiteKeyFile.empty() && !mNoEncryption) { - cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED))); + cTWUtil::PrintErrorMsg( + eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED))); return 1; } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, - TSS_GetString(cTWAdmin, twadmin::STR_UPCONFIG_VERBOSE_PT_POLICY).c_str(), - cDisplayEncoder::EncodeInline( mPlaintextPolicy ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + TSS_GetString(cTWAdmin, twadmin::STR_UPCONFIG_VERBOSE_PT_POLICY).c_str(), + cDisplayEncoder::EncodeInline(mPlaintextPolicy).c_str()); // open policy file as text cFileArchive arch; arch.OpenRead(mPlaintextPolicy.c_str(), cFileArchive::FA_OPEN_TEXT); // Note: eArchive may be thrown - + // read in policy text std::string plaintext; plaintext.resize(arch.Length()); // NOTE: archive may write fewer than arch.Length() bytes since // it is converting CR/LF to CR. int cbRead = arch.ReadBlob((void*)plaintext.data(), arch.Length()); - plaintext.resize( cbRead ); // may have garbage after plaintext[cbRead] due to text mode conversion + plaintext.resize(cbRead); // may have garbage after plaintext[cbRead] due to text mode conversion // // make sure the policy file parses correctly before we update the old one // - std::istringstream in( plaintext ); - cPolicyParser parser( in ); + std::istringstream in(plaintext); + cPolicyParser parser(in); try { - parser.Check( pQueue ); + parser.Check(pQueue); } - catch(eError& e) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, - TSS_GetString(cTWAdmin, twadmin::STR_POL_NOT_UPDATED).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_POL_NOT_UPDATED).c_str()); return 1; } @@ -626,7 +664,8 @@ int cTWAModeCreatePol::Execute(cErrorQueue* pQueue) if (!mNoEncryption) { cTWUtil::OpenKeyFile(keyfile, mSiteKeyFile); - pPrivateKey = cTWUtil::CreatePrivateKey(keyfile, mPassPhraseProvided ? mPassPhrase.c_str() : NULL, cTWUtil::KEY_SITE); + pPrivateKey = + cTWUtil::CreatePrivateKey(keyfile, mPassPhraseProvided ? mPassPhrase.c_str() : NULL, cTWUtil::KEY_SITE); } else pPrivateKey = 0; @@ -649,23 +688,32 @@ int cTWAModeCreatePol::Execute(cErrorQueue* pQueue) } /////////////////////////////////////////////////////////////////////////////// -// cTWAModePrintCfg +// cTWAModePrintCfg class cTWAModePrintCfg : public cTWAModeCommon { public: cTWAModePrintCfg(); virtual ~cTWAModePrintCfg(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_PRINT_CONFIG; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_PRINT_CONFIG; + } private: - TSTRING mEncryptedConfig; + TSTRING mEncryptedConfig; }; cTWAModePrintCfg::cTWAModePrintCfg() @@ -680,7 +728,8 @@ void cTWAModePrintCfg::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_PRINT_CONFIG, TSTRING(_T("")), TSTRING(_T("print-cfgfile")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::MODE_PRINT_CONFIG, TSTRING(_T("")), TSTRING(_T("print-cfgfile")), cCmdLineParser::PARAM_NONE); } bool cTWAModePrintCfg::Init(const cConfigFile* cf, const cCmdLineParser& parser) //throw(eTWUTil) @@ -689,16 +738,16 @@ bool cTWAModePrintCfg::Init(const cConfigFile* cf, const cCmdLineParser& parser) FillOutCmdLineInfo(parser); mEncryptedConfig = cTWUtil::GetCfgFilePath(parser, cTWAdminCmdLine::CFG_FILE); - - // check that the config file and site key file are in sync... - // - if( ! mCfgFilePath.empty() ) - try + + // check that the config file and site key file are in sync... + // + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -714,9 +763,9 @@ int cTWAModePrintCfg::Execute(cErrorQueue* pQueue) TSTRING configText; cTWUtil::ReadConfigText(mEncryptedConfig.c_str(), configText); - // Note: I believe print config and print policy are the only time we should + // Note: I believe print config and print policy are the only time we should // print to standard out directly. - TCOUT << cDisplayEncoder::EncodeInlineAllowWS( configText ); + TCOUT << cDisplayEncoder::EncodeInlineAllowWS(configText); TCOUT << std::endl; } catch (eError& e) @@ -724,7 +773,7 @@ int cTWAModePrintCfg::Execute(cErrorQueue* pQueue) TSTRING extra; extra += TSS_GetString(cTW, tw::STR_NEWLINE); extra += TSS_GetString(cTW, tw::STR_ERR_TWCFG_CANT_READ); - cTWUtil::PrintErrorMsg(e, extra); + cTWUtil::PrintErrorMsg(e, extra); return 1; } @@ -732,20 +781,30 @@ int cTWAModePrintCfg::Execute(cErrorQueue* pQueue) } /////////////////////////////////////////////////////////////////////////////// -// cTWAModePrintPol +// cTWAModePrintPol class cTWAModePrintPol : public cTWAModeCommon { public: cTWAModePrintPol(); virtual ~cTWAModePrintPol(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_PRINT_POLICY; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_PRINT_POLICY; + } + private: }; @@ -761,8 +820,10 @@ void cTWAModePrintPol::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_PRINT_POLICY, TSTRING(_T("")), TSTRING(_T("print-polfile")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::MODE_PRINT_POLICY, TSTRING(_T("")), TSTRING(_T("print-polfile")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); } bool cTWAModePrintPol::Init(const cConfigFile* cf, const cCmdLineParser& parser) @@ -779,19 +840,23 @@ int cTWAModePrintPol::Execute(cErrorQueue* pQueue) { cKeyFile sitekey; - bool policyEncrypted = cTWUtil::IsObjectEncrypted(mPolFile.c_str(), cPolicyFile::GetFileHeaderID(), TSS_GetString( cTWAdmin, twadmin::STR_ERR2_UNABLE_TO_PRINT_POLICY ) ); + bool policyEncrypted = + cTWUtil::IsObjectEncrypted(mPolFile.c_str(), + cPolicyFile::GetFileHeaderID(), + TSS_GetString(cTWAdmin, twadmin::STR_ERR2_UNABLE_TO_PRINT_POLICY)); if (policyEncrypted) { // check that the config file and site key file are in sync... // - if( ! mCfgFilePath.empty() ) - try + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg( + eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -799,20 +864,21 @@ int cTWAModePrintPol::Execute(cErrorQueue* pQueue) cTWUtil::OpenKeyFile(sitekey, mSiteKeyFile); } - else - cTWUtil::PrintErrorMsg(eTWUtilPolUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + else + cTWUtil::PrintErrorMsg(eTWUtilPolUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); std::string policyText; - iUserNotify::GetInstance()->Notify( iUserNotify::V_VERBOSE, _T("%s%s\n"), - TSS_GetString(cTW, tw::STR_OPEN_POLICY_FILE).c_str(), - cDisplayEncoder::EncodeInline( mPolFile ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + _T("%s%s\n"), + TSS_GetString(cTW, tw::STR_OPEN_POLICY_FILE).c_str(), + cDisplayEncoder::EncodeInline(mPolFile).c_str()); cTWUtil::ReadPolicyText(mPolFile.c_str(), policyText, policyEncrypted ? sitekey.GetPublicKey() : 0); - // Note: I believe print config and print policy are the only time we should + // Note: I believe print config and print policy are the only time we should // print to standard out directly. - TCOUT << cDisplayEncoder::EncodeInlineAllowWS( cStringUtil::StrToTstr( policyText ) ); + TCOUT << cDisplayEncoder::EncodeInlineAllowWS(cStringUtil::StrToTstr(policyText)); TCOUT << std::endl; } catch (eError& e) @@ -832,24 +898,34 @@ class cTWAModeRemoveEncryption : public cTWAModeCommon public: cTWAModeRemoveEncryption(); virtual ~cTWAModeRemoveEncryption(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage () { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; + } + private: std::list mFileList; - wc16_string mSitePassphrase; - wc16_string mLocalPassphrase; - bool mSitePassphraseProvided; - bool mLocalPassphraseProvided; + wc16_string mSitePassphrase; + wc16_string mLocalPassphrase; + bool mSitePassphraseProvided; + bool mLocalPassphraseProvided; }; cTWAModeRemoveEncryption::cTWAModeRemoveEncryption() { - mSitePassphraseProvided = false; + mSitePassphraseProvided = false; mLocalPassphraseProvided = false; } @@ -861,12 +937,19 @@ void cTWAModeRemoveEncryption::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION, TSTRING(_T("")), TSTRING(_T("remove-encryption")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + parser.AddArg(cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION, + TSTRING(_T("")), + TSTRING(_T("remove-encryption")), + cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); parser.AddMutEx(cTWAdminCmdLine::KEY_FILE, cTWAdminCmdLine::LOCAL_KEY_FILE); parser.AddMutEx(cTWAdminCmdLine::KEY_FILE, cTWAdminCmdLine::LOCAL_KEY_FILE); @@ -881,41 +964,41 @@ bool cTWAModeRemoveEncryption::Init(const cConfigFile* cf, const cCmdLineParser& FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::LOCALPASSPHRASE: ASSERT(iter.NumParams() == 1); mLocalPassphraseProvided = true; - mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); break; case cTWAdminCmdLine::SITEPASSPHRASE: ASSERT(iter.NumParams() == 1); mSitePassphraseProvided = true; - mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); break; case cTWAdminCmdLine::PARAMS: for (i = 0; i < iter.NumParams(); ++i) - { + { // get full path to files TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, iter.ParamAt(i) ) ) - mFileList.push_back( strFullPath ); + if (iFSServices::GetInstance()->FullPath(strFullPath, iter.ParamAt(i))) + mFileList.push_back(strFullPath); else - mFileList.push_back( iter.ParamAt(i) ); + mFileList.push_back(iter.ParamAt(i)); } break; } } - + // check that the config file and site key file are in sync... // - if( ! mCfgFilePath.empty() ) - try + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } catch (eTWUtilCfgKeyMismatch& e) { @@ -928,15 +1011,15 @@ bool cTWAModeRemoveEncryption::Init(const cConfigFile* cf, const cCmdLineParser& int cTWAModeRemoveEncryption::Execute(cErrorQueue* pQueue) { - TSTRING keyfile; + TSTRING keyfile; cTWUtil::KeyType keyType; - bool userKnowsLocalPassphrase = false; - bool userKnowsSitePassphrase = false; + bool userKnowsLocalPassphrase = false; + bool userKnowsSitePassphrase = false; bool bResult = true; - bool firstFile = true; - bool warningGiven = false; + bool firstFile = true; + bool warningGiven = false; bool lastMsgWasError = false; // used to send the separating newline to stderr instead of stdout if (mFileList.empty()) @@ -957,170 +1040,185 @@ int cTWAModeRemoveEncryption::Execute(cErrorQueue* pQueue) TCERR << std::endl; lastMsgWasError = false; } - else + else firstFile = false; - if( cFileUtil::IsDir( i->c_str() ) ) + if (cFileUtil::IsDir(i->c_str())) { // Ignore directories for this particular operation. cTWUtil::PrintErrorMsg(eTWASkippingDirectory(*i, eError::NON_FATAL)); lastMsgWasError = true; } - else - try - { - cFileManipulator manip(i->c_str()); - manip.Init(); - - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, - _T("%s %s\n"), - TSS_GetString(cTWAdmin, twadmin::STR_EXAMINING_FILE).c_str(), - cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); - - if (NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_VERBOSE) == false) + else + try { - throw eTWAFileTypeUnknown(manip.GetFileName()); - } + cFileManipulator manip(i->c_str()); + manip.Init(); - // can't decrypt keyfiles - if (*manip.GetHeaderID() == cKeyFile::GetFileHeaderID()) - { - cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE), manip.GetFileName(), eError::NON_FATAL)); - lastMsgWasError = true; - bResult = false; - continue; - } + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s %s\n"), + TSS_GetString(cTWAdmin, twadmin::STR_EXAMINING_FILE).c_str(), + cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); - // if this is a config file, make sure its embedded key is the - // same as the provided keyfile - if (*manip.GetHeaderID() == cConfigFile::GetFileHeaderID()) - { - try + if (NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_VERBOSE) == false) { - cTWUtil::VerifyCfgSiteKey( *i, mSiteKeyFile ); + throw eTWAFileTypeUnknown(manip.GetFileName()); } - catch (eTWUtil& e) - { - e.SetSupressThird(true); - e.SetFatality(false); - cTWUtil::PrintErrorMsg(e); - - if (e.GetID() == eError::CalcHash("eTWUtilCorruptedFile")) - cTWUtil::PrintErrorMsg( eTWADecryptCorrupt( manip.GetFileName(), eError::NON_FATAL )); - else - cTWUtil::PrintErrorMsg( eTWADecrypt( manip.GetFileName(), eError::NON_FATAL )); - //cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_REMOVE_ENCRYPTION_FAILED), manip.GetFileName(), eError::NON_FATAL)); + // can't decrypt keyfiles + if (*manip.GetHeaderID() == cKeyFile::GetFileHeaderID()) + { + cTWUtil::PrintErrorMsg( + eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE), + manip.GetFileName(), + eError::NON_FATAL)); lastMsgWasError = true; - bResult = false; + bResult = false; continue; } - } - - if (cFileManipulator::UseSiteKey(*manip.GetHeaderID())) - { - keyType = cTWUtil::KEY_SITE; - keyfile = mSiteKeyFile; - } - else - { - keyType = cTWUtil::KEY_LOCAL; - keyfile = mLocalKeyFile; - } - - if (NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_VERBOSE) == false) - { - cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN), manip.GetFileName(), eError::NON_FATAL)); - lastMsgWasError = true; - bResult = false; - continue; - } - else if (manip.GetEncoding() != cFileHeader::ASYM_ENCRYPTION) - { - cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_FILE_NOT_ENCRYPED), manip.GetFileName(), eError::NON_FATAL)); - lastMsgWasError = true; - bResult = false; - continue; - } - else - { - // If we got here we have an Asymmetrically encrypted file - - // warn user about removing encryption - if (!warningGiven) - { - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_REMOVE_ENCRYPTION_WARNING).c_str()); - TCERR << std::endl; - warningGiven = true; - } - cKeyFile key; - key.ReadFile( keyfile.c_str() ); - - if (keyType == cTWUtil::KEY_LOCAL) + // if this is a config file, make sure its embedded key is the + // same as the provided keyfile + if (*manip.GetHeaderID() == cConfigFile::GetFileHeaderID()) { - if (!userKnowsLocalPassphrase) + try { - cTWUtil::CreatePrivateKey(key, mLocalPassphraseProvided ? mLocalPassphrase.c_str() : 0, keyType); // note: this throws an exception on failure - key.ReleasePrivateKey(); - if (!mLatePassphrase) // force user to enter passphrase each time - userKnowsLocalPassphrase = true; + cTWUtil::VerifyCfgSiteKey(*i, mSiteKeyFile); } - } - else if (keyType == cTWUtil::KEY_SITE) - { - if (!userKnowsSitePassphrase) + catch (eTWUtil& e) { - // Check to see if we can even use the site key to decrypt this file. - cTWUtil::CreatePrivateKey(key, mSitePassphraseProvided ? mSitePassphrase.c_str() : 0, keyType); // note: this throws an exception on failure - key.ReleasePrivateKey(); - if (!mLatePassphrase) // force user to enter passphrase each time - userKnowsSitePassphrase = true; + e.SetSupressThird(true); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + + if (e.GetID() == eError::CalcHash("eTWUtilCorruptedFile")) + cTWUtil::PrintErrorMsg(eTWADecryptCorrupt(manip.GetFileName(), eError::NON_FATAL)); + else + cTWUtil::PrintErrorMsg(eTWADecrypt(manip.GetFileName(), eError::NON_FATAL)); + + //cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_REMOVE_ENCRYPTION_FAILED), manip.GetFileName(), eError::NON_FATAL)); + lastMsgWasError = true; + bResult = false; + continue; } } - else - ASSERT(false); - try + if (cFileManipulator::UseSiteKey(*manip.GetHeaderID())) { - manip.ChangeEncryption(key.GetPublicKey(), NULL, false); + keyType = cTWUtil::KEY_SITE; + keyfile = mSiteKeyFile; } - catch(eError& e) + else { - // Let the user know the decryption failed - e.SetSupressThird( true ); - e.SetFatality( false ); - cTWUtil::PrintErrorMsg( e ); - - if (e.GetID() == eError::CalcHash("eArchiveCrypto")) - cTWUtil::PrintErrorMsg( eTWADecryptCorrupt( manip.GetFileName(), eError::NON_FATAL )); - else - cTWUtil::PrintErrorMsg( eTWADecrypt( manip.GetFileName(), eError::NON_FATAL )); + keyType = cTWUtil::KEY_LOCAL; + keyfile = mLocalKeyFile; + } + if (NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_VERBOSE) == false) + { + cTWUtil::PrintErrorMsg( + eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN), + manip.GetFileName(), + eError::NON_FATAL)); lastMsgWasError = true; - bResult = false; + bResult = false; continue; } + else if (manip.GetEncoding() != cFileHeader::ASYM_ENCRYPTION) + { + cTWUtil::PrintErrorMsg( + eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_FILE_NOT_ENCRYPED), + manip.GetFileName(), + eError::NON_FATAL)); + lastMsgWasError = true; + bResult = false; + continue; + } + else + { + // If we got here we have an Asymmetrically encrypted file + + // warn user about removing encryption + if (!warningGiven) + { + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, + TSS_GetString(cTWAdmin, twadmin::STR_REMOVE_ENCRYPTION_WARNING).c_str()); + TCERR << std::endl; + warningGiven = true; + } + + cKeyFile key; + key.ReadFile(keyfile.c_str()); + + if (keyType == cTWUtil::KEY_LOCAL) + { + if (!userKnowsLocalPassphrase) + { + cTWUtil::CreatePrivateKey(key, + mLocalPassphraseProvided ? mLocalPassphrase.c_str() : 0, + keyType); // note: this throws an exception on failure + key.ReleasePrivateKey(); + if (!mLatePassphrase) // force user to enter passphrase each time + userKnowsLocalPassphrase = true; + } + } + else if (keyType == cTWUtil::KEY_SITE) + { + if (!userKnowsSitePassphrase) + { + // Check to see if we can even use the site key to decrypt this file. + cTWUtil::CreatePrivateKey(key, + mSitePassphraseProvided ? mSitePassphrase.c_str() : 0, + keyType); // note: this throws an exception on failure + key.ReleasePrivateKey(); + if (!mLatePassphrase) // force user to enter passphrase each time + userKnowsSitePassphrase = true; + } + } + else + ASSERT(false); + + try + { + manip.ChangeEncryption(key.GetPublicKey(), NULL, false); + } + catch (eError& e) + { + // Let the user know the decryption failed + e.SetSupressThird(true); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + + if (e.GetID() == eError::CalcHash("eArchiveCrypto")) + cTWUtil::PrintErrorMsg(eTWADecryptCorrupt(manip.GetFileName(), eError::NON_FATAL)); + else + cTWUtil::PrintErrorMsg(eTWADecrypt(manip.GetFileName(), eError::NON_FATAL)); + + lastMsgWasError = true; + bResult = false; + continue; + } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, - TSS_GetString(cTWAdmin, twadmin::STR_ENCRYPTION_REMOVED).c_str(), - cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + TSS_GetString(cTWAdmin, twadmin::STR_ENCRYPTION_REMOVED).c_str(), + cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); + } + } + catch (eFileManip& e) + { + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + lastMsgWasError = true; + bResult = false; + } + catch (eArchive& e) + { + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + lastMsgWasError = true; + bResult = false; } - } - catch (eFileManip& e) - { - e.SetFatality(false); - cTWUtil::PrintErrorMsg(e); - lastMsgWasError = true; - bResult = false; - } - catch (eArchive& e) - { - e.SetFatality(false); - cTWUtil::PrintErrorMsg(e); - lastMsgWasError = true; - bResult = false; - } } return bResult == false; @@ -1134,27 +1232,37 @@ class cTWAModeEncrypt : public cTWAModeCommon public: cTWAModeEncrypt(); virtual ~cTWAModeEncrypt(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; + } + private: std::list mFileList; - wc16_string mSitePassphrase; - wc16_string mLocalPassphrase; - bool mSitePassphraseProvided; - bool mLocalPassphraseProvided; - bool mbLatePassphrase; + wc16_string mSitePassphrase; + wc16_string mLocalPassphrase; + bool mSitePassphraseProvided; + bool mLocalPassphraseProvided; + bool mbLatePassphrase; }; cTWAModeEncrypt::cTWAModeEncrypt() { - mSitePassphraseProvided = false; + mSitePassphraseProvided = false; mLocalPassphraseProvided = false; - mbLatePassphrase = false; + mbLatePassphrase = false; } cTWAModeEncrypt::~cTWAModeEncrypt() @@ -1165,12 +1273,16 @@ void cTWAModeEncrypt::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_ENCRYPT, TSTRING(_T("")), TSTRING(_T("encrypt")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + parser.AddArg(cTWAdminCmdLine::MODE_ENCRYPT, TSTRING(_T("")), TSTRING(_T("encrypt")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); } bool cTWAModeEncrypt::Init(const cConfigFile* cf, const cCmdLineParser& parser) @@ -1180,52 +1292,52 @@ bool cTWAModeEncrypt::Init(const cConfigFile* cf, const cCmdLineParser& parser) FillOutConfigInfo(cf); TSTRING str; - if(cf->Lookup(TSTRING(_T("LATEPROMPTING")), str)) + if (cf->Lookup(TSTRING(_T("LATEPROMPTING")), str)) { if (_tcsicmp(str.c_str(), _T("true")) == 0) - mbLatePassphrase = true; + mbLatePassphrase = true; } FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::PARAMS: for (i = 0; i < iter.NumParams(); ++i) { TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, iter.ParamAt(i) ) ) - mFileList.push_back( strFullPath ); + if (iFSServices::GetInstance()->FullPath(strFullPath, iter.ParamAt(i))) + mFileList.push_back(strFullPath); else - mFileList.push_back( iter.ParamAt(i) ); + mFileList.push_back(iter.ParamAt(i)); } break; case cTWAdminCmdLine::LOCALPASSPHRASE: ASSERT(iter.NumParams() == 1); mLocalPassphraseProvided = true; - mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); break; case cTWAdminCmdLine::SITEPASSPHRASE: ASSERT(iter.NumParams() == 1); mSitePassphraseProvided = true; - mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); + mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); break; } } - + // check that the config file and site key file are in sync... // - if( ! mCfgFilePath.empty() ) - try + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -1245,16 +1357,16 @@ int cTWAModeEncrypt::Execute(cErrorQueue* pQueue) return 1; } - bool bResult = true; + bool bResult = true; std::list::iterator i; - // We cycle through all the files twice. This first time we + // We cycle through all the files twice. This first time we // check for file validity and open any keyfiles needed. for (i = mFileList.begin(); i != mFileList.end(); /* incrementing done below...*/) { try { - if( cFileUtil::IsDir( i->c_str() ) ) + if (cFileUtil::IsDir(i->c_str())) { // Ignore directories for this particular operation. // Note: We don't throw here because we don't want to set bResult to false @@ -1275,7 +1387,9 @@ int cTWAModeEncrypt::Execute(cErrorQueue* pQueue) // can't encrypt keyfiles if (*manip.GetHeaderID() == cKeyFile::GetFileHeaderID()) { - throw eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE), manip.GetFileName(), eError::NON_FATAL); + throw eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE), + manip.GetFileName(), + eError::NON_FATAL); } if (cFileManipulator::UseSiteKey(*manip.GetHeaderID())) @@ -1299,16 +1413,16 @@ int cTWAModeEncrypt::Execute(cErrorQueue* pQueue) TCERR << std::endl; // extra newline to separate filenames // erase this file so that it is skipped in the next round - i = mFileList.erase(i); + i = mFileList.erase(i); bResult = false; continue; } } - - // On this second pass we go through and convert all files + + // On this second pass we go through and convert all files for (i = mFileList.begin(); i != mFileList.end(); ++i) { - if( cFileUtil::IsDir( i->c_str() ) ) + if (cFileUtil::IsDir(i->c_str())) { // Ignore directories for this particular operation. } @@ -1318,83 +1432,96 @@ int cTWAModeEncrypt::Execute(cErrorQueue* pQueue) bResult = false; } else - try - { - cFileManipulator manip(i->c_str()); - manip.Init(); - - if (*manip.GetHeaderID() == cKeyFile::GetFileHeaderID()) - { - continue; - } - - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, - _T("%s %s\n"), - TSS_GetString(cTWAdmin, twadmin::STR_EXAMINING_FILE).c_str(), - cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); - - if (NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_VERBOSE) == false) - { - cTWUtil::PrintErrorMsg(eTWAFileTypeUnknown(manip.GetFileName(), eError::NON_FATAL)); - TCERR << std::endl; // extra newline to separate filenames - bResult = false; - } - - if (NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_VERBOSE) == false) + try { - cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN), manip.GetFileName(), eError::NON_FATAL)); - TCERR << std::endl; // extra newline to separate filenames - bResult = false; - } - else if (manip.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) - { - cTWUtil::PrintErrorMsg(eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_FILE_ALREADY_ENCRYPTED), manip.GetFileName(), eError::NON_FATAL)); - TCERR << std::endl; // extra newline to separate filenames - bResult = false; - } - else - { - cPrivateKeyProxy* pPrivateKey; + cFileManipulator manip(i->c_str()); + manip.Init(); - if (cFileManipulator::UseSiteKey(*manip.GetHeaderID())) + if (*manip.GetHeaderID() == cKeyFile::GetFileHeaderID()) { - if (mbLatePassphrase || !siteKey.Valid()) - cTWUtil::CreatePrivateKey(siteKey, siteKeyFile, mSitePassphraseProvided ? mSitePassphrase.c_str() : 0, cTWUtil::KEY_SITE); - - pPrivateKey = &siteKey; + continue; } - else - { - if (mbLatePassphrase || !localKey.Valid()) - cTWUtil::CreatePrivateKey(localKey, localKeyFile, mLocalPassphraseProvided ? mLocalPassphrase.c_str() : 0, cTWUtil::KEY_LOCAL); - pPrivateKey = &localKey; + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + _T("%s %s\n"), + TSS_GetString(cTWAdmin, twadmin::STR_EXAMINING_FILE).c_str(), + cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); + + if (NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_VERBOSE) == false) + { + cTWUtil::PrintErrorMsg(eTWAFileTypeUnknown(manip.GetFileName(), eError::NON_FATAL)); + TCERR << std::endl; // extra newline to separate filenames + bResult = false; } - try + if (NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_VERBOSE) == false) { - manip.ChangeEncryption(NULL, pPrivateKey->GetKey(), false); - - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, - TSS_GetString(cTWAdmin, twadmin::STR_ENCRYPTION_SUCCEEDED).c_str(), - cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, - TSS_GetString(cTW, tw::STR_NEWLINE).c_str(), - cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); + cTWUtil::PrintErrorMsg( + eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN), + manip.GetFileName(), + eError::NON_FATAL)); + TCERR << std::endl; // extra newline to separate filenames + bResult = false; } - catch (eFileManip& e) + else if (manip.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { - cTWUtil::PrintErrorMsg(e); + cTWUtil::PrintErrorMsg( + eTWAEncryptionChange(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_FILE_ALREADY_ENCRYPTED), + manip.GetFileName(), + eError::NON_FATAL)); TCERR << std::endl; // extra newline to separate filenames bResult = false; } + else + { + cPrivateKeyProxy* pPrivateKey; + + if (cFileManipulator::UseSiteKey(*manip.GetHeaderID())) + { + if (mbLatePassphrase || !siteKey.Valid()) + cTWUtil::CreatePrivateKey(siteKey, + siteKeyFile, + mSitePassphraseProvided ? mSitePassphrase.c_str() : 0, + cTWUtil::KEY_SITE); + + pPrivateKey = &siteKey; + } + else + { + if (mbLatePassphrase || !localKey.Valid()) + cTWUtil::CreatePrivateKey(localKey, + localKeyFile, + mLocalPassphraseProvided ? mLocalPassphrase.c_str() : 0, + cTWUtil::KEY_LOCAL); + + pPrivateKey = &localKey; + } + + try + { + manip.ChangeEncryption(NULL, pPrivateKey->GetKey(), false); + + iUserNotify::GetInstance()->Notify( + iUserNotify::V_VERBOSE, + TSS_GetString(cTWAdmin, twadmin::STR_ENCRYPTION_SUCCEEDED).c_str(), + cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTW, tw::STR_NEWLINE).c_str(), + cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); + } + catch (eFileManip& e) + { + cTWUtil::PrintErrorMsg(e); + TCERR << std::endl; // extra newline to separate filenames + bResult = false; + } + } + } + catch (eFileManip&) + { + continue; } - } - catch (eFileManip&) - { - continue; - } } return bResult == false; @@ -1408,13 +1535,23 @@ class cTWAModeExamine : public cTWAModeCommon public: cTWAModeExamine(); virtual ~cTWAModeExamine(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE ); } - virtual bool LoadConfigFile() { return true; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE); + } + virtual bool LoadConfigFile() + { + return true; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION; + } + private: std::list mFileList; }; @@ -1431,10 +1568,12 @@ void cTWAModeExamine::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_EXAMINE, TSTRING(_T("")), TSTRING(_T("examine")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + parser.AddArg(cTWAdminCmdLine::MODE_EXAMINE, TSTRING(_T("")), TSTRING(_T("examine")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); } bool cTWAModeExamine::Init(const cConfigFile* cf, const cCmdLineParser& parser) @@ -1445,18 +1584,18 @@ bool cTWAModeExamine::Init(const cConfigFile* cf, const cCmdLineParser& parser) FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::PARAMS: for (i = 0; i < iter.NumParams(); ++i) { TSTRING strFullPath; - if( iFSServices::GetInstance()->FullPath( strFullPath, iter.ParamAt(i) ) ) - mFileList.push_back( strFullPath ); + if (iFSServices::GetInstance()->FullPath(strFullPath, iter.ParamAt(i))) + mFileList.push_back(strFullPath); else - mFileList.push_back( iter.ParamAt(i) ); + mFileList.push_back(iter.ParamAt(i)); } break; } @@ -1464,13 +1603,13 @@ bool cTWAModeExamine::Init(const cConfigFile* cf, const cCmdLineParser& parser) // check that the config file and site key file are in sync... // - if( ! mCfgFilePath.empty() ) - try + if (!mCfgFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mCfgFilePath, mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mCfgFilePath, mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -1501,7 +1640,7 @@ int cTWAModeExamine::Execute(cErrorQueue* pQueue) cTWUtil::PrintErrorMsg(e); bResult = false; } - catch (eError&) + catch (eError&) { } @@ -1515,7 +1654,7 @@ int cTWAModeExamine::Execute(cErrorQueue* pQueue) cTWUtil::PrintErrorMsg(e); bResult = false; } - catch (eError&) + catch (eError&) { } @@ -1523,7 +1662,7 @@ int cTWAModeExamine::Execute(cErrorQueue* pQueue) std::list::iterator i; for (i = mFileList.begin(); i != mFileList.end(); ++i) { - if( cFileUtil::IsDir(i->c_str())) + if (cFileUtil::IsDir(i->c_str())) { //Ignore directories in examine encryption mode. cTWUtil::PrintErrorMsg(eTWASkippingDirectory(*i, eError::NON_FATAL)); @@ -1537,102 +1676,139 @@ int cTWAModeExamine::Execute(cErrorQueue* pQueue) bResult = false; } else - try - { - cFileManipulator manip(i->c_str()); - manip.Init(); - - // print out: "File: filename.ext" - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_FILE).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), cDisplayEncoder::EncodeInline( manip.GetFileName() ).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_ENDQUOTE_NEWLINE).c_str()); - - NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_NORMAL); - NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_NORMAL); - - // Try different keys to see if they decrypt this file - if (manip.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) + try { - // Output the keys that decrypt the file. - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_KEYS_DECRYPT ).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTW, tw::STR_NEWLINE ).c_str()); - - bool siteDecrypts = false, localDecrypts = false; - - if (siteKey.KeysLoaded()) - try + cFileManipulator manip(i->c_str()); + manip.Init(); + + // print out: "File: filename.ext" + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cTWAdmin, twadmin::STR_FILE).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), cDisplayEncoder::EncodeInline(manip.GetFileName()).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cTWAdmin, twadmin::STR_ENDQUOTE_NEWLINE).c_str()); + + NotifyFileType(*manip.GetHeaderID(), manip.GetFileVersion(), iUserNotify::V_NORMAL); + NotifyEncryptionType(manip.GetEncoding(), iUserNotify::V_NORMAL); + + // Try different keys to see if they decrypt this file + if (manip.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { - if (manip.TestDecryption(*siteKey.GetPublicKey(), false) != false) + bool bFound = false; + + // Output the keys that decrypt the file. + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_KEYS_DECRYPT).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); + + if (siteKey.KeysLoaded()) + try + { + if (manip.TestDecryption(*siteKey.GetPublicKey(), false) != false) + { + bFound = true; + + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_SITEKEYFILE).c_str()); + + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + cDisplayEncoder::EncodeInline(mSiteKeyFile).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); + } + } + catch (eError&) + { + } + + if (localKey.KeysLoaded()) + try + { + if (manip.TestDecryption(*localKey.GetPublicKey(), false) != false) + { + bFound = true; + + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_LOCALKEYFILE).c_str()); + + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, cDisplayEncoder::EncodeInline(mLocalKeyFile).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); + } + } + catch (eError&) + { + } + + if (!bFound) { - siteDecrypts = true; - - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_SITEKEYFILE ).c_str()); - - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, cDisplayEncoder::EncodeInline( mSiteKeyFile ).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE ).c_str()); + bResult = false; + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, "\t"); + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cCore, core::STR_UNKNOWN).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, + TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); } } - catch (eError&) {} - - if (localKey.KeysLoaded()) - try - { - if (manip.TestDecryption(*localKey.GetPublicKey(), false) != false) - { - localDecrypts = true; - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTWAdmin, twadmin::STR_LOCALKEYFILE ).c_str()); - - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, cDisplayEncoder::EncodeInline( mLocalKeyFile ).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE ).c_str()); - } - } - catch (eError&) {} + TCOUT << std::endl; + } + catch (eFileManip& e) + { + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + TCERR << std::endl; + bResult = false; } - TCOUT << std::endl; - } - catch (eFileManip& e) - { - e.SetFatality(false); - cTWUtil::PrintErrorMsg(e); - TCERR << std::endl; - bResult = false; - } } return bResult == false; } /////////////////////////////////////////////////////////////////////////////// -// cTWAModeGenerateKeys +// cTWAModeGenerateKeys class cTWAModeGenerateKeys : public cTWAModeCommon { public: cTWAModeGenerateKeys(); virtual ~cTWAModeGenerateKeys(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS ); } - virtual bool LoadConfigFile() { return false; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_GENERATE_KEYS; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS); + } + virtual bool LoadConfigFile() + { + return false; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_GENERATE_KEYS; + } private: - bool mSiteProvided; // A site passphrase has been passed. - wc16_string mSitePassphrase; - bool mLocalProvided; // A local passphrase has been passed. - wc16_string mLocalPassphrase; - bool mGenerateSite; // A Site key has been specified. - bool mGenerateLocal; // A Local key has been specified. + bool mSiteProvided; // A site passphrase has been passed. + wc16_string mSitePassphrase; + bool mLocalProvided; // A local passphrase has been passed. + wc16_string mLocalPassphrase; + bool mGenerateSite; // A Site key has been specified. + bool mGenerateLocal; // A Local key has been specified. + cElGamalSig::KeySize mKeySize; }; cTWAModeGenerateKeys::cTWAModeGenerateKeys() { mLocalProvided = false; - mSiteProvided = false; - mGenerateSite = false; + mSiteProvided = false; + mGenerateSite = false; mGenerateLocal = false; + mKeySize = cElGamalSig::KEY1024; } cTWAModeGenerateKeys::~cTWAModeGenerateKeys() @@ -1643,11 +1819,17 @@ void cTWAModeGenerateKeys::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_GENERATE_KEYS, TSTRING(_T("")), TSTRING(_T("generate-keys")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::MODE_GENERATE_KEYS, TSTRING(_T("")), TSTRING(_T("generate-keys")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::KEY_SIZE, TSTRING(_T("K")), TSTRING(_T("key-size")), cCmdLineParser::PARAM_ONE); } bool cTWAModeGenerateKeys::Init(const cConfigFile* cf, const cCmdLineParser& parser) @@ -1659,19 +1841,19 @@ bool cTWAModeGenerateKeys::Init(const cConfigFile* cf, const cCmdLineParser& par FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::SITEPASSPHRASE: ASSERT(iter.NumParams() == 1); mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mSiteProvided = true; + mSiteProvided = true; break; case cTWAdminCmdLine::LOCALPASSPHRASE: ASSERT(iter.NumParams() == 1); mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mLocalProvided = true; + mLocalProvided = true; break; case cTWAdminCmdLine::SITE_KEY_FILE: mGenerateSite = true; @@ -1679,11 +1861,19 @@ bool cTWAModeGenerateKeys::Init(const cConfigFile* cf, const cCmdLineParser& par case cTWAdminCmdLine::LOCAL_KEY_FILE: mGenerateLocal = true; break; + case cTWAdminCmdLine::KEY_SIZE: + if (iter.ParamAt(0) == "2048") + mKeySize = cElGamalSig::KEY2048; + else if (iter.ParamAt(0) == "1024") + mKeySize = cElGamalSig::KEY1024; + else + throw eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_INVALID_KEY_SIZE)); + break; } } if (mSiteProvided || mLocalProvided) - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_PASSPHRASES).c_str()); return true; @@ -1699,10 +1889,9 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) return 1; } - if ((mGenerateSite && mSiteKeyFile.empty()) || - (mGenerateLocal && mLocalKeyFile.empty())) + if ((mGenerateSite && mSiteKeyFile.empty()) || (mGenerateLocal && mLocalKeyFile.empty())) { - // This case should not occur (it should be caught by Init() logic), but in case it does we will spit out + // This case should not occur (it should be caught by Init() logic), but in case it does we will spit out // a generic error string. ASSERT(false); cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYS_NOT_SPECIFIED))); @@ -1721,7 +1910,7 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) return 1; } - if( (mSiteProvided && !mGenerateSite) || (mLocalProvided && !mGenerateLocal) ) + if ((mSiteProvided && !mGenerateSite) || (mLocalProvided && !mGenerateLocal)) { //This is an error, a passphrase should not be specified if the corresponding key has not been passed. cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_PASSPHRASE_NOKEY))); @@ -1738,7 +1927,7 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) { TSTRING prompt; prompt += TSS_GetString(cTWAdmin, twadmin::STR_SITEKEY_EXISTS_1); - prompt += cDisplayEncoder::EncodeInline( mSiteKeyFile ); + prompt += cDisplayEncoder::EncodeInline(mSiteKeyFile); prompt += TSS_GetString(cTWAdmin, twadmin::STR_SITEKEY_EXISTS_2); if (cTWUtil::ConfirmYN(prompt.c_str()) == false) @@ -1749,7 +1938,7 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) { TSTRING prompt; prompt += TSS_GetString(cTWAdmin, twadmin::STR_LOCALKEY_EXISTS_1); - prompt += cDisplayEncoder::EncodeInline( mLocalKeyFile ); + prompt += cDisplayEncoder::EncodeInline(mLocalKeyFile); prompt += TSS_GetString(cTWAdmin, twadmin::STR_LOCALKEY_EXISTS_2); if (cTWUtil::ConfirmYN(prompt.c_str()) == false) @@ -1759,9 +1948,9 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) // // make sure that we can write to both of the files before we continue // - if(mGenerateLocal) + if (mGenerateLocal) cFileUtil::TestFileWritable(mLocalKeyFile); - if(mGenerateSite) + if (mGenerateSite) cFileUtil::TestFileWritable(mSiteKeyFile); wc16_string verify; @@ -1774,16 +1963,17 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) { // give the user a passphrase hint... // - if(! bPrintedPassphraseHint) + if (!bPrintedPassphraseHint) { bPrintedPassphraseHint = true; - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str()); } - for (i=1; ; i++) + for (i = 1;; i++) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_SITE_PASS); cTWUtil::GetString(mSitePassphrase); @@ -1792,8 +1982,8 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_VERIFY_SITE_PASS); cTWUtil::GetString(verify); TCOUT << TSS_GetString(cTW, tw::STR_NEWLINE); - - if ( 0 == verify.compare( mSitePassphrase ) ) + + if (0 == verify.compare(mSitePassphrase)) break; TCOUT << TSS_GetString(cTW, tw::STR_ERR_WRONG_PASSPHRASE_SITE) << std::endl; @@ -1803,14 +1993,14 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) } } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_SITEKEY).c_str(), - cDisplayEncoder::EncodeInline( mSiteKeyFile ).c_str()); + cDisplayEncoder::EncodeInline(mSiteKeyFile).c_str()); // backup current file if it exists cFileUtil::BackupFile(mSiteKeyFile); - if (GenerateKey(mSiteKeyFile.c_str(), mSitePassphrase) == false) + if (GenerateKey(mSiteKeyFile.c_str(), mSitePassphrase, mKeySize) == false) return 1; } @@ -1820,16 +2010,16 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) { // give the user a passphrase hint... // - if(! bPrintedPassphraseHint) + if (!bPrintedPassphraseHint) { - bPrintedPassphraseHint = true; - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str()); } - - for (i=1; ; i++) + + for (i = 1;; i++) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_LOCAL_PASS); cTWUtil::GetString(mLocalPassphrase); @@ -1839,7 +2029,7 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) cTWUtil::GetString(verify); TCOUT << TSS_GetString(cTW, tw::STR_NEWLINE); - if ( 0 == verify.compare( mLocalPassphrase ) ) + if (0 == verify.compare(mLocalPassphrase)) break; TCOUT << TSS_GetString(cTW, tw::STR_ERR_WRONG_PASSPHRASE_LOCAL) << std::endl; @@ -1849,14 +2039,14 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) } } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, - TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_LOCALKEY).c_str(), - cDisplayEncoder::EncodeInline( mLocalKeyFile ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_LOCALKEY).c_str(), + cDisplayEncoder::EncodeInline(mLocalKeyFile).c_str()); // backup current file if it exists cFileUtil::BackupFile(mLocalKeyFile); - if (GenerateKey(mLocalKeyFile.c_str(), mLocalPassphrase) == false) + if (GenerateKey(mLocalKeyFile.c_str(), mLocalPassphrase, mKeySize) == false) return 1; } @@ -1864,44 +2054,42 @@ int cTWAModeGenerateKeys::Execute(cErrorQueue* pQueue) } /////////////////////////////////////////////////////////////////////////////// -// cTWAModeChangePassphrases +// cTWAModeChangePassphrases -static bool ChangePassphrase( - const TCHAR* keyPath, wc16_string passphraseOld, wc16_string passphrase) +static bool ChangePassphrase(const TCHAR* keyPath, wc16_string passphraseOld, wc16_string passphrase) { // in order to leave original password data intact upon return, // we must allocate a BIGENDIAN copy // and delete it before we return. // auto_ptr does not help (won't work with arrays). - size_t passphraseLenOld = passphraseOld.length() * sizeof(WCHAR16); - size_t passphraseLen = passphrase .length() * sizeof(WCHAR16); - int8 * passphraseCopyOld = new int8[passphraseLenOld]; - int8 * passphraseCopy = new int8[passphraseLen]; + size_t passphraseLenOld = passphraseOld.length() * sizeof(WCHAR16); + size_t passphraseLen = passphrase.length() * sizeof(WCHAR16); + int8* passphraseCopyOld = new int8[passphraseLenOld]; + int8* passphraseCopy = new int8[passphraseLen]; #ifdef WORDS_BIGENDIAN - memcpy(passphraseCopyOld, passphraseOld.data(), passphraseLenOld); - memcpy(passphraseCopy, passphrase .data(), passphraseLen); + memcpy(passphraseCopyOld, passphraseOld.data(), passphraseLenOld); + memcpy(passphraseCopy, passphrase.data(), passphraseLen); #else - swab(passphraseOld.data(), passphraseCopyOld, passphraseLenOld); - swab(passphrase .data(), passphraseCopy, passphraseLen); + swab(passphraseOld.data(), passphraseCopyOld, passphraseLenOld); + swab(passphrase.data(), passphraseCopy, passphraseLen); #endif bool result; - try { + try + { cKeyFile keyfile; keyfile.ReadFile(keyPath); - keyfile.ChangePassphrase( - passphraseCopyOld, passphraseLenOld, - passphraseCopy, passphraseLen); + keyfile.ChangePassphrase(passphraseCopyOld, passphraseLenOld, passphraseCopy, passphraseLen); keyfile.WriteFile(keyPath); result = true; } - catch (eKeyFile & e) + catch (eKeyFile& e) { cTWUtil::PrintErrorMsg(e); result = false; } - delete[] passphraseCopyOld; - delete[] passphraseCopy; + delete [] passphraseCopyOld; + delete [] passphraseCopy; return result; } @@ -1910,35 +2098,44 @@ class cTWAModeChangePassphrases : public cTWAModeCommon public: cTWAModeChangePassphrases(); virtual ~cTWAModeChangePassphrases(); - + virtual void InitCmdLineParser(cCmdLineParser& parser); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& parser); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES ); } - virtual bool LoadConfigFile() { return false; } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES; } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& parser); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES); + } + virtual bool LoadConfigFile() + { + return false; + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES; + } private: - bool mSiteProvidedOld; // A site passphrase-old has been passed. + bool mSiteProvidedOld; // A site passphrase-old has been passed. wc16_string mSitePassphraseOld; - bool mLocalProvidedOld; // A local passphrase-old has been passed. + bool mLocalProvidedOld; // A local passphrase-old has been passed. wc16_string mLocalPassphraseOld; - bool mSiteProvided; // A site passphrase has been passed. + bool mSiteProvided; // A site passphrase has been passed. wc16_string mSitePassphrase; bool mLocalProvided; // A local passphrase has been passed. wc16_string mLocalPassphrase; - bool mChangeSite; // A Site key has been specified. - bool mChangeLocal; // A Local key has been specified. + bool mChangeSite; // A Site key has been specified. + bool mChangeLocal; // A Local key has been specified. }; cTWAModeChangePassphrases::cTWAModeChangePassphrases() { mLocalProvidedOld = false; - mSiteProvidedOld = false; - mLocalProvided = false; - mSiteProvided = false; - mChangeSite = false; - mChangeLocal = false; + mSiteProvidedOld = false; + mLocalProvided = false; + mSiteProvided = false; + mChangeSite = false; + mChangeLocal = false; } cTWAModeChangePassphrases::~cTWAModeChangePassphrases() @@ -1949,13 +2146,26 @@ void cTWAModeChangePassphrases::InitCmdLineParser(cCmdLineParser& parser) { InitCmdLineCommon(parser); - parser.AddArg(cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES,TSTRING(_T("")), TSTRING(_T("change-passphrases")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASEOLD, TSTRING(_T("")), TSTRING(_T("site-passphrase-old")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASEOLD, TSTRING(_T("")), TSTRING(_T("local-passphrase-old")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES, + TSTRING(_T("")), + TSTRING(_T("change-passphrases")), + cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWAdminCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::SITEPASSPHRASE, TSTRING(_T("Q")), TSTRING(_T("site-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWAdminCmdLine::LOCALPASSPHRASE, TSTRING(_T("P")), TSTRING(_T("local-passphrase")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::SITEPASSPHRASEOLD, + TSTRING(_T("")), + TSTRING(_T("site-passphrase-old")), + cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWAdminCmdLine::LOCALPASSPHRASEOLD, + TSTRING(_T("")), + TSTRING(_T("local-passphrase-old")), + cCmdLineParser::PARAM_ONE); } bool cTWAModeChangePassphrases::Init(const cConfigFile* cf, const cCmdLineParser& parser) @@ -1967,29 +2177,29 @@ bool cTWAModeChangePassphrases::Init(const cConfigFile* cf, const cCmdLineParser FillOutCmdLineInfo(parser); cCmdLineIter iter(parser); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { case cTWAdminCmdLine::SITEPASSPHRASE: ASSERT(iter.NumParams() == 1); mSitePassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mSiteProvided = true; + mSiteProvided = true; break; case cTWAdminCmdLine::LOCALPASSPHRASE: ASSERT(iter.NumParams() == 1); mLocalPassphrase = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mLocalProvided = true; + mLocalProvided = true; break; case cTWAdminCmdLine::SITEPASSPHRASEOLD: ASSERT(iter.NumParams() == 1); mSitePassphraseOld = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mSiteProvidedOld = true; + mSiteProvidedOld = true; break; case cTWAdminCmdLine::LOCALPASSPHRASEOLD: ASSERT(iter.NumParams() == 1); mLocalPassphraseOld = cStringUtil::TstrToWstr(iter.ParamAt(0)); - mLocalProvidedOld = true; + mLocalProvidedOld = true; break; case cTWAdminCmdLine::SITE_KEY_FILE: mChangeSite = true; @@ -2001,7 +2211,7 @@ bool cTWAModeChangePassphrases::Init(const cConfigFile* cf, const cCmdLineParser } if ((mSiteProvidedOld && mSiteProvided) || (mLocalProvidedOld && mLocalProvided)) - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_PASSPHRASES).c_str()); return true; @@ -2009,9 +2219,9 @@ bool cTWAModeChangePassphrases::Init(const cConfigFile* cf, const cCmdLineParser int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) { - int i; - bool bSiteProvided = mSiteProvided || mSiteProvidedOld; - bool bLocalProvided = mLocalProvided || mLocalProvidedOld; + int i; + bool bSiteProvided = mSiteProvided || mSiteProvidedOld; + bool bLocalProvided = mLocalProvided || mLocalProvidedOld; if (!mChangeSite && !mChangeLocal) { @@ -2019,10 +2229,9 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) return 1; } - if ((mChangeSite && mSiteKeyFile.empty()) || - (mChangeLocal && mLocalKeyFile.empty())) + if ((mChangeSite && mSiteKeyFile.empty()) || (mChangeLocal && mLocalKeyFile.empty())) { - // This case should not occur (it should be caught by Init() logic), but in case it does we will spit out + // This case should not occur (it should be caught by Init() logic), but in case it does we will spit out // a generic error string. ASSERT(false); cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_KEYS_NOT_SPECIFIED))); @@ -2041,7 +2250,7 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) return 1; } - if( (bSiteProvided && !mChangeSite) || (bLocalProvided && !mChangeLocal) ) + if ((bSiteProvided && !mChangeSite) || (bLocalProvided && !mChangeLocal)) { //This is an error, a passphrase should not be specified if the corresponding key has not been passed. cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTWAdmin, twadmin::STR_ERR2_PASSPHRASE_NOKEY))); @@ -2069,9 +2278,9 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) // // make sure that we can write to both of the files before we continue // - if(mChangeLocal) + if (mChangeLocal) cFileUtil::TestFileWritable(mLocalKeyFile); - if(mChangeSite) + if (mChangeSite) cFileUtil::TestFileWritable(mSiteKeyFile); wc16_string verify; @@ -2083,7 +2292,7 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) if (!mSiteProvidedOld) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_SITE_PASS_OLD); cTWUtil::GetString(mSitePassphraseOld); @@ -2093,16 +2302,17 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) { // give the user a passphrase hint... // - if(! bPrintedPassphraseHint) + if (!bPrintedPassphraseHint) { bPrintedPassphraseHint = true; - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str()); } - for (i=1; ; i++) + for (i = 1;; i++) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_SITE_PASS); cTWUtil::GetString(mSitePassphrase); @@ -2111,8 +2321,8 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_VERIFY_SITE_PASS); cTWUtil::GetString(verify); TCOUT << TSS_GetString(cTW, tw::STR_NEWLINE); - - if ( 0 == verify.compare( mSitePassphrase ) ) + + if (0 == verify.compare(mSitePassphrase)) break; TCOUT << TSS_GetString(cTW, tw::STR_ERR_WRONG_PASSPHRASE_SITE) << std::endl; @@ -2122,9 +2332,9 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) } } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_SITEKEY).c_str(), - cDisplayEncoder::EncodeInline( mSiteKeyFile ).c_str()); + cDisplayEncoder::EncodeInline(mSiteKeyFile).c_str()); // backup current file if it exists cFileUtil::BackupFile(mSiteKeyFile); @@ -2138,7 +2348,7 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) if (!mLocalProvidedOld) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_LOCAL_PASS_OLD); cTWUtil::GetString(mLocalPassphraseOld); @@ -2148,16 +2358,16 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) { // give the user a passphrase hint... // - if(! bPrintedPassphraseHint) + if (!bPrintedPassphraseHint) { - bPrintedPassphraseHint = true; - iUserNotify::GetInstance()->Notify( iUserNotify::V_NORMAL, TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str() ); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTWAdmin, twadmin::STR_PASSPHRASE_HINT).c_str()); } - - for (i=1; ; i++) + + for (i = 1;; i++) { cTWUtil::NoEcho noEcho; - // Note: Since we are interacting directly with the user here, + // Note: Since we are interacting directly with the user here, // I think it is o.k. to use cout directly. TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_ENTER_LOCAL_PASS); cTWUtil::GetString(mLocalPassphrase); @@ -2167,7 +2377,7 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) cTWUtil::GetString(verify); TCOUT << TSS_GetString(cTW, tw::STR_NEWLINE); - if ( 0 == verify.compare( mLocalPassphrase ) ) + if (0 == verify.compare(mLocalPassphrase)) break; TCOUT << TSS_GetString(cTW, tw::STR_ERR_WRONG_PASSPHRASE_LOCAL) << std::endl; @@ -2177,9 +2387,9 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) } } - iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, - TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_LOCALKEY).c_str(), - cDisplayEncoder::EncodeInline( mLocalKeyFile ).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, + TSS_GetString(cTWAdmin, twadmin::STR_KEYGEN_VERBOSE_LOCALKEY).c_str(), + cDisplayEncoder::EncodeInline(mLocalKeyFile).c_str()); // backup current file if it exists cFileUtil::BackupFile(mLocalKeyFile); @@ -2199,25 +2409,32 @@ int cTWAModeChangePassphrases::Execute(cErrorQueue* pQueue) class cTWAModeHelp : public iTWAMode { public: - cTWAModeHelp() {} - virtual ~cTWAModeHelp() {} - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual cTWAdminCmdLine::CmdLineArgs GetModeID ( void ) const; - virtual TSTRING GetModeUsage( ) { return _T(""); } //TODO: dra Output something here? - + cTWAModeHelp() + { + } + virtual ~cTWAModeHelp() + { + } + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual cTWAdminCmdLine::CmdLineArgs GetModeID(void) const; + virtual TSTRING GetModeUsage() + { + return _T(""); + } //TODO: dra Output something here? + private: // A list of modes to output usage statements for: - std::set< TSTRING > mModes; - std::set< TSTRING > mPrinted; + std::set mModes; + std::set mPrinted; }; /////////////////////////////////////////////////////////////////////////////// // GetModeID /////////////////////////////////////////////////////////////////////////////// -cTWAdminCmdLine::CmdLineArgs cTWAModeHelp::GetModeID( void ) const +cTWAdminCmdLine::CmdLineArgs cTWAModeHelp::GetModeID(void) const { return cTWAdminCmdLine::MODE_HELP; } @@ -2229,18 +2446,35 @@ void cTWAModeHelp::InitCmdLineParser(cCmdLineParser& cmdLine) { // We're only interested in one parameter, that being help. Anything else // passed to this mode should be a cmdlineparser error. - cmdLine.AddArg(cTWAdminCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true ); - cmdLine.AddArg(cTWAdminCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_CREATE_CONFIG, TSTRING(_T("F")), TSTRING(_T("create-cfgfile")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_PRINT_CONFIG, TSTRING(_T("f")), TSTRING(_T("print-cfgfile")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_CREATE_POLICY, TSTRING(_T("P")), TSTRING(_T("create-polfile")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_PRINT_POLICY, TSTRING(_T("p")), TSTRING(_T("print-polfile")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION, TSTRING(_T("R")), TSTRING(_T("remove-encryption")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_ENCRYPT, TSTRING(_T("E")), TSTRING(_T("encrypt")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_EXAMINE, TSTRING(_T("e")), TSTRING(_T("examine")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_GENERATE_KEYS, TSTRING(_T("G")), TSTRING(_T("generate-keys")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES,TSTRING(_T("C")), TSTRING(_T("change-passphrases")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true); + cmdLine.AddArg(cTWAdminCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_CREATE_CONFIG, + TSTRING(_T("F")), + TSTRING(_T("create-cfgfile")), + cCmdLineParser::PARAM_MANY); + cmdLine.AddArg( + cTWAdminCmdLine::MODE_PRINT_CONFIG, TSTRING(_T("f")), TSTRING(_T("print-cfgfile")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_CREATE_POLICY, + TSTRING(_T("P")), + TSTRING(_T("create-polfile")), + cCmdLineParser::PARAM_MANY); + cmdLine.AddArg( + cTWAdminCmdLine::MODE_PRINT_POLICY, TSTRING(_T("p")), TSTRING(_T("print-polfile")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION, + TSTRING(_T("R")), + TSTRING(_T("remove-encryption")), + cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_ENCRYPT, TSTRING(_T("E")), TSTRING(_T("encrypt")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_EXAMINE, TSTRING(_T("e")), TSTRING(_T("examine")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_GENERATE_KEYS, + TSTRING(_T("G")), + TSTRING(_T("generate-keys")), + cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES, + TSTRING(_T("C")), + TSTRING(_T("change-passphrases")), + cCmdLineParser::PARAM_MANY); } /////////////////////////////////////////////////////////////////////////////// @@ -2251,58 +2485,58 @@ bool cTWAModeHelp::Init(const cConfigFile* cf, const cCmdLineParser& cmdLine) cCmdLineIter iter(cmdLine); // Grab the arguments from the help parameter: - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { - case cTWAdminCmdLine::MODE_HELP: - { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - { - mModes.insert( iter.ParamAt(i) ); - } - } - break; - case cTWAdminCmdLine::MODE: - { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - { - mModes.insert( iter.ParamAt(i) ); - } - } - break; - case cTWAdminCmdLine::MODE_HELP_ALL: //fall through - case cTWAdminCmdLine::MODE_CREATE_CONFIG: //fall through - case cTWAdminCmdLine::MODE_PRINT_CONFIG: //fall through - case cTWAdminCmdLine::MODE_CREATE_POLICY: //fall through - case cTWAdminCmdLine::MODE_PRINT_POLICY: //fall through - case cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION: //fall through - case cTWAdminCmdLine::MODE_ENCRYPT: //fall through - case cTWAdminCmdLine::MODE_EXAMINE: //fall through - case cTWAdminCmdLine::MODE_GENERATE_KEYS: - case cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES: - { - int i; - TSTRING str = iter.ActualParam(); - // Kill off the initial "--" or "-" - str.erase( 0, 1 ); - if( str.length() != 1) - str.erase( 0, 1 ); - - // push back the parameter that was actually passed. - mModes.insert( str ); - // grab all the "parameters" following the mode/switch, since - // they may be valid modes without the "--" prepended. - for( i = 0; i < iter.NumParams(); ++i ) - mModes.insert( iter.ParamAt(i) ); - } - break; - default: - // should I do anything, or just ignore this? - // cmdlineparser will catch the bad args. - ; + case cTWAdminCmdLine::MODE_HELP: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) + { + mModes.insert(iter.ParamAt(i)); + } + } + break; + case cTWAdminCmdLine::MODE: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) + { + mModes.insert(iter.ParamAt(i)); + } + } + break; + case cTWAdminCmdLine::MODE_HELP_ALL: //fall through + case cTWAdminCmdLine::MODE_CREATE_CONFIG: //fall through + case cTWAdminCmdLine::MODE_PRINT_CONFIG: //fall through + case cTWAdminCmdLine::MODE_CREATE_POLICY: //fall through + case cTWAdminCmdLine::MODE_PRINT_POLICY: //fall through + case cTWAdminCmdLine::MODE_REMOVE_ENCRYPTION: //fall through + case cTWAdminCmdLine::MODE_ENCRYPT: //fall through + case cTWAdminCmdLine::MODE_EXAMINE: //fall through + case cTWAdminCmdLine::MODE_GENERATE_KEYS: + case cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES: + { + int i; + TSTRING str = iter.ActualParam(); + // Kill off the initial "--" or "-" + str.erase(0, 1); + if (str.length() != 1) + str.erase(0, 1); + + // push back the parameter that was actually passed. + mModes.insert(str); + // grab all the "parameters" following the mode/switch, since + // they may be valid modes without the "--" prepended. + for (i = 0; i < iter.NumParams(); ++i) + mModes.insert(iter.ParamAt(i)); + } + break; + default: + // should I do anything, or just ignore this? + // cmdlineparser will catch the bad args. + ; } } @@ -2317,122 +2551,122 @@ int cTWAModeHelp::Execute(cErrorQueue* pQueue) cDebug d("cTWAModeHelp::Execute"); // The iterator we will use to traverse the list of arguments: - std::set< TSTRING >::iterator it = mModes.begin(); + std::set::iterator it = mModes.begin(); // We'll want to output the version information, regardless: - TCOUT<< TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION ) << std::endl; - TCOUT<< TSS_GetString(cTW, tw::STR_VERSION ) << std::endl; + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; - if( it == mModes.end() ) // all that was passed was --help + if (it == mModes.end()) // all that was passed was --help { // Output a shorter usage statement for each mode - TCOUT<< TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_USAGE_SUMMARY); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_USAGE_SUMMARY); // //That's it, return return 1; } - for( ; it != mModes.end(); ++it ) + for (; it != mModes.end(); ++it) { - if( _tcscmp( (*it).c_str(), _T("all")) == 0 ) + if (_tcscmp((*it).c_str(), _T("all")) == 0) { //Since --help all was passed, emit all help messages and return. - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS ); - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES); //We're done, return return 1; } } - + //We need some subset of the usage statements. Figure out which modes have //been specified: it = mModes.begin(); - for( ; it != mModes.end(); ++it ) + for (; it != mModes.end(); ++it) { - if ( _tcscmp( (*it).c_str(), _T("create-cfgfile") ) == 0 || _tcscmp( (*it).c_str(), _T("F") ) == 0) + if (_tcscmp((*it).c_str(), _T("create-cfgfile")) == 0 || _tcscmp((*it).c_str(), _T("F")) == 0) { //make sure we don't print the same help twice... - if( mPrinted.find(_T("create-cfgfile")) == mPrinted.end() ) + if (mPrinted.find(_T("create-cfgfile")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE); mPrinted.insert(_T("create-cfgfile")); } } - else if( _tcscmp( (*it).c_str(), _T("print-cfgfile") ) == 0 || _tcscmp( (*it).c_str(), _T("f") ) == 0) + else if (_tcscmp((*it).c_str(), _T("print-cfgfile")) == 0 || _tcscmp((*it).c_str(), _T("f")) == 0) { - if( mPrinted.find(_T("print-cfgfile")) == mPrinted.end() ) + if (mPrinted.find(_T("print-cfgfile")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE); mPrinted.insert(_T("print-cfgfile")); } } - else if( _tcscmp( (*it).c_str(), _T("create-polfile") ) == 0 || _tcscmp( (*it).c_str(), _T("P") ) == 0) + else if (_tcscmp((*it).c_str(), _T("create-polfile")) == 0 || _tcscmp((*it).c_str(), _T("P")) == 0) { - if( mPrinted.find(_T("create-polfile")) == mPrinted.end() ) + if (mPrinted.find(_T("create-polfile")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CREATE_POLFILE); mPrinted.insert(_T("create-polfile")); } } - else if( _tcscmp( (*it).c_str(), _T("print-polfile") ) == 0 || _tcscmp( (*it).c_str(), _T("p") ) == 0) + else if (_tcscmp((*it).c_str(), _T("print-polfile")) == 0 || _tcscmp((*it).c_str(), _T("p")) == 0) { - if( mPrinted.find(_T("print-polfile")) == mPrinted.end() ) + if (mPrinted.find(_T("print-polfile")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_PRINT_POLFILE); mPrinted.insert(_T("print-polfile")); } } - else if( _tcscmp( (*it).c_str(), _T("remove-encryption") ) == 0 || _tcscmp( (*it).c_str(), _T("R") ) == 0) + else if (_tcscmp((*it).c_str(), _T("remove-encryption")) == 0 || _tcscmp((*it).c_str(), _T("R")) == 0) { - if( mPrinted.find(_T("remove-encryption")) == mPrinted.end() ) + if (mPrinted.find(_T("remove-encryption")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION); mPrinted.insert(_T("remove-encryption")); } } - else if( _tcscmp( (*it).c_str(), _T("encrypt") ) == 0 || _tcscmp( (*it).c_str(), _T("E") ) == 0) + else if (_tcscmp((*it).c_str(), _T("encrypt")) == 0 || _tcscmp((*it).c_str(), _T("E")) == 0) { - if( mPrinted.find(_T("encrypt")) == mPrinted.end() ) + if (mPrinted.find(_T("encrypt")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_ENCRYPT); mPrinted.insert(_T("encrypt")); } } - else if( _tcscmp( (*it).c_str(), _T("examine") ) == 0 || _tcscmp( (*it).c_str(), _T("e") ) == 0) + else if (_tcscmp((*it).c_str(), _T("examine")) == 0 || _tcscmp((*it).c_str(), _T("e")) == 0) { - if( mPrinted.find(_T("examine")) == mPrinted.end() ) + if (mPrinted.find(_T("examine")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_EXAMINE); mPrinted.insert(_T("examine")); } } - else if( _tcscmp( (*it).c_str(), _T("generate-keys") ) == 0 || _tcscmp( (*it).c_str(), _T("G") ) == 0) + else if (_tcscmp((*it).c_str(), _T("generate-keys")) == 0 || _tcscmp((*it).c_str(), _T("G")) == 0) { - if( mPrinted.find(_T("generate-keys")) == mPrinted.end() ) + if (mPrinted.find(_T("generate-keys")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_GENERATE_KEYS); mPrinted.insert(_T("generate-keys")); } } - else if( _tcscmp( (*it).c_str(), _T("change-passphrases") ) == 0 || _tcscmp( (*it).c_str(), _T("C") ) == 0) + else if (_tcscmp((*it).c_str(), _T("change-passphrases")) == 0 || _tcscmp((*it).c_str(), _T("C")) == 0) { - if( mPrinted.find(_T("change-passphrases")) == mPrinted.end() ) + if (mPrinted.find(_T("change-passphrases")) == mPrinted.end()) { - TCOUT<< TSS_GetString( cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES ); + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES); mPrinted.insert(_T("change-passphrases")); } } else { - cTWUtil::PrintErrorMsg( eTWAInvalidHelpMode( (*it), eError::NON_FATAL ) ); + cTWUtil::PrintErrorMsg(eTWAInvalidHelpMode((*it), eError::NON_FATAL)); TCOUT << std::endl; // emit error string, this mode does not exist } @@ -2448,59 +2682,87 @@ int cTWAModeHelp::Execute(cErrorQueue* pQueue) class cTWAModeVersion : public iTWAMode { public: - cTWAModeVersion() {} - virtual ~cTWAModeVersion() {} - - virtual void InitCmdLineParser(cCmdLineParser& cmdLine) { ASSERT(false); } - virtual bool Init (const cConfigFile* cf, const cCmdLineParser& cmdLine) { ASSERT(false); return true; } - virtual int Execute (cErrorQueue* pQueue) { ASSERT(false); return 0; } - virtual TSTRING GetModeUsage( ) { ASSERT(false); return _T(""); } - virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const { return cTWAdminCmdLine::MODE_VERSION; } + cTWAModeVersion() + { + } + virtual ~cTWAModeVersion() + { + } + + virtual void InitCmdLineParser(cCmdLineParser& cmdLine) + { + ASSERT(false); + } + virtual bool Init(const cConfigFile* cf, const cCmdLineParser& cmdLine) + { + ASSERT(false); + return true; + } + virtual int Execute(cErrorQueue* pQueue) + { + ASSERT(false); + return 0; + } + virtual TSTRING GetModeUsage() + { + ASSERT(false); + return _T(""); + } + virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const + { + return cTWAdminCmdLine::MODE_VERSION; + } + private: }; - //############################################################################# /////////////////////////////////////////////////////////////////////////////// // cTWAdminCmdLine::GetMode() // -iTWAMode* cTWAdminCmdLine::GetMode(int argc, const TCHAR *const * argv) +iTWAMode* cTWAdminCmdLine::GetMode(int argc, const TCHAR* const* argv) { // note -- it is assumed the executable name is the first parameter - if(argc < 2) + if (argc < 2) { - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_VERSION).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_VERSION).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); return NULL; } - int mode = MODE; + int mode = MODE; const TCHAR* pcMode; - if(_tcscmp(argv[1], _T("-m")) == 0) + if (_tcscmp(argv[1], _T("-m")) == 0) { - if(argc < 3) + if (argc < 3) { - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_VERSION).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_VERSION).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); cTWUtil::PrintErrorMsg(eBadCmdLine(TSS_GetString(cTW, tw::STR_ERR_NO_MODE), eError::SUPRESS_THIRD_MSG)); - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); return NULL; } pcMode = argv[2]; - if (_tcscmp(argv[2], _T("F")) == 0) + if (_tcscmp(argv[2], _T("F")) == 0) mode = MODE_CREATE_CONFIG; else if (_tcscmp(argv[2], _T("f")) == 0) mode = MODE_PRINT_CONFIG; @@ -2522,7 +2784,7 @@ iTWAMode* cTWAdminCmdLine::GetMode(int argc, const TCHAR *const * argv) else { pcMode = argv[1]; - if (_tcscmp(argv[1], _T("--create-cfgfile")) == 0) + if (_tcscmp(argv[1], _T("--create-cfgfile")) == 0) mode = MODE_CREATE_CONFIG; else if (_tcscmp(argv[1], _T("--print-cfgfile")) == 0) mode = MODE_PRINT_CONFIG; @@ -2552,8 +2814,8 @@ iTWAMode* cTWAdminCmdLine::GetMode(int argc, const TCHAR *const * argv) mode = MODE_HELP; break; } - - if(mode == MODE) + + if (mode == MODE) { // unknown mode switch cDebug d("cTWAdminCmdLine::GetMode"); @@ -2562,15 +2824,16 @@ iTWAMode* cTWAdminCmdLine::GetMode(int argc, const TCHAR *const * argv) TSTRING estr = TSS_GetString(cTW, tw::STR_ERR2_BAD_MODE_SWITCH); estr.append(pcMode); cTWUtil::PrintErrorMsg(eBadModeSwitch(estr, eError::SUPRESS_THIRD_MSG)); - - iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); + + iUserNotify::GetInstance()->Notify( + iUserNotify::V_SILENT, _T("%s"), TSS_GetString(cTW, tw::STR_GET_HELP).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_SILENT, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); return NULL; } iTWAMode* pRtn = 0; - switch(mode) + switch (mode) { case MODE_CREATE_CONFIG: pRtn = new cTWAModeCreateCfg; @@ -2619,51 +2882,51 @@ static bool NotifyFileType(const cFileHeaderID& id, uint32 version, iUserNotify: { if (id == cFCODatabaseFile::GetFileHeaderID()) { - iUserNotify::GetInstance()->Notify(vl, - TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_DB).c_str(), + iUserNotify::GetInstance()->Notify(vl, + TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_DB).c_str(), (version & 0xff000000) >> 24, - (version & 0x00ff0000) >> 16, - (version & 0x0000ff00) >> 8, + (version & 0x00ff0000) >> 16, + (version & 0x0000ff00) >> 8, (version & 0x000000ff)); return true; } else if (id == cFCOReport::GetFileHeaderID()) { - iUserNotify::GetInstance()->Notify(vl, - TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_REP).c_str(), + iUserNotify::GetInstance()->Notify(vl, + TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_REP).c_str(), (version & 0xff000000) >> 24, - (version & 0x00ff0000) >> 16, - (version & 0x0000ff00) >> 8, + (version & 0x00ff0000) >> 16, + (version & 0x0000ff00) >> 8, (version & 0x000000ff)); return true; } else if (id == cConfigFile::GetFileHeaderID()) { - iUserNotify::GetInstance()->Notify(vl, - TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_CFG).c_str(), + iUserNotify::GetInstance()->Notify(vl, + TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_CFG).c_str(), (version & 0xff000000) >> 24, - (version & 0x00ff0000) >> 16, - (version & 0x0000ff00) >> 8, + (version & 0x00ff0000) >> 16, + (version & 0x0000ff00) >> 8, (version & 0x000000ff)); return true; } else if (id == cPolicyFile::GetFileHeaderID()) { - iUserNotify::GetInstance()->Notify(vl, - TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_POL).c_str(), + iUserNotify::GetInstance()->Notify(vl, + TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_POL).c_str(), (version & 0xff000000) >> 24, - (version & 0x00ff0000) >> 16, - (version & 0x0000ff00) >> 8, + (version & 0x00ff0000) >> 16, + (version & 0x0000ff00) >> 8, (version & 0x000000ff)); return true; } else if (id == cKeyFile::GetFileHeaderID()) { - iUserNotify::GetInstance()->Notify(vl, - TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_KEY).c_str(), + iUserNotify::GetInstance()->Notify(vl, + TSS_GetString(cTWAdmin, twadmin::STR_FILE_TYPE_KEY).c_str(), (version & 0xff000000) >> 24, - (version & 0x00ff0000) >> 16, - (version & 0x0000ff00) >> 8, + (version & 0x00ff0000) >> 16, + (version & 0x0000ff00) >> 8, (version & 0x000000ff)); return true; } @@ -2695,4 +2958,3 @@ static bool NotifyEncryptionType(cFileHeader::Encoding encoding, iUserNotify::Ve iUserNotify::GetInstance()->Notify(vl, TSS_GetString(cTWAdmin, twadmin::STR_ENCRYPT_TYPE_UNK).c_str()); return false; } - diff --git a/src/twadmin/twadmincl.h b/src/twadmin/twadmincl.h index 9d319b2..1544212 100644 --- a/src/twadmin/twadmincl.h +++ b/src/twadmin/twadmincl.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,26 +42,28 @@ #include "core/error.h" -TSS_EXCEPTION( eTWA, eError ) -TSS_EXCEPTION( eTWASkippingDirectory, eTWA ) -TSS_EXCEPTION( eTWAFileNotFound, eTWA ) -TSS_EXCEPTION( eTWAFileAccess, eTWA ) -TSS_EXCEPTION( eTWAFileTypeUnknown, eTWA ) -TSS_EXCEPTION( eTWAInvalidHelpMode, eTWA ) -TSS_EXCEPTION( eTWADecrypt, eTWA ) -TSS_EXCEPTION( eTWADecryptCorrupt, eTWA ) - -TSS_BEGIN_EXCEPTION_NO_CTOR( eTWAEncryptionChange, eTWA ) - eTWAEncryptionChange( const TSTRING& strMsg1, const TSTRING& strMsg2 = _T(""), uint32 flags = 0) - : eTWA( strMsg1 + strMsg2, flags ) {} +TSS_EXCEPTION(eTWA, eError) +TSS_EXCEPTION(eTWASkippingDirectory, eTWA) +TSS_EXCEPTION(eTWAFileNotFound, eTWA) +TSS_EXCEPTION(eTWAFileAccess, eTWA) +TSS_EXCEPTION(eTWAFileTypeUnknown, eTWA) +TSS_EXCEPTION(eTWAInvalidHelpMode, eTWA) +TSS_EXCEPTION(eTWADecrypt, eTWA) +TSS_EXCEPTION(eTWADecryptCorrupt, eTWA) + +TSS_BEGIN_EXCEPTION_NO_CTOR(eTWAEncryptionChange, eTWA) +eTWAEncryptionChange(const TSTRING& strMsg1, const TSTRING& strMsg2 = _T(""), uint32 flags = 0) + : eTWA(strMsg1 + strMsg2, flags) +{ +} TSS_END_EXCEPTION(); -TSS_BEGIN_EXCEPTION_NO_CTOR( eTWACreateCfgMissingSitekey, eTWA ) - eTWACreateCfgMissingSitekey( const TSTRING& msg, uint32 flags = 0 ); +TSS_BEGIN_EXCEPTION_NO_CTOR(eTWACreateCfgMissingSitekey, eTWA) +eTWACreateCfgMissingSitekey(const TSTRING& msg, uint32 flags = 0); TSS_END_EXCEPTION(); -TSS_BEGIN_EXCEPTION_NO_CTOR( eTWACreateCfgSitekeyMismatch, eTWA ) - eTWACreateCfgSitekeyMismatch( const TSTRING& specifiedKeyfile, const TSTRING& configKeyfile, uint32 flags = 0 ) ; +TSS_BEGIN_EXCEPTION_NO_CTOR(eTWACreateCfgSitekeyMismatch, eTWA) +eTWACreateCfgSitekeyMismatch(const TSTRING& specifiedKeyfile, const TSTRING& configKeyfile, uint32 flags = 0); TSS_END_EXCEPTION(); @@ -76,12 +78,12 @@ class cTWAdminCmdLine { public: //static void InitCmdLineParser(cCmdLineParser& parser); - // call this to initialize the command line parser + // call this to initialize the command line parser - static iTWAMode* GetMode(int argc, const TCHAR *const * argv); - // this will look at the beginning of the command line, determine the appropriate - // mode to create, and returns it. If the mode can't be determined, an error message - // is printed and null is returned. + static iTWAMode* GetMode(int argc, const TCHAR* const* argv); + // this will look at the beginning of the command line, determine the appropriate + // mode to create, and returns it. If the mode can't be determined, an error message + // is printed and null is returned. // constants for all the command line arguments enum CmdLineArgs @@ -89,7 +91,7 @@ class cTWAdminCmdLine HELP, // modes - MODE, // generic -m + MODE, // generic -m MODE_CREATE_CONFIG, MODE_PRINT_CONFIG, MODE_CREATE_POLICY, @@ -119,6 +121,7 @@ class cTWAdminCmdLine LOCALPASSPHRASE, SITEPASSPHRASEOLD, LOCALPASSPHRASEOLD, + KEY_SIZE, PARAMS, // the final params @@ -127,7 +130,7 @@ class cTWAdminCmdLine }; /////////////////////////////////////////////////////////////////////////////// -// iTWAMode -- base class that contains an interface for initializing tripwire +// iTWAMode -- base class that contains an interface for initializing tripwire // in a mode of operation and executing in that mode; a class is derived // from this for each mode of operation /////////////////////////////////////////////////////////////////////////////// @@ -140,29 +143,31 @@ class iTWAMode { public: virtual void InitCmdLineParser(cCmdLineParser& cmdLine) = 0; - // fills out the command line parser with all the switches that are appropriate for - // the given mode. + // fills out the command line parser with all the switches that are appropriate for + // the given mode. virtual bool Init(const cConfigFile* cf, const cCmdLineParser& cmdLine) = 0; - // call this to ask the mode object to initialize all of its data structures - // with the passed in information. If it returns false, it can be assumed that an error - // message was spit to stderr. + // call this to ask the mode object to initialize all of its data structures + // with the passed in information. If it returns false, it can be assumed that an error + // message was spit to stderr. virtual int Execute(cErrorQueue* pQueue) = 0; - // go to work! Returns error level to exit with; 0 implies success + // go to work! Returns error level to exit with; 0 implies success virtual cTWAdminCmdLine::CmdLineArgs GetModeID() const = 0; - // return MODE_* enumeration coresponding to the current mode. + // return MODE_* enumeration coresponding to the current mode. + + virtual TSTRING GetModeUsage(void) = 0; + // return a mode-specific usage string ( a subset of the entire usage statement for + // twadmin - virtual TSTRING GetModeUsage( void ) = 0; - // return a mode-specific usage string ( a subset of the entire usage statement for - // twadmin + void SetCfgFilePath(const TSTRING& path) + { + mCfgFilePath = path; + } + // if the config file is opened in main(), this should be called so the modes know what the path + // to the config file is. + virtual ~iTWAMode(){}; - void SetCfgFilePath( const TSTRING& path ) { mCfgFilePath = path; } - // if the config file is opened in main(), this should be called so the modes know what the path - // to the config file is. - virtual ~iTWAMode() {}; protected: TSTRING mCfgFilePath; - }; #endif - diff --git a/src/twadmin/twadminerrors.cpp b/src/twadmin/twadminerrors.cpp index 5c650ad..c192281 100644 --- a/src/twadmin/twadminerrors.cpp +++ b/src/twadmin/twadminerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,18 +40,17 @@ #include "twadmincl.h" -TSS_BEGIN_ERROR_REGISTRATION( twadmin ) +TSS_BEGIN_ERROR_REGISTRATION(twadmin) -TSS_REGISTER_ERROR( eTWASkippingDirectory(), _T("Skipping Directory.") ) -TSS_REGISTER_ERROR( eTWAFileNotFound(), _T("File not found.") ) -TSS_REGISTER_ERROR( eTWAFileAccess(), _T("File Access.") ) -TSS_REGISTER_ERROR( eTWAFileTypeUnknown(), _T("File Type Unknown.") ) -TSS_REGISTER_ERROR( eTWAEncryptionChange(), _T("Encryption change.") ) -TSS_REGISTER_ERROR( eTWAInvalidHelpMode(), _T("Invalid mode parameter to help:") ) -TSS_REGISTER_ERROR( eTWADecrypt(), _T("Remove encryption failed.\nFilename: ") ) -TSS_REGISTER_ERROR( eTWADecryptCorrupt(), _T("Remove encryption failed.\nThe file may be corrupt.\nFilename: ") ) -TSS_REGISTER_ERROR( eTWACreateCfgMissingSitekey(), _T("Config file text is missing sitekey.") ) -TSS_REGISTER_ERROR( eTWACreateCfgSitekeyMismatch(), _T("Config file key mismatch.") ) +TSS_REGISTER_ERROR(eTWASkippingDirectory(), _T("Skipping Directory.")) +TSS_REGISTER_ERROR(eTWAFileNotFound(), _T("File not found.")) +TSS_REGISTER_ERROR(eTWAFileAccess(), _T("File Access.")) +TSS_REGISTER_ERROR(eTWAFileTypeUnknown(), _T("File Type Unknown.")) +TSS_REGISTER_ERROR(eTWAEncryptionChange(), _T("Encryption change.")) +TSS_REGISTER_ERROR(eTWAInvalidHelpMode(), _T("Invalid mode parameter to help:")) +TSS_REGISTER_ERROR(eTWADecrypt(), _T("Remove encryption failed.\nFilename: ")) +TSS_REGISTER_ERROR(eTWADecryptCorrupt(), _T("Remove encryption failed.\nThe file may be corrupt.\nFilename: ")) +TSS_REGISTER_ERROR(eTWACreateCfgMissingSitekey(), _T("Config file text is missing sitekey.")) +TSS_REGISTER_ERROR(eTWACreateCfgSitekeyMismatch(), _T("Config file key mismatch.")) TSS_END_ERROR_REGISTRATION() - diff --git a/src/twadmin/twadminerrors.h b/src/twadmin/twadminerrors.h index ead4837..fc2eec0 100644 --- a/src/twadmin/twadminerrors.h +++ b/src/twadmin/twadminerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,7 +40,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( twadmin ) - -#endif//__FCOERRORS_H +TSS_DECLARE_ERROR_REGISTRATION(twadmin) +#endif //__FCOERRORS_H diff --git a/src/twadmin/twadminmain.cpp b/src/twadmin/twadminmain.cpp index 500cef5..4dab534 100644 --- a/src/twadmin/twadminmain.cpp +++ b/src/twadmin/twadminmain.cpp @@ -1,36 +1,36 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// -// twadminmain.cpp +// twadminmain.cpp // #include "stdtwadmin.h" @@ -42,17 +42,14 @@ #include "tw/twutil.h" #include "tw/twstrings.h" #include "twadminstrings.h" -#include "core/timebomb.h" +#include "core/epoch.h" #include "core/errorbucketimpl.h" #include "core/archive.h" -#include "twadmin.h" // for package initialization +#include "twadmin.h" // for package initialization #include - -#if IS_UNIX #include -#endif /////////////////////////////////////////////////////////////////////////////// // terminate and unexpected handlers @@ -70,18 +67,18 @@ void tw_unexpected_handler() _exit(1); } -int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) -{ +int __cdecl _tmain(int argc, const TCHAR* argv[], const TCHAR* envp[]) +{ + - int ret = 0; - if (TimeBombExploded()) + if (CheckEpoch()) return 1; cTWInit twInit; - try + try { // set unexpected and terminate handlers // Note: we do this before Init() in case it attempts to call these handlers @@ -89,16 +86,16 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) EXCEPTION_NAMESPACE set_terminate(tw_terminate_handler); EXCEPTION_NAMESPACE set_unexpected(tw_unexpected_handler); - twInit.Init( argv[0] ); - TSS_Dependency( cTWAdmin ); + twInit.Init(argv[0]); + TSS_Dependency(cTWAdmin); // set up the debug output - cDebug::SetDebugLevel( cDebug::D_DEBUG ); + cDebug::SetDebugLevel(cDebug::D_DEBUG); // first, get the right mode... - std::auto_ptr pMode(cTWAdminCmdLine::GetMode(argc, argv)); - if(! pMode.get()) + TW_UNIQUE_PTR pMode(cTWAdminCmdLine::GetMode(argc, argv)); + if (!pMode.get()) { // no valid mode passed; GetMode will display an appropriate string (include usage statement) ret = 1; @@ -112,40 +109,38 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) ret = 0; goto exit; } - + // process the command line cCmdLineParser cmdLine; pMode->InitCmdLineParser(cmdLine); - + try { cmdLine.Parse(argc, argv); } - catch( eError& e ) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; - + ret = 1; goto exit; } - - #if IS_UNIX + // erase the command line // TODO: it might be a good idea to move this to cTWUtil int i; for (i = 1; i < argc; ++i) - memset((char*)argv[i], 0, strlen(argv[i])*sizeof(TCHAR)); - #endif + memset((char*)argv[i], 0, strlen(argv[i]) * sizeof(TCHAR)); cCmdLineIter iter(cmdLine); if (iter.SeekToArg(cTWAdminCmdLine::HELP)) { - TCOUT<< TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION ) << std::endl; - TCOUT<< TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTWAdmin, twadmin::STR_TWADMIN_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; //Output a mode specific usage statement - TCOUT<< pMode->GetModeUsage(); + TCOUT << pMode->GetModeUsage(); ret = 1; goto exit; } @@ -156,13 +151,13 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) } // open up the config file, possibly using the passed in path - cConfigFile config; - bool configFileOpened = false; + cConfigFile config; + bool configFileOpened = false; cErrorBucketNull errorNull; // don't spit errors to the user - - if (pMode->GetModeID() != cTWAdminCmdLine::MODE_GENERATE_KEYS && - pMode->GetModeID() != cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES && - pMode->GetModeID() != cTWAdminCmdLine::MODE_CREATE_CONFIG && + + if (pMode->GetModeID() != cTWAdminCmdLine::MODE_GENERATE_KEYS && + pMode->GetModeID() != cTWAdminCmdLine::MODE_CHANGE_PASSPHRASES && + pMode->GetModeID() != cTWAdminCmdLine::MODE_CREATE_CONFIG && pMode->GetModeID() != cTWAdminCmdLine::MODE_PRINT_CONFIG && pMode->GetModeID() != cTWAdminCmdLine::MODE_HELP) { @@ -170,23 +165,23 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) { //open cfg file TSTRING cfgPath; - cTWUtil::OpenConfigFile( config, cmdLine, cTWAdminCmdLine::CFG_FILE, errorNull, cfgPath); - pMode->SetCfgFilePath( cfgPath ); + cTWUtil::OpenConfigFile(config, cmdLine, cTWAdminCmdLine::CFG_FILE, errorNull, cfgPath); + pMode->SetCfgFilePath(cfgPath); configFileOpened = true; } - catch(eError& error) + catch (eError& error) { TSTRING extra; extra += TSS_GetString(cTW, tw::STR_NEWLINE); extra += TSS_GetString(cTWAdmin, twadmin::STR_ERR2_CONFIG_OPEN); - cTWUtil::PrintErrorMsg(error, extra); + cTWUtil::PrintErrorMsg(error, extra); ret = 1; goto exit; } } // ok, now we can initialize the mode object and have it execute - if(! pMode->Init(configFileOpened ? &config : NULL, cmdLine)) + if (!pMode->Init(configFileOpened ? &config : NULL, cmdLine)) { TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; ret = 1; @@ -194,7 +189,7 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) } ret = pMode->Execute(&twInit.errorQueue); - }//end try block + } //end try block catch (eError& error) { @@ -203,14 +198,14 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) ret = 1; } - catch (std::bad_alloc e) + catch (std::bad_alloc& e) { TCERR << _T("*** Fatal exception: Out of memory "); TCERR << _T("*** Exiting...\n"); ret = 1; } - catch (std::exception e) + catch (std::exception& e) { TCERR << _T("*** Fatal exception: "); std::cerr << e.what() << std::endl; @@ -232,4 +227,3 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ], const TCHAR* envp[ ] ) return ret; } - diff --git a/src/twadmin/twadminstrings.cpp b/src/twadmin/twadminstrings.cpp index a3ecc86..8b6df8e 100644 --- a/src/twadmin/twadminstrings.cpp +++ b/src/twadmin/twadminstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,260 +39,273 @@ #include "twadmin.h" #include "twadminstrings.h" -TSS_BeginStringtable( cTWAdmin ) - - TSS_StringEntry( twadmin::STR_TWADMIN_VERSION, _T("twadmin: Tripwire administrative tool.\n") ), +#if IS_AROS +# define VERSION_PREFIX "$VER: " +#else +# define VERSION_PREFIX "@(#)" +#endif + +TSS_BeginStringtable(cTWAdmin) + + TSS_StringEntry(twadmin::STR_TWADMIN_VERSION, _T("twadmin: Tripwire administrative tool.\n")), + TSS_StringEntry(twadmin::STR_EMBEDDED_VERSION, _T(VERSION_PREFIX "twadmin " PACKAGE_VERSION)), - TSS_StringEntry( twadmin::STR_TWADMIN_USAGE_SUMMARY, - _T("Usage:\n") - _T("\n") - _T("Create Configuration File: twadmin [-m F|--create-cfgfile][options] cfgfile.txt\n") - _T("Print Configuration File: twadmin [-m f|--print-cfgfile] [options]\n") - _T("Create Policy File: twadmin [-m P|--create-polfile] [options] polfile.txt\n") - _T("Print Policy File: twadmin [-m p|--print-polfile] [options]\n") - _T("Remove Encryption: twadmin [-m R|--remove-encryption] [options] [file1...]\n") - _T("Encryption: twadmin [-m E|--encrypt] [options] [file1...]\n") - _T("Examine Encryption: twadmin [-m e|--examine] [options] [file1...]\n") - _T("Generate Keys: twadmin [-m G|--generate-keys] [options]\n") - _T("Change Passphrases: twadmin [-m C|--change-passphrases] [options]\n") - _T("\n") - _T("Type 'twadmin [mode] --help' OR\n") - _T("'twadmin --help mode [mode...]' OR\n") - _T("'twadmin --help all' for extended help\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_USAGE_SUMMARY, + _T("Usage:\n") + _T("\n") + _T("Create Configuration File: twadmin [-m F|--create-cfgfile][options] cfgfile.txt\n") + _T("Print Configuration File: twadmin [-m f|--print-cfgfile] [options]\n") + _T("Create Policy File: twadmin [-m P|--create-polfile] [options] polfile.txt\n") + _T("Print Policy File: twadmin [-m p|--print-polfile] [options]\n") + _T("Remove Encryption: twadmin [-m R|--remove-encryption] [options] [file1...]\n") + _T("Encryption: twadmin [-m E|--encrypt] [options] [file1...]\n") + _T("Examine Encryption: twadmin [-m e|--examine] [options] [file1...]\n") + _T("Generate Keys: twadmin [-m G|--generate-keys] [options]\n") + _T("Change Passphrases: twadmin [-m C|--change-passphrases] [options]\n") + _T("\n") + _T("Type 'twadmin [mode] --help' OR\n") + _T("'twadmin --help mode [mode...]' OR\n") + _T("'twadmin --help all' for extended help\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE, - _T("Create Configuration File mode:\n") - _T(" -m F --create-cfgfile\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T(" -e --no-encryption\n") - _T("configfile.txt\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("Exactly one of -e or -S must be specified.\n") - _T("The -Q option is valid only with -S.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_CREATE_CFGFILE, + _T("Create Configuration File mode:\n") + _T(" -m F --create-cfgfile\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T(" -e --no-encryption\n") + _T("configfile.txt\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("Exactly one of -e or -S must be specified.\n") + _T("The -Q option is valid only with -S.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE, - _T("Print Configuration File mode:\n") - _T(" -m f --print-cfgfile\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_PRINT_CFGFILE, + _T("Print Configuration File mode:\n") + _T(" -m f --print-cfgfile\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_CREATE_POLFILE, - _T("Replace Policy File mode:\n") - _T(" -m P --create-polfile\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T(" -e --no-encryption\n") - _T("policyfile.txt\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("The -e and -S options are mutually exclusive.\n") - _T("The -e and -Q options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_CREATE_POLFILE, + _T("Replace Policy File mode:\n") + _T(" -m P --create-polfile\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T(" -e --no-encryption\n") + _T("policyfile.txt\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("The -e and -S options are mutually exclusive.\n") + _T("The -e and -Q options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_PRINT_POLFILE, - _T("Print Policy File mode:\n") - _T(" -m p --print-polfile\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -p polfile --polfile polfile\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_PRINT_POLFILE, + _T("Print Policy File mode:\n") + _T(" -m p --print-polfile\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -p polfile --polfile polfile\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION, - _T("Remove Encryption mode:\n") - _T(" -m R --remove-encryption\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T("file1 [file2 ...]\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_REMOVE_ENCRYPTION, + _T("Remove Encryption mode:\n") + _T(" -m R --remove-encryption\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T("file1 [file2 ...]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_ENCRYPT, - _T("Encryption mode:\n") - _T(" -m E --encrypt\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T("file1 [file2 ...]\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_ENCRYPT, + _T("Encryption mode:\n") + _T(" -m E --encrypt\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T("file1 [file2 ...]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_EXAMINE, - _T("Examine Encryption mode:\n") - _T(" -m e --examine\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T("file1 [file2 ...]\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_EXAMINE, + _T("Examine Encryption mode:\n") + _T(" -m e --examine\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T("file1 [file2 ...]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_GENERATE_KEYS, - _T("Generate Keys mode:\n") - _T(" -m G --generate-keys\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("Exactly one of -S or -L must be specified.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_GENERATE_KEYS, + _T("Generate Keys mode:\n") + _T(" -m G --generate-keys\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T(" -K size --key-size size [1024 or 2048]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("Exactly one of -S or -L must be specified.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES, - _T("Change Passphrases mode:\n") - _T(" -m C --change-passphrases\n") - _T(" -v --verbose\n") - _T(" -s --silent, --quiet\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -S sitekey --site-keyfile sitekey\n") - _T(" -P passphrase --local-passphrase passphrase\n") - _T(" -Q passphrase --site-passphrase passphrase\n") - _T(" --local-passphrase-old passphrase-old\n") - _T(" --site-passphrase-old passphrase-old\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("At least one of -S or -L must be specified.\n") - _T("\n") - ), + TSS_StringEntry(twadmin::STR_TWADMIN_HELP_CHANGE_PASSPHRASES, + _T("Change Passphrases mode:\n") + _T(" -m C --change-passphrases\n") + _T(" -v --verbose\n") + _T(" -s --silent, --quiet\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -S sitekey --site-keyfile sitekey\n") + _T(" -P passphrase --local-passphrase passphrase\n") + _T(" -Q passphrase --site-passphrase passphrase\n") + _T(" --local-passphrase-old passphrase-old\n") + _T(" --site-passphrase-old passphrase-old\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("At least one of -S or -L must be specified.\n") + _T("\n")), - TSS_StringEntry( twadmin::STR_KEYGEN_VERBOSE_OUTPUT_FILES, _T("Using site keyfile: \"%s\" and local keyfile: \"%s\"\n") ), - TSS_StringEntry( twadmin::STR_KEYGEN_VERBOSE_PASSPHRASES, _T("Using supplied passphrases.\n") ), - TSS_StringEntry( twadmin::STR_KEYGEN_VERBOSE_SITEKEY, _T("Generating site key: %s\n") ), - TSS_StringEntry( twadmin::STR_KEYGEN_VERBOSE_LOCALKEY, _T("Generating local key: %s\n") ), - TSS_StringEntry( twadmin::STR_UPCONFIG_VERBOSE_PT_CONFIG, _T("Using plaintext config file: %s\n") ), - TSS_StringEntry( twadmin::STR_UPCONFIG_CREATING_CONFIG, _T("Writing configuration file: %s\n") ), - TSS_StringEntry( twadmin::STR_UPCONFIG_VERBOSE_PT_POLICY, _T("Using plaintext policy file: %s\n") ), - TSS_StringEntry( twadmin::STR_GENERATING_KEYS, _T("Generating key (this may take several minutes)...") ), - TSS_StringEntry( twadmin::STR_GENERATION_COMPLETE, _T("Key generation complete.\n") ), - TSS_StringEntry( twadmin::STR_SITEKEYFILE, _T("\tSite Keyfile: ") ), - TSS_StringEntry( twadmin::STR_LOCALKEYFILE, _T("\tLocal Keyfile: ") ), - TSS_StringEntry( twadmin::STR_SITEKEY_EXISTS_1, _T("The site key file: \"") ), - TSS_StringEntry( twadmin::STR_SITEKEY_EXISTS_2, _T("\" exists. Overwrite (Y/N)? ") ), - TSS_StringEntry( twadmin::STR_LOCALKEY_EXISTS_1, _T("The local key file: \"") ), - TSS_StringEntry( twadmin::STR_LOCALKEY_EXISTS_2, _T("\" exists. Overwrite (Y/N)? ") ), - TSS_StringEntry( twadmin::STR_KEYFILE_BACKED_UP_AS, _T("Keyfile backed up as %s\n") ), - TSS_StringEntry( twadmin::STR_CONVERTING_FILES, _T("Converting files.\n") ), - TSS_StringEntry( twadmin::STR_EXAMINING_FILE, _T("Examining file: ") ), - TSS_StringEntry( twadmin::STR_KEYS_DECRYPT, _T("The following keys decrypt this file: ") ), - TSS_StringEntry( twadmin::STR_BACKUP_EXISTS_1, _T("Backup file ") ), - TSS_StringEntry( twadmin::STR_BACKUP_EXISTS_2, _T(" exists. Overwrite (Y/N)? ") ), - TSS_StringEntry( twadmin::STR_PASSPHRASE_HINT, _T("\n(When selecting a passphrase, keep in mind that good passphrases typically\n") - _T("have upper and lower case letters, digits and punctuation marks, and are\n") - _T("at least 8 characters in length.)\n\n") - ), - TSS_StringEntry( twadmin::STR_POL_NOT_UPDATED, _T("The policy file was not altered.\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPT_TYPE_NONE, _T("Encoding: None\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPT_TYPE_COMP, _T("Encoding: Compressed\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPT_TYPE_ASYM, _T("Encoding: Asymmetric Encryption\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPT_TYPE_UNK, _T("Encoding: Unrecognized\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_DB, _T("File Type: Tripwire Database (Ver %X.%X.%X.%X)\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_REP, _T("File Type: Tripwire Report (Ver %X.%X.%X.%X)\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_CFG, _T("File Type: Tripwire Config File (Ver %X.%X.%X.%X)\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_POL, _T("File Type: Tripwire Policy File (Ver %X.%X.%X.%X)\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_KEY, _T("File Type: Tripwire Key File (Ver %X.%X.%X.%X)\n") ), - TSS_StringEntry( twadmin::STR_FILE_TYPE_UNK, _T("File Type: Unknown\n") ), - TSS_StringEntry( twadmin::STR_ENTER_SITE_PASS, _T("Enter the site keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_VERIFY_SITE_PASS, _T("Verify the site keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_ENTER_LOCAL_PASS, _T("Enter the local keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_VERIFY_LOCAL_PASS, _T("Verify the local keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_ENTER_SITE_PASS_OLD, _T("Enter the old site keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_ENTER_LOCAL_PASS_OLD, _T("Enter the old local keyfile passphrase:") ), - TSS_StringEntry( twadmin::STR_REMOVE_ENCRYPTION_WARNING, _T("NOTE: Removing encryption on a file leaves it open to tampering!\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPTION_REMOVED, _T("Encryption removed from \"%s\" successfully.\n") ), - TSS_StringEntry( twadmin::STR_ENCRYPTION_SUCCEEDED, _T("\"%s\" encrypted successfully.\n") ), - TSS_StringEntry( twadmin::STR_FILE, _T("File: \"") ), - TSS_StringEntry( twadmin::STR_ENDQUOTE_NEWLINE, _T("\"\n") ), + TSS_StringEntry(twadmin::STR_KEYGEN_VERBOSE_OUTPUT_FILES, + _T("Using site keyfile: \"%s\" and local keyfile: \"%s\"\n")), + TSS_StringEntry(twadmin::STR_KEYGEN_VERBOSE_PASSPHRASES, _T("Using supplied passphrases.\n")), + TSS_StringEntry(twadmin::STR_KEYGEN_VERBOSE_SITEKEY, _T("Generating site key: %s\n")), + TSS_StringEntry(twadmin::STR_KEYGEN_VERBOSE_LOCALKEY, _T("Generating local key: %s\n")), + TSS_StringEntry(twadmin::STR_UPCONFIG_VERBOSE_PT_CONFIG, _T("Using plaintext config file: %s\n")), + TSS_StringEntry(twadmin::STR_UPCONFIG_CREATING_CONFIG, _T("Writing configuration file: %s\n")), + TSS_StringEntry(twadmin::STR_UPCONFIG_VERBOSE_PT_POLICY, _T("Using plaintext policy file: %s\n")), + TSS_StringEntry(twadmin::STR_GENERATING_KEYS, _T("Generating key (this may take several minutes)...")), + TSS_StringEntry(twadmin::STR_GENERATION_COMPLETE, _T("Key generation complete.\n")), + TSS_StringEntry(twadmin::STR_SITEKEYFILE, _T("\tSite Keyfile: ")), + TSS_StringEntry(twadmin::STR_LOCALKEYFILE, _T("\tLocal Keyfile: ")), + TSS_StringEntry(twadmin::STR_SITEKEY_EXISTS_1, _T("The site key file: \"")), + TSS_StringEntry(twadmin::STR_SITEKEY_EXISTS_2, _T("\" exists. Overwrite (Y/N)? ")), + TSS_StringEntry(twadmin::STR_LOCALKEY_EXISTS_1, _T("The local key file: \"")), + TSS_StringEntry(twadmin::STR_LOCALKEY_EXISTS_2, _T("\" exists. Overwrite (Y/N)? ")), + TSS_StringEntry(twadmin::STR_KEYFILE_BACKED_UP_AS, _T("Keyfile backed up as %s\n")), + TSS_StringEntry(twadmin::STR_CONVERTING_FILES, _T("Converting files.\n")), + TSS_StringEntry(twadmin::STR_EXAMINING_FILE, _T("Examining file: ")), + TSS_StringEntry(twadmin::STR_KEYS_DECRYPT, _T("The following keys decrypt this file: ")), + TSS_StringEntry(twadmin::STR_BACKUP_EXISTS_1, _T("Backup file ")), + TSS_StringEntry(twadmin::STR_BACKUP_EXISTS_2, _T(" exists. Overwrite (Y/N)? ")), + TSS_StringEntry(twadmin::STR_PASSPHRASE_HINT, + _T("\n(When selecting a passphrase, keep in mind that good passphrases typically\n") + _T("have upper and lower case letters, digits and punctuation marks, and are\n") + _T("at least 8 characters in length.)\n\n")), + TSS_StringEntry(twadmin::STR_POL_NOT_UPDATED, _T("The policy file was not altered.\n")), + TSS_StringEntry(twadmin::STR_ENCRYPT_TYPE_NONE, _T("Encoding: None\n")), + TSS_StringEntry(twadmin::STR_ENCRYPT_TYPE_COMP, _T("Encoding: Compressed\n")), + TSS_StringEntry(twadmin::STR_ENCRYPT_TYPE_ASYM, _T("Encoding: Asymmetric Encryption\n")), + TSS_StringEntry(twadmin::STR_ENCRYPT_TYPE_UNK, _T("Encoding: Unrecognized\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_DB, _T("File Type: Tripwire Database (Ver %X.%X.%X.%X)\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_REP, _T("File Type: Tripwire Report (Ver %X.%X.%X.%X)\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_CFG, _T("File Type: Tripwire Config File (Ver %X.%X.%X.%X)\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_POL, _T("File Type: Tripwire Policy File (Ver %X.%X.%X.%X)\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_KEY, _T("File Type: Tripwire Key File (Ver %X.%X.%X.%X)\n")), + TSS_StringEntry(twadmin::STR_FILE_TYPE_UNK, _T("File Type: Unknown\n")), + TSS_StringEntry(twadmin::STR_ENTER_SITE_PASS, _T("Enter the site keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_VERIFY_SITE_PASS, _T("Verify the site keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_ENTER_LOCAL_PASS, _T("Enter the local keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_VERIFY_LOCAL_PASS, _T("Verify the local keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_ENTER_SITE_PASS_OLD, _T("Enter the old site keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_ENTER_LOCAL_PASS_OLD, _T("Enter the old local keyfile passphrase:")), + TSS_StringEntry(twadmin::STR_REMOVE_ENCRYPTION_WARNING, + _T("NOTE: Removing encryption on a file leaves it open to tampering!\n")), + TSS_StringEntry(twadmin::STR_ENCRYPTION_REMOVED, _T("Encryption removed from \"%s\" successfully.\n")), + TSS_StringEntry(twadmin::STR_ENCRYPTION_SUCCEEDED, _T("\"%s\" encrypted successfully.\n")), + TSS_StringEntry(twadmin::STR_FILE, _T("File: \"")), TSS_StringEntry(twadmin::STR_ENDQUOTE_NEWLINE, _T("\"\n")), - TSS_StringEntry( twadmin::STR_ERR2_NO_PT_CONFIG, _T("No plaintext config file specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_NO_CONFIG, _T("No config file specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_NO_PT_POLICY, _T("No plaintext policy file specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_NO_POLICY, _T("No policy file specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_CONFIG_OPEN, _T("Config file could not be opened.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED, _T("Site key file or no-encryption must be specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_LOCAL_KEY_NOT_SPECIFIED, _T("Local key file must be specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_KEYS_NOT_SPECIFIED, _T("Site or local key file must be specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_KEY_FILENAMES_IDENTICAL, _T("Site and local key filenames may not be identical.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_SITE_KEY_DOESNT_EXIST, _T("Site key does not exist. Use -m G mode to generate a new key.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_SITE_KEY_READ_ONLY, _T("Site key is read only, cannot overwrite.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_LOCAL_KEY_DOESNT_EXIST, _T("Local key does not exist. Use -m G mode to generate a new key.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_LOCAL_KEY_READ_ONLY, _T("Local key is read only, cannot overwrite.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_COULDNT_RENAME_FILE, _T("File could not be renamed ") ), - TSS_StringEntry( twadmin::STR_ERR2_CONVERSION_FILE_READ_ONLY1, _T("File to be converted ") ), - TSS_StringEntry( twadmin::STR_ERR2_CONVERSION_FILE_READ_ONLY2, _T(" is Read Only, key change aborted.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_UNABLE_TO_PRINT_POLICY, _T("\nUnable to print policy file.") ), - TSS_StringEntry( twadmin::STR_ERR2_CAN_NOT_ENCRYPT_KEYFILE, _T("Can not encrypt a keyfile.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE, _T("Can not remove encryption on a keyfile.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_NO_FILES_SPECIFIED, _T("No files specified.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_LONE_SITE_PASSPHRASE, _T("Site passphrase was specified without corresponding site keyfile.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_LONE_LOCAL_PASSPHRASE, _T("Local passphrase was specified without corresponding local keyfile.\n") ), + TSS_StringEntry(twadmin::STR_ERR2_NO_PT_CONFIG, _T("No plaintext config file specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_NO_CONFIG, _T("No config file specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_NO_PT_POLICY, _T("No plaintext policy file specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_NO_POLICY, _T("No policy file specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_CONFIG_OPEN, _T("Config file could not be opened.\n")), + TSS_StringEntry(twadmin::STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED, + _T("Site key file or no-encryption must be specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_LOCAL_KEY_NOT_SPECIFIED, _T("Local key file must be specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_KEYS_NOT_SPECIFIED, _T("Site or local key file must be specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_KEY_FILENAMES_IDENTICAL, + _T("Site and local key filenames may not be identical.\n")), + TSS_StringEntry(twadmin::STR_ERR2_SITE_KEY_DOESNT_EXIST, + _T("Site key does not exist. Use -m G mode to generate a new key.\n")), + TSS_StringEntry(twadmin::STR_ERR2_SITE_KEY_READ_ONLY, _T("Site key is read only, cannot overwrite.\n")), + TSS_StringEntry(twadmin::STR_ERR2_LOCAL_KEY_DOESNT_EXIST, + _T("Local key does not exist. Use -m G mode to generate a new key.\n")), + TSS_StringEntry(twadmin::STR_ERR2_LOCAL_KEY_READ_ONLY, _T("Local key is read only, cannot overwrite.\n")), + TSS_StringEntry(twadmin::STR_ERR2_COULDNT_RENAME_FILE, _T("File could not be renamed ")), + TSS_StringEntry(twadmin::STR_ERR2_CONVERSION_FILE_READ_ONLY1, _T("File to be converted ")), + TSS_StringEntry(twadmin::STR_ERR2_CONVERSION_FILE_READ_ONLY2, _T(" is Read Only, key change aborted.\n")), + TSS_StringEntry(twadmin::STR_ERR2_UNABLE_TO_PRINT_POLICY, _T("\nUnable to print policy file.")), + TSS_StringEntry(twadmin::STR_ERR2_CAN_NOT_ENCRYPT_KEYFILE, _T("Can not encrypt a keyfile.\n")), + TSS_StringEntry(twadmin::STR_ERR2_CAN_NOT_DECRYPT_KEYFILE, _T("Can not remove encryption on a keyfile.\n")), + TSS_StringEntry(twadmin::STR_ERR2_NO_FILES_SPECIFIED, _T("No files specified.\n")), + TSS_StringEntry(twadmin::STR_ERR2_LONE_SITE_PASSPHRASE, + _T("Site passphrase was specified without corresponding site keyfile.\n")), + TSS_StringEntry(twadmin::STR_ERR2_LONE_LOCAL_PASSPHRASE, + _T("Local passphrase was specified without corresponding local keyfile.\n")), - TSS_StringEntry( twadmin::STR_ERR2_FILE_DOES_NOT_EXIST, _T("File does not exist.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_COULD_NOT_BE_OPENED, _T("File could not be opened.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_COULD_NOT_BE_READ, _T("File could not be read.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_NOT_A_TW_FILE, _T("File is not a Tripwire data file.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_COULD_NOT_BE_EXAMINED,_T("File could not be examined.\n") ), + TSS_StringEntry(twadmin::STR_ERR2_FILE_DOES_NOT_EXIST, _T("File does not exist.\n")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_COULD_NOT_BE_OPENED, _T("File could not be opened.\n")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_COULD_NOT_BE_READ, _T("File could not be read.\n")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_NOT_A_TW_FILE, _T("File is not a Tripwire data file.\n")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_COULD_NOT_BE_EXAMINED, _T("File could not be examined.\n")), //TSS_StringEntry( twadmin::STR_ERR2_FILE_TYPE_UNKNOWN, _T("Error: File type is unknown for file %s\n") ), - TSS_StringEntry( twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN, _T("Encoding type is unknown.") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_NOT_ENCRYPED, _T("This file is not encrypted, decryption skipped.\nFilename: ") ), - TSS_StringEntry( twadmin::STR_ERR2_REMOVE_ENCRYPTION_FAILED, _T("Encryption removal failed.\nFilename: ") ), - TSS_StringEntry( twadmin::STR_ERR2_COULD_NOT_OPEN_PROVIDED_KEYFILE, _T("Error: Provided keyfile could not be opened ") ), - TSS_StringEntry( twadmin::STR_ERR2_FILE_ALREADY_ENCRYPTED, _T("File is currently encrypted. Skipping.\n") ), - TSS_StringEntry( twadmin::STR_ERR2_ENCRYPTION_FAILED, _T("Encryption failed.\n") ), + TSS_StringEntry(twadmin::STR_ERR2_ENCODING_TYPE_UNKNOWN, _T("Encoding type is unknown.")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_NOT_ENCRYPED, + _T("This file is not encrypted, decryption skipped.\nFilename: ")), + TSS_StringEntry(twadmin::STR_ERR2_REMOVE_ENCRYPTION_FAILED, _T("Encryption removal failed.\nFilename: ")), + TSS_StringEntry(twadmin::STR_ERR2_COULD_NOT_OPEN_PROVIDED_KEYFILE, + _T("Error: Provided keyfile could not be opened ")), + TSS_StringEntry(twadmin::STR_ERR2_FILE_ALREADY_ENCRYPTED, _T("File is currently encrypted. Skipping.\n")), + TSS_StringEntry(twadmin::STR_ERR2_ENCRYPTION_FAILED, _T("Encryption failed.\n")), // keygeneration - TSS_StringEntry( twadmin::STR_ERR2_KEYGEN_FILEWRITE, _T("Error: File could not be written to: ") ), - TSS_StringEntry( twadmin::STR_ERR2_KEYGEN, _T("Error generating key, ") ), - TSS_StringEntry( twadmin::STR_ERR2_KEYGEN2, _T(" not written.") ), - TSS_StringEntry( twadmin::STR_ERR2_PASSPHRASE_NOKEY, _T("Error: A passphrase has been specified without the corresponding key.") ), + TSS_StringEntry(twadmin::STR_ERR2_KEYGEN_FILEWRITE, _T("Error: File could not be written to: ")), + TSS_StringEntry(twadmin::STR_ERR2_KEYGEN, _T("Error generating key, ")), + TSS_StringEntry(twadmin::STR_ERR2_KEYGEN2, _T(" not written.")), + TSS_StringEntry(twadmin::STR_ERR2_PASSPHRASE_NOKEY, + _T("Error: A passphrase has been specified without the corresponding key.")), - TSS_StringEntry( twadmin::STR_ERR2_CREATE_CFG_MISSING_KEYFILE, _T("A config file can not be created and encrypted with a keyfile unless the same keyfile is specified as the SITEKEYFILE within the new config file text.") ), - TSS_StringEntry( twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1, _T("The specified keyfile \"") ), - TSS_StringEntry( twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2, _T("\" does not match the keyfile specified in the new config file text \"") ), - TSS_StringEntry( twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3, _T("\".") ), + TSS_StringEntry(twadmin::STR_ERR2_CREATE_CFG_MISSING_KEYFILE, + _T("A config file can not be created and encrypted with a keyfile unless the same keyfile is ") + _T("specified as the SITEKEYFILE within the new config file text.")), + TSS_StringEntry(twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1, _T("The specified keyfile \"")), + TSS_StringEntry(twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2, + _T("\" does not match the keyfile specified in the new config file text \"")), + TSS_StringEntry(twadmin::STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3, _T("\".")), -TSS_EndStringtable( cTWAdmin ) + TSS_StringEntry(twadmin::STR_ERR2_INVALID_KEY_SIZE, + _T("Invalid key size specified. Valid sizes are 1024 & 2048 bits.")), + TSS_EndStringtable(cTWAdmin) diff --git a/src/twadmin/twadminstrings.h b/src/twadmin/twadminstrings.h index 7262fa7..f3cfc81 100644 --- a/src/twadmin/twadminstrings.h +++ b/src/twadmin/twadminstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,122 +38,57 @@ #ifndef __TWADMINSTRINGS_H #define __TWADMINSTRINGS_H -#include "twadmin.h" // for: STRINGTABLE syntax +#include "twadmin.h" // for: STRINGTABLE syntax //--Message Keys -TSS_BeginStringIds( twadmin ) +TSS_BeginStringIds(twadmin) STR_TWADMIN_VERSION, - STR_TWADMIN_USAGE_SUMMARY, - STR_TWADMIN_HELP_CREATE_CFGFILE, - STR_TWADMIN_HELP_PRINT_CFGFILE, - STR_TWADMIN_HELP_CREATE_POLFILE, - STR_TWADMIN_HELP_PRINT_POLFILE, - STR_TWADMIN_HELP_REMOVE_ENCRYPTION, - STR_TWADMIN_HELP_ENCRYPT, - STR_TWADMIN_HELP_EXAMINE, - STR_TWADMIN_HELP_GENERATE_KEYS, - STR_TWADMIN_HELP_CHANGE_PASSPHRASES, - STR_KEYGEN_VERBOSE_OUTPUT_FILES, - STR_KEYGEN_VERBOSE_PASSPHRASES, - STR_KEYGEN_VERBOSE_SITEKEY, - STR_KEYGEN_VERBOSE_LOCALKEY, - STR_UPCONFIG_VERBOSE_PT_CONFIG, - STR_UPCONFIG_CREATING_CONFIG, - STR_UPCONFIG_VERBOSE_PT_POLICY, - STR_SITEKEYFILE, - STR_LOCALKEYFILE, - STR_SITEKEY_EXISTS_1, - STR_SITEKEY_EXISTS_2, - STR_LOCALKEY_EXISTS_1, - STR_LOCALKEY_EXISTS_2, - STR_KEYFILE_BACKED_UP_AS, - STR_CONVERTING_FILES, - STR_EXAMINING_FILE, - STR_KEYS_DECRYPT, - STR_BACKUP_EXISTS_1, - STR_BACKUP_EXISTS_2, - STR_PASSPHRASE_HINT, - STR_POL_NOT_UPDATED, - STR_ENCRYPT_TYPE_NONE, - STR_ENCRYPT_TYPE_COMP, - STR_ENCRYPT_TYPE_ASYM, - STR_ENCRYPT_TYPE_UNK, - STR_FILE_TYPE_DB, - STR_FILE_TYPE_REP, - STR_FILE_TYPE_CFG, - STR_FILE_TYPE_POL, - STR_FILE_TYPE_KEY, - STR_FILE_TYPE_UNK, - STR_ENTER_SITE_PASS, - STR_VERIFY_SITE_PASS, - STR_ENTER_LOCAL_PASS, - STR_VERIFY_LOCAL_PASS, - STR_ENTER_SITE_PASS_OLD, - STR_ENTER_LOCAL_PASS_OLD, - STR_REMOVE_ENCRYPTION_WARNING, - STR_ENCRYPTION_REMOVED, - STR_ENCRYPTION_SUCCEEDED, - STR_FILE, - STR_ENDQUOTE_NEWLINE, + STR_EMBEDDED_VERSION, STR_TWADMIN_USAGE_SUMMARY, STR_TWADMIN_HELP_CREATE_CFGFILE, STR_TWADMIN_HELP_PRINT_CFGFILE, + STR_TWADMIN_HELP_CREATE_POLFILE, STR_TWADMIN_HELP_PRINT_POLFILE, STR_TWADMIN_HELP_REMOVE_ENCRYPTION, + STR_TWADMIN_HELP_ENCRYPT, STR_TWADMIN_HELP_EXAMINE, STR_TWADMIN_HELP_GENERATE_KEYS, + STR_TWADMIN_HELP_CHANGE_PASSPHRASES, STR_KEYGEN_VERBOSE_OUTPUT_FILES, STR_KEYGEN_VERBOSE_PASSPHRASES, + STR_KEYGEN_VERBOSE_SITEKEY, STR_KEYGEN_VERBOSE_LOCALKEY, STR_UPCONFIG_VERBOSE_PT_CONFIG, + STR_UPCONFIG_CREATING_CONFIG, STR_UPCONFIG_VERBOSE_PT_POLICY, STR_SITEKEYFILE, STR_LOCALKEYFILE, + STR_SITEKEY_EXISTS_1, STR_SITEKEY_EXISTS_2, STR_LOCALKEY_EXISTS_1, STR_LOCALKEY_EXISTS_2, STR_KEYFILE_BACKED_UP_AS, + STR_CONVERTING_FILES, STR_EXAMINING_FILE, STR_KEYS_DECRYPT, STR_BACKUP_EXISTS_1, STR_BACKUP_EXISTS_2, + STR_PASSPHRASE_HINT, STR_POL_NOT_UPDATED, STR_ENCRYPT_TYPE_NONE, STR_ENCRYPT_TYPE_COMP, STR_ENCRYPT_TYPE_ASYM, + STR_ENCRYPT_TYPE_UNK, STR_FILE_TYPE_DB, STR_FILE_TYPE_REP, STR_FILE_TYPE_CFG, STR_FILE_TYPE_POL, STR_FILE_TYPE_KEY, + STR_FILE_TYPE_UNK, STR_ENTER_SITE_PASS, STR_VERIFY_SITE_PASS, STR_ENTER_LOCAL_PASS, STR_VERIFY_LOCAL_PASS, + STR_ENTER_SITE_PASS_OLD, STR_ENTER_LOCAL_PASS_OLD, STR_REMOVE_ENCRYPTION_WARNING, STR_ENCRYPTION_REMOVED, + STR_ENCRYPTION_SUCCEEDED, STR_FILE, STR_ENDQUOTE_NEWLINE, // key generation - STR_GENERATING_KEYS, - STR_GENERATION_COMPLETE, + STR_GENERATING_KEYS, STR_GENERATION_COMPLETE, // Extra error strings - STR_ERR2_NO_PT_CONFIG, - STR_ERR2_NO_CONFIG, - STR_ERR2_NO_PT_POLICY, - STR_ERR2_NO_POLICY, - STR_ERR2_CONFIG_OPEN, - STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED, - STR_ERR2_LOCAL_KEY_NOT_SPECIFIED, - STR_ERR2_KEYS_NOT_SPECIFIED, - STR_ERR2_KEY_FILENAMES_IDENTICAL, - STR_ERR2_SITE_KEY_DOESNT_EXIST, - STR_ERR2_SITE_KEY_READ_ONLY, - STR_ERR2_LOCAL_KEY_DOESNT_EXIST, - STR_ERR2_LOCAL_KEY_READ_ONLY, - STR_ERR2_COULDNT_RENAME_FILE, - STR_ERR2_CONVERSION_FILE_READ_ONLY1, - STR_ERR2_CONVERSION_FILE_READ_ONLY2, - STR_ERR2_UNABLE_TO_PRINT_POLICY, - STR_ERR2_CAN_NOT_ENCRYPT_KEYFILE, - STR_ERR2_CAN_NOT_DECRYPT_KEYFILE, - STR_ERR2_NO_FILES_SPECIFIED, - STR_ERR2_LONE_SITE_PASSPHRASE, - STR_ERR2_LONE_LOCAL_PASSPHRASE, + STR_ERR2_NO_PT_CONFIG, STR_ERR2_NO_CONFIG, STR_ERR2_NO_PT_POLICY, STR_ERR2_NO_POLICY, STR_ERR2_CONFIG_OPEN, + STR_ERR2_SITE_KEY_NOENCRYPT_NOT_SPECIFIED, STR_ERR2_LOCAL_KEY_NOT_SPECIFIED, STR_ERR2_KEYS_NOT_SPECIFIED, + STR_ERR2_KEY_FILENAMES_IDENTICAL, STR_ERR2_SITE_KEY_DOESNT_EXIST, STR_ERR2_SITE_KEY_READ_ONLY, + STR_ERR2_LOCAL_KEY_DOESNT_EXIST, STR_ERR2_LOCAL_KEY_READ_ONLY, STR_ERR2_COULDNT_RENAME_FILE, + STR_ERR2_CONVERSION_FILE_READ_ONLY1, STR_ERR2_CONVERSION_FILE_READ_ONLY2, STR_ERR2_UNABLE_TO_PRINT_POLICY, + STR_ERR2_CAN_NOT_ENCRYPT_KEYFILE, STR_ERR2_CAN_NOT_DECRYPT_KEYFILE, STR_ERR2_NO_FILES_SPECIFIED, + STR_ERR2_LONE_SITE_PASSPHRASE, STR_ERR2_LONE_LOCAL_PASSPHRASE, - STR_ERR2_FILE_DOES_NOT_EXIST, - STR_ERR2_FILE_COULD_NOT_BE_OPENED, - STR_ERR2_FILE_COULD_NOT_BE_READ, - STR_ERR2_FILE_NOT_A_TW_FILE, - STR_ERR2_FILE_COULD_NOT_BE_EXAMINED, + STR_ERR2_FILE_DOES_NOT_EXIST, STR_ERR2_FILE_COULD_NOT_BE_OPENED, STR_ERR2_FILE_COULD_NOT_BE_READ, + STR_ERR2_FILE_NOT_A_TW_FILE, STR_ERR2_FILE_COULD_NOT_BE_EXAMINED, - //now a ERR1 str STR_ERR2_FILE_TYPE_UNKNOWN, - STR_ERR2_ENCODING_TYPE_UNKNOWN, - STR_ERR2_FILE_NOT_ENCRYPED, + //now a ERR1 str STR_ERR2_FILE_TYPE_UNKNOWN, + STR_ERR2_ENCODING_TYPE_UNKNOWN, STR_ERR2_FILE_NOT_ENCRYPED, //STR_ERR2_REMOVE_ENCRYPTION_WARNING, STR_ERR2_REMOVE_ENCRYPTION_FAILED, //STR_ERR2_ENCRYPTION_REMOVED, - STR_ERR2_COULD_NOT_OPEN_PROVIDED_KEYFILE, - STR_ERR2_FILE_ALREADY_ENCRYPTED, - STR_ERR2_ENCRYPTION_FAILED, - + STR_ERR2_COULD_NOT_OPEN_PROVIDED_KEYFILE, STR_ERR2_FILE_ALREADY_ENCRYPTED, STR_ERR2_ENCRYPTION_FAILED, + // keygeneration - STR_ERR2_KEYGEN_FILEWRITE, - STR_ERR2_KEYGEN, - STR_ERR2_KEYGEN2, - STR_ERR2_PASSPHRASE_NOKEY, + STR_ERR2_KEYGEN_FILEWRITE, STR_ERR2_KEYGEN, STR_ERR2_KEYGEN2, STR_ERR2_PASSPHRASE_NOKEY, - STR_ERR2_CREATE_CFG_MISSING_KEYFILE, - STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1, - STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2, - STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3 + STR_ERR2_CREATE_CFG_MISSING_KEYFILE, STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH1, STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH2, + STR_ERR2_CREATE_CFG_SITEKEY_MISMATCH3, -TSS_EndStringIds( twadmin ) + STR_ERR2_INVALID_KEY_SIZE -#endif//__TWADMINSTRINGS_H + TSS_EndStringIds(twadmin) +#endif //__TWADMINSTRINGS_H diff --git a/src/twcrypto/Makefile.am b/src/twcrypto/Makefile.am index 7685ffd..27aaa0c 100644 --- a/src/twcrypto/Makefile.am +++ b/src/twcrypto/Makefile.am @@ -1,13 +1,19 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtwcrypto.a +libtwcrypto_adir=. libtwcrypto_a_SOURCES = \ bytequeue.cpp crypto.cpp cryptoarchive.cpp keyfile.cpp \ stdtwcrypto.cpp twcrypto.cpp twcryptoerrors.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +libtwcrypto_a_HEADERS = \ + bytequeue.h crypto.h cryptoarchive.h keyfile.h \ + stdtwcrypto.h twcrypto.h twcryptoerrors.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtwcrypto_a_OBJECTS) diff --git a/src/twcrypto/Makefile.in b/src/twcrypto/Makefile.in index 855b82a..9afae2e 100644 --- a/src/twcrypto/Makefile.in +++ b/src/twcrypto/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libtwcrypto_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/twcrypto -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libtwcrypto_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libtwcrypto_a_AR = $(AR) $(ARFLAGS) libtwcrypto_a_LIBADD = am_libtwcrypto_a_OBJECTS = bytequeue.$(OBJEXT) crypto.$(OBJEXT) \ @@ -57,23 +115,95 @@ am_libtwcrypto_a_OBJECTS = bytequeue.$(OBJEXT) crypto.$(OBJEXT) \ stdtwcrypto.$(OBJEXT) twcrypto.$(OBJEXT) \ twcryptoerrors.$(OBJEXT) libtwcrypto_a_OBJECTS = $(am_libtwcrypto_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libtwcrypto_a_SOURCES) DIST_SOURCES = $(libtwcrypto_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libtwcrypto_adir)" +HEADERS = $(libtwcrypto_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -89,7 +219,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -97,6 +227,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -108,6 +239,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -124,21 +256,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -168,19 +303,29 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtwcrypto.a +libtwcrypto_adir = . libtwcrypto_a_SOURCES = \ bytequeue.cpp crypto.cpp cryptoarchive.cpp keyfile.cpp \ stdtwcrypto.cpp twcrypto.cpp twcryptoerrors.cpp +libtwcrypto_a_HEADERS = \ + bytequeue.h crypto.h cryptoarchive.h keyfile.h \ + stdtwcrypto.h twcrypto.h twcryptoerrors.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -189,15 +334,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twcrypto/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/twcrypto/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twcrypto/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/twcrypto/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -214,13 +358,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libtwcrypto.a: $(libtwcrypto_a_OBJECTS) $(libtwcrypto_a_DEPENDENCIES) - -rm -f libtwcrypto.a - $(libtwcrypto_a_AR) libtwcrypto.a $(libtwcrypto_a_OBJECTS) $(libtwcrypto_a_LIBADD) - $(RANLIB) libtwcrypto.a + +libtwcrypto.a: $(libtwcrypto_a_OBJECTS) $(libtwcrypto_a_DEPENDENCIES) $(EXTRA_libtwcrypto_a_DEPENDENCIES) + $(AM_V_at)-rm -f libtwcrypto.a + $(AM_V_AR)$(libtwcrypto_a_AR) libtwcrypto.a $(libtwcrypto_a_OBJECTS) $(libtwcrypto_a_LIBADD) + $(AM_V_at)$(RANLIB) libtwcrypto.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -229,91 +375,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libtwcrypto_aHEADERS: $(libtwcrypto_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libtwcrypto_a_HEADERS)'; test -n "$(libtwcrypto_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libtwcrypto_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libtwcrypto_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libtwcrypto_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libtwcrypto_adir)" || exit $$?; \ + done + +uninstall-libtwcrypto_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libtwcrypto_a_HEADERS)'; test -n "$(libtwcrypto_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libtwcrypto_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libtwcrypto_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -324,16 +500,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -353,18 +536,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libtwcrypto_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -383,22 +586,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libtwcrypto_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libtwcrypto_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libtwcrypto_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtwcrypto_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/twcrypto/bytequeue.cpp b/src/twcrypto/bytequeue.cpp index 9d7ade5..5896e8f 100644 --- a/src/twcrypto/bytequeue.cpp +++ b/src/twcrypto/bytequeue.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,86 +46,98 @@ class cByteQueueNode { public: - cByteQueueNode(unsigned int maxSize); + explicit cByteQueueNode(unsigned int maxSize); unsigned int CurrentSize() const - {return tail-head;} + { + return tail - head; + } unsigned int UsedUp() const - {return (head==MaxSize());} + { + return (head == MaxSize()); + } unsigned int Put(byte inByte); - unsigned int Put(const byte *inString, unsigned int length); + unsigned int Put(const byte* inString, unsigned int length); - unsigned int Get(byte &outByte); - unsigned int Get(byte *outString, unsigned int getMax); + unsigned int Get(byte& outByte); + unsigned int Get(byte* outString, unsigned int getMax); - unsigned int Peek(byte &outByte) const; + unsigned int Peek(byte& outByte) const; - void CopyTo(BufferedTransformation &target) const - {target.Put(buf+head, tail-head);} - void CopyTo(byte *target) const - {memcpy(target, buf+head, tail-head);} + void CopyTo(BufferedTransformation& target) const + { + target.Put(buf + head, tail - head); + } + void CopyTo(byte* target) const + { + memcpy(target, buf + head, tail - head); + } byte operator[](unsigned int i) const - {return buf[i-head];} + { + return buf[i - head]; + } - cByteQueueNode *next; + cByteQueueNode* next; private: - unsigned int MaxSize() const {return buf.size;} + unsigned int MaxSize() const + { + return buf.size; + } SecByteBlock buf; unsigned int head, tail; }; -cByteQueueNode::cByteQueueNode(unsigned int maxSize) - : buf(maxSize) +cByteQueueNode::cByteQueueNode(unsigned int maxSize) : buf(maxSize) { head = tail = 0; - next = 0; + next = 0; } unsigned int cByteQueueNode::Put(byte inByte) { - if (MaxSize()==tail) + if (MaxSize() == tail) return 0; - buf[tail++]=inByte; + buf[tail++] = inByte; return 1; } -unsigned int cByteQueueNode::Put(const byte *inString, unsigned int length) +unsigned int cByteQueueNode::Put(const byte* inString, unsigned int length) { - unsigned int l = STDMIN(length, MaxSize()-tail); - memcpy(buf+tail, inString, l); + unsigned int l = STDMIN(length, MaxSize() - tail); + memcpy(buf + tail, inString, l); tail += l; return l; } -unsigned int cByteQueueNode::Get(byte &outByte) +unsigned int cByteQueueNode::Get(byte& outByte) { - if (tail==head) + if (tail == head) return 0; - outByte=buf[head++]; + outByte = buf[head++]; return 1; } -unsigned int cByteQueueNode::Get(byte *outString, unsigned int getMax) +unsigned int cByteQueueNode::Get(byte* outString, unsigned int getMax) { - unsigned int l = STDMIN(getMax, tail-head); - memcpy(outString, buf+head, l); + unsigned int l = STDMIN(getMax, tail - head); + memcpy(outString, buf + head, l); head += l; return l; } -unsigned int cByteQueueNode::Peek(byte &outByte) const +unsigned int cByteQueueNode::Peek(byte& outByte) const { - if (tail==head) + if (tail == head) return 0; - outByte=buf[head]; + outByte = buf[head]; return 1; } @@ -133,30 +145,27 @@ unsigned int cByteQueueNode::Peek(byte &outByte) const // cByteQueue //----------------------------------------------------------------------------- -cByteQueue::cByteQueue(int mNodeSize) - : BufferedTransformation(), - mNodeSize(mNodeSize), - mCurrentSize(0) +cByteQueue::cByteQueue(int nodeSize) : BufferedTransformation(), mNodeSize(nodeSize), mCurrentSize(0) { head = tail = new cByteQueueNode(mNodeSize); } -cByteQueue::cByteQueue(const cByteQueue ©) : BufferedTransformation() +cByteQueue::cByteQueue(const cByteQueue& copy) : BufferedTransformation() { CopyFrom(copy); } -void cByteQueue::CopyFrom(const cByteQueue ©) +void cByteQueue::CopyFrom(const cByteQueue& copy) { - mNodeSize = copy.mNodeSize; - mCurrentSize = copy.mCurrentSize; + mNodeSize = copy.mNodeSize; + mCurrentSize = copy.mCurrentSize; head = tail = new cByteQueueNode(*copy.head); - for (cByteQueueNode *current=copy.head->next; current; current=current->next) + for (cByteQueueNode* current = copy.head->next; current; current = current->next) { tail->next = new cByteQueueNode(*current); - tail = tail->next; + tail = tail->next; } tail->next = NULL; @@ -169,11 +178,11 @@ cByteQueue::~cByteQueue() void cByteQueue::Destroy() { - cByteQueueNode *next; + cByteQueueNode* next; - for (cByteQueueNode *current=head; current; current=next) + for (cByteQueueNode* current = head; current; current = next) { - next=current->next; + next = current->next; delete current; } @@ -183,15 +192,15 @@ void cByteQueue::Destroy() /////////////////////////////////////////////////////////////////////////////// // CopyTo -- note that this does not remove anything from the queue /////////////////////////////////////////////////////////////////////////////// -void cByteQueue::CopyTo(BufferedTransformation &target) const +void cByteQueue::CopyTo(BufferedTransformation& target) const { - for (cByteQueueNode *current=head; current; current=current->next) + for (cByteQueueNode* current = head; current; current = current->next) current->CopyTo(target); } -void cByteQueue::CopyTo(byte *target) const +void cByteQueue::CopyTo(byte* target) const { - for (cByteQueueNode *current=head; current; current=current->next) + for (cByteQueueNode* current = head; current; current = current->next) { current->CopyTo(target); target += current->CurrentSize(); @@ -216,38 +225,38 @@ void cByteQueue::Put(byte inByte) if (!tail->Put(inByte)) { tail->next = new cByteQueueNode(mNodeSize); - tail = tail->next; + tail = tail->next; tail->Put(inByte); } // put increases the size of the queue by one mCurrentSize++; } -void cByteQueue::Put(const byte *inString, unsigned int length) +void cByteQueue::Put(const byte* inString, unsigned int length) { unsigned int l; // put increases the size of the queue by length mCurrentSize += length; - while ((l=tail->Put(inString, length)) < length) + while ((l = tail->Put(inString, length)) < length) { tail->next = new cByteQueueNode(mNodeSize); - tail = tail->next; + tail = tail->next; inString += l; length -= l; } } -unsigned int cByteQueue::Get(byte &outByte) +unsigned int cByteQueue::Get(byte& outByte) { int l = head->Get(outByte); if (head->UsedUp()) { - cByteQueueNode *temp=head; - head = head->next; + cByteQueueNode* temp = head; + head = head->next; delete temp; - if (!head) // just deleted the last node + if (!head) // just deleted the last node head = tail = new cByteQueueNode(mNodeSize); } // put decreases the size of the queue by one @@ -256,14 +265,14 @@ unsigned int cByteQueue::Get(byte &outByte) return l; } -unsigned int cByteQueue::Get(byte *outString, unsigned int getMax) +unsigned int cByteQueue::Get(byte* outString, unsigned int getMax) { - unsigned int getMaxSave=getMax; - cByteQueueNode *current=head; + unsigned int getMaxSave = getMax; + cByteQueueNode* current = head; while (getMax && current) { - int l=current->Get(outString, getMax); + int l = current->Get(outString, getMax); outString += l; getMax -= l; @@ -275,8 +284,8 @@ unsigned int cByteQueue::Get(byte *outString, unsigned int getMax) // that used to be below.... while (head && head->UsedUp() && (head != tail)) { - current=head; - head=head->next; + current = head; + head = head->next; delete current; } @@ -285,32 +294,32 @@ unsigned int cByteQueue::Get(byte *outString, unsigned int getMax) head = tail = new cByteQueueNode(mNodeSize); */ - int rtn = getMaxSave-getMax; + int rtn = getMaxSave - getMax; mCurrentSize -= rtn; return (rtn); } -unsigned int cByteQueue::Peek(byte &outByte) const +unsigned int cByteQueue::Peek(byte& outByte) const { return head->Peek(outByte); } -cByteQueue & cByteQueue::operator=(const cByteQueue &rhs) +cByteQueue& cByteQueue::operator=(const cByteQueue& rhs) { Destroy(); CopyFrom(rhs); return *this; } -bool cByteQueue::operator==(const cByteQueue &rhs) const +bool cByteQueue::operator==(const cByteQueue& rhs) const { const unsigned long currentSize = CurrentSize(); if (currentSize != rhs.CurrentSize()) return false; - for (unsigned long i = 0; inext) + for (cByteQueueNode* current = head; current; current = current->next) { if (i < current->CurrentSize()) return (*current)[i]; - + i -= current->CurrentSize(); } @@ -331,4 +340,3 @@ byte cByteQueue::operator[](unsigned long i) const assert(false); return 0; } - diff --git a/src/twcrypto/bytequeue.h b/src/twcrypto/bytequeue.h index e64484e..f5aada0 100644 --- a/src/twcrypto/bytequeue.h +++ b/src/twcrypto/bytequeue.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,7 +33,7 @@ // bytequeue.h // // cByteQueue -- specification file for an unlimited queue for storing bytes -// +// // this is a superior implementation of the byte queue supplied with the crypto++ lib #ifndef __BYTEQUEUE_H #define __BYTEQUEUE_H @@ -45,39 +45,40 @@ class cByteQueueNode; class cByteQueue : public BufferedTransformation { public: - cByteQueue(int nodeSize=1024); - cByteQueue(const cByteQueue ©); + explicit cByteQueue(int nodeSize = 1024); + cByteQueue(const cByteQueue& copy); ~cByteQueue(); // how many bytes currently stored unsigned long CurrentSize() const; unsigned long MaxRetrieveable() - {return CurrentSize();} + { + return CurrentSize(); + } void Put(byte inByte); - void Put(const byte *inString, unsigned int length); + void Put(const byte* inString, unsigned int length); // both functions returns the number of bytes actually retrived - unsigned int Get(byte &outByte); - unsigned int Get(byte *outString, unsigned int getMax); + unsigned int Get(byte& outByte); + unsigned int Get(byte* outString, unsigned int getMax); - unsigned int Peek(byte &outByte) const; + unsigned int Peek(byte& outByte) const; - void CopyTo(BufferedTransformation &target) const; - void CopyTo(byte *target) const; + void CopyTo(BufferedTransformation& target) const; + void CopyTo(byte* target) const; - cByteQueue & operator=(const cByteQueue &rhs); - bool operator==(const cByteQueue &rhs) const; - byte operator[](unsigned long i) const; + cByteQueue& operator=(const cByteQueue& rhs); + bool operator==(const cByteQueue& rhs) const; + byte operator[](unsigned long i) const; private: - void CopyFrom(const cByteQueue ©); + void CopyFrom(const cByteQueue& copy); void Destroy(); - int mNodeSize; - int mCurrentSize; + int mNodeSize; + int mCurrentSize; cByteQueueNode *head, *tail; }; #endif //__BYTEQUEUE_H - diff --git a/src/twcrypto/crypto.cpp b/src/twcrypto/crypto.cpp index 92dbf25..6c1c80a 100644 --- a/src/twcrypto/crypto.cpp +++ b/src/twcrypto/crypto.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,6 +39,7 @@ #include "core/errorgeneral.h" #include "time.h" #include "core/archive.h" +#include "core/usernotify.h" #include "cryptlib/sha.h" #include "cryptlib/rng.h" @@ -53,33 +54,36 @@ #include "cryptlib/rsa.h" #endif -const uint32 EL_GAMAL_SIG_PUBLIC_MAGIC_NUM = 0x7ae2c945; +#include +#include + +const uint32 EL_GAMAL_SIG_PUBLIC_MAGIC_NUM = 0x7ae2c945; const uint32 EL_GAMAL_SIG_PRIVATE_MAGIC_NUM = 0x0d0ffa12; /////////////////////////////////////////////////////////////////////////////// // macros for reading and writing integers -#define WRITE_INTEGER(I) \ +#define WRITE_INTEGER(I) \ len = I.MinEncodedSize(Integer::UNSIGNED); \ - ASSERT(len >=0 && len < 9000); \ - i32 = tw_htonl(len); \ - memcpy(pOut, &i32, sizeof(i32)); \ - pOut += sizeof(int32); \ - I.Encode(pOut, len, Integer::UNSIGNED); \ + ASSERT(len >= 0 && len < 9000); \ + i32 = tw_htonl(len); \ + memcpy(pOut, &i32, sizeof(i32)); \ + pOut += sizeof(int32); \ + I.Encode(pOut, len, Integer::UNSIGNED); \ pOut += len; -#define READ_INTEGER(I) \ - memcpy(&i32, pIn, sizeof(i32)); \ - len = tw_ntohl(i32); \ - ASSERT(len >= 0 && len < 9000); \ - pIn += sizeof(int32); \ +#define READ_INTEGER(I) \ + memcpy(&i32, pIn, sizeof(i32)); \ + len = tw_ntohl(i32); \ + ASSERT(len >= 0 && len < 9000); \ + pIn += sizeof(int32); \ I.Decode(pIn, len, Integer::UNSIGNED); \ pIn += len; /////////////////////////////////////////////////////////////////////////////// // class cNullCipher -- no encryption cipher -int cNullCipher::GetBlockSizePlain() +int cNullCipher::GetBlockSizePlain() { // lets use the blocksize of TripleDES_Encryption since that may be // better than picking a blocksize at random @@ -87,11 +91,11 @@ int cNullCipher::GetBlockSizePlain() } // return the size of data blocks for plaintext and cipertext -int cNullCipher::GetBlockSizeCipher() +int cNullCipher::GetBlockSizeCipher() { return TripleDES_Encryption::BLOCKSIZE; } - + // process a block of data. indata and outdata may be the same memory void cNullCipher::ProcessBlock(const void* indata, void* outdata) { @@ -107,7 +111,7 @@ void cNullCipher::ProcessBlock(const void* indata, void* outdata) class cIDEA_i { public: - IDEA* mpIDEA; + IDEA* mpIDEA; }; cIDEA::cIDEA() @@ -139,12 +143,12 @@ int cIDEA::GetBlockSizePlain() { return IDEA::BLOCKSIZE; } - + int cIDEA::GetBlockSizeCipher() { return IDEA::BLOCKSIZE; } - + // process a block of data. indata and outdata may be the same memory void cIDEA::ProcessBlock(const void* indata, void* outdata) { @@ -167,8 +171,8 @@ void cIDEA::ProcessBlock(const void* indata, void* outdata) class cTripleDES_i { public: - TripleDES_Encryption* mpEncryptor; - TripleDES_Decryption* mpDecryptor; + TripleDES_Encryption* mpEncryptor; + TripleDES_Decryption* mpDecryptor; }; cTripleDES::cTripleDES() @@ -216,13 +220,13 @@ int cTripleDES::GetBlockSizePlain() ASSERT(TripleDES_Encryption::BLOCKSIZE == TripleDES_Decryption::BLOCKSIZE); return TripleDES_Encryption::BLOCKSIZE; } - + int cTripleDES::GetBlockSizeCipher() { ASSERT(TripleDES_Encryption::BLOCKSIZE == TripleDES_Decryption::BLOCKSIZE); return TripleDES_Encryption::BLOCKSIZE; } - + // process a block of data. indata and outdata may be the same memory void cTripleDES::ProcessBlock(const void* indata, void* outdata) { @@ -231,7 +235,8 @@ void cTripleDES::ProcessBlock(const void* indata, void* outdata) if (!mpData->mpEncryptor && !mpData->mpDecryptor) { - ThrowAndAssert(INTERNAL_ERROR("crypto.cpp")); //cTWError::E_INTERNAL, TSTRING(_T("Key not set in symmetric encryption.")))); + ThrowAndAssert(INTERNAL_ERROR( + "crypto.cpp")); //cTWError::E_INTERNAL, TSTRING(_T("Key not set in symmetric encryption.")))); } if (mpData->mpEncryptor) @@ -256,8 +261,8 @@ class cRSAPrivateKey_i cRSAPrivateKey::cRSAPrivateKey() { - mpData = new cRSAPrivateKey_i; - mpData->mpKey = 0; + mpData = new cRSAPrivateKey_i; + mpData->mpKey = 0; mpData->mKeyLength = 0; } @@ -291,7 +296,7 @@ cRSAPrivateKey::cRSAPrivateKey(void* pDataStream) cRSAPrivateKey::~cRSAPrivateKey() { - if (mpData) + if (mpData) { delete mpData->mpKey; delete mpData; @@ -311,15 +316,16 @@ int cRSAPrivateKey::GetWriteLen() const ASSERT(mpData->mpKey->GetTrapdoorFunction().GetParameterDQ().IsPositive()); ASSERT(mpData->mpKey->GetTrapdoorFunction().GetParameterU().IsPositive()); - int len = sizeof(int16) + - mpData->mpKey->GetTrapdoorFunction().GetModulus().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetExponent().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetPrime1().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetPrime2().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetDecryptionExponent().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetParameterDP().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetParameterDQ().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetParameterU().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32); + int len = sizeof(int16) + mpData->mpKey->GetTrapdoorFunction().GetModulus().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetExponent().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetPrime1().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetPrime2().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + + mpData->mpKey->GetTrapdoorFunction().GetDecryptionExponent().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetParameterDP().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetParameterDQ().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetParameterU().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32); return len; } @@ -346,25 +352,25 @@ void cRSAPrivateKey::Write(void* pDataStream) const pOut += sizeof(int16); Integer n, e, d, p, q, dp, dq, u; - - n = mpData->mpKey->GetTrapdoorFunction().GetModulus(); - e = mpData->mpKey->GetTrapdoorFunction().GetExponent(); - p = mpData->mpKey->GetTrapdoorFunction().GetPrime1(); - q = mpData->mpKey->GetTrapdoorFunction().GetPrime2(); - d = mpData->mpKey->GetTrapdoorFunction().GetDecryptionExponent(); + + n = mpData->mpKey->GetTrapdoorFunction().GetModulus(); + e = mpData->mpKey->GetTrapdoorFunction().GetExponent(); + p = mpData->mpKey->GetTrapdoorFunction().GetPrime1(); + q = mpData->mpKey->GetTrapdoorFunction().GetPrime2(); + d = mpData->mpKey->GetTrapdoorFunction().GetDecryptionExponent(); dp = mpData->mpKey->GetTrapdoorFunction().GetParameterDP(); dq = mpData->mpKey->GetTrapdoorFunction().GetParameterDQ(); - u = mpData->mpKey->GetTrapdoorFunction().GetParameterU(); + u = mpData->mpKey->GetTrapdoorFunction().GetParameterU(); int32 len; -#define WRITE_INTEGER(I) \ - len = I.MinEncodedSize(Integer::UNSIGNED); \ - i32 = tw_htonl(len); \ - memcpy(pOut, &i32, sizeof(i32)); \ - pOut += sizeof(int32); \ - I.Encode(pOut, len, Integer::UNSIGNED); \ - pOut += len; +# define WRITE_INTEGER(I) \ + len = I.MinEncodedSize(Integer::UNSIGNED); \ + i32 = tw_htonl(len); \ + memcpy(pOut, &i32, sizeof(i32)); \ + pOut += sizeof(int32); \ + I.Encode(pOut, len, Integer::UNSIGNED); \ + pOut += len; WRITE_INTEGER(n); WRITE_INTEGER(e); @@ -381,14 +387,14 @@ void cRSAPrivateKey::Write(void* pDataStream) const class cRSAPublicKey_i { public: - int16 mKeyLength; - RSAPublicKey* mpKey; + int16 mKeyLength; + RSAPublicKey* mpKey; }; cRSAPublicKey::cRSAPublicKey() { - mpData = new cRSAPublicKey_i; - mpData->mpKey = 0; + mpData = new cRSAPublicKey_i; + mpData->mpKey = 0; mpData->mKeyLength = 0; } @@ -397,9 +403,9 @@ cRSAPublicKey::cRSAPublicKey(void* pDataStream) mpData = new cRSAPublicKey_i; Integer n, e; - int32 len; - int16 i16; - int32 i32; + int32 len; + int16 i16; + int32 i32; byte* pIn = (byte*)pDataStream; @@ -424,12 +430,12 @@ cRSAPublicKey::cRSAPublicKey(const cRSAPrivateKey& privateKey) ASSERT(privateKey.mpData->mpKey); mpData->mKeyLength = privateKey.mpData->mKeyLength; - mpData->mpKey = new RSAPublicKey(*privateKey.mpData->mpKey); + mpData->mpKey = new RSAPublicKey(*privateKey.mpData->mpKey); } cRSAPublicKey::~cRSAPublicKey() { - if (mpData) + if (mpData) { delete mpData->mpKey; delete mpData; @@ -443,9 +449,9 @@ int cRSAPublicKey::GetWriteLen() const ASSERT(mpData->mpKey->GetTrapdoorFunction().GetModulus().IsPositive()); ASSERT(mpData->mpKey->GetTrapdoorFunction().GetExponent().IsPositive()); - int len = sizeof(int16) + - mpData->mpKey->GetTrapdoorFunction().GetModulus().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetTrapdoorFunction().GetExponent().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32); + int len = sizeof(int16) + mpData->mpKey->GetTrapdoorFunction().GetModulus().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetTrapdoorFunction().GetExponent().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32); return len; } @@ -466,7 +472,7 @@ void cRSAPublicKey::Write(void* pDataStream) const pOut += sizeof(int16); Integer n, e; - + n = mpData->mpKey->GetTrapdoorFunction().GetModulus(); e = mpData->mpKey->GetTrapdoorFunction().GetExponent(); @@ -476,23 +482,23 @@ void cRSAPublicKey::Write(void* pDataStream) const WRITE_INTEGER(e); } -#ifdef _DEBUG +# ifdef DEBUG void cRSAPublicKey::TraceContents() { cDebug d("cRSAPublicKey::TraceContents"); { - std::ostringstream os; - os << mpData->mpKey->GetTrapdoorFunction().GetModulus(); - d.TraceDebug("Modulus = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetTrapdoorFunction().GetModulus(); + d.TraceDebug("Modulus = %s\n", os.str().c_str()); } { - std::ostringstream os; - os << mpData->mpKey->GetTrapdoorFunction().GetExponent(); - d.TraceDebug("Exponent = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetTrapdoorFunction().GetExponent(); + d.TraceDebug("Exponent = %s\n", os.str().c_str()); } } -#endif +# endif // class cRSA @@ -501,12 +507,18 @@ class cRSA_i public: int mKeyBits; - enum Action { ENCRYPT, DECRYPT, SIGN, VERIFY }; + enum Action + { + ENCRYPT, + DECRYPT, + SIGN, + VERIFY + }; Action mAction; const cRSAPrivateKey* mpPrivateKey; - const cRSAPublicKey* mpPublicKey; + const cRSAPublicKey* mpPublicKey; X917RNG* mpRNG; }; @@ -530,15 +542,13 @@ cRSA::cRSA(const cRSAPrivateKey& privateKey) void cRSA::Init(KeySize keysize) { - mpData = new cRSA_i; + mpData = new cRSA_i; mpData->mpPrivateKey = 0; - mpData->mpPublicKey = 0; + mpData->mpPublicKey = 0; - mpData->mKeyBits = (keysize == KEY256) ? 256 : - (keysize == KEY512) ? 512 : - (keysize == KEY1024) ? 1024 : - (keysize == KEY2048) ? 2048 : - 256; + mpData->mKeyBits = (keysize == KEY256) ? + 256 : + (keysize == KEY512) ? 512 : (keysize == KEY1024) ? 1024 : (keysize == KEY2048) ? 2048 : 256; // Create a random seed and a key byte seed[MD5::DATASIZE]; @@ -551,7 +561,7 @@ void cRSA::Init(KeySize keysize) cRSA::~cRSA() { - if (mpData) + if (mpData) { delete mpData->mpRNG; delete mpData; @@ -566,8 +576,8 @@ void cRSA::SetEncrypting(const cRSAPublicKey* pKey) ThrowAndAssert(eInternal(_T("RSA Key length mismatch."))); - mpData->mAction = cRSA_i::ENCRYPT; - mpData->mpPublicKey = pKey; + mpData->mAction = cRSA_i::ENCRYPT; + mpData->mpPublicKey = pKey; mpData->mpPrivateKey = 0; } @@ -577,9 +587,9 @@ void cRSA::SetDecrypting(const cRSAPrivateKey* pKey) if (pKey->mpData->mKeyLength != mpData->mKeyBits) ThrowAndAssert(eInternal(_T("RSA Key length mismatch."))); - mpData->mAction = cRSA_i::DECRYPT; + mpData->mAction = cRSA_i::DECRYPT; mpData->mpPrivateKey = pKey; - mpData->mpPublicKey = 0; + mpData->mpPublicKey = 0; } void cRSA::SetSigning(const cRSAPrivateKey* pKey) @@ -588,9 +598,9 @@ void cRSA::SetSigning(const cRSAPrivateKey* pKey) if (pKey->mpData->mKeyLength != mpData->mKeyBits) ThrowAndAssert(eInternal(_T("RSA Key length mismatch."))); - mpData->mAction = cRSA_i::SIGN; + mpData->mAction = cRSA_i::SIGN; mpData->mpPrivateKey = pKey; - mpData->mpPublicKey = 0; + mpData->mpPublicKey = 0; } void cRSA::SetVerifying(const cRSAPublicKey* pKey) @@ -599,14 +609,14 @@ void cRSA::SetVerifying(const cRSAPublicKey* pKey) if (pKey->mpData->mKeyLength != mpData->mKeyBits) ThrowAndAssert(eInternal(_T("RSA Key length mismatch."))); - mpData->mAction = cRSA_i::VERIFY; - mpData->mpPublicKey = pKey; + mpData->mAction = cRSA_i::VERIFY; + mpData->mpPublicKey = pKey; mpData->mpPrivateKey = 0; } // Lets encrypt in 128 bit chunks, even though the crypto // lib implementation can do arbitrary length plaintext -// encryptions. We will most likely only use this to +// encryptions. We will most likely only use this to // encrypt a 128 bit random number anyway. int cRSA::GetBlockSizePlain() { @@ -631,63 +641,65 @@ void cRSA::ProcessBlock(const void* indata, void* outdata) unsigned int l; switch (mpData->mAction) - { - case cRSA_i::ENCRYPT: - { - ASSERT(mpData->mpPublicKey); - ASSERT(mpData->mpPublicKey->mpData->mpKey->MaxPlainTextLength() == GetBlockSizePlain()); - ASSERT(mpData->mpPublicKey->mpData->mpKey->CipherTextLength() == GetBlockSizeCipher()); - mpData->mpPublicKey->mpData->mpKey->Encrypt(*mpData->mpRNG, (const byte *)indata, GetBlockSizePlain(), (byte *)outdata); - break; - } - case cRSA_i::DECRYPT: - { - ASSERT(mpData->mpPrivateKey); - ASSERT(mpData->mpPrivateKey->mpData->mpKey->CipherTextLength() == GetBlockSizeCipher()); - l = mpData->mpPrivateKey->mpData->mpKey->Decrypt((const byte *)indata, (byte *)outdata); - if (l != GetBlockSizePlain()) - throw eArchiveCrypto(); - break; - } - case cRSA_i::SIGN: - { - ASSERT(mpData->mpPrivateKey); - ASSERT(mpData->mpPrivateKey->mpData->mpKey->MaxMessageLength() == GetBlockSizePlain()); - ASSERT(mpData->mpPrivateKey->mpData->mpKey->SignatureLength() == GetBlockSizeCipher()); - mpData->mpPrivateKey->mpData->mpKey->Sign(*mpData->mpRNG, (const byte *)indata, GetBlockSizePlain(), (byte *)outdata); - break; - } - case cRSA_i::VERIFY: - { - ASSERT(mpData->mpPublicKey); - ASSERT(mpData->mpPublicKey->mpData->mpKey->SignatureLength() == GetBlockSizeCipher()); - l = mpData->mpPublicKey->mpData->mpKey->Recover((const byte *)indata, (byte *)outdata); - if (l != GetBlockSizePlain()) - throw eArchiveCrypto(); - break; - } - default: - { - ASSERT(false); - break; - } + { + case cRSA_i::ENCRYPT: + { + ASSERT(mpData->mpPublicKey); + ASSERT(mpData->mpPublicKey->mpData->mpKey->MaxPlainTextLength() == GetBlockSizePlain()); + ASSERT(mpData->mpPublicKey->mpData->mpKey->CipherTextLength() == GetBlockSizeCipher()); + mpData->mpPublicKey->mpData->mpKey->Encrypt( + *mpData->mpRNG, (const byte*)indata, GetBlockSizePlain(), (byte*)outdata); + break; + } + case cRSA_i::DECRYPT: + { + ASSERT(mpData->mpPrivateKey); + ASSERT(mpData->mpPrivateKey->mpData->mpKey->CipherTextLength() == GetBlockSizeCipher()); + l = mpData->mpPrivateKey->mpData->mpKey->Decrypt((const byte*)indata, (byte*)outdata); + if (l != GetBlockSizePlain()) + throw eArchiveCrypto(); + break; + } + case cRSA_i::SIGN: + { + ASSERT(mpData->mpPrivateKey); + ASSERT(mpData->mpPrivateKey->mpData->mpKey->MaxMessageLength() == GetBlockSizePlain()); + ASSERT(mpData->mpPrivateKey->mpData->mpKey->SignatureLength() == GetBlockSizeCipher()); + mpData->mpPrivateKey->mpData->mpKey->Sign( + *mpData->mpRNG, (const byte*)indata, GetBlockSizePlain(), (byte*)outdata); + break; + } + case cRSA_i::VERIFY: + { + ASSERT(mpData->mpPublicKey); + ASSERT(mpData->mpPublicKey->mpData->mpKey->SignatureLength() == GetBlockSizeCipher()); + l = mpData->mpPublicKey->mpData->mpKey->Recover((const byte*)indata, (byte*)outdata); + if (l != GetBlockSizePlain()) + throw eArchiveCrypto(); + break; + } + default: + { + ASSERT(false); + break; + } } } void cRSA::GenerateKeys(cRSAPrivateKey*& retPrivate, cRSAPublicKey*& retPublic) { RSAPrivateKey* pNewPrivateKey = new RSAPrivateKey(*mpData->mpRNG, mpData->mKeyBits); - RSAPublicKey* pNewPublicKey = new RSAPublicKey(*pNewPrivateKey); + RSAPublicKey* pNewPublicKey = new RSAPublicKey(*pNewPrivateKey); - retPrivate = new cRSAPrivateKey(); - retPrivate->mpData->mpKey = pNewPrivateKey; + retPrivate = new cRSAPrivateKey(); + retPrivate->mpData->mpKey = pNewPrivateKey; retPrivate->mpData->mKeyLength = mpData->mKeyBits; - retPublic = new cRSAPublicKey(); - retPublic->mpData->mpKey = pNewPublicKey; + retPublic = new cRSAPublicKey(); + retPublic->mpData->mpKey = pNewPublicKey; retPublic->mpData->mKeyLength = mpData->mKeyBits; -#ifdef _DEBUG +# ifdef DEBUG int l; l = retPublic->mpData->mpKey->MaxPlainTextLength(); ASSERT(l == GetBlockSizePlain()); @@ -695,7 +707,7 @@ void cRSA::GenerateKeys(cRSAPrivateKey*& retPrivate, cRSAPublicKey*& retPublic) ASSERT(l == GetBlockSizeCipher()); l = retPrivate->mpData->mpKey->CipherTextLength(); ASSERT(l == GetBlockSizeCipher()); -#endif +# endif } #endif // _RSA_ENCRYPTION @@ -708,14 +720,14 @@ void cRSA::GenerateKeys(cRSAPrivateKey*& retPrivate, cRSAPublicKey*& retPublic) class cElGamalSigPrivateKey_i { public: - int16 mKeyLength; + int16 mKeyLength; ElGamalSigPrivateKey* mpKey; }; cElGamalSigPrivateKey::cElGamalSigPrivateKey() { - mpData = new cElGamalSigPrivateKey_i; - mpData->mpKey = 0; + mpData = new cElGamalSigPrivateKey_i; + mpData->mpKey = 0; mpData->mKeyLength = 0; } @@ -723,9 +735,9 @@ cElGamalSigPrivateKey::cElGamalSigPrivateKey(void* pDataStream) { mpData = new cElGamalSigPrivateKey_i; - int32 len; - int32 i32; - int16 i16; + int32 len; + int32 i32; + int16 i16; uint32 magicNum; byte* pIn = (byte*)pDataStream; @@ -739,7 +751,7 @@ cElGamalSigPrivateKey::cElGamalSigPrivateKey(void* pDataStream) pIn += sizeof(int32); if (magicNum != EL_GAMAL_SIG_PRIVATE_MAGIC_NUM) - ThrowAndAssert( eArchiveOpen() ); + ThrowAndAssert(eArchiveOpen()); Integer p, q, g, y, x; @@ -754,7 +766,7 @@ cElGamalSigPrivateKey::cElGamalSigPrivateKey(void* pDataStream) cElGamalSigPrivateKey::~cElGamalSigPrivateKey() { - if (mpData) + if (mpData) { delete mpData->mpKey; delete mpData; @@ -771,9 +783,8 @@ int cElGamalSigPrivateKey::GetWriteLen() const ASSERT(mpData->mpKey->GetParameterY().IsPositive()); ASSERT(mpData->mpKey->GetParameterX().IsPositive()); - int len = sizeof(int16) + sizeof(int32) + - mpData->mpKey->GetPrime().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetParameterQ().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + + int len = sizeof(int16) + sizeof(int32) + mpData->mpKey->GetPrime().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetParameterQ().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + mpData->mpKey->GetParameterG().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + mpData->mpKey->GetParameterY().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + mpData->mpKey->GetParameterX().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32); @@ -804,7 +815,7 @@ void cElGamalSigPrivateKey::Write(void* pDataStream) const pOut += sizeof(int32); Integer p, q, g, y, x; - + p = mpData->mpKey->GetPrime(); q = mpData->mpKey->GetParameterQ(); g = mpData->mpKey->GetParameterG(); @@ -825,14 +836,14 @@ void cElGamalSigPrivateKey::Write(void* pDataStream) const class cElGamalSigPublicKey_i { public: - int16 mKeyLength; - ElGamalSigPublicKey* mpKey; + int16 mKeyLength; + ElGamalSigPublicKey* mpKey; }; cElGamalSigPublicKey::cElGamalSigPublicKey() { - mpData = new cElGamalSigPublicKey_i; - mpData->mpKey = 0; + mpData = new cElGamalSigPublicKey_i; + mpData->mpKey = 0; mpData->mKeyLength = 0; } @@ -841,10 +852,10 @@ cElGamalSigPublicKey::cElGamalSigPublicKey(void* pDataStream) mpData = new cElGamalSigPublicKey_i; Integer p, q, g, y; - int32 len; - int16 i16; - int32 i32; - uint32 magicNum; + int32 len; + int16 i16; + int32 i32; + uint32 magicNum; byte* pIn = (byte*)pDataStream; @@ -857,7 +868,7 @@ cElGamalSigPublicKey::cElGamalSigPublicKey(void* pDataStream) pIn += sizeof(int32); if (magicNum != EL_GAMAL_SIG_PUBLIC_MAGIC_NUM) - ThrowAndAssert( eArchiveOpen() ); + ThrowAndAssert(eArchiveOpen()); READ_INTEGER(p); READ_INTEGER(q); @@ -878,12 +889,12 @@ cElGamalSigPublicKey::cElGamalSigPublicKey(const cElGamalSigPrivateKey& privateK ASSERT(privateKey.mpData->mpKey != 0); mpData->mKeyLength = privateKey.mpData->mKeyLength; - mpData->mpKey = new ElGamalSigPublicKey(*privateKey.mpData->mpKey); + mpData->mpKey = new ElGamalSigPublicKey(*privateKey.mpData->mpKey); } cElGamalSigPublicKey::~cElGamalSigPublicKey() { - if (mpData) + if (mpData) { delete mpData->mpKey; delete mpData; @@ -899,14 +910,12 @@ int cElGamalSigPublicKey::GetWriteLen() const ASSERT(mpData->mpKey->GetParameterG().IsPositive()); ASSERT(mpData->mpKey->GetParameterY().IsPositive()); - int len = sizeof(int16) + sizeof(int32) + - mpData->mpKey->GetPrime().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + - mpData->mpKey->GetParameterQ().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + + int len = sizeof(int16) + sizeof(int32) + mpData->mpKey->GetPrime().MinEncodedSize(Integer::UNSIGNED) + + sizeof(int32) + mpData->mpKey->GetParameterQ().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + mpData->mpKey->GetParameterG().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32) + mpData->mpKey->GetParameterY().MinEncodedSize(Integer::UNSIGNED) + sizeof(int32); return len; - } void cElGamalSigPublicKey::Write(void* pDataStream) const @@ -931,7 +940,7 @@ void cElGamalSigPublicKey::Write(void* pDataStream) const pOut += sizeof(int32); Integer p, q, g, y; - + p = mpData->mpKey->GetPrime(); q = mpData->mpKey->GetParameterQ(); g = mpData->mpKey->GetParameterG(); @@ -948,36 +957,35 @@ void cElGamalSigPublicKey::Write(void* pDataStream) const bool cElGamalSigPublicKey::IsEqual(const cElGamalSigPublicKey& rhs) const { return this->mpData->mpKey->GetPrime() == rhs.mpData->mpKey->GetPrime() && - this->mpData->mpKey->GetParameterQ() == rhs.mpData->mpKey->GetParameterQ() && + this->mpData->mpKey->GetParameterQ() == rhs.mpData->mpKey->GetParameterQ() && this->mpData->mpKey->GetParameterG() == rhs.mpData->mpKey->GetParameterG() && - this->mpData->mpKey->GetParameterY() == rhs.mpData->mpKey->GetParameterY() - ; + this->mpData->mpKey->GetParameterY() == rhs.mpData->mpKey->GetParameterY(); } -#ifdef _DEBUG +#ifdef DEBUG void cElGamalSigPublicKey::TraceContents() { cDebug d("cElGamalSigPublicKey::TraceContents"); { - std::ostringstream os; - os << mpData->mpKey->GetPrime(); - d.TraceDebug("Prime = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetPrime(); + d.TraceDebug("Prime = %s\n", os.str().c_str()); } { - std::ostringstream os; - os << mpData->mpKey->GetParameterQ(); - d.TraceDebug("Q = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetParameterQ(); + d.TraceDebug("Q = %s\n", os.str().c_str()); } { - std::ostringstream os; - os << mpData->mpKey->GetParameterG(); - d.TraceDebug("G = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetParameterG(); + d.TraceDebug("G = %s\n", os.str().c_str()); } { - std::ostringstream os; - os << mpData->mpKey->GetParameterY(); - d.TraceDebug("Y = %s\n", os.str().c_str()); + std::ostringstream os; + os << mpData->mpKey->GetParameterY(); + d.TraceDebug("Y = %s\n", os.str().c_str()); } } #endif @@ -989,14 +997,16 @@ class cElGamalSig_i public: int mKeyBits; - enum Action { /*ENCRYPT, DECRYPT,*/ SIGN, VERIFY }; + enum Action + { /*ENCRYPT, DECRYPT,*/ SIGN, + VERIFY }; Action mAction; const cElGamalSigPrivateKey* mpPrivateKey; - const cElGamalSigPublicKey* mpPublicKey; + const cElGamalSigPublicKey* mpPublicKey; - SHA mSHA; + SHA mSHA; X917RNG* mpRNG; }; @@ -1019,15 +1029,13 @@ cElGamalSig::cElGamalSig(const cElGamalSigPrivateKey& privateKey) void cElGamalSig::Init(KeySize keysize) { - mpData = new cElGamalSig_i; + mpData = new cElGamalSig_i; mpData->mpPrivateKey = 0; - mpData->mpPublicKey = 0; + mpData->mpPublicKey = 0; - mpData->mKeyBits = (keysize == KEY256) ? 256 : - (keysize == KEY512) ? 512 : - (keysize == KEY1024) ? 1024 : - (keysize == KEY2048) ? 2048 : - 256; + mpData->mKeyBits = (keysize == KEY256) ? + 256 : + (keysize == KEY512) ? 512 : (keysize == KEY1024) ? 1024 : (keysize == KEY2048) ? 2048 : 256; // Create a random seed and a key byte seed[SHA::DATASIZE]; @@ -1040,7 +1048,7 @@ void cElGamalSig::Init(KeySize keysize) cElGamalSig::~cElGamalSig() { - if (mpData) + if (mpData) { delete mpData->mpRNG; delete mpData; @@ -1054,9 +1062,9 @@ void cElGamalSig::SetSigning(const cElGamalSigPrivateKey* pKey) if (pKey->mpData->mKeyLength != mpData->mKeyBits) ThrowAndAssert(eInternal(_T("Signature Key length mismatch."))); - mpData->mAction = cElGamalSig_i::SIGN; + mpData->mAction = cElGamalSig_i::SIGN; mpData->mpPrivateKey = pKey; - mpData->mpPublicKey = 0; + mpData->mpPublicKey = 0; } void cElGamalSig::SetVerifying(const cElGamalSigPublicKey* pKey) @@ -1065,8 +1073,8 @@ void cElGamalSig::SetVerifying(const cElGamalSigPublicKey* pKey) if (pKey->mpData->mKeyLength != mpData->mKeyBits) ThrowAndAssert(eInternal(_T("Signature Key length mismatch."))); - mpData->mAction = cElGamalSig_i::VERIFY; - mpData->mpPublicKey = pKey; + mpData->mAction = cElGamalSig_i::VERIFY; + mpData->mpPublicKey = pKey; mpData->mpPrivateKey = 0; } @@ -1078,8 +1086,8 @@ int cElGamalSig::GetBlockSizePlain() int cElGamalSig::GetBlockSizeCipher() { return PLAIN_BLOCK_SIZE + (NumberTheory::DiscreteLogWorkFactor(mpData->mKeyBits) >> 1) + 4; - // got this from nbtheory.cpp in crypto++ lib - // El Gamal's sig size = 2 * 2 * (DiscreteLogWorkFactor() >> 3) + // got this from nbtheory.cpp in crypto++ lib + // El Gamal's sig size = 2 * 2 * (DiscreteLogWorkFactor() >> 3) } void cElGamalSig::ProcessBlock(const void* indata, void* outdata) @@ -1093,20 +1101,21 @@ void cElGamalSig::ProcessBlock(const void* indata, void* outdata) ThrowAndAssert(eInternal(_T("Signature Key length mismatch."))); switch (mpData->mAction) - { - case cElGamalSig_i::SIGN: - { - ASSERT(mpData->mpPrivateKey != 0); - ASSERT((int)mpData->mpPrivateKey->mpData->mpKey->SignatureLength() + PLAIN_BLOCK_SIZE <= GetBlockSizeCipher()); + { + case cElGamalSig_i::SIGN: + { + ASSERT(mpData->mpPrivateKey != 0); + ASSERT((int)mpData->mpPrivateKey->mpData->mpKey->SignatureLength() + PLAIN_BLOCK_SIZE <= GetBlockSizeCipher()); - memmove(outdata, indata, PLAIN_BLOCK_SIZE); + memmove(outdata, indata, PLAIN_BLOCK_SIZE); - mpData->mSHA.CalculateDigest((byte*)shaSig, (byte*)outdata, PLAIN_BLOCK_SIZE); + mpData->mSHA.CalculateDigest((byte*)shaSig, (byte*)outdata, PLAIN_BLOCK_SIZE); - RandomizeBytes((int8 *)outdata + PLAIN_BLOCK_SIZE, GetBlockSizeCipher() - PLAIN_BLOCK_SIZE); - mpData->mpPrivateKey->mpData->mpKey->Sign(*mpData->mpRNG, (const byte *)shaSig, SHA::DIGESTSIZE, (byte *)outdata + PLAIN_BLOCK_SIZE); + RandomizeBytes((int8*)outdata + PLAIN_BLOCK_SIZE, GetBlockSizeCipher() - PLAIN_BLOCK_SIZE); + mpData->mpPrivateKey->mpData->mpKey->Sign( + *mpData->mpRNG, (const byte*)shaSig, SHA::DIGESTSIZE, (byte*)outdata + PLAIN_BLOCK_SIZE); - /* + /* Integer m((const byte*)indata, PLAIN_BLOCK_SIZE); std::cout << "Signing:\n"; @@ -1120,16 +1129,16 @@ void cElGamalSig::ProcessBlock(const void* indata, void* outdata) std::cout << "Stored S = " << ss << std::endl; */ - break; - } - case cElGamalSig_i::VERIFY: - { - ASSERT(mpData->mpPublicKey != 0); - ASSERT((int)mpData->mpPublicKey->mpData->mpKey->SignatureLength() + PLAIN_BLOCK_SIZE <= GetBlockSizeCipher()); + break; + } + case cElGamalSig_i::VERIFY: + { + ASSERT(mpData->mpPublicKey != 0); + ASSERT((int)mpData->mpPublicKey->mpData->mpKey->SignatureLength() + PLAIN_BLOCK_SIZE <= GetBlockSizeCipher()); - mpData->mSHA.CalculateDigest((byte*)shaSig, (byte*)indata, PLAIN_BLOCK_SIZE); + mpData->mSHA.CalculateDigest((byte*)shaSig, (byte*)indata, PLAIN_BLOCK_SIZE); - /* + /* const byte* signature = (const byte *)indata + PLAIN_BLOCK_SIZE; int qLen = mpData->mpPublicKey->mpData->mpKey->q.ByteCount(); Integer m((const byte*)indata, PLAIN_BLOCK_SIZE); @@ -1141,33 +1150,34 @@ void cElGamalSig::ProcessBlock(const void* indata, void* outdata) std::cout << "S = " << s << std::endl; */ - if (mpData->mpPublicKey->mpData->mpKey->Verify((const byte *)shaSig, SHA::DIGESTSIZE, (const byte *)indata + PLAIN_BLOCK_SIZE) == false) - throw eArchiveCrypto(); - memmove(outdata, indata, PLAIN_BLOCK_SIZE); - break; - } - default: - { - ASSERT(false); - break; - } + if (mpData->mpPublicKey->mpData->mpKey->Verify( + (const byte*)shaSig, SHA::DIGESTSIZE, (const byte*)indata + PLAIN_BLOCK_SIZE) == false) + throw eArchiveCrypto(); + memmove(outdata, indata, PLAIN_BLOCK_SIZE); + break; + } + default: + { + ASSERT(false); + break; + } } } void cElGamalSig::GenerateKeys(cElGamalSigPrivateKey*& retPrivate, cElGamalSigPublicKey*& retPublic) { ElGamalSigPrivateKey* pNewPrivateKey = new ElGamalSigPrivateKey(*mpData->mpRNG, mpData->mKeyBits); - ElGamalSigPublicKey* pNewPublicKey = new ElGamalSigPublicKey(*pNewPrivateKey); + ElGamalSigPublicKey* pNewPublicKey = new ElGamalSigPublicKey(*pNewPrivateKey); - retPrivate = new cElGamalSigPrivateKey(); - retPrivate->mpData->mpKey = pNewPrivateKey; + retPrivate = new cElGamalSigPrivateKey(); + retPrivate->mpData->mpKey = pNewPrivateKey; retPrivate->mpData->mKeyLength = (int16)mpData->mKeyBits; - retPublic = new cElGamalSigPublicKey(); - retPublic->mpData->mpKey = pNewPublicKey; + retPublic = new cElGamalSigPublicKey(); + retPublic->mpData->mpKey = pNewPublicKey; retPublic->mpData->mKeyLength = (int16)mpData->mKeyBits; -#ifdef _DEBUG +#ifdef DEBUG int l; l = retPublic->mpData->mpKey->SignatureLength(); ASSERT(l + PLAIN_BLOCK_SIZE <= GetBlockSizeCipher()); @@ -1210,7 +1220,7 @@ cHashedKey192::cHashedKey192(const TSTRING& data) ASSERT(SHA::DIGESTSIZE == 20); ASSERT(40 >= KEYLEN); - + byte localKey[40]; sha.CalculateDigest(localKey, (byte*)data.data(), data.length() * sizeof(TCHAR)); sha.CalculateDigest(localKey + 20, localKey, 20); @@ -1223,7 +1233,7 @@ cHashedKey192::cHashedKey192(void* pData, int dataLen) ASSERT(SHA::DIGESTSIZE == 20); ASSERT(40 >= KEYLEN); - + byte localKey[40]; sha.CalculateDigest(localKey, (byte*)pData, dataLen); sha.CalculateDigest(localKey + 20, localKey, 20); @@ -1235,13 +1245,40 @@ cHashedKey192::~cHashedKey192() RandomizeBytes(mKey, KEYLEN); } -/////////////////////////////////////////////////////////////////////////////// -// void RandomizeBytes(byte* destbuf, int len) -- Fill a buffer with random bytes +///////////////////////////////////////////////////////// + +#if USE_DEV_URANDOM +static bool randomize_by_device(const char* device_name, int8* destbuf, int len) +{ + static int rng_device = -1; + + if (-1 == rng_device) + rng_device = open(device_name, O_RDONLY | O_NONBLOCK); + + if (rng_device >= 0) + { + int bytes_read = read(rng_device, destbuf, len); + if (bytes_read == len) + return true; + } + return false; +} +#else static bool gRandomizeBytesSeeded = false; +#endif + +/////////////////////////////////////////////////////////////////////////////// +// void RandomizeBytes(byte* destbuf, int len) -- Fill a buffer with random bytes void RandomizeBytes(int8* destbuf, int len) { +#if USE_DEV_URANDOM + if (randomize_by_device("/dev/urandom", destbuf, len)) + return; + + ThrowAndAssert(eInternal(_T("Failed to read from RNG device"))); +#else if (!gRandomizeBytesSeeded) { // generate a rancom number from processor timing. @@ -1250,22 +1287,22 @@ void RandomizeBytes(int8* destbuf, int len) for (mask = 0xb147688c; time(NULL) - start < 1; mask += 0x8984cc88) ; - #ifdef _DEBUG +# ifdef DEBUG time_t t = time(NULL); t ^= mask; - + //time_t t = 920492046 - 3600; // try to the same random values each time //std::cerr << (*(time_t*)mask()) << ":" << t << std::endl; - srand( t ); - #else - srand( time(NULL) ^ mask ); - #endif + srand(t); +# else + srand(time(NULL) ^ mask); +# endif gRandomizeBytesSeeded = true; } int i; for (i = 0; i < len; ++i) - destbuf[i] = (byte)( (rand() * 256 / RAND_MAX) ^ 0xdc ); // 0xdc came from random.org + destbuf[i] = (byte)((rand() * 256 / RAND_MAX) ^ 0xdc); // 0xdc came from random.org +#endif } - diff --git a/src/twcrypto/crypto.h b/src/twcrypto/crypto.h index 6dd5d08..4e8d639 100644 --- a/src/twcrypto/crypto.h +++ b/src/twcrypto/crypto.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -50,13 +50,19 @@ class iCipher { public: - virtual ~iCipher() {} - - enum EncryptionDir { ENCRYPT, DECRYPT }; + virtual ~iCipher() + { + } + + enum EncryptionDir + { + ENCRYPT, + DECRYPT + }; - virtual int GetBlockSizePlain() = 0; - virtual int GetBlockSizeCipher() = 0; - // return the size of data blocks this crypter works on. + virtual int GetBlockSizePlain() = 0; + virtual int GetBlockSizeCipher() = 0; + // return the size of data blocks this crypter works on. virtual void ProcessBlock(const void* indata, void* outdata) = 0; // throw eArchive // process a block of data. indata and outdata may be the same memory }; @@ -67,14 +73,18 @@ class iCipher class cNullCipher : public iCipher { public: - cNullCipher() {} - virtual ~cNullCipher() {} - - virtual int GetBlockSizePlain(); - virtual int GetBlockSizeCipher(); - // return the size of data blocks for plaintext and cipertext + cNullCipher() + { + } + virtual ~cNullCipher() + { + } + + virtual int GetBlockSizePlain(); + virtual int GetBlockSizeCipher(); + // return the size of data blocks for plaintext and cipertext virtual void ProcessBlock(const void* indata, void* outdata); - // process a block of data. indata and outdata may be the same memory + // process a block of data. indata and outdata may be the same memory }; /////////////////////////////////////////////////////////////////////////////// @@ -92,11 +102,11 @@ class cIDEA : public iCipher void SetKey(iCipher::EncryptionDir dir, const cHashedKey128& key); - virtual int GetBlockSizePlain(); - virtual int GetBlockSizeCipher(); - // return the size of data blocks for plaintext and cipertext + virtual int GetBlockSizePlain(); + virtual int GetBlockSizeCipher(); + // return the size of data blocks for plaintext and cipertext virtual void ProcessBlock(const void* indata, void* outdata); - // process a block of data. indata and outdata may be the same memory + // process a block of data. indata and outdata may be the same memory protected: cIDEA_i* mpData; @@ -117,11 +127,11 @@ class cTripleDES : public iCipher void SetKey(iCipher::EncryptionDir dir, const cHashedKey192& key); - virtual int GetBlockSizePlain(); - virtual int GetBlockSizeCipher(); - // return the size of data blocks for plaintext and cipertext + virtual int GetBlockSizePlain(); + virtual int GetBlockSizeCipher(); + // return the size of data blocks for plaintext and cipertext virtual void ProcessBlock(const void* indata, void* outdata); - // process a block of data. indata and outdata may be the same memory + // process a block of data. indata and outdata may be the same memory protected: cTripleDES_i* mpData; @@ -139,17 +149,17 @@ class cRSAPrivateKey; class cRSA : public iCipher { public: - enum KeySize - { - KEY256 = 256, - KEY512 = 512, - KEY1024 = 1024, + enum KeySize + { + KEY256 = 256, + KEY512 = 512, + KEY1024 = 1024, KEY2048 = 2048 }; - - cRSA(KeySize keysize); - cRSA(const cRSAPublicKey& publicKey); // read keysize from key - cRSA(const cRSAPrivateKey& privateKey); // ditto + + explicit cRSA(KeySize keysize); + explicit cRSA(const cRSAPublicKey& publicKey); // read keysize from key + explicit cRSA(const cRSAPrivateKey& privateKey); // ditto virtual ~cRSA(); void SetEncrypting(const cRSAPublicKey* pKey); @@ -157,14 +167,14 @@ class cRSA : public iCipher void SetSigning(const cRSAPrivateKey* pKey); void SetVerifying(const cRSAPublicKey* pKey); - virtual int GetBlockSizePlain(); - virtual int GetBlockSizeCipher(); - // return the size of data blocks for plaintext and cipertext + virtual int GetBlockSizePlain(); + virtual int GetBlockSizeCipher(); + // return the size of data blocks for plaintext and cipertext virtual void ProcessBlock(const void* indata, void* outdata); - // process a block of data. indata and outdata may be the same memory + // process a block of data. indata and outdata may be the same memory void GenerateKeys(cRSAPrivateKey*& retPrivate, cRSAPublicKey*& retPublic); - // generate public and private keys. Caller is responsible for deleting these keys when done + // generate public and private keys. Caller is responsible for deleting these keys when done protected: cRSA_i* mpData; @@ -182,15 +192,16 @@ class cRSAPrivateKey { friend class cRSA; friend class cRSAPublicKey; + public: - cRSAPrivateKey(void* pDataStream); + explicit cRSAPrivateKey(void* pDataStream); ~cRSAPrivateKey(); - int GetWriteLen() const; - void Write(void* pDataStream) const; + int GetWriteLen() const; + void Write(void* pDataStream) const; protected: - cRSAPrivateKey_i* mpData; + cRSAPrivateKey_i* mpData; private: cRSAPrivateKey(); // cRSA should be used to generate keys @@ -201,20 +212,21 @@ class cRSAPrivateKey class cRSAPublicKey { friend class cRSA; + public: - cRSAPublicKey(void* pDataStream); - cRSAPublicKey(const cRSAPrivateKey& privateKey); + explicit cRSAPublicKey(void* pDataStream); + explicit cRSAPublicKey(const cRSAPrivateKey& privateKey); ~cRSAPublicKey(); - int GetWriteLen() const; - void Write(void* pDataStream) const; + int GetWriteLen() const; + void Write(void* pDataStream) const; -#ifdef _DEBUG +# ifdef DEBUG void TraceContents(); -#endif +# endif protected: - cRSAPublicKey_i* mpData; + cRSAPublicKey_i* mpData; private: cRSAPublicKey(); // cRSA should be used to generate keys @@ -241,30 +253,30 @@ class cElGamalSigPrivateKey; class cElGamalSig : public iCipher { public: - enum KeySize - { - KEY256 = 256, - KEY512 = 512, - KEY1024 = 1024, + enum KeySize + { + KEY256 = 256, + KEY512 = 512, + KEY1024 = 1024, KEY2048 = 2048 }; - - cElGamalSig(KeySize keysize); - cElGamalSig(const cElGamalSigPublicKey& publicKey); // read keysize from key - cElGamalSig(const cElGamalSigPrivateKey& privateKey); // ditto + + explicit cElGamalSig(KeySize keysize); + explicit cElGamalSig(const cElGamalSigPublicKey& publicKey); // read keysize from key + explicit cElGamalSig(const cElGamalSigPrivateKey& privateKey); // ditto virtual ~cElGamalSig(); void SetSigning(const cElGamalSigPrivateKey* pKey); void SetVerifying(const cElGamalSigPublicKey* pKey); - virtual int GetBlockSizePlain(); - virtual int GetBlockSizeCipher(); - // return the size of data blocks for plaintext and cipertext + virtual int GetBlockSizePlain(); + virtual int GetBlockSizeCipher(); + // return the size of data blocks for plaintext and cipertext virtual void ProcessBlock(const void* indata, void* outdata); - // process a block of data. indata and outdata may be the same memory + // process a block of data. indata and outdata may be the same memory void GenerateKeys(cElGamalSigPrivateKey*& retPrivate, cElGamalSigPublicKey*& retPublic); - // generate public and private keys. Caller is responsible for deleting these keys when done + // generate public and private keys. Caller is responsible for deleting these keys when done protected: cElGamalSig_i* mpData; @@ -272,7 +284,10 @@ class cElGamalSig : public iCipher private: void Init(KeySize keysize); - enum { PLAIN_BLOCK_SIZE = 4083 }; + enum + { + PLAIN_BLOCK_SIZE = 4083 + }; }; class cElGamalSigPrivateKey_i; @@ -284,15 +299,16 @@ class cElGamalSigPrivateKey { friend class cElGamalSig; friend class cElGamalSigPublicKey; + public: - cElGamalSigPrivateKey(void* pDataStream); + explicit cElGamalSigPrivateKey(void* pDataStream); ~cElGamalSigPrivateKey(); - int GetWriteLen() const; - void Write(void* pDataStream) const; + int GetWriteLen() const; + void Write(void* pDataStream) const; protected: - cElGamalSigPrivateKey_i* mpData; + cElGamalSigPrivateKey_i* mpData; private: cElGamalSigPrivateKey(); // cElGamal should be used to generate keys @@ -303,19 +319,20 @@ class cElGamalSigPrivateKey class cElGamalSigPublicKey { friend class cElGamalSig; + public: - cElGamalSigPublicKey(void* pDataStream); - cElGamalSigPublicKey(const cElGamalSigPrivateKey& privateKey); + explicit cElGamalSigPublicKey(void* pDataStream); + explicit cElGamalSigPublicKey(const cElGamalSigPrivateKey& privateKey); ~cElGamalSigPublicKey(); - int GetWriteLen() const; - void Write(void* pDataStream) const; + int GetWriteLen() const; + void Write(void* pDataStream) const; - bool IsEqual(const cElGamalSigPublicKey& rhs) const; - // This is used to make sure the key used to sign the config - // file is the same as the key we are currently using. + bool IsEqual(const cElGamalSigPublicKey& rhs) const; + // This is used to make sure the key used to sign the config + // file is the same as the key we are currently using. -#ifdef _DEBUG +#ifdef DEBUG void TraceContents(); #endif @@ -332,7 +349,7 @@ class cElGamalSigPublicKey class cHashedKey128 { public: - cHashedKey128(const TSTRING& data); + explicit cHashedKey128(const TSTRING& data); cHashedKey128(void* pData, int dataLen); ~cHashedKey128(); @@ -342,9 +359,13 @@ class cHashedKey128 void Write(void* pDataStream); protected: - enum { KEYLEN = 16, BUFSIZE = 20}; + enum + { + KEYLEN = 16, + BUFSIZE = 20 + }; - int8 mKey[BUFSIZE]; + int8 mKey[BUFSIZE]; }; inline const int8* cHashedKey128::GetKey() const @@ -352,7 +373,7 @@ inline const int8* cHashedKey128::GetKey() const return mKey; } -inline int cHashedKey128::GetWriteLen() +inline int cHashedKey128::GetWriteLen() { return KEYLEN; } @@ -368,7 +389,7 @@ inline void cHashedKey128::Write(void* pDataStream) class cHashedKey192 { public: - cHashedKey192(const TSTRING& data); + explicit cHashedKey192(const TSTRING& data); cHashedKey192(void* pData, int dataLen); ~cHashedKey192(); @@ -378,9 +399,12 @@ class cHashedKey192 void Write(void* pDataStream); protected: - enum { KEYLEN = 24 }; + enum + { + KEYLEN = 24 + }; - int8 mKey[KEYLEN]; + int8 mKey[KEYLEN]; }; inline const int8* cHashedKey192::GetKey() const @@ -388,7 +412,7 @@ inline const int8* cHashedKey192::GetKey() const return mKey; } -inline int cHashedKey192::GetWriteLen() +inline int cHashedKey192::GetWriteLen() { return KEYLEN; } @@ -404,4 +428,3 @@ inline void cHashedKey192::Write(void* pDataStream) void RandomizeBytes(int8* destbuf, int len); #endif // __CRYPTO_H - diff --git a/src/twcrypto/cryptoarchive.cpp b/src/twcrypto/cryptoarchive.cpp index d484360..18a18f9 100644 --- a/src/twcrypto/cryptoarchive.cpp +++ b/src/twcrypto/cryptoarchive.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,7 +43,7 @@ //#include "cryptlib/queue.h" #include "bytequeue.h" -enum mAction +enum mAction { MA_UNSTARTED, MA_UNKNOWN, @@ -58,7 +58,7 @@ const int CRYPTO_COMPRESSION_LEVEL = 6; // folowing interfaces were added to use Crypto++'s implementation // of gzip -// class that takes a plaintext input via Put() and +// class that takes a plaintext input via Put() and // outputs encrypted data to the passed in cArchive class cCryptoSink : public Sink { @@ -66,57 +66,63 @@ class cCryptoSink : public Sink cCryptoSink(cArchive* pDestArchive, iCipher* pCipher); ~cCryptoSink(); - virtual void Put(const byte *inString, unsigned int length); + virtual void Put(const byte* inString, unsigned int length); virtual void InputFinished(); - virtual void Put(byte inByte) { Put(&inByte, 1); } + virtual void Put(byte inByte) + { + Put(&inByte, 1); + } private: - cArchive* mpDestArchive; - iCipher* mpCipher; + cArchive* mpDestArchive; + iCipher* mpCipher; // buffer to cache bytes in - int8* mpBuffer; - int mBufferLen; - int mBufferUsed; + int8* mpBuffer; + int mBufferLen; + int mBufferUsed; }; class cCryptoSource : public Source { public: - cCryptoSource(cArchive* pSrcArchive, iCipher* pCipher, BufferedTransformation *outQueue); + cCryptoSource(cArchive* pSrcArchive, iCipher* pCipher, BufferedTransformation* outQueue); ~cCryptoSource(); - unsigned int Pump(unsigned int size); + unsigned int Pump(unsigned int size); unsigned long PumpAll(); private: - cArchive* mpSrcArchive; - iCipher* mpCipher; + cArchive* mpSrcArchive; + iCipher* mpCipher; // buffer to cache bytes in - int8* mpBuffer; - int mBufferLen; - int mBufferUsed; + int8* mpBuffer; + int mBufferLen; + int mBufferUsed; }; cCryptoArchive::cCryptoArchive() { - mpArchive = 0; - mpCipher = 0; - mpDeflator = 0; - mpInflator = 0; - mpCryptoSink = 0; - mpCryptoSource = 0; + mpArchive = 0; + mpCipher = 0; + mpDeflator = 0; + mpInflator = 0; + mpCryptoSink = 0; + mpCryptoSource = 0; mpInflatedBytes = 0; - mAction = MA_UNSTARTED; + mAction = MA_UNSTARTED; } cCryptoArchive::~cCryptoArchive() { ASSERT(mAction == MA_UNSTARTED || mAction == MA_UNKNOWN || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten - + // check we did not leave a buffer unwritten + + Finish(); + + // Finish() normally zeroes these out, but hey. delete mpDeflator; delete mpInflator; } @@ -124,10 +130,10 @@ cCryptoArchive::~cCryptoArchive() void cCryptoArchive::Start(cArchive* pArchive, iCipher* pCipher) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_UNKNOWN || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten - + // check we did not leave a buffer unwritten + mpArchive = pArchive; - mpCipher = pCipher; + mpCipher = pCipher; delete mpDeflator; mpDeflator = 0; @@ -157,7 +163,7 @@ int cCryptoArchive::Write(const void* pSrc, int count) ASSERT(mpInflatedBytes == 0); mpCryptoSink = new cCryptoSink(mpArchive, mpCipher); - mpDeflator = new Deflator(CRYPTO_COMPRESSION_LEVEL, mpCryptoSink); + mpDeflator = new Deflator(CRYPTO_COMPRESSION_LEVEL, mpCryptoSink); } else if (mAction != MA_WRITING) { @@ -184,10 +190,10 @@ int cCryptoArchive::Read(void* pDest, int count) ASSERT(mpInflator == 0); ASSERT(mpCryptoSource == 0); ASSERT(mpInflatedBytes == 0); - + mpInflatedBytes = new cByteQueue; - mpInflator = new Inflator(mpInflatedBytes); - mpCryptoSource = new cCryptoSource(mpArchive, mpCipher, mpInflator); + mpInflator = new Inflator(mpInflatedBytes); + mpCryptoSource = new cCryptoSource(mpArchive, mpCipher, mpInflator); } else if (mAction != MA_READING) { @@ -195,13 +201,13 @@ int cCryptoArchive::Read(void* pDest, int count) throw eArchiveInvalidOp(); } - while ( (int)mpInflatedBytes->CurrentSize() < count ) + while ((int)mpInflatedBytes->CurrentSize() < count) { len = mpCipher->GetBlockSizePlain(); - if ( (int)mpCryptoSource->Pump(len) < len ) // RAD: Cast to int + if ((int)mpCryptoSource->Pump(len) < len) // RAD: Cast to int { mpInflator->InputFinished(); - if ( (int)mpInflatedBytes->CurrentSize() < count ) // RAD: Cast to int + if ((int)mpInflatedBytes->CurrentSize() < count) // RAD: Cast to int { len = mpInflatedBytes->CurrentSize(); mpInflatedBytes->Get((byte*)pDest, len); @@ -218,7 +224,7 @@ int cCryptoArchive::Read(void* pDest, int count) bool cCryptoArchive::EndOfFile() { - ASSERT(mAction == MA_READING); // why would you call this if not reading? + ASSERT(mAction == MA_READING); // why would you call this if not reading? if (mAction != MA_READING) return true; @@ -238,7 +244,7 @@ void cCryptoArchive::Finish() mpDeflator->InputFinished(); mpCryptoSink->InputFinished(); delete mpDeflator; - mpDeflator = 0; + mpDeflator = 0; mpCryptoSink = 0; // mpCryptoSink is deleted by ~Deflator() mAction = MA_FINISHED; @@ -247,7 +253,7 @@ void cCryptoArchive::Finish() { delete mpCryptoSource; mpCryptoSource = 0; - mpInflator = 0; // deleting mpCryptoSource is deleted by ~Inflator() + mpInflator = 0; // deleting mpCryptoSource is deleted by ~Inflator() mAction = MA_FINISHED; } @@ -261,10 +267,10 @@ void cCryptoArchive::Finish() cCryptoSink::cCryptoSink(cArchive* pDestArchive, iCipher* pCipher) { mpDestArchive = pDestArchive; - mpCipher = pCipher; - mpBuffer = 0; - mBufferLen = 0; - mBufferUsed = 0; + mpCipher = pCipher; + mpBuffer = 0; + mBufferLen = 0; + mBufferUsed = 0; } cCryptoSink::~cCryptoSink() @@ -272,22 +278,22 @@ cCryptoSink::~cCryptoSink() delete [] mpBuffer; } -void cCryptoSink::Put(const byte *inString, unsigned int length) +void cCryptoSink::Put(const byte* inString, unsigned int length) { if (mpBuffer == 0) { // this is the first write - mBufferLen = mpCipher->GetBlockSizePlain(); - mpBuffer = new int8[mBufferLen]; + mBufferLen = mpCipher->GetBlockSizePlain(); + mpBuffer = new int8[mBufferLen]; mBufferUsed = 0; } // RAD: Cast to int - ASSERT( length <= std::numeric_limits::max() ); - int nLength = static_cast( length ); + ASSERT(length <= std::numeric_limits::max()); + int nLength = static_cast(length); int i = 0; - while ( i < nLength ) + while (i < nLength) { int bytesToCopy = mBufferLen - mBufferUsed; if (bytesToCopy > nLength - i) @@ -312,7 +318,7 @@ void cCryptoSink::Put(const byte *inString, unsigned int length) i += bytesToCopy; } - ASSERT( i == nLength ); // should be if our math is right + ASSERT(i == nLength); // should be if our math is right } void cCryptoSink::InputFinished() @@ -331,21 +337,21 @@ void cCryptoSink::InputFinished() mBufferUsed = 0; } - delete [] mpBuffer; - mpBuffer = 0; - mBufferLen = 0; + delete [] mpBuffer; + mpBuffer = 0; + mBufferLen = 0; mBufferUsed = 0; } -cCryptoSource::cCryptoSource(cArchive* pSrcArchive, iCipher* pCipher, BufferedTransformation *outQueue) -: Source(outQueue) +cCryptoSource::cCryptoSource(cArchive* pSrcArchive, iCipher* pCipher, BufferedTransformation* outQueue) + : Source(outQueue) { mpSrcArchive = pSrcArchive; - mpCipher = pCipher; + mpCipher = pCipher; - mpBuffer = 0; - mBufferLen = 0; + mpBuffer = 0; + mBufferLen = 0; mBufferUsed = 0; } @@ -359,32 +365,32 @@ unsigned int cCryptoSource::Pump(unsigned int size) if (mpBuffer == 0) { // first time this has been called - mBufferLen = mpCipher->GetBlockSizePlain(); - mpBuffer = new int8[mBufferLen]; + mBufferLen = mpCipher->GetBlockSizePlain(); + mpBuffer = new int8[mBufferLen]; mBufferUsed = mBufferLen; } // RAD: Cast to int (Why are these locals signed if the interface is unsigned?) - ASSERT( size <= std::numeric_limits::max() ); - int nSize = static_cast( size ); + ASSERT(size <= std::numeric_limits::max()); + int nSize = static_cast(size); int i = 0; - while ( i < nSize ) + while (i < nSize) { if (mBufferUsed >= mBufferLen) { - ASSERT( mBufferUsed == mBufferLen ); // should be if our math is right + ASSERT(mBufferUsed == mBufferLen); // should be if our math is right int8* pTmp = new int8[mpCipher->GetBlockSizeCipher()]; - int l = mpSrcArchive->ReadBlob( pTmp, mpCipher->GetBlockSizeCipher() ); - if ( l != mpCipher->GetBlockSizeCipher() ) + int l = mpSrcArchive->ReadBlob(pTmp, mpCipher->GetBlockSizeCipher()); + if (l != mpCipher->GetBlockSizeCipher()) { delete [] pTmp; return 0; } - mpCipher->ProcessBlock( pTmp, mpBuffer ); + mpCipher->ProcessBlock(pTmp, mpBuffer); delete [] pTmp; mBufferUsed = 0; @@ -394,33 +400,33 @@ unsigned int cCryptoSource::Pump(unsigned int size) if (bytesToCopy > nSize - i) bytesToCopy = nSize - i; - outQueue->Put( (byte*)(mpBuffer + mBufferUsed), bytesToCopy ); + outQueue->Put((byte*)(mpBuffer + mBufferUsed), bytesToCopy); mBufferUsed += bytesToCopy; i += bytesToCopy; } - ASSERT( i == nSize ); // should be if our math is right + ASSERT(i == nSize); // should be if our math is right return i; } unsigned long cCryptoSource::PumpAll() { - unsigned long total=0; - unsigned int l; + unsigned long total = 0; + unsigned int l; if (mBufferLen == 0) mBufferLen = mpCipher->GetBlockSizePlain(); - while ((l=Pump(mBufferLen)) != 0) + while ((l = Pump(mBufferLen)) != 0) total += l; return total; } /////////////////////////////////////////////////////////////////////////////// -// class cNullCryptoArchive +// class cNullCryptoArchive // // Works like crypto archive but uses no encryption. However, the compression // functionality of cCryptoArchive is still utilized. @@ -437,13 +443,13 @@ cNullCryptoArchive::~cNullCryptoArchive() } void cNullCryptoArchive::Start(cArchive* pArchive) -{ - mCryptoArchive.Start(pArchive, mpNullCipher); +{ + mCryptoArchive.Start(pArchive, mpNullCipher); } void cNullCryptoArchive::Finish() -{ - mCryptoArchive.Finish(); +{ + mCryptoArchive.Finish(); } bool cNullCryptoArchive::EndOfFile() @@ -464,46 +470,40 @@ int cNullCryptoArchive::Write(const void* pSrc, int count) #ifdef _RSA_ENCRYPTION /////////////////////////////////////////////////////////////////////////////// -// class cRSAArchive +// class cRSAArchive - cCryptoArchive mCryptoArchive; +cCryptoArchive mCryptoArchive; - int mAction; +int mAction; - cArchive* mpArchive; - cRSAPublicKey* mpPublicKey; - cRSAPrivateKey* mpPrivateKey; - -cRSAArchive::cRSAArchive() -{ - mAction = MA_UNSTARTED; - mpArchive = 0; - mpPublicKey = 0; - mpPrivateKey = 0; +cArchive* mpArchive; +cRSAPublicKey* mpPublicKey; +cRSAPrivateKey* mpPrivateKey; - mpIDEA = new cIDEA; +cRSAArchive::cRSAArchive() : mAction(MA_UNSTARTED), mpArchive(0), mpPublicKey(0), mpPrivaeKey(0), mpIDEA(new cIDEA) +{ } cRSAArchive::~cRSAArchive() { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten delete mpIDEA; } void cRSAArchive::SetWrite(cArchive* pDestArchive, const cRSAPublicKey* pPublicKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_WRITING; - mpArchive = pDestArchive; - mpPublicKey = pPublicKey; + mAction = MA_WRITING; + mpArchive = pDestArchive; + mpPublicKey = pPublicKey; mpPrivateKey = 0; // Create a random number and encode using public key cRSA rsa(*mpPublicKey); - int8* key = new int8[rsa.GetBlockSizePlain()]; + int8* key = new int8[rsa.GetBlockSizePlain()]; int8* encryptedKey = new int8[rsa.GetBlockSizeCipher()]; RandomizeBytes(key, rsa.GetBlockSizePlain()); @@ -526,16 +526,16 @@ void cRSAArchive::SetWrite(cArchive* pDestArchive, const cRSAPublicKey* pPublicK void cRSAArchive::SetWrite(cArchive* pDestArchive, const cRSAPrivateKey* pPrivateKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_WRITING; - mpArchive = pDestArchive; + mAction = MA_WRITING; + mpArchive = pDestArchive; mpPrivateKey = pPrivateKey; - mpPublicKey = 0; + mpPublicKey = 0; // Create a random number and encode using public key cRSA rsa(*mpPrivateKey); - int8* key = new int8[rsa.GetBlockSizePlain()]; + int8* key = new int8[rsa.GetBlockSizePlain()]; int8* encryptedKey = new int8[rsa.GetBlockSizeCipher()]; RandomizeBytes(key, rsa.GetBlockSizePlain()); @@ -570,21 +570,21 @@ void cRSAArchive::FlushWrite() void cRSAArchive::SetRead(cArchive* pSrcArchive, const cRSAPublicKey* pPublicKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_READING; - mpArchive = pSrcArchive; - mpPublicKey = pPublicKey; + mAction = MA_READING; + mpArchive = pSrcArchive; + mpPublicKey = pPublicKey; mpPrivateKey = 0; cRSA rsa(*mpPublicKey); - int8* key = new int8[rsa.GetBlockSizePlain()]; + int8* key = new int8[rsa.GetBlockSizePlain()]; int8* encryptedKey = new int8[rsa.GetBlockSizeCipher()]; mpArchive->ReadBlob(encryptedKey, rsa.GetBlockSizeCipher()); rsa.SetVerifying(mpPublicKey); rsa.ProcessBlock(encryptedKey, key); - + mpIDEA->SetKey(iCipher::DECRYPT, cHashedKey128(key, rsa.GetBlockSizePlain())); mCryptoArchive.Start(mpArchive, mpIDEA); @@ -600,21 +600,21 @@ void cRSAArchive::SetRead(cArchive* pSrcArchive, const cRSAPublicKey* pPublicKey void cRSAArchive::SetRead(cArchive* pSrcArchive, const cRSAPrivateKey* pPrivateKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_READING; - mpArchive = pSrcArchive; + mAction = MA_READING; + mpArchive = pSrcArchive; mpPrivateKey = pPrivateKey; - mpPublicKey = 0; + mpPublicKey = 0; cRSA rsa(*mpPrivateKey); - int8* key = new int8[rsa.GetBlockSizePlain()]; + int8* key = new int8[rsa.GetBlockSizePlain()]; int8* encryptedKey = new int8[rsa.GetBlockSizeCipher()]; mpArchive->ReadBlob(encryptedKey, rsa.GetBlockSizeCipher()); rsa.SetDecrypting(mpPrivateKey); rsa.ProcessBlock(encryptedKey, key); - + mpIDEA->SetKey(iCipher::DECRYPT, cHashedKey128(key, rsa.GetBlockSizePlain())); mCryptoArchive.Start(mpArchive, mpIDEA); @@ -648,7 +648,7 @@ int cRSAArchive::Write(const void* pSrc, int count) bool cRSAArchive::EndOfFile() { - ASSERT(mAction == MA_READING); // why would you call this if not reading? + ASSERT(mAction == MA_READING); // why would you call this if not reading? if (mAction != MA_READING) return true; @@ -659,33 +659,29 @@ bool cRSAArchive::EndOfFile() /////////////////////////////////////////////////////////////////////////////// -// class cElGamalSigArchive +// class cElGamalSigArchive cElGamalSigArchive::cElGamalSigArchive() + : mAction(MA_UNSTARTED), mpArchive(0), mpElGamal(0), mpPublicKey(0), mpPrivateKey(0) { - mAction = MA_UNSTARTED; - mpArchive = 0; - mpPublicKey = 0; - mpPrivateKey = 0; - mpElGamal = 0; } cElGamalSigArchive::~cElGamalSigArchive() { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten delete mpElGamal; } void cElGamalSigArchive::SetWrite(cArchive* pDestArchive, const cElGamalSigPrivateKey* pPrivateKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_WRITING; - mpArchive = pDestArchive; + mAction = MA_WRITING; + mpArchive = pDestArchive; mpPrivateKey = pPrivateKey; - mpPublicKey = 0; + mpPublicKey = 0; mpElGamal = new cElGamalSig(*mpPrivateKey); mpElGamal->SetSigning(mpPrivateKey); @@ -707,17 +703,17 @@ void cElGamalSigArchive::FlushWrite() void cElGamalSigArchive::SetRead(cArchive* pSrcArchive, const cElGamalSigPublicKey* pPublicKey) { ASSERT(mAction == MA_UNSTARTED || mAction == MA_FINISHED || mAction == MA_READING); - // check we did not leave a buffer unwritten + // check we did not leave a buffer unwritten - mAction = MA_READING; - mpArchive = pSrcArchive; - mpPublicKey = pPublicKey; + mAction = MA_READING; + mpArchive = pSrcArchive; + mpPublicKey = pPublicKey; mpPrivateKey = 0; mpElGamal = new cElGamalSig(*mpPublicKey); mpElGamal->SetVerifying(mpPublicKey); - + mCryptoArchive.Start(mpArchive, mpElGamal); } @@ -742,10 +738,9 @@ int cElGamalSigArchive::Write(const void* pSrc, int count) bool cElGamalSigArchive::EndOfFile() { - ASSERT(mAction == MA_READING); // why would you call this if not reading? + ASSERT(mAction == MA_READING); // why would you call this if not reading? if (mAction != MA_READING) return true; return mCryptoArchive.EndOfFile(); } - diff --git a/src/twcrypto/cryptoarchive.h b/src/twcrypto/cryptoarchive.h index ff443ed..3260cfd 100644 --- a/src/twcrypto/cryptoarchive.h +++ b/src/twcrypto/cryptoarchive.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,7 +40,7 @@ #endif /////////////////////////////////////////////////////////////////////////////// -// class cCryptoArchive +// class cCryptoArchive // // Takes an archive and a cipher. Bytes written to this archive are compressed, // passed through the cipher, and then written to the archive provided. When @@ -49,10 +49,10 @@ // // Start() must be called before the first read or write to set the archive and // cipher. The cCryptoArchive can be reused for reading and writing, but -// Start() must be called each time. Finish() should be called when done +// Start() must be called each time. Finish() should be called when done // writing or not all bytes will be written. // -// An eArchive exception will be thrown if the archvie is read from after being +// An eArchive exception will be thrown if the archvie is read from after being // written to without calling Start(); // // Will throw an EOF() exception if the data source runs out @@ -74,44 +74,44 @@ class cCryptoArchive : public cArchive cCryptoArchive(); virtual ~cCryptoArchive(); - // TODO: Start and Finish should be virtual so derived classes can override them - // (and in the case of RSA and ElGamal archives, throw an exception or something). + // TODO: Start and Finish should be virtual so derived classes can override them + // (and in the case of RSA and ElGamal archives, throw an exception or something). - void Start(cArchive* pArchive, iCipher* pCipher); - // Initialize this cCryptoArchive. This function may be called - // multiple times to set new dest archives and ciphers. These - // pointers will not be deleted by this class, it is the responsibility - // of the caller to do so. - void Finish(); - // Call when done writing to the archive to flush any buffered bytes. - // An ASSERT() will occur if further reads or write are called - // You may call when done reading to cause an ASSERT() if further - // reads are attempted. + void Start(cArchive* pArchive, iCipher* pCipher); + // Initialize this cCryptoArchive. This function may be called + // multiple times to set new dest archives and ciphers. These + // pointers will not be deleted by this class, it is the responsibility + // of the caller to do so. + void Finish(); + // Call when done writing to the archive to flush any buffered bytes. + // An ASSERT() will occur if further reads or write are called + // You may call when done reading to cause an ASSERT() if further + // reads are attempted. virtual bool EndOfFile(); protected: - cArchive* mpArchive; - iCipher* mpCipher; + cArchive* mpArchive; + iCipher* mpCipher; // set on first read/write or when Finish() is called - int mAction; + int mAction; // members needed for writing - Deflator* mpDeflator; - cCryptoSink* mpCryptoSink; + Deflator* mpDeflator; + cCryptoSink* mpCryptoSink; // members needed for reading - Inflator* mpInflator; - cCryptoSource* mpCryptoSource; - cByteQueue* mpInflatedBytes; + Inflator* mpInflator; + cCryptoSource* mpCryptoSource; + cByteQueue* mpInflatedBytes; virtual int Read(void* pDest, int count); virtual int Write(const void* pSrc, int count); // throw(eArchive); }; /////////////////////////////////////////////////////////////////////////////// -// class cNullCryptoArchive +// class cNullCryptoArchive // // Works like crypto archive but uses no encryption. However, the compression // functionality of cCryptoArchive is still utilized. @@ -124,22 +124,22 @@ class cNullCryptoArchive : public cArchive cNullCryptoArchive(); virtual ~cNullCryptoArchive(); - void Start(cArchive* pArchive); - void Finish(); + void Start(cArchive* pArchive); + void Finish(); virtual bool EndOfFile(); protected: - cCryptoArchive mCryptoArchive; - cNullCipher* mpNullCipher; - + cCryptoArchive mCryptoArchive; + cNullCipher* mpNullCipher; + virtual int Read(void* pDest, int count); virtual int Write(const void* pSrc, int count); // throw(eArchive); }; #ifdef _RSA_ENCRYPTION /////////////////////////////////////////////////////////////////////////////// -// class cRSAArchive +// class cRSAArchive class cRSAPublicKey; class cRSAPrivateKey; @@ -162,12 +162,12 @@ class cRSAArchive : public cArchive virtual bool EndOfFile(); protected: - cCryptoArchive mCryptoArchive; - cIDEA* mpIDEA; + cCryptoArchive mCryptoArchive; + cIDEA* mpIDEA; - int mAction; + int mAction; - cArchive* mpArchive; + cArchive* mpArchive; const cRSAPublicKey* mpPublicKey; const cRSAPrivateKey* mpPrivateKey; @@ -177,7 +177,7 @@ class cRSAArchive : public cArchive #endif // _RSA_ENCRYPTION /////////////////////////////////////////////////////////////////////////////// -// class cElGamalSigArchive +// class cElGamalSigArchive class cElGamalSigPublicKey; class cElGamalSigPrivateKey; @@ -198,12 +198,12 @@ class cElGamalSigArchive : public cArchive virtual bool EndOfFile(); protected: - cCryptoArchive mCryptoArchive; + cCryptoArchive mCryptoArchive; - int mAction; + int mAction; - cArchive* mpArchive; - cElGamalSig* mpElGamal; + cArchive* mpArchive; + cElGamalSig* mpElGamal; const cElGamalSigPublicKey* mpPublicKey; const cElGamalSigPrivateKey* mpPrivateKey; @@ -212,4 +212,3 @@ class cElGamalSigArchive : public cArchive }; #endif // __CRYPTOARCHIVE_H - diff --git a/src/twcrypto/keyfile.cpp b/src/twcrypto/keyfile.cpp index 1c6ec9e..923a6ef 100644 --- a/src/twcrypto/keyfile.cpp +++ b/src/twcrypto/keyfile.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,19 +44,19 @@ // A magic number to identify key files // I just picked this at random (I took the current time (14:34) squared it, // converted it to hex and xor'ed with 0xffffffff, just in case you are wondering) - dmb -const uint32 KEY_MAGIC_NUMBER = 0xffe09f5b; -static const uint32 CURRENT_FIXED_VERSION = 0x02020000; -static const uint32 TW_21_VERSION = 0x02010000; +const uint32 KEY_MAGIC_NUMBER = 0xffe09f5b; +static const uint32 CURRENT_FIXED_VERSION = 0x02020000; +static const uint32 TW_21_VERSION = 0x02010000; /////////////////////////////////////////////////////////////////////////////// // class cKeyFile cKeyFile::cKeyFile() { - mpPrivateKeyMem = 0; - mPrivateKeyMemLen = 0; - mpPrivateKey = 0; - mpPublicKey = 0; + mpPrivateKeyMem = 0; + mPrivateKeyMemLen = 0; + mpPrivateKey = 0; + mpPublicKey = 0; mPrivateKeyUseCount = 0; } @@ -72,10 +72,10 @@ void cKeyFile::ReleaseMem() delete [] mpPrivateKeyMem; delete mpPrivateKey; delete mpPublicKey; - mpPrivateKeyMem = 0; - mPrivateKeyMemLen = 0; - mpPrivateKey = 0; - mpPublicKey = 0; + mpPrivateKeyMem = 0; + mPrivateKeyMemLen = 0; + mpPrivateKey = 0; + mpPublicKey = 0; mPrivateKeyUseCount = 0; } @@ -83,11 +83,18 @@ void cKeyFile::ReleaseMem() // GetFileHeaderID() /////////////////////////////////////////////////////////////////////////////// -struct cKeyFileFHID { +struct cKeyFileFHID +{ cFileHeaderID* KeyFileID; - cKeyFileFHID() { KeyFileID = 0; } - ~cKeyFileFHID() { delete KeyFileID; } + cKeyFileFHID() + { + KeyFileID = 0; + } + ~cKeyFileFHID() + { + delete KeyFileID; + } } gKeyFileFHID; const cFileHeaderID& cKeyFile::GetFileHeaderID() @@ -119,7 +126,7 @@ void cKeyFile::ReadFile(const TCHAR* filename) // throw eKeyFile() try { cFileArchive inFile; - cFileHeader fileHeader; + cFileHeader fileHeader; inFile.OpenRead(filename); @@ -144,8 +151,7 @@ void cKeyFile::ReadFile(const TCHAR* filename) // throw eKeyFile() // tw21 key files, since their formatting is exactly the same besides // the version number. // - if( (fileHeader.GetVersion() != CURRENT_FIXED_VERSION) && - (fileHeader.GetVersion() != TW_21_VERSION) ) + if ((fileHeader.GetVersion() != CURRENT_FIXED_VERSION) && (fileHeader.GetVersion() != TW_21_VERSION)) { ASSERT(false); throw eKeyFileInvalidFmt(); @@ -181,28 +187,28 @@ void cKeyFile::ReadFile(const TCHAR* filename) // throw eKeyFile() } mPrivateKeyMemLen = len; - mpPrivateKeyMem = new int8[len]; + mpPrivateKeyMem = new int8[len]; if (inFile.ReadBlob(mpPrivateKeyMem, mPrivateKeyMemLen) < mPrivateKeyMemLen) { ASSERT(false); delete mpPublicKey; delete [] mpPrivateKeyMem; - mpPublicKey = 0; - mpPrivateKeyMem = 0; + mpPublicKey = 0; + mpPrivateKeyMem = 0; mPrivateKeyMemLen = 0; throw eKeyFileInvalidFmt(); } } - catch(eArchive&) + catch (eArchive&) { delete mpPublicKey; delete [] mpPrivateKeyMem; - mpPublicKey = 0; - mpPrivateKeyMem = 0; + mpPublicKey = 0; + mpPrivateKeyMem = 0; mPrivateKeyMemLen = 0; throw eKeyFileArchive(filename); } - catch(eKeyFile&) + catch (eKeyFile&) { throw; } @@ -215,7 +221,7 @@ void cKeyFile::WriteFile(const TCHAR* filename) const // throw eKeyFile() try { cFileArchive outFile; - cFileHeader fileHeader; + cFileHeader fileHeader; outFile.OpenReadWrite(filename); @@ -234,7 +240,7 @@ void cKeyFile::WriteFile(const TCHAR* filename) const // throw eKeyFile() } // save public key - int16 len = mpPublicKey->GetWriteLen(); + int16 len = mpPublicKey->GetWriteLen(); int8* publicMem = new int8[len]; mpPublicKey->Write(publicMem); @@ -248,7 +254,7 @@ void cKeyFile::WriteFile(const TCHAR* filename) const // throw eKeyFile() outFile.WriteInt16(len); outFile.WriteBlob(mpPrivateKeyMem, mPrivateKeyMemLen); } - catch(eArchive&) + catch (eArchive&) { throw eKeyFileArchive(filename); } @@ -268,7 +274,7 @@ void cKeyFile::ReadMem(const int8* pMem) // throw eKeyFile() if ((unsigned int)tw_ntohl(i32) != KEY_MAGIC_NUMBER) throw eKeyFileInvalidFmt(); pMem += sizeof(int32); - + memcpy(&i32, pMem, sizeof(i32)); if (tw_ntohl(i32) != 1) // version check throw eKeyFileInvalidFmt(); @@ -321,7 +327,7 @@ void cKeyFile::WriteMem(int8* pMem) const // throw eKeyFile() // save public key int16 len = mpPublicKey->GetWriteLen(); - i16 = tw_htons(len); + i16 = tw_htons(len); memcpy(pMem, &i16, sizeof(i16)); pMem += sizeof(int16); @@ -355,11 +361,11 @@ int cKeyFile::GetWriteLen() // throw eKeyFile() void cKeyFile::ProtectKeys(int8* passphrase, int passphraseLen) // throw eKeyFile() { - int i; + int i; int16 i16; // generate the hash value of the private key - int len = mpPrivateKey->GetWriteLen(); + int len = mpPrivateKey->GetWriteLen(); int8* privateKeyBits = new int8[len]; mpPrivateKey->Write(privateKeyBits); cHashedKey128 privateHash(privateKeyBits, len); @@ -368,7 +374,7 @@ void cKeyFile::ProtectKeys(int8* passphrase, int passphraseLen) // throw eKeyFil // generate cipher for encrypting private key cHashedKey192 desKey(passphrase, passphraseLen); - cTripleDES des; + cTripleDES des; des.SetKey(iCipher::ENCRYPT, desKey); ASSERT(des.GetBlockSizeCipher() == des.GetBlockSizePlain()); @@ -376,7 +382,7 @@ void cKeyFile::ProtectKeys(int8* passphrase, int passphraseLen) // throw eKeyFil // calculate size of the memory image of the private key mPrivateKeyMemLen = cHashedKey128::GetWriteLen() + sizeof(int16) + mpPrivateKey->GetWriteLen(); mPrivateKeyMemLen = (mPrivateKeyMemLen / des.GetBlockSizePlain() + 1) * des.GetBlockSizePlain(); - int sluff = mPrivateKeyMemLen - cHashedKey128::GetWriteLen() - sizeof(int16) - mpPrivateKey->GetWriteLen(); + int sluff = mPrivateKeyMemLen - cHashedKey128::GetWriteLen() - sizeof(int16) - mpPrivateKey->GetWriteLen(); // write the hash of the private key, the size of the private key, and the private key, // all as plaintext. @@ -398,7 +404,7 @@ void cKeyFile::ProtectKeys(int8* passphrase, int passphraseLen) // throw eKeyFil des.ProcessBlock(mpPrivateKeyMem + i, mpPrivateKeyMem + i); } -#ifdef _DEBUG +#ifdef DEBUG // try decoding it just to see if it worked if (GetPrivateKey(passphrase, passphraseLen) == 0) { @@ -425,7 +431,10 @@ void cKeyFile::GenerateKeys(int keySize, int8* passphrase, int passphraseLen) // ProtectKeys(passphrase, passphraseLen); } -void cKeyFile::ChangePassphrase(int8* passphraseOld, int passphraseOldLen, int8* passphrase, int passphraseLen) // throw eKeyFile() +void cKeyFile::ChangePassphrase(int8* passphraseOld, + int passphraseOldLen, + int8* passphrase, + int passphraseLen) // throw eKeyFile() { if (GetPrivateKey(passphraseOld, passphraseOldLen) == 0) { @@ -455,7 +464,7 @@ const cElGamalSigPrivateKey* cKeyFile::GetPrivateKey(int8* passphrase, int passp { // generate cipher for decrypting private key cHashedKey192 desKey(passphrase, passphraseLen); - cTripleDES des; + cTripleDES des; des.SetKey(iCipher::DECRYPT, desKey); ASSERT(des.GetBlockSizeCipher() == des.GetBlockSizePlain()); @@ -497,7 +506,7 @@ const cElGamalSigPrivateKey* cKeyFile::GetPrivateKey(int8* passphrase, int passp } mpPrivateKey = new cElGamalSigPrivateKey(plainPrivateKeyMem + cHashedKey128::GetWriteLen() + sizeof(int16)); - + RandomizeBytes(plainPrivateKeyMem, mPrivateKeyMemLen); delete [] plainPrivateKeyMem; @@ -552,8 +561,8 @@ bool cPrivateKeyProxy::AquireKey(cKeyFile& keyFile, int8* passphrase, int passph } mpKeyFile = &keyFile; - mpKey = keyFile.GetPrivateKey(passphrase, passphraseLen); - + mpKey = keyFile.GetPrivateKey(passphrase, passphraseLen); + return mpKey != 0; } @@ -577,4 +586,3 @@ const cElGamalSigPrivateKey* cPrivateKeyProxy::GetKey() const // throw eKeyFile( return mpKey; } - diff --git a/src/twcrypto/keyfile.h b/src/twcrypto/keyfile.h index df844a0..aa887ad 100644 --- a/src/twcrypto/keyfile.h +++ b/src/twcrypto/keyfile.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -55,11 +55,11 @@ class cElGamalSigPrivateKey; class cElGamalSigPublicKey; class cFileHeaderID; -TSS_EXCEPTION( eKeyFile, eFileError ); -TSS_EXCEPTION( eKeyFileInvalidFmt, eKeyFile ); -TSS_EXCEPTION( eKeyFileBadPassphrase, eKeyFile ); -TSS_EXCEPTION( eKeyFileArchive, eKeyFile ); -TSS_EXCEPTION( eKeyFileUninitialized, eKeyFile ); +TSS_EXCEPTION(eKeyFile, eFileError); +TSS_EXCEPTION(eKeyFileInvalidFmt, eKeyFile); +TSS_EXCEPTION(eKeyFileBadPassphrase, eKeyFile); +TSS_EXCEPTION(eKeyFileArchive, eKeyFile); +TSS_EXCEPTION(eKeyFileUninitialized, eKeyFile); class cKeyFile @@ -68,49 +68,52 @@ class cKeyFile cKeyFile(); ~cKeyFile(); - void ReadFile(const TCHAR* filename); // throw eKeyFile() + void ReadFile(const TCHAR* filename); // throw eKeyFile() void WriteFile(const TCHAR* filename) const; // throw eKeyFile() // Read and write keys to a keyfile - void ReadMem(const int8* pMem); // throw eKeyFile() + void ReadMem(const int8* pMem); // throw eKeyFile() void WriteMem(int8* pMem) const; // throw eKeyFile() - int GetWriteLen(); // throw eKeyFile() + int GetWriteLen(); // throw eKeyFile() // Functions to read and write the key to memory. GetWriteLen() will throw an // exception if keys are not currently loaded. - bool KeysLoaded() const; + bool KeysLoaded() const; void GenerateKeys(int keySize, int8* passphrase, int passphraseLen); // throw eKeyFile() // Generate new keys // Note: Bytes in passphrase will be cleared after keys are generated for safety - void ChangePassphrase(int8* passphraseOld, int passphraseOldLen, int8* passphrase, int passphraseLen); // throw eKeyFile() - // Change passphrase - // Note: Bytes in passphrases will be cleared after change for safety + void ChangePassphrase(int8* passphraseOld, + int passphraseOldLen, + int8* passphrase, + int passphraseLen); // throw eKeyFile() + // Change passphrase + // Note: Bytes in passphrases will be cleared after change for safety const cElGamalSigPrivateKey* GetPrivateKey(int8* passphrase, int passphraseLen); - void ReleasePrivateKey(); - // Access to the private key. Key is normally stored encrypted for safety. Call - // ReleasePrivateKey() to destory the plaintext version of the key as soon as you - // are done using the key. - // Note: Bytes in passphrase will be cleared after keys are generated for safety + void ReleasePrivateKey(); + // Access to the private key. Key is normally stored encrypted for safety. Call + // ReleasePrivateKey() to destory the plaintext version of the key as soon as you + // are done using the key. + // Note: Bytes in passphrase will be cleared after keys are generated for safety - const cElGamalSigPublicKey* GetPublicKey() const; + const cElGamalSigPublicKey* GetPublicKey() const; static const cFileHeaderID& GetFileHeaderID(); - + protected: - int8* mpPrivateKeyMem; // encrypted version of private key - int mPrivateKeyMemLen; + int8* mpPrivateKeyMem; // encrypted version of private key + int mPrivateKeyMemLen; - cElGamalSigPrivateKey* mpPrivateKey; // only valid between calls to GetPrivateKey() and ReleasePrivateKey() + cElGamalSigPrivateKey* mpPrivateKey; // only valid between calls to GetPrivateKey() and ReleasePrivateKey() cElGamalSigPublicKey* mpPublicKey; - int mPrivateKeyUseCount; + int mPrivateKeyUseCount; -private: - void ProtectKeys(int8* passphrase, int passphraseLen); // throw eKeyFile() - void ReleaseMem(); +private: + void ProtectKeys(int8* passphrase, int passphraseLen); // throw eKeyFile() + void ReleaseMem(); }; @@ -127,25 +130,31 @@ class cPrivateKeyProxy ~cPrivateKeyProxy(); bool AquireKey(cKeyFile& keyFile, int8* passphrase, int passphraseLen); - // note: be sure to check return value for failure!!! + // note: be sure to check return value for failure!!! - bool Valid() const { return mpKey != 0; } + bool Valid() const + { + return mpKey != 0; + } const cElGamalSigPrivateKey* GetKey() const; - const cElGamalSigPrivateKey& operator ->() const { return *GetKey(); } - const cElGamalSigPrivateKey& operator *() const { return *GetKey(); } - // In all access to the key, an exception will be thrown - // if key has not been successfully aquired. + const cElGamalSigPrivateKey& operator->() const + { + return *GetKey(); + } + const cElGamalSigPrivateKey& operator*() const + { + return *GetKey(); + } + // In all access to the key, an exception will be thrown + // if key has not been successfully aquired. private: - cKeyFile* mpKeyFile; + cKeyFile* mpKeyFile; const cElGamalSigPrivateKey* mpKey; }; -inline cPrivateKeyProxy::cPrivateKeyProxy() -: mpKeyFile(0), - mpKey(0) +inline cPrivateKeyProxy::cPrivateKeyProxy() : mpKeyFile(0), mpKey(0) { } #endif - diff --git a/src/twcrypto/stdtwcrypto.cpp b/src/twcrypto/stdtwcrypto.cpp index b5a0e4b..cd2ba2a 100644 --- a/src/twcrypto/stdtwcrypto.cpp +++ b/src/twcrypto/stdtwcrypto.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,6 +36,3 @@ // // #include "stdtwcrypto.h" - - -// eof: stdtwcrypto.cpp diff --git a/src/twcrypto/stdtwcrypto.h b/src/twcrypto/stdtwcrypto.h index 70e0c55..cdfb248 100644 --- a/src/twcrypto/stdtwcrypto.h +++ b/src/twcrypto/stdtwcrypto.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/twcrypto/twcrypto.cpp b/src/twcrypto/twcrypto.cpp index ba4dba7..6207c10 100644 --- a/src/twcrypto/twcrypto.cpp +++ b/src/twcrypto/twcrypto.cpp @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // // Name....: twcrypto.cpp // Date....: 05/12/99 -// Creator.: +// Creator.: // // Implementation for the cTWCrypto package // @@ -43,12 +43,12 @@ // Dependencies //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#include "stdtwcrypto.h" // for: precompiled-header -#include "twcrypto.h" // for: cTWCrypto +#include "stdtwcrypto.h" // for: precompiled-header +#include "twcrypto.h" // for: cTWCrypto #include "twcryptoerrors.h" -TSS_ImplementPackage( cTWCrypto ) +TSS_ImplementPackage(cTWCrypto) //============================================================================= // cTWCrypto::cTWCrypto() @@ -60,7 +60,5 @@ TSS_ImplementPackage( cTWCrypto ) // cTWCrypto::cTWCrypto() { - TSS_REGISTER_PKG_ERRORS( twcrypto ) + TSS_REGISTER_PKG_ERRORS(twcrypto) } - -// eof: twcrypto.cpp diff --git a/src/twcrypto/twcrypto.h b/src/twcrypto/twcrypto.h index 27fe6e3..a9cb5fd 100644 --- a/src/twcrypto/twcrypto.h +++ b/src/twcrypto/twcrypto.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,18 +43,17 @@ //--Requirements -#include "core/package.h" // for: TSS_DeclarePackage +#include "core/package.h" // for: TSS_DeclarePackage //--Classes -TSS_BeginPackage( cTWCrypto ) - - public: +TSS_BeginPackage(cTWCrypto) - cTWCrypto(); + public : -TSS_EndPackage( cTWCrypto ) + cTWCrypto(); +TSS_EndPackage(cTWCrypto) -#endif//__TWCRYPTO_H +#endif //__TWCRYPTO_H diff --git a/src/twcrypto/twcryptoerrors.cpp b/src/twcrypto/twcryptoerrors.cpp index 64cc046..10b2969 100644 --- a/src/twcrypto/twcryptoerrors.cpp +++ b/src/twcrypto/twcryptoerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,15 +39,15 @@ #include "keyfile.h" -TSS_BEGIN_ERROR_REGISTRATION( twcrypto ) +TSS_BEGIN_ERROR_REGISTRATION(twcrypto) // // Keyfile // -TSS_REGISTER_ERROR( eKeyFile(), _T("Unknown Keyfile error.") ); -TSS_REGISTER_ERROR( eKeyFileInvalidFmt(), _T("Invalid Keyfile format") ); -TSS_REGISTER_ERROR( eKeyFileBadPassphrase(), _T("Keyfile passphrase incorrect.") ); -TSS_REGISTER_ERROR( eKeyFileArchive(), _T("Keyfile Read/Write error.") ); -TSS_REGISTER_ERROR( eKeyFileUninitialized(), _T("Internal Keyfile error.") ); +TSS_REGISTER_ERROR(eKeyFile(), _T("Unknown Keyfile error.")); +TSS_REGISTER_ERROR(eKeyFileInvalidFmt(), _T("Invalid Keyfile format")); +TSS_REGISTER_ERROR(eKeyFileBadPassphrase(), _T("Keyfile passphrase incorrect.")); +TSS_REGISTER_ERROR(eKeyFileArchive(), _T("Keyfile Read/Write error.")); +TSS_REGISTER_ERROR(eKeyFileUninitialized(), _T("Internal Keyfile error.")); TSS_END_ERROR_REGISTRATION() diff --git a/src/twcrypto/twcryptoerrors.h b/src/twcrypto/twcryptoerrors.h index 149b9c3..1f35268 100644 --- a/src/twcrypto/twcryptoerrors.h +++ b/src/twcrypto/twcryptoerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,8 +41,7 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( twcrypto ) - +TSS_DECLARE_ERROR_REGISTRATION(twcrypto) -#endif//__COREERRORS_H +#endif //__COREERRORS_H diff --git a/src/twparser/Makefile.am b/src/twparser/Makefile.am index 138b838..61fa23d 100644 --- a/src/twparser/Makefile.am +++ b/src/twparser/Makefile.am @@ -1,14 +1,21 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtwparser.a +libtwparser_adir=. libtwparser_a_SOURCES = \ genreparseinfo.cpp parserhelper.cpp parserobjects.cpp \ policyparser.cpp stdtwparser.cpp twparser.cpp twparsererrors.cpp \ twparserstrings.cpp yylex.cpp yyparse.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +libtwparser_a_HEADERS = \ + genreparseinfo.h parserhelper.h parserobjects.h policyparser.h \ + stdtwparser.h twparser.h twparsererrors.h twparserstrings.h \ + yylex.h yyparse.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtwparser_a_OBJECTS) diff --git a/src/twparser/Makefile.in b/src/twparser/Makefile.in index afc136d..102f0d9 100644 --- a/src/twparser/Makefile.in +++ b/src/twparser/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libtwparser_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,20 +87,27 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/twparser -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libtwparser_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libtwparser_a_AR = $(AR) $(ARFLAGS) libtwparser_a_LIBADD = am_libtwparser_a_OBJECTS = genreparseinfo.$(OBJEXT) \ @@ -58,23 +116,95 @@ am_libtwparser_a_OBJECTS = genreparseinfo.$(OBJEXT) \ twparser.$(OBJEXT) twparsererrors.$(OBJEXT) \ twparserstrings.$(OBJEXT) yylex.$(OBJEXT) yyparse.$(OBJEXT) libtwparser_a_OBJECTS = $(am_libtwparser_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libtwparser_a_SOURCES) DIST_SOURCES = $(libtwparser_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libtwparser_adir)" +HEADERS = $(libtwparser_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -90,7 +220,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -98,6 +228,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -109,6 +240,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -125,21 +257,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -169,20 +304,31 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libtwparser.a +libtwparser_adir = . libtwparser_a_SOURCES = \ genreparseinfo.cpp parserhelper.cpp parserobjects.cpp \ policyparser.cpp stdtwparser.cpp twparser.cpp twparsererrors.cpp \ twparserstrings.cpp yylex.cpp yyparse.cpp +libtwparser_a_HEADERS = \ + genreparseinfo.h parserhelper.h parserobjects.h policyparser.h \ + stdtwparser.h twparser.h twparsererrors.h twparserstrings.h \ + yylex.h yyparse.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -191,15 +337,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twparser/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/twparser/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twparser/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/twparser/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -216,13 +361,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libtwparser.a: $(libtwparser_a_OBJECTS) $(libtwparser_a_DEPENDENCIES) - -rm -f libtwparser.a - $(libtwparser_a_AR) libtwparser.a $(libtwparser_a_OBJECTS) $(libtwparser_a_LIBADD) - $(RANLIB) libtwparser.a + +libtwparser.a: $(libtwparser_a_OBJECTS) $(libtwparser_a_DEPENDENCIES) $(EXTRA_libtwparser_a_DEPENDENCIES) + $(AM_V_at)-rm -f libtwparser.a + $(AM_V_AR)$(libtwparser_a_AR) libtwparser.a $(libtwparser_a_OBJECTS) $(libtwparser_a_LIBADD) + $(AM_V_at)$(RANLIB) libtwparser.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -231,91 +378,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libtwparser_aHEADERS: $(libtwparser_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libtwparser_a_HEADERS)'; test -n "$(libtwparser_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libtwparser_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libtwparser_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libtwparser_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libtwparser_adir)" || exit $$?; \ + done + +uninstall-libtwparser_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libtwparser_a_HEADERS)'; test -n "$(libtwparser_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libtwparser_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libtwparser_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -326,16 +503,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -355,18 +539,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libtwparser_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -385,22 +589,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libtwparser_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libtwparser_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libtwparser_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libtwparser_a_OBJECTS) + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/twparser/genreparseinfo.cpp b/src/twparser/genreparseinfo.cpp index fa1fa51..8cf38a2 100644 --- a/src/twparser/genreparseinfo.cpp +++ b/src/twparser/genreparseinfo.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -75,26 +75,33 @@ cGenreParseInfo::cGenreParseInfo() InitPredefinedVariables(); } - +cGenreParseInfo::~cGenreParseInfo() +{ + RuleListType::iterator itr; + for (itr = mRuleList.begin(); itr != mRuleList.end(); ++itr) + { + delete *itr; + } +} + + /////////////////////////////////////////////////////////////////////////////// // AddStopPoint // NOTE: the list copies the string, so it is safe for the parser to // free the lexeme /////////////////////////////////////////////////////////////////////////////// -void -cGenreParseInfo::AddStopPoint( const cFCOName& name ) +void cGenreParseInfo::AddStopPoint(const cFCOName& name) { - mStopList.push_back( name ); + mStopList.push_back(name); } /////////////////////////////////////////////////////////////////////////////// -// AddRule -- adds the specified rule to our list. we will eventually call +// AddRule -- adds the specified rule to our list. we will eventually call // MakeFCOSpecs(), which will use this list as its source. // // NOTE: the list is responsible for freeing the pointers /////////////////////////////////////////////////////////////////////////////// -void -cGenreParseInfo::AddRule(const cParseRule *pnode) +void cGenreParseInfo::AddRule(const cParseRule* pnode) { mRuleList.push_back(pnode); } @@ -103,44 +110,46 @@ cGenreParseInfo::AddRule(const cParseRule *pnode) // RulePointAlreadyDefined -- returns true if the given name was already used // as a start or stop point /////////////////////////////////////////////////////////////////////////////// -bool cGenreParseInfo::RulePointAlreadyDefined( const cFCOName& fcoName ) +bool cGenreParseInfo::RulePointAlreadyDefined(const cFCOName& fcoName) { bool fFound = false; // check start points - for( RuleListType::iterator i = mRuleList.begin(); i != mRuleList.end(); i++ ) + for (RuleListType::iterator i = mRuleList.begin(); i != mRuleList.end(); ++i) { - if( (*i)->GetName() == fcoName ) + if ((*i)->GetName() == fcoName) fFound = true; } // check stop points - if( ! fFound ) + if (!fFound) { - for( StopListType::iterator j = mStopList.begin(); j != mStopList.end(); j++ ) + for (StopListType::iterator j = mStopList.begin(); j != mStopList.end(); ++j) { - if( *j == fcoName ) + if (*j == fcoName) fFound = true; } } - return( fFound ); + return (fFound); } /////////////////////////////////////////////////////////////////////////////// -// InitPredefinedVariables -- +// InitPredefinedVariables -- /////////////////////////////////////////////////////////////////////////////// void cGenreParseInfo::InitPredefinedVariables() { iParserGenreUtil* pGU = iTWFactory::GetInstance()->CreateParserGenreUtil(); TSTRING sVarName, sValue; - int index = 0; - while( pGU->EnumPredefinedVariables( index++, sVarName, sValue ) ) + int index = 0; + while (pGU->EnumPredefinedVariables(index++, sVarName, sValue)) { - mLocalPredefVarTable.Insert( sVarName, sValue ); + mLocalPredefVarTable.Insert(sVarName, sValue); } + + delete pGU; } @@ -150,7 +159,7 @@ void cGenreParseInfo::InitPredefinedVariables() // a backslash. Fails if symbol isn't found /////////////////////////////////////////////////////////////////////////////// -bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper ) +bool cGenreParseInfo::DoVarSubstitution(TSTRING& rval) //throw( eParserHelper ) { cDebug d("cConfigFile::DoVarSubst()"); d.TraceDebug("ORIG: %s\n", rval.c_str()); @@ -166,23 +175,23 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper // step through string // iterate to (slen-1), because we are looking for a two-character sentinel "$(" bool fEscaping = false; - for (TSTRING::size_type i = 0; i < rval.size(); i++) + for (TSTRING::size_type i = 0; i < rval.size(); i++) { TCHAR c = rval[i]; // is it the "$(" sentinel? (an escaped '$' is not a variable) - if (c == '$' && ! fEscaping ) + if (c == '$' && !fEscaping) { - c = rval[i+1]; - if (c == '(') + c = rval[i + 1]; + if (c == '(') { // ooh, wow! it's a variable! find the end - bool found = false; + bool found = false; TSTRING::size_type j; - for (j = i+1; j < rval.size(); j++) + for (j = i + 1; j < rval.size(); j++) { - if (rval[j] == ')') + if (rval[j] == ')') { found = true; break; @@ -190,7 +199,7 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper } // did we find it? - if (!found) + if (!found) { // TODO: throw error return false; @@ -198,19 +207,19 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper // otherwise, cut out the variable name TSTRING::size_type begin = i + 2; - TSTRING::size_type size = j - i - 2; - TSTRING varname; + TSTRING::size_type size = j - i - 2; + TSTRING varname; varname = rval.substr(begin, size); d.TraceDebug("symbol = %s\n", varname.c_str()); // look up in symbol table TSTRING varvalue; - if ( ! LookupVariable( varname, varvalue ) ) - throw eParserUseUndefVar( varname ); + if (!LookupVariable(varname, varvalue)) + throw eParserUseUndefVar(varname); // replace varname with varvalue - rval.replace(begin-2, size+3, varvalue); + rval.replace(begin - 2, size + 3, varvalue); d.TraceDebug("POST: %s\n", rval.c_str()); @@ -219,7 +228,7 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper // update counters - // we should bump the cursor over by the length of the + // we should bump the cursor over by the length of the // varvalue (minus one, to compensate for post-increment of index) i += varvalue.size() - 1; goto nextchar; @@ -227,18 +236,16 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper } else if (c == '\\') { - fEscaping = ! fEscaping; + fEscaping = !fEscaping; } else { fEscaping = false; } -nextchar: - ; + nextchar:; } - d.TraceDebug("DONE: %s\n", rval.c_str()); // switch around @@ -248,14 +255,14 @@ bool cGenreParseInfo::DoVarSubstitution( TSTRING &rval ) //throw( eParserHelper /////////////////////////////////////////////////////////////////////////////// // Insert -- add definition to symbol table /////////////////////////////////////////////////////////////////////////////// -bool cGenreParseInfo::InsertVariable( const TSTRING& var, const TSTRING& val ) //throw( eParserHelper ) +bool cGenreParseInfo::InsertVariable(const TSTRING& var, const TSTRING& val) //throw( eParserHelper ) { TSTRING dummy; // don't let them redefine predefined vars - if( mLocalPredefVarTable.Lookup(var, dummy) ) - throw eParserRedefineVar( var ); + if (mLocalPredefVarTable.Lookup(var, dummy)) + throw eParserRedefineVar(var); - return mLocalVarTable.Insert( var, val ); + return mLocalVarTable.Insert(var, val); } /////////////////////////////////////////////////////////////////////////////// @@ -263,10 +270,10 @@ bool cGenreParseInfo::InsertVariable( const TSTRING& var, const TSTRING& val ) / // This method will return false only if the given variable is not defined // in any of the three symbol tables. /////////////////////////////////////////////////////////////////////////////// -bool cGenreParseInfo::LookupVariable( const TSTRING& var, TSTRING& val ) +bool cGenreParseInfo::LookupVariable(const TSTRING& var, TSTRING& val) { - if( mLocalPredefVarTable.Lookup( var, val ) || mLocalVarTable.Lookup( var, val ) ) + if (mLocalPredefVarTable.Lookup(var, val) || mLocalVarTable.Lookup(var, val)) return true; else - return ( cParserHelper::GetGlobalVarTable().Lookup( var, val ) ); + return (cParserHelper::GetGlobalVarTable().Lookup(var, val)); } diff --git a/src/twparser/genreparseinfo.h b/src/twparser/genreparseinfo.h index d47a0dc..6de348d 100644 --- a/src/twparser/genreparseinfo.h +++ b/src/twparser/genreparseinfo.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -63,8 +63,14 @@ class cSymbolTable { public: - bool Insert( const TSTRING &var, const TSTRING &val ) { return mTable.Insert( var, val ); } - bool Lookup( const TSTRING &var, TSTRING &val ) { return mTable.Lookup( var, val ); } + bool Insert(const TSTRING& var, const TSTRING& val) + { + return mTable.Insert(var, val); + } + bool Lookup(const TSTRING& var, TSTRING& val) + { + return mTable.Lookup(var, val); + } private: cHashTable mTable; @@ -76,57 +82,65 @@ class cSymbolTable // along -- the goal is to reduce the code that lives in the yacc // -class cGenreParseInfo -{ +class cGenreParseInfo +{ public: cGenreParseInfo(); + ~cGenreParseInfo(); + + void AddStopPoint(const cFCOName& name); + // adds the specified path as a stop point -- for now, we just queue it up, + // since we don't know which rule to attach it to. to do that, we call + // AttachStopPoints() - void AddStopPoint( const cFCOName& name ); - // adds the specified path as a stop point -- for now, we just queue it up, - // since we don't know which rule to attach it to. to do that, we call - // AttachStopPoints() + bool RulePointAlreadyDefined(const cFCOName& fcoName); + // checks if szName is in mSpecNameList - bool RulePointAlreadyDefined( const cFCOName& fcoName ); - // checks if szName is in mSpecNameList + void AddRule(const cParseRule* pnode); + // adds the specified rule to our list. we will eventually call CreateFCOSpecs(), + // which will use the list as its source. - void AddRule(const cParseRule *pnode); - // adds the specified rule to our list. we will eventually call CreateFCOSpecs(), - // which will use the list as its source. + bool DoVarSubstitution(TSTRING& rval); //throw( eParserHelper ) - bool DoVarSubstitution(TSTRING &rval); //throw( eParserHelper ) - - bool InsertVariable( const TSTRING& var, const TSTRING& val); //throw( eParserHelper ) - bool LookupVariable( const TSTRING& var, TSTRING& val); - // This method now looks in the global variable table (defined in cParserHelper ), - // if a variable is not found in the local or predefined tables. + bool InsertVariable(const TSTRING& var, const TSTRING& val); //throw( eParserHelper ) + bool LookupVariable(const TSTRING& var, TSTRING& val); + // This method now looks in the global variable table (defined in cParserHelper ), + // if a variable is not found in the local or predefined tables. // // data retreval // - typedef std::list< cFCOName > StopListType; - typedef std::list< const cParseRule* > RuleListType; - RuleListType* GetRules() { return &mRuleList; }; - StopListType* GetStopList() { return &mStopList; }; - - cSymbolTable& GetPredefVarTable( void ) { return mLocalPredefVarTable; } + typedef std::list StopListType; + typedef std::list RuleListType; + RuleListType* GetRules() + { + return &mRuleList; + }; + StopListType* GetStopList() + { + return &mStopList; + }; + + cSymbolTable& GetPredefVarTable(void) + { + return mLocalPredefVarTable; + } private: - void InitPredefinedVariables(); + void InitPredefinedVariables(); - - StopListType mStopList; - // this is where all the stop points are stored at parse-time, since we - // don't know enough to bind them to fcospecs yet. + StopListType mStopList; + // this is where all the stop points are stored at parse-time, since we + // don't know enough to bind them to fcospecs yet. - RuleListType mRuleList; - // these are the list of parser generated rules + RuleListType mRuleList; + // these are the list of parser generated rules - cSymbolTable mLocalVarTable; - // contains all the variable symbol definitions - cSymbolTable mLocalPredefVarTable; - // Contains the predefined variable definitions. + cSymbolTable mLocalVarTable; + // contains all the variable symbol definitions + cSymbolTable mLocalPredefVarTable; + // Contains the predefined variable definitions. }; #endif // __GENREPARSEINFO_H - diff --git a/src/twparser/parserhelper.cpp b/src/twparser/parserhelper.cpp index b5543d1..6ba2d07 100644 --- a/src/twparser/parserhelper.cpp +++ b/src/twparser/parserhelper.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -57,58 +57,57 @@ // UTIL FUNCTION PROTOTYES //========================================================================= -static int util_ConvertHex( const char* psz, int* const pnCharsRead ); -static int util_ConvertUnicode( const char* psz, int* const pnCharsRead ); -static int util_ConvertOctal( const char* psz, int* const pnCharsRead ); -static bool util_IsOctal( const char ch ); -static int util_GetEscapeValueOfChar( char ch ); -static int util_GetRecurseDepth( const cParseNamedAttrList* pList ); //throw( eParserHelper ) -static void util_EatAllSpaces( TSTRING& str ); -static void util_LoseSurroundingWS( TSTRING& str ); -#ifdef _DEBUG +static int util_ConvertHex(const char* psz, int* const pnCharsRead); +static int util_ConvertUnicode(const char* psz, int* const pnCharsRead); +static int util_ConvertOctal(const char* psz, int* const pnCharsRead); +static bool util_IsOctal(const char ch); +static int util_GetEscapeValueOfChar(char ch); +static int util_GetRecurseDepth(const cParseNamedAttrList* pList); //throw( eParserHelper ) +static void util_LoseSurroundingWS(TSTRING& str); +#ifdef DEBUG static bool util_AsciiCharsActLikeTheyShould(); #endif // finds first '&', '+', '-' on or after str[i] -static TSTRING::size_type util_FindNextDelim( const TSTRING& str, TSTRING::size_type i ); +static TSTRING::size_type util_FindNextDelim(const TSTRING& str, TSTRING::size_type i); //========================================================================= // STATIC DATA MEMBERS //========================================================================= -cErrorBucket* cParserHelper::mpError; -int cParserHelper::miLineNum; -cPreprocessor::AcceptStack cPreprocessor::mStateStack; -bool cPreprocessor::mfIgnoreSection; +cErrorBucket* cParserHelper::mpError; +int cParserHelper::miLineNum; +cPreprocessor::AcceptStack cPreprocessor::mStateStack; +bool cPreprocessor::mfIgnoreSection; -cParserHelper::ScopedAttrContainer cParserHelper::mScopedAttrs; -cParserHelper::GenreContainer cParserHelper::mAph; -cGenreParseInfo* cParserHelper::pCurrentGenreInfo; -cSymbolTable cParserHelper::mGlobalVarTable; -bool cParserHelper::mfParseOnly; +cParserHelper::ScopedAttrContainer cParserHelper::mScopedAttrs; +cParserHelper::GenreContainer cParserHelper::mAph; +cGenreParseInfo* cParserHelper::pCurrentGenreInfo; +cSymbolTable cParserHelper::mGlobalVarTable; +bool cParserHelper::mfParseOnly; //========================================================================= // METHOD CODE //========================================================================= -eParserHelper::eParserHelper( const TSTRING& strMsg, int nLine /*= CURRENT_LINE */) +eParserHelper::eParserHelper(const TSTRING& strMsg, int nLine /*= CURRENT_LINE */) { TOSTRINGSTREAM strErr; strErr << strMsg; - if( NO_LINE != nLine ) + if (NO_LINE != nLine) { // separate the message from the line number - if( ! strMsg.empty() ) + if (!strMsg.empty()) strErr << _T(": "); // output the line number - strErr << TSS_GetString( cTWParser, twparser::STR_LINE_NUMBER ); - - if( CURRENT_LINE == nLine ) + strErr << TSS_GetString(cTWParser, twparser::STR_LINE_NUMBER); + + if (CURRENT_LINE == nLine) strErr << cParserHelper::GetLineNumber(); else strErr << nLine; @@ -116,27 +115,27 @@ eParserHelper::eParserHelper( const TSTRING& strMsg, int nLine /*= CURRENT_LINE mMsg = strErr.str(); } - -void cParserHelper::Init( cErrorBucket* pE ) + +void cParserHelper::Init(cErrorBucket* pE) { - // start off in default genre - cGenreSwitcher::GetInstance()->SelectGenre( cGenreSwitcher::GetInstance()->GetDefaultGenre() ); + // start off in default genre + cGenreSwitcher::GetInstance()->SelectGenre(cGenreSwitcher::GetInstance()->GetDefaultGenre()); mpError = pE; - cPreprocessor::PushState( cPreprocessor::STATE_ACCEPT ); + cPreprocessor::PushState(cPreprocessor::STATE_ACCEPT); miLineNum = 1; cPreprocessor::ReadSection(); pCurrentGenreInfo = NULL; - mfParseOnly = false; + mfParseOnly = false; } -void cParserHelper::Finit( cGenreSpecListVector* pPolicy ) +void cParserHelper::Finit(cGenreSpecListVector* pPolicy) { // // don't build spec list if just checking syntax // - if( ! pPolicy ) + if (!pPolicy) { CleanUp(); return; @@ -145,30 +144,30 @@ void cParserHelper::Finit( cGenreSpecListVector* pPolicy ) int nRulesInPolicy = 0; GenreContainer::iterator i; - for( i = mAph.begin(); i != mAph.end(); i++ ) + for (i = mAph.begin(); i != mAph.end(); ++i) { cGenreSpecListPair slp; - cGenre::Genre g = i->first; - cGenreParseInfo* pgpi = i->second; + cGenre::Genre g = i->first; + cGenreParseInfo* pgpi = i->second; // // create the specs from rules // - cParserUtil::CreateFCOSpecs( g, pgpi, slp.GetSpecList() ); - slp.SetGenre( g ); - + cParserUtil::CreateFCOSpecs(g, pgpi, slp.GetSpecList()); + slp.SetGenre(g); + // // get rule count for section // int nRulesInSection = slp.GetSpecList().Size(); - if( 0 == nRulesInSection ) + if (0 == nRulesInSection) { - TSTRING str = TSS_GetString( cTWParser, twparser::STR_ERR2_PARSER_NO_RULES_IN_SECTION); - str.append( cGenreSwitcher::GetInstance()->GenreToString( slp.GetGenre(), true ) ); + TSTRING str = TSS_GetString(cTWParser, twparser::STR_ERR2_PARSER_NO_RULES_IN_SECTION); + str.append(cGenreSwitcher::GetInstance()->GenreToString(slp.GetGenre(), true)); - eParserNoRulesInSection e( str ); - e.SetFatality( false ); - cParserHelper::GetErrorBucket()->AddError( e ); + eParserNoRulesInSection e(str); + e.SetFatality(false); + cParserHelper::GetErrorBucket()->AddError(e); } // @@ -179,7 +178,7 @@ void cParserHelper::Finit( cGenreSpecListVector* pPolicy ) // // add to policy // - pPolicy->push_back( slp ); + pPolicy->push_back(slp); } CleanUp(); @@ -187,34 +186,34 @@ void cParserHelper::Finit( cGenreSpecListVector* pPolicy ) // // check that we have some rules // - if( 0 == nRulesInPolicy ) - throw eParserNoRules( _T(""), eParserHelper::NO_LINE ); + if (0 == nRulesInPolicy) + throw eParserNoRules(_T(""), eParserHelper::NO_LINE); } void cParserHelper::CleanUp() { GenreContainer::iterator i; - for( i = mAph.begin(); i != mAph.end(); i++ ) + for (i = mAph.begin(); i != mAph.end(); ++i) delete i->second; - while( ! cPreprocessor::Empty() ) - cPreprocessor::PopState(); - while( ! cParserHelper::ScopeEmpty() ) + while (!cPreprocessor::Empty()) + cPreprocessor::PopState(); + while (!cParserHelper::ScopeEmpty()) cParserHelper::PopScope(); } cPreprocessor::cPreprocessor() { // start in the accept state - mStateStack.push( STATE_ACCEPT ); + mStateStack.push(STATE_ACCEPT); } -void cPreprocessor::PushState( AcceptState state ) +void cPreprocessor::PushState(AcceptState state) { - mStateStack.push( state ); + mStateStack.push(state); cDebug d("cPreprocessor::PushState"); - if( state == STATE_ACCEPT ) + if (state == STATE_ACCEPT) d.TraceDebug(_T("State == STATE_ACCEPT\n")); else d.TraceDebug(_T("State == STATE_IGNORE\n")); @@ -224,11 +223,11 @@ void cPreprocessor::PopState() { cDebug d("cPreprocessor::PopState"); - ASSERT( ! mStateStack.empty() ); + ASSERT(!mStateStack.empty()); mStateStack.pop(); -#ifdef _DEBUG - if( !Empty() && TopState() == STATE_ACCEPT ) +#ifdef DEBUG + if (!Empty() && TopState() == STATE_ACCEPT) d.TraceDebug(_T("State == STATE_ACCEPT\n")); else d.TraceDebug(_T("State == STATE_IGNORE\n")); @@ -236,8 +235,8 @@ void cPreprocessor::PopState() } cPreprocessor::AcceptState cPreprocessor::GetState() -{ - if( STATE_ACCEPT == TopState() && false == mfIgnoreSection ) +{ + if (STATE_ACCEPT == TopState() && false == mfIgnoreSection) return STATE_ACCEPT; else return STATE_IGNORE; @@ -245,47 +244,47 @@ cPreprocessor::AcceptState cPreprocessor::GetState() cPreprocessor::AcceptState cPreprocessor::TopState() { - ASSERT( ! mStateStack.empty() ); + ASSERT(!mStateStack.empty()); return mStateStack.top(); } cPreprocessor::AcceptState cPreprocessor::UnderneathTopState() { - ASSERT( mStateStack.size() > 1 ); + ASSERT(mStateStack.size() > 1); AcceptState stateRet, stateSave; stateSave = mStateStack.top(); mStateStack.pop(); stateRet = mStateStack.top(); - mStateStack.push( stateSave ); + mStateStack.push(stateSave); - return( stateRet ); + return (stateRet); } void cPreprocessor::ToggleTopState() { - ASSERT( ! mStateStack.empty() ); + ASSERT(!mStateStack.empty()); cDebug d("cPreprocessor::ToggleState"); AcceptState state = TopState(); - + mStateStack.pop(); // toggle state - mStateStack.push( GetOppositeState( state ) ); - - if( GetOppositeState( state ) == STATE_ACCEPT ) + mStateStack.push(GetOppositeState(state)); + + if (GetOppositeState(state) == STATE_ACCEPT) d.TraceDebug(_T("State == STATE_ACCEPT\n")); else d.TraceDebug(_T("State == STATE_IGNORE\n")); } -cPreprocessor::AcceptState cPreprocessor::GetOppositeState( AcceptState state ) +cPreprocessor::AcceptState cPreprocessor::GetOppositeState(AcceptState state) { - if( state == STATE_IGNORE ) + if (state == STATE_IGNORE) return STATE_ACCEPT; else return STATE_IGNORE; @@ -294,9 +293,9 @@ cPreprocessor::AcceptState cPreprocessor::GetOppositeState( AcceptState state ) bool cPreprocessor::AtTopLevel() { - ASSERT( ! mStateStack.empty() ); + ASSERT(!mStateStack.empty()); - bool fAtTop; + bool fAtTop; AcceptState stateSave; // save and pop current state @@ -307,45 +306,46 @@ bool cPreprocessor::AtTopLevel() fAtTop = mStateStack.empty(); // return item to stack - mStateStack.push( stateSave ); + mStateStack.push(stateSave); - return( fAtTop ); + return (fAtTop); } -// pushes cPreprocessor::STATE_IGNORE onto the state stack if +// pushes cPreprocessor::STATE_IGNORE onto the state stack if // strSection is not an acceptable genre for this OS -void cParserHelper::SetSection( TSTRING& strSection ) // throw( eParserHelper ) +void cParserHelper::SetSection(TSTRING& strSection) // throw( eParserHelper ) { // // do we recognize the section string? // - cGenre::Genre g = cGenreSwitcher::GetInstance()->StringToGenre( strSection.c_str() ); - if( cGenre::GENRE_INVALID != g && cGenreSwitcher::GetInstance()->IsGenreAppropriate( g ) ) - { - cGenreSwitcher::GetInstance()->SelectGenre( g ); - - // set current genre info pointer - GenreContainer::iterator i = mAph.find( cGenreSwitcher::GetInstance()->CurrentGenre() ); - if( mAph.end() == i ) + cGenre::Genre g = cGenreSwitcher::GetInstance()->StringToGenre(strSection.c_str()); + if (cGenre::GENRE_INVALID != g && cGenreSwitcher::GetInstance()->IsGenreAppropriate(g)) + { + cGenreSwitcher::GetInstance()->SelectGenre(g); + + // set current genre info pointer + GenreContainer::iterator i = mAph.find(cGenreSwitcher::GetInstance()->CurrentGenre()); + if (mAph.end() == i) { pCurrentGenreInfo = new cGenreParseInfo; - mAph.insert( GenreContainer::value_type( cGenreSwitcher::GetInstance()->CurrentGenre(), pCurrentGenreInfo ) ); + mAph.insert(GenreContainer::value_type(cGenreSwitcher::GetInstance()->CurrentGenre(), pCurrentGenreInfo)); cPreprocessor::ReadSection(); } - else + else { - throw eParserSectionAlreadyDefined( strSection ); + throw eParserSectionAlreadyDefined(strSection); } } else // ignore { - if( ! ParseOnly() ) + if (!ParseOnly()) { - eParserIgnoringSection e( strSection ); - e.SetFatality( false ); - if( mpError ) mpError->AddError( e ); + eParserIgnoringSection e(strSection); + e.SetFatality(false); + if (mpError) + mpError->AddError(e); } cPreprocessor::IgnoreSection(); @@ -355,48 +355,48 @@ void cParserHelper::SetSection( TSTRING& strSection ) // throw( eParserHelper ) // A function for inserting a global variable into the global variable table. Throws // an exception if they try to redefine one of the predefined variables. Returns // the return value of the hash table insert. -bool cParserHelper::InsertGlobalVariable( const TSTRING& var, const TSTRING& val ) +bool cParserHelper::InsertGlobalVariable(const TSTRING& var, const TSTRING& val) { TSTRING dummy; /* if( cParserHelper::GetGenreInfo()->GetPredefVarTable().Lookup(var, dummy) ) throw eParserRedefineVar( var ); */ - // TODO : Verify that there is no feasible way to search the predefines without + // TODO : Verify that there is no feasible way to search the predefines without // messing everything up, given our current architecture. - return mGlobalVarTable.Insert( var, val ); + return mGlobalVarTable.Insert(var, val); } cGenreParseInfo* cParserHelper::GetGenreInfo() { - if( ! pCurrentGenreInfo ) - { + if (!pCurrentGenreInfo) + { pCurrentGenreInfo = new cGenreParseInfo; - mAph.insert( GenreContainer::value_type( cGenreSwitcher::GetInstance()->CurrentGenre(), pCurrentGenreInfo ) ); + mAph.insert(GenreContainer::value_type(cGenreSwitcher::GetInstance()->CurrentGenre(), pCurrentGenreInfo)); } return pCurrentGenreInfo; } -bool cParserUtil::AnyOfTheseHostsExists( cParseStringList* pList ) +bool cParserUtil::AnyOfTheseHostsExists(cParseStringList* pList) { TSTRING strHostName; - cDebug d("cPreprocessor::AnyOfTheseHostsExists"); + cDebug d("cPreprocessor::AnyOfTheseHostsExists"); // this throws an exception. let it go on up, since we can't do any ifhosting // if we don't know what machine we're on - iFSServices::GetInstance()->GetMachineName( strHostName ); + iFSServices::GetInstance()->GetMachineName(strHostName); // want to do a case-insensitive compare - std::transform( strHostName.begin(), strHostName.end(), strHostName.begin(), _totlower ); - + std::transform(strHostName.begin(), strHostName.end(), strHostName.begin(), _totlower); + // if the host name matches any in the list, return true - for( std::list::iterator iter = pList->begin(); iter != pList->end(); iter++ ) + for (std::list::iterator iter = pList->begin(); iter != pList->end(); ++iter) { // want to do case-insensitive compare - std::transform( (*iter).begin(), (*iter).end(), (*iter).begin(), _totlower ); + std::transform((*iter).begin(), (*iter).end(), (*iter).begin(), _totlower); - if( 0 == strHostName.compare( (*iter) ) ) + if (0 == strHostName.compare((*iter))) { d.TraceDebug(_T("host exists\n")); return true; @@ -407,19 +407,19 @@ bool cParserUtil::AnyOfTheseHostsExists( cParseStringList* pList ) return false; } -// converts escaped character sequences in strEscapedString into their escape characters in strInterpretedString +// converts escaped character sequences in strEscapedString into their escape characters in strInterpretedString //( e.g. turns "Hello World!\n" (literal backslash) into "Hello World!" -// all C++ escape sequences are recognized: -// (1) octal numbers \012 (1, 2, or 3 octal digits), -// (2) hex numbers \x2A ( 'x' followed by one or two hex digits ), +// all C++ escape sequences are recognized: +// (1) octal numbers \012 (1, 2, or 3 octal digits), +// (2) hex numbers \x2A ( 'x' followed by one or two hex digits ), // (3) unicode characters \uABCD ( 'u' followed by exactly 4 hex digits ) // (4) chars: \t, \v, \b, \r, \f, \a, \\, \?, \', and \" // (5) all other escaped chars are treated as if not escaped -void cParserUtil::InterpretEscapedString( const std::string& strEscapedString, TSTRING& strInterpretedString ) -{ +void cParserUtil::InterpretEscapedString(const std::string& strEscapedString, TSTRING& strInterpretedString) +{ cDebug d("cParserHelper::InterpretEscapedString"); - ASSERT( (void*)&strEscapedString != (void*)&strInterpretedString ); // don't let us read and write to same string + ASSERT((void*)&strEscapedString != (void*)&strInterpretedString); // don't let us read and write to same string // The source string may contain literal multibyte characters, escaped MB characters, and escaped Unicode characters. // On Unix TCHAR == char always, therefore literal and esacped mb chars can be stored in strInterpretedString @@ -427,60 +427,45 @@ void cParserUtil::InterpretEscapedString( const std::string& strEscapedString, T // But on Windows we need to build an intermediate narrow string because it needs to be passed through // cStringUtil::StrToTstr() to convert literal and escaped mb chars to TCHARs (which are wchar_t in this case). // Escaped Unicode chars are included in this intermediate string specially encoded so that StrToTstr() - // leaves it alone. After we have the wide string, we convert these encoded Unicode chars into true 16 bit + // leaves it alone. After we have the wide string, we convert these encoded Unicode chars into true 16 bit // Unicode chars. - #ifdef _UNICODE - typedef char INTERCHAR; - const char unicodeEscape = '\x01'; // This value must be chosen carefully so not to conflict with escape chars or mb chars - const char unicodeBase = 'A'; // This value must not fool the convertion from single to multibyte - bool unicodeWasEscaped = false; - std::string strIntermediateString; - #else - // for unix we cheat a bit and do the initial interpretation + + // for unix we cheat a bit and do the initial interpretation // directly to the final string. typedef TCHAR INTERCHAR; - TSTRING& strIntermediateString = strInterpretedString; - #endif - + TSTRING& strIntermediateString = strInterpretedString; + const char* pchCur = strEscapedString.c_str(); - for( strIntermediateString.erase(); - *pchCur != 0; - pchCur++ ) // only single byte in this part of the policy file + for (strIntermediateString.erase(); *pchCur != 0; pchCur++) // only single byte in this part of the policy file { - if( *pchCur != '\\' ) // just regular char + if (*pchCur != '\\') // just regular char { - #ifdef _UNICODE - // check for our special unicode escape char, and escape it if necessary - if ( *pchCur == unicodeEscape ) - { - strIntermediateString += unicodeEscape; - unicodeWasEscaped = true; - } - #endif - strIntermediateString += *pchCur; } else // deal with escaped character sequence { // make sure the '\' isn't the end of the string // ( if it is, the "for" will ++ pchCur, see it's 0, then break ) - if( *(pchCur + 1 ) ) + if (*(pchCur + 1)) { int nCharsRead; pchCur++; // go to char past '\' - if (*pchCur == 'x' && std::isxdigit(*(pchCur+1), std::locale() ) ) // deal with \xXXXX where 'x' is the character 'x', and 'X' is a hex number + if (*pchCur == 'x' && + std::isxdigit( + *(pchCur + 1), + std::locale())) // deal with \xXXXX where 'x' is the character 'x', and 'X' is a hex number { pchCur++; // go to char past 'x' - char cEscapedChar = static_cast( util_ConvertHex( pchCur, &nCharsRead ) ); - pchCur += ( nCharsRead == 0 ) ? 0 : nCharsRead - 1; //increment pointer to last char we read + char cEscapedChar = static_cast(util_ConvertHex(pchCur, &nCharsRead)); + pchCur += (nCharsRead == 0) ? 0 : nCharsRead - 1; //increment pointer to last char we read if (cEscapedChar == 0) // null characters are not allowed { - throw eParserBadHex( cStringUtil::StrToTstr( pchCur - (( nCharsRead == 0 ) ? 0 : nCharsRead - 1) ) ); + throw eParserBadHex(cStringUtil::StrToTstr(pchCur - ((nCharsRead == 0) ? 0 : nCharsRead - 1))); } else { @@ -490,109 +475,48 @@ void cParserUtil::InterpretEscapedString( const std::string& strEscapedString, T else if (*pchCur == 'u') // unicode escape { pchCur++; // go to char past 'x' - wchar_t wcEscapedChar = static_cast( util_ConvertUnicode( pchCur, &nCharsRead ) ); - pchCur += ( nCharsRead == 0 ) ? 0 : nCharsRead - 1; //increment pointer to last char we read + wchar_t wcEscapedChar = static_cast(util_ConvertUnicode(pchCur, &nCharsRead)); + pchCur += (nCharsRead == 0) ? 0 : nCharsRead - 1; //increment pointer to last char we read if (wcEscapedChar == 0) // null characters are not allowed { - throw eParserBadHex( cStringUtil::StrToTstr( pchCur - (( nCharsRead == 0 ) ? 0 : nCharsRead - 1) ) ); + throw eParserBadHex(cStringUtil::StrToTstr(pchCur - ((nCharsRead == 0) ? 0 : nCharsRead - 1))); } - - // For non-unicode Unix, we don't support > 0xff characters. - // Unicode Windows supports it just fine. - #ifndef _UNICODE else if (wcEscapedChar > 0xff) { - throw eParserBadHex( cStringUtil::StrToTstr( pchCur - (( nCharsRead == 0 ) ? 0 : nCharsRead - 1) ) ); + throw eParserBadHex(cStringUtil::StrToTstr(pchCur - ((nCharsRead == 0) ? 0 : nCharsRead - 1))); } else { strIntermediateString += static_cast(wcEscapedChar); } - #else - else if (wcEscapedChar <= 0xff) - { - strIntermediateString += static_cast(wcEscapedChar); - } - else - { - strIntermediateString += unicodeEscape; - strIntermediateString += static_cast((wcEscapedChar >> 12 & 0xf) + unicodeBase); - strIntermediateString += static_cast((wcEscapedChar >> 8 & 0xf) + unicodeBase); - strIntermediateString += static_cast((wcEscapedChar >> 4 & 0xf) + unicodeBase); - strIntermediateString += static_cast((wcEscapedChar & 0xf) + unicodeBase); - unicodeWasEscaped = true; - } - #endif } - else if( util_IsOctal( *pchCur ) ) // deal with \xxx where 'x' is an octal digit + else if (util_IsOctal(*pchCur)) // deal with \xxx where 'x' is an octal digit { - strIntermediateString += static_cast( util_ConvertOctal( pchCur, &nCharsRead ) ); - pchCur += ( nCharsRead == 0 ) ? 0 : nCharsRead - 1; //increment pointer to last char we read + strIntermediateString += static_cast(util_ConvertOctal(pchCur, &nCharsRead)); + pchCur += (nCharsRead == 0) ? 0 : nCharsRead - 1; //increment pointer to last char we read } else // deal with \x where 'x' is any other character { - strIntermediateString += static_cast( util_GetEscapeValueOfChar( *pchCur ) ); - } - } - } - } - - #ifdef _UNICODE - // now convert to the wide vertion - strInterpretedString = cStringUtil::StrToTstr(strIntermediateString); - - // search for unicode escapes - if (unicodeWasEscaped) - { - TSTRING::iterator i; - for (i = strInterpretedString.begin(); i != strInterpretedString.end(); ++i) - { - if (*i == static_cast(unicodeEscape)) - { - i = strInterpretedString.erase(i); - ASSERT(i != strInterpretedString.end()); // This would indicate a logic error above - - if (*i != static_cast(unicodeEscape)) // check that this is escaped unicode - { - wchar_t wc; - TSTRING::iterator j = i; - - ASSERT(*j >= unicodeBase && *j < unicodeBase + 16); - wc = static_cast((*j++ - unicodeBase) << 12); - ASSERT(j != strInterpretedString.end()); - - ASSERT(*j >= unicodeBase && *j < unicodeBase + 16); - wc |= static_cast((*j++ - unicodeBase) << 8); - ASSERT(j != strInterpretedString.end()); - - ASSERT(*j >= unicodeBase && *j < unicodeBase + 16); - wc |= static_cast((*j++ - unicodeBase) << 4); - ASSERT(j != strInterpretedString.end()); - - ASSERT(*j >= unicodeBase && *j < unicodeBase + 16); - wc |= static_cast((*j++ - unicodeBase)); - i = strInterpretedString.erase(i, j); - i = strInterpretedString.insert(i, wc); + strIntermediateString += static_cast(util_GetEscapeValueOfChar(*pchCur)); } } } } - #endif -#ifdef _DEBUG +#ifdef DEBUG std::string str; str = "before: <"; str += strEscapedString; str += ">\n"; - d.TraceDebug( str.c_str() ); - + d.TraceDebug(str.c_str()); + TSTRING tstr; tstr = _T("after: <"); tstr += strInterpretedString; tstr += _T(">\n"); - d.TraceDebug( tstr.c_str() ); + d.TraceDebug(tstr.c_str()); #endif } @@ -600,54 +524,57 @@ void cParserUtil::InterpretEscapedString( const std::string& strEscapedString, T // CreateFCOSpecs -- foreach rule, create an FCOSpec. then attach the stop // points. /////////////////////////////////////////////////////////////////////////////// -void cParserUtil::CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSpecList &fcospeclist) //throw( eParserHelper ) +void cParserUtil::CreateFCOSpecs(cGenre::Genre g, + cGenreParseInfo* pgpi, + cFCOSpecList& fcospeclist) //throw( eParserHelper ) { - cGenreSwitcher::GetInstance()->SelectGenre( g ); + cGenreSwitcher::GetInstance()->SelectGenre(g); iParserGenreUtil* pHelper = iTWFactory::GetInstance()->CreateParserGenreUtil(); cDebug d("cGenreParseInfo::CreateFCOSpecs"); // foreach rule - std::list::iterator rule; - for (rule = pgpi->GetRules()->begin(); rule != pgpi->GetRules()->end(); rule++) + std::list::iterator rule; + for (rule = pgpi->GetRules()->begin(); rule != pgpi->GetRules()->end(); ++rule) { // // create the spec with its the last element of its start point as its name. // if the attribute 'rulename' is specified, we'll set it as the spec name later // Need to set the start point after the helper is set - // - cFCOName startpoint = (*rule)->GetName(); - iFCOSpec *pfcospec = iTWFactory::GetInstance()->CreateSpec( startpoint.GetShortName() ); // we'll set the helper below + // + cFCOName startpoint = (*rule)->GetName(); + iFCOSpec* pfcospec = + iTWFactory::GetInstance()->CreateSpec(startpoint.GetShortName()); // we'll set the helper below ////////////////////////////////////////////////////////////// // look to see if no recurse was specified. if it is, set the helper to a cFCOSpecNoChildren, - // otherwise set it to a cFCOSpecStopPointSet - int depth = util_GetRecurseDepth( (*rule)->GetAttrList() ); - if( 0 == depth ) + // otherwise set it to a cFCOSpecStopPointSet + int depth = util_GetRecurseDepth((*rule)->GetAttrList()); + if (0 == depth) { // don't use stop point set. say don't recurse cFCOSpecNoChildren* pNoKids = new cFCOSpecNoChildren; - pfcospec->SetHelper( pNoKids ); + pfcospec->SetHelper(pNoKids); } else { cFCOSpecStopPointSet* pStopPtSet = new cFCOSpecStopPointSet; - + // set stop points cGenreParseInfo::StopListType::iterator stop; - for (stop = pgpi->GetStopList()->begin(); stop != pgpi->GetStopList()->end(); stop++) + for (stop = pgpi->GetStopList()->begin(); stop != pgpi->GetStopList()->end(); ++stop) { // add stop point if below start point cFCOName::Relationship relate = startpoint.GetRelationship(*stop); - if (relate == cFCOName::REL_ABOVE) + if (relate == cFCOName::REL_ABOVE) { - pStopPtSet->Add( *stop ); + pStopPtSet->Add(*stop); } } - pStopPtSet->SetRecurseDepth( -1 == depth ? cFCOSpecStopPointSet::RECURSE_INFINITE : depth ); - pfcospec->SetHelper( pStopPtSet ); + pStopPtSet->SetRecurseDepth(-1 == depth ? cFCOSpecStopPointSet::RECURSE_INFINITE : depth); + pfcospec->SetHelper(pStopPtSet); } // ////////////////////////////////////////////////////////////// @@ -655,28 +582,28 @@ void cParserUtil::CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSp // // set start point // - pfcospec->SetStartPoint( startpoint ); + pfcospec->SetStartPoint(startpoint); // // set default mask // - const iFCOSpecMask *pdefspecmask = iFCOSpecMask::GetDefaultMask(); + const iFCOSpecMask* pdefspecmask = iFCOSpecMask::GetDefaultMask(); ASSERT(pdefspecmask != 0); // // build property vector // - cFCOPropVector v = (*rule)->GetDefSpecMask().GetPropVector(); - pHelper->AddSubTypeProps( v ); - pfcospec->SetPropVector( pdefspecmask, v); + cFCOPropVector v = (*rule)->GetDefSpecMask().GetPropVector(); + pHelper->AddSubTypeProps(v); + pfcospec->SetPropVector(pdefspecmask, v); // // add attributes // - TSTRING strAttrVal; - cParseNamedAttrList* pal = (*rule)->GetAttrList(); - cFCOSpecAttr* pAttr = new cFCOSpecAttr; - if( pal != NULL ) + TSTRING strAttrVal; + cParseNamedAttrList* pal = (*rule)->GetAttrList(); + cFCOSpecAttr* pAttr = new cFCOSpecAttr; + if (pal != NULL) { // TODO: make storage place for these keywords // attribute names are stored in lowercase @@ -685,41 +612,41 @@ void cParserUtil::CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSp // // get rulename // - pa = pal->Lookup( TSS_GetString( cTWParser, twparser::STR_PARSER_RULENAME ) ); - if( pa ) + pa = pal->Lookup(TSS_GetString(cTWParser, twparser::STR_PARSER_RULENAME)); + if (pa) { - // TODO -- at some future date, remove the name in the spec + // TODO -- at some future date, remove the name in the spec // and only set it in pAttr - pfcospec->SetName( pa->GetValue() ); - pAttr->SetName( pa->GetValue() ); + pfcospec->SetName(pa->GetValue()); + pAttr->SetName(pa->GetValue()); } - + // // get severity // - pa = pal->Lookup( TSS_GetString( cTWParser, twparser::STR_PARSER_SEVERITY ) ); - if( pa ) + pa = pal->Lookup(TSS_GetString(cTWParser, twparser::STR_PARSER_SEVERITY)); + if (pa) { - int iSev; + int iSev; cSeverityLimits sl; - if( ! sl.InterpretInt( pa->GetValue(), &iSev ) ) - throw eParserBadSevVal( pa->GetValue(), pa->GetLineNum() ); + if (!sl.InterpretInt(pa->GetValue(), &iSev)) + throw eParserBadSevVal(pa->GetValue(), pa->GetLineNum()); - pAttr->SetSeverity( iSev ); + pAttr->SetSeverity(iSev); } // // get emailto // - pa = pal->Lookup( TSS_GetString( cTWParser, twparser::STR_PARSER_EMAILTO ) ) ; - if( pa ) + pa = pal->Lookup(TSS_GetString(cTWParser, twparser::STR_PARSER_EMAILTO)); + if (pa) { TSTRING strAddressee; - int index = 0; - while( cParserUtil::GetNextMailName( pa->GetValue(), strAddressee, index++ ) ) + int index = 0; + while (cParserUtil::GetNextMailName(pa->GetValue(), strAddressee, index++)) { - d.TraceDebug( _T("email to recip: <%s>\n"), strAddressee.c_str() ); - pAttr->AddEmail( strAddressee ); + d.TraceDebug(_T("email to recip: <%s>\n"), strAddressee.c_str()); + pAttr->AddEmail(strAddressee); } } } @@ -727,7 +654,7 @@ void cParserUtil::CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSp // // store rule in the spec list // - fcospeclist.Add( pfcospec, pAttr ); + fcospeclist.Add(pfcospec, pAttr); pfcospec->Release(); pAttr->Release(); } @@ -738,151 +665,146 @@ void cParserUtil::CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSp // CreatePropVector -- given the string representation of the attribute vector, // create an FCOPropVector /////////////////////////////////////////////////////////////////////////////// -void cParserUtil::CreatePropVector( const TSTRING& strPropListC, class cFCOPropVector& v, iParserGenreUtil* pHelper ) +void cParserUtil::CreatePropVector(const TSTRING& strPropListC, class cFCOPropVector& v, iParserGenreUtil* pHelper) { - ASSERT( pHelper != NULL ); + ASSERT(pHelper != NULL); // state: turning modes on or off - enum Mode { MO_TURNON, MO_TURNOFF }; + enum Mode + { + MO_TURNON, + MO_TURNOFF + }; Mode mode = MO_TURNON; - // clear out all spaces in the string + // clear out all spaces in the string TSTRING strPropList = strPropListC; - util_EatAllSpaces( strPropList ); + strPropList.erase(std::remove_if(strPropList.begin(), strPropList.end(), std::ptr_fun(std::isspace)), + strPropList.end()); // zero it out v.Clear(); TSTRING::const_iterator iter; - TSTRING::size_type i; // index into string - for ( iter = strPropList.begin(), i = 0; iter != strPropList.end(); iter++, i++ ) + TSTRING::size_type i; // index into string + for (iter = strPropList.begin(), i = 0; iter != strPropList.end(); ++iter, ++i) { - int propIndex = -1; // index into propvector + int propIndex = -1; // index into propvector - switch (*iter) + switch (*iter) { - ///////////////////////////////////////////////////////////// - // parsing modes - case '+': - mode = MO_TURNON; - continue; - case '-': - mode = MO_TURNOFF; - continue; - ///////////////////////////////////////////////////////////// - - ///////////////////////////////////////////////////////////// - // long attribute names - case '&': - { - // - // collect string - // + ///////////////////////////////////////////////////////////// + // parsing modes + case '+': + mode = MO_TURNON; + continue; + case '-': + mode = MO_TURNOFF; + continue; + ///////////////////////////////////////////////////////////// + + ///////////////////////////////////////////////////////////// + // long attribute names + case '&': + { + // + // collect string + // - // find next '&', '+', or '-' - TSTRING::size_type next = util_FindNextDelim( strPropList, i+1 ); + // find next '&', '+', or '-' + TSTRING::size_type next = util_FindNextDelim(strPropList, i + 1); - // get attribute name - TSTRING strProp; - if( next == TSTRING::npos ) - strProp = strPropList.substr( i+1 ); - else - strProp = strPropList.substr( i+1, next - i - 1 ); + // get attribute name + TSTRING strProp; + if (next == TSTRING::npos) + strProp = strPropList.substr(i + 1); + else + strProp = strPropList.substr(i + 1, next - i - 1); - // increment past string - iter += strProp.length(); - i += strProp.length(); + // increment past string + iter += strProp.length(); + i += strProp.length(); - // map attribute - if( ! pHelper->MapStringToProperty( strProp, propIndex ) ) - throw eParserPropChar( strProp ); - } - break; - ///////////////////////////////////////////////////////////// + // map attribute + if (!pHelper->MapStringToProperty(strProp, propIndex)) + throw eParserPropChar(strProp); + } + break; + ///////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////// - // not '+' or '-' or '&' so map the char to a property - default: - if( ! pHelper->MapStringToProperty( TSTRING( 1, *iter ), propIndex ) ) - throw eParserPropChar( TSTRING( 1, *iter ) ); + ///////////////////////////////////////////////////////////// + // not '+' or '-' or '&' so map the char to a property + default: + if (!pHelper->MapStringToProperty(TSTRING(1, *iter), propIndex)) + throw eParserPropChar(TSTRING(1, *iter)); break; // ///////////////////////////////////////////////////////////// } // now turn on or turn off bit, according to mode - ASSERT( propIndex != -1 ); + ASSERT(propIndex != -1); if (mode == MO_TURNON) - v.AddItemAndGrow( propIndex ); - else - v.RemoveItem( propIndex ); - } - - /* for 1.5, allow no properties (just track file existence) - // if v is empty, error - cFCOPropVector emptyPropVector; - emptyPropVector.Clear(); - if( v == emptyPropVector ) - { - d.TraceError("CreatePropVector failed!!\n"); - throw eError( ERR_BAD_PROP_STRING, strPropV.c_str() ); + v.AddItemAndGrow(propIndex); + else + v.RemoveItem(propIndex); } - */ return; } // gets semicolon-delimited words in a string. index starts at 0. // strNameRet has surronding WS discarded -bool cParserUtil::GetNextMailName( const TSTRING& strNameList, TSTRING& strNameRet, int index ) +bool cParserUtil::GetNextMailName(const TSTRING& strNameList, TSTRING& strNameRet, int index) { - ASSERT( index >= 0 ); + ASSERT(index >= 0); // go to nth name TSTRING::size_type nextSC, lastSC = (TSTRING::size_type)-1; // algorithm starts searching for next ';' - // at lastSC+1 - for( ; index >= 0; index-- ) - { - nextSC = strNameList.find( _T(';'), ( lastSC + 1 ) ); - - if( 0 == index ) // if the name # we're looking for + // at lastSC+1 + for (; index >= 0; index--) + { + nextSC = strNameList.find(_T(';'), (lastSC + 1)); + + if (0 == index) // if the name # we're looking for { - strNameRet = strNameList.substr( ( lastSC + 1 ), TSTRING::npos == nextSC ? TSTRING::npos : nextSC - ( lastSC + 1 ) ); - util_LoseSurroundingWS( strNameRet ); + strNameRet = + strNameList.substr((lastSC + 1), TSTRING::npos == nextSC ? TSTRING::npos : nextSC - (lastSC + 1)); + util_LoseSurroundingWS(strNameRet); return true; } - else if( TSTRING::npos == nextSC ) // didn't get to index'th naem: no names left + else if (TSTRING::npos == nextSC) // didn't get to index'th naem: no names left { return false; } lastSC = nextSC; } - + // unreachable code - ASSERT( false ); + ASSERT(false); return false; // just to placate the compiler } -void cParserUtil::MergeMailLists( TSTRING& tstrMergeIntoMe, const TSTRING& tstrRHS ) +void cParserUtil::MergeMailLists(TSTRING& tstrMergeIntoMe, const TSTRING& tstrRHS) { // foreach word in rhs TSTRING tstrWordToAdd; - int index = 0; - while( cParserUtil::GetNextMailName( tstrRHS, tstrWordToAdd, index++ ) ) + int index = 0; + while (cParserUtil::GetNextMailName(tstrRHS, tstrWordToAdd, index++)) { // if it isn't in lhs, add it - bool fAlreadyInList = false; - int index2 = 0; + bool fAlreadyInList = false; + int index2 = 0; TSTRING tstrWordInLHS; - while( !fAlreadyInList && cParserUtil::GetNextMailName( tstrMergeIntoMe, tstrWordInLHS, index2++ ) ) + while (!fAlreadyInList && cParserUtil::GetNextMailName(tstrMergeIntoMe, tstrWordInLHS, index2++)) { - if( 0 == tstrWordInLHS.compare( tstrWordToAdd ) ) + if (0 == tstrWordInLHS.compare(tstrWordToAdd)) fAlreadyInList = true; } - if( ! fAlreadyInList ) - { + if (!fAlreadyInList) + { tstrMergeIntoMe += _T(";"); tstrMergeIntoMe += tstrWordToAdd; } @@ -892,56 +814,56 @@ void cParserUtil::MergeMailLists( TSTRING& tstrMergeIntoMe, const TSTRING& tstrR bool cParserHelper::AtTopScope() { - return( mScopedAttrs.empty() ); + return (mScopedAttrs.empty()); } -void cParserHelper::PopScope() -{ - ASSERT( ! mScopedAttrs.empty() ); +void cParserHelper::PopScope() +{ + ASSERT(!mScopedAttrs.empty()); - delete mScopedAttrs.back(); - mScopedAttrs.pop_back(); + delete mScopedAttrs.back(); + mScopedAttrs.pop_back(); } -cParseNamedAttrList* cParserHelper::GetGlobalAttrList() -{ - if( ! mScopedAttrs.empty() ) +cParseNamedAttrList* cParserHelper::GetGlobalAttrList() +{ + if (!mScopedAttrs.empty()) return mScopedAttrs.back()->GetAttrList(); else return NULL; } void cParserHelper::IncrementScopeStatementCount() -{ +{ // must add count to ALL previous scopes. - for( ScopedAttrContainer::iterator i = mScopedAttrs.begin(); i != mScopedAttrs.end(); i++ ) + for (ScopedAttrContainer::iterator i = mScopedAttrs.begin(); i != mScopedAttrs.end(); ++i) (*i)->IncrementStatementCount(); } int cParserHelper::GetScopeStatementCount() -{ - if( ! mScopedAttrs.empty() ) +{ + if (!mScopedAttrs.empty()) { return mScopedAttrs.back()->GetStatementCount(); } else { // should never ask for this when we aren't in a scope - ASSERT( false ); + ASSERT(false); return 0; } } -void cParserHelper::PushScope( cAttrScopeInfo* pSI ) +void cParserHelper::PushScope(cAttrScopeInfo* pSI) { // add previous scope's info to this one - if( ! mScopedAttrs.empty() ) + if (!mScopedAttrs.empty()) { - pSI->GetAttrList()->MergeNoOverwrite( mScopedAttrs.back()->GetAttrList() ); + pSI->GetAttrList()->MergeNoOverwrite(mScopedAttrs.back()->GetAttrList()); } - - mScopedAttrs.push_back( pSI ); + + mScopedAttrs.push_back(pSI); } @@ -951,32 +873,29 @@ void cParserHelper::PushScope( cAttrScopeInfo* pSI ) int util_ConvertHex(const char* const cpsz, int* const pnCharsRead) { - ASSERT( util_AsciiCharsActLikeTheyShould() ); - ASSERT( cpsz && pnCharsRead ); + ASSERT(util_AsciiCharsActLikeTheyShould()); + ASSERT(cpsz && pnCharsRead); - if (*cpsz == 0 || !std::isxdigit( *cpsz, std::locale() )) - throw eParserBadHex( cStringUtil::StrToTstr( cpsz ) ); + if (*cpsz == 0 || !std::isxdigit(*cpsz, std::locale())) + throw eParserBadHex(cStringUtil::StrToTstr(cpsz)); - int iValue; + int iValue; const char* psz = cpsz; - for( - *pnCharsRead = 0, iValue = 0; - *psz && std::isxdigit( *psz, std::locale() ) && (*pnCharsRead < 2); - psz++, (*pnCharsRead)++ - ) + for (*pnCharsRead = 0, iValue = 0; *psz && std::isxdigit(*psz, std::locale()) && (*pnCharsRead < 2); + psz++, (*pnCharsRead)++) { iValue *= 0x10; - - if( std::isdigit( *psz, std::locale() ) ) + + if (std::isdigit(*psz, std::locale())) { - iValue += ( *psz - '0' ); + iValue += (*psz - '0'); } else { - if( std::islower( *psz, std::locale() ) ) - iValue += ( *psz - 'a' + 10 ); // so that A=10, B=11, ..., F=15 - else // is uppercase - iValue += ( *psz - 'A' + 10 ); // so that a=10, a=11, ..., f=15 + if (std::islower(*psz, std::locale())) + iValue += (*psz - 'a' + 10); // so that A=10, B=11, ..., F=15 + else // is uppercase + iValue += (*psz - 'A' + 10); // so that a=10, a=11, ..., f=15 } } @@ -985,36 +904,32 @@ int util_ConvertHex(const char* const cpsz, int* const pnCharsRead) int util_ConvertUnicode(const char* const cpsz, int* const pnCharsRead) { - ASSERT( util_AsciiCharsActLikeTheyShould() ); - ASSERT( cpsz && pnCharsRead ); + ASSERT(util_AsciiCharsActLikeTheyShould()); + ASSERT(cpsz && pnCharsRead); - if (*cpsz == 0 || !std::isxdigit( *cpsz, std::locale() )) - throw eParserBadHex( cStringUtil::StrToTstr( cpsz ) ); + if (*cpsz == 0 || !std::isxdigit(*cpsz, std::locale())) + throw eParserBadHex(cStringUtil::StrToTstr(cpsz)); - int iValue; + int iValue; const char* psz = cpsz; - for( - *pnCharsRead = 0, iValue = 0; - *pnCharsRead < 4; - psz++, (*pnCharsRead)++ - ) + for (*pnCharsRead = 0, iValue = 0; *pnCharsRead < 4; psz++, (*pnCharsRead)++) { // we require 4 chars for unicode escapes - if (*psz == 0 || !std::isxdigit( *psz, std::locale() )) - throw eParserBadHex( cStringUtil::StrToTstr( cpsz ) ); + if (*psz == 0 || !std::isxdigit(*psz, std::locale())) + throw eParserBadHex(cStringUtil::StrToTstr(cpsz)); iValue *= 0x10; - - if( std::isdigit( *psz, std::locale() ) ) + + if (std::isdigit(*psz, std::locale())) { - iValue += ( *psz - '0' ); + iValue += (*psz - '0'); } else { - if( std::islower( *psz, std::locale() ) ) - iValue += ( *psz - 'a' + 10 ); // so that A=10, B=11, ..., F=15 - else // is uppercase - iValue += ( *psz - 'A' + 10 ); // so that a=10, a=11, ..., f=15 + if (std::islower(*psz, std::locale())) + iValue += (*psz - 'a' + 10); // so that A=10, B=11, ..., F=15 + else // is uppercase + iValue += (*psz - 'A' + 10); // so that a=10, a=11, ..., f=15 } } @@ -1022,183 +937,160 @@ int util_ConvertUnicode(const char* const cpsz, int* const pnCharsRead) } // only 3 octal chars allowed -int util_ConvertOctal( const char* psz, int* const pnCharsRead ) +int util_ConvertOctal(const char* psz, int* const pnCharsRead) { - ASSERT( util_AsciiCharsActLikeTheyShould() ); - ASSERT( psz && pnCharsRead ); - ASSERT( util_IsOctal( *psz ) ); // at least one oct char - + ASSERT(util_AsciiCharsActLikeTheyShould()); + ASSERT(psz && pnCharsRead); + ASSERT(util_IsOctal(*psz)); // at least one oct char + int iValue; - for( - iValue = 0, *pnCharsRead = 0; - *psz && util_IsOctal( *psz ) && *pnCharsRead < 3; // limit of 3 octal chars - psz++, (*pnCharsRead)++ - ) + for (iValue = 0, *pnCharsRead = 0; *psz && util_IsOctal(*psz) && *pnCharsRead < 3; // limit of 3 octal chars + psz++, (*pnCharsRead)++) { - iValue *= 010; - iValue += ( *psz - '0' ); + iValue *= 010; + iValue += (*psz - '0'); } - return( iValue ); + return (iValue); } -bool util_IsOctal( const char ch ) +bool util_IsOctal(const char ch) { - ASSERT( util_AsciiCharsActLikeTheyShould() ); + ASSERT(util_AsciiCharsActLikeTheyShould()); - return( ch >= '0' && ch <= '7' ); + return (ch >= '0' && ch <= '7'); } -int util_GetEscapeValueOfChar( char ch ) +int util_GetEscapeValueOfChar(char ch) { - int iValue = -1; - - switch( ch ) + int iValue = -1; + + switch (ch) { - case 'n': - iValue = 10; - break; - case 't': - iValue = 9; + case 'n': + iValue = 10; break; - case 'v': - iValue = 11; + case 't': + iValue = 9; break; - case 'b': - iValue = 8; + case 'v': + iValue = 11; break; - case 'r': - iValue = 13; + case 'b': + iValue = 8; break; - case 'f': - iValue = 12; + case 'r': + iValue = 13; break; - case 'a': - iValue = 7; + case 'f': + iValue = 12; break; - case '\\': - iValue = 92; + case 'a': + iValue = 7; break; - case '\?': - iValue = 63; + case '\\': + iValue = 92; break; - case '\'': - iValue = 39; + case '\?': + iValue = 63; break; - case '\"': - iValue = 34; + case '\'': + iValue = 39; break; - default: - { - // unrecognized escape char: just return character - iValue = static_cast( ch ); - } + case '\"': + iValue = 34; break; + default: + { + // unrecognized escape char: just return character + iValue = static_cast(ch); + } + break; } - ASSERT( iValue != -1 ); //should have *some* value at this point + ASSERT(iValue != -1); //should have *some* value at this point - return( iValue ); + return (iValue); } // -1 means recurse all levels -int util_GetRecurseDepth( const cParseNamedAttrList* pList ) //throw( eParserHelper ) +int util_GetRecurseDepth(const cParseNamedAttrList* pList) //throw( eParserHelper ) { - if( pList != NULL ) - { - const cParseNamedAttr* pa = pList->Lookup( TSS_GetString( cTWParser, twparser::STR_PARSER_RECURSE ) ); - if( pa ) + if (pList != NULL) + { + const cParseNamedAttr* pa = pList->Lookup(TSS_GetString(cTWParser, twparser::STR_PARSER_RECURSE)); + if (pa) { TSTRING str = pa->GetValue(); - std::transform( str.begin(), str.end(), str.begin(), _totlower ); + std::transform(str.begin(), str.end(), str.begin(), _totlower); - if( 0 == str.compare( TSS_GetString( cTWParser, twparser::STR_PARSER_FALSE ) ) ) + if (0 == str.compare(TSS_GetString(cTWParser, twparser::STR_PARSER_FALSE))) { return 0; } - else if( 0 == str.compare( TSS_GetString( cTWParser, twparser::STR_PARSER_TRUE ) ) ) + else if (0 == str.compare(TSS_GetString(cTWParser, twparser::STR_PARSER_TRUE))) { return -1; } - else + else { // must be number - int i; + int i; cRecurseDepthLimits rdl; - if( ! rdl.InterpretInt( str, &i ) ) - throw eParserUnrecognizedAttrVal( str, pa->GetLineNum() ); + if (!rdl.InterpretInt(str, &i)) + throw eParserUnrecognizedAttrVal(str, pa->GetLineNum()); return i; } } } - return( -1 ); // defaults to recurse all levels + return (-1); // defaults to recurse all levels } // finds first '&', '+', '-' on or after str[i] -TSTRING::size_type util_FindNextDelim( const TSTRING& str, TSTRING::size_type i ) +TSTRING::size_type util_FindNextDelim(const TSTRING& str, TSTRING::size_type i) { - TSTRING::size_type min = TSTRING::npos; - TSTRING::size_type amp = str.find( '&', i ); - TSTRING::size_type plus = str.find( '+', i ); - TSTRING::size_type minus = str.find( '-', i ); + TSTRING::size_type min = TSTRING::npos; + TSTRING::size_type amp = str.find('&', i); + TSTRING::size_type plus = str.find('+', i); + TSTRING::size_type minus = str.find('-', i); // now find minimum of the three - if( amp != TSTRING::npos ) + if (amp != TSTRING::npos) min = amp; - if( min != TSTRING::npos && plus != TSTRING::npos && plus < min ) + if (min != TSTRING::npos && plus != TSTRING::npos && plus < min) min = plus; - if( min != TSTRING::npos && minus != TSTRING::npos && minus < min ) + if (min != TSTRING::npos && minus != TSTRING::npos && minus < min) min = minus; return min; } -// deletes each space in the string -void util_EatAllSpaces( TSTRING& str ) +void util_LoseSurroundingWS(TSTRING& str) { - for( TSTRING::iterator i = str.begin(); i != str.end(); i++ ) - { - if( *i == _T(' ') ) - { - str.erase( i ); - } - } -} + TSTRING::size_type nonWSStart = str.find_first_not_of(_T(" \t"), 0); + TSTRING::size_type nonWSEnd = str.find_last_not_of(_T(" \t")); -void util_LoseSurroundingWS( TSTRING& str ) -{ - TSTRING::size_type nonWSStart = str.find_first_not_of( _T(" \t"), 0 ); - TSTRING::size_type nonWSEnd = str.find_last_not_of( _T(" \t") ); - - if( TSTRING::npos == nonWSStart ) // if only whitespace + if (TSTRING::npos == nonWSStart) // if only whitespace { - ASSERT( TSTRING::npos == nonWSEnd ); + ASSERT(TSTRING::npos == nonWSEnd); str = str.erase(); } else // has non WS chars { - ASSERT( TSTRING::npos != nonWSEnd ); - str = str.substr( nonWSStart, nonWSEnd - nonWSStart + 1 ); + ASSERT(TSTRING::npos != nonWSEnd); + str = str.substr(nonWSStart, nonWSEnd - nonWSStart + 1); } } -#ifdef _DEBUG +#ifdef DEBUG bool util_AsciiCharsActLikeTheyShould() { - // we need numbers whose character + // we need numbers whose character // representation increase by one - return( - ( '0' < '1' ) && - ( '0' + 1 == '1' ) && - ( 'a' < 'b' ) && - ( 'a' + 1 == 'b' ) && - ( 'A' < 'B' ) && - ( 'A' + 1 == 'B' ) - ); + return (('0' < '1') && ('0' + 1 == '1') && ('a' < 'b') && ('a' + 1 == 'b') && ('A' < 'B') && ('A' + 1 == 'B')); } #endif - diff --git a/src/twparser/parserhelper.h b/src/twparser/parserhelper.h index 3392414..c723271 100644 --- a/src/twparser/parserhelper.h +++ b/src/twparser/parserhelper.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -75,51 +75,53 @@ class cFCOPropVector; //////////////////////////////////////////////////////////// // Parser Base Exception //////////////////////////////////////////////////////////// -TSS_BEGIN_EXCEPTION_NO_CTOR( eParserHelper, eError ) - enum { CURRENT_LINE = -1, NO_LINE = 0 }; - // if ( nLine != NO_LINE ) appends the "Line number: " to the - // end of the strMsg if fShowLineNum is true, then returns string - eParserHelper( const TSTRING& strMsg, int nLine = CURRENT_LINE ); +TSS_BEGIN_EXCEPTION_NO_CTOR(eParserHelper, eError) +enum +{ + CURRENT_LINE = -1, + NO_LINE = 0 +}; +// if ( nLine != NO_LINE ) appends the "Line number: " to the +// end of the strMsg if fShowLineNum is true, then returns string +eParserHelper(const TSTRING& strMsg, int nLine = CURRENT_LINE); TSS_END_EXCEPTION(); //////////////////////////////////////////////////////////// // Helper Macro For Parser Exceptions //////////////////////////////////////////////////////////// -#define TSS_PARSER_EXCEPTION( except ) \ - TSS_BEGIN_EXCEPTION_NO_CTOR( except, eParserHelper ) \ - except( const TSTRING& strMsg, int nLine = CURRENT_LINE ) \ - : eParserHelper( strMsg, nLine ) \ - {}; \ +#define TSS_PARSER_EXCEPTION(except) \ + TSS_BEGIN_EXCEPTION_NO_CTOR(except, eParserHelper) \ + except(const TSTRING& strMsg, int nLine = CURRENT_LINE) : eParserHelper(strMsg, nLine){}; \ TSS_END_EXCEPTION() //////////////////////////////////////////////////////////// // Parser Exceptions //////////////////////////////////////////////////////////// -TSS_PARSER_EXCEPTION( eParseFailed ); -TSS_PARSER_EXCEPTION( eParserRedefineVar ); -TSS_PARSER_EXCEPTION( eParserUnrecognizedAttr ); -TSS_PARSER_EXCEPTION( eParserUnrecognizedAttrVal ); -TSS_PARSER_EXCEPTION( eParserPropChar ); -TSS_PARSER_EXCEPTION( eParserNoRules ); -TSS_PARSER_EXCEPTION( eParserNoRulesInSection ); -TSS_PARSER_EXCEPTION( eParserUseUndefVar ); -TSS_PARSER_EXCEPTION( eParserBadSevVal ); -TSS_PARSER_EXCEPTION( eParserBadFCONameFmt ); -TSS_PARSER_EXCEPTION( eParserSectionAlreadyDefined ); -TSS_PARSER_EXCEPTION( eParserPointAlreadyDefined ); -TSS_PARSER_EXCEPTION( eParserSectionInsideBlock ); -TSS_PARSER_EXCEPTION( eParserRelativePath ); -TSS_PARSER_EXCEPTION( eParserIgnoringSection ); -TSS_PARSER_EXCEPTION( eParserNoStatementsInScope ); -TSS_PARSER_EXCEPTION( eParserBadHex ); -TSS_PARSER_EXCEPTION( eParserBadCharacter ); +TSS_PARSER_EXCEPTION(eParseFailed); +TSS_PARSER_EXCEPTION(eParserRedefineVar); +TSS_PARSER_EXCEPTION(eParserUnrecognizedAttr); +TSS_PARSER_EXCEPTION(eParserUnrecognizedAttrVal); +TSS_PARSER_EXCEPTION(eParserPropChar); +TSS_PARSER_EXCEPTION(eParserNoRules); +TSS_PARSER_EXCEPTION(eParserNoRulesInSection); +TSS_PARSER_EXCEPTION(eParserUseUndefVar); +TSS_PARSER_EXCEPTION(eParserBadSevVal); +TSS_PARSER_EXCEPTION(eParserBadFCONameFmt); +TSS_PARSER_EXCEPTION(eParserSectionAlreadyDefined); +TSS_PARSER_EXCEPTION(eParserPointAlreadyDefined); +TSS_PARSER_EXCEPTION(eParserSectionInsideBlock); +TSS_PARSER_EXCEPTION(eParserRelativePath); +TSS_PARSER_EXCEPTION(eParserIgnoringSection); +TSS_PARSER_EXCEPTION(eParserNoStatementsInScope); +TSS_PARSER_EXCEPTION(eParserBadHex); +TSS_PARSER_EXCEPTION(eParserBadCharacter); /////////////////////////////////////////////////////////////////////////////// // class cPreprocessor // used for directives #ifhost, to determine if parserhelper acts on input from parser // if current state is STATE_ACCEPT, it will create specs from rules, set variables, etc. -// if current state is STATE_IGNORE, it will not. +// if current state is STATE_IGNORE, it will not. // -- assumes there is at least one state in stack at all times class cPreprocessor { @@ -127,7 +129,7 @@ class cPreprocessor cPreprocessor(); // - // if we're in accept, then we process + // if we're in accept, then we process // input, otherwise we ignore it // enum AcceptState @@ -139,28 +141,40 @@ class cPreprocessor // // basic functionality // - static void PushState( AcceptState state ); - static void PopState(); - static AcceptState TopState(); - static AcceptState GetState(); - static AcceptState UnderneathTopState(); // gets the item in the stack underneath top item - static AcceptState GetLastState() { return UnderneathTopState(); }; - static void ToggleTopState(); - static AcceptState GetOppositeState( AcceptState state ); - static bool AtTopLevel(); - static bool Empty() { return mStateStack.empty(); }; - // returns true if there is only one element in the stack - - static void IgnoreSection() { mfIgnoreSection = true; }; - static void ReadSection() { mfIgnoreSection = false; }; + static void PushState(AcceptState state); + static void PopState(); + static AcceptState TopState(); + static AcceptState GetState(); + static AcceptState UnderneathTopState(); // gets the item in the stack underneath top item + static AcceptState GetLastState() + { + return UnderneathTopState(); + }; + static void ToggleTopState(); + static AcceptState GetOppositeState(AcceptState state); + static bool AtTopLevel(); + static bool Empty() + { + return mStateStack.empty(); + }; + // returns true if there is only one element in the stack + + static void IgnoreSection() + { + mfIgnoreSection = true; + }; + static void ReadSection() + { + mfIgnoreSection = false; + }; private: // // data members // typedef std::stack AcceptStack; - static AcceptStack mStateStack; - static bool mfIgnoreSection; + static AcceptStack mStateStack; + static bool mfIgnoreSection; }; // encapsulates utility functions @@ -170,28 +184,30 @@ class cParserUtil // // general utility functions // - static void InterpretEscapedString( const std::string& strEscapedString, TSTRING& strInterpretedString ); - // converts escaped character sequences in strEscapedString into their escape characters in strInterpretedString - //( e.g. turns "Hello World!\n" (literal backslash) into "Hello World!" - // all C++ escape sequences are recognized: - // (1) octal numbers \012 (1, 2, or 3 octal digits), - // (2) hex numbers \x2AFB1... ( 'x' followed by one or more hex digits ), - // (3) chars: \t, \v, \b, \r, \f, \a, \\, \?, \', and \" - // (4) all other escaped chars are treated as if not escaped - static bool AnyOfTheseHostsExists( cParseStringList* pList ); - // is this machine is in pList? - - static bool GetNextMailName( const TSTRING& strNameList, TSTRING& strNameRet, int index ); - // gets semicolon-delimited words in a string. index starts at 0. - static void MergeMailLists( TSTRING& tstrMergeIntoMe, const TSTRING& tstrRHS ); - // merges semicolon-delimited mailnames. will not add a duplicate name. - - static void CreatePropVector( const TSTRING& attr, cFCOPropVector& v, iParserGenreUtil* pHelper ); // throw( eParserHelper ) + static void InterpretEscapedString(const std::string& strEscapedString, TSTRING& strInterpretedString); + // converts escaped character sequences in strEscapedString into their escape characters in strInterpretedString + //( e.g. turns "Hello World!\n" (literal backslash) into "Hello World!" + // all C++ escape sequences are recognized: + // (1) octal numbers \012 (1, 2, or 3 octal digits), + // (2) hex numbers \x2AFB1... ( 'x' followed by one or more hex digits ), + // (3) chars: \t, \v, \b, \r, \f, \a, \\, \?, \', and \" + // (4) all other escaped chars are treated as if not escaped + static bool AnyOfTheseHostsExists(cParseStringList* pList); + // is this machine is in pList? + + static bool GetNextMailName(const TSTRING& strNameList, TSTRING& strNameRet, int index); + // gets semicolon-delimited words in a string. index starts at 0. + static void MergeMailLists(TSTRING& tstrMergeIntoMe, const TSTRING& tstrRHS); + // merges semicolon-delimited mailnames. will not add a duplicate name. + + static void + CreatePropVector(const TSTRING& attr, cFCOPropVector& v, iParserGenreUtil* pHelper); // throw( eParserHelper ) // takes a string of the form (+pinguam...) and turns it into a file system property vector; throws an error if // the string is in an invalid format. Grows the prop vector if necessary. - static void CreateFCOSpecs( cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSpecList &fcospeclist ); // throw( eParserHelper ) + static void + CreateFCOSpecs(cGenre::Genre g, cGenreParseInfo* pgpi, cFCOSpecList& fcospeclist); // throw( eParserHelper ) // this uses the internal list of rules and stop points to generate the list of - // fco specs. + // fco specs. }; /////////////////////////////////////////////////////////////////////////////// @@ -202,48 +218,69 @@ class cParserUtil class cParserHelper { public: - static void Init( cErrorBucket* pE ); // initializes static member vars - static void Finit( cGenreSpecListVector* pPolicy ); // creates policy and cleans up + static void Init(cErrorBucket* pE); // initializes static member vars + static void Finit(cGenreSpecListVector* pPolicy); // creates policy and cleans up // // data accesss // - static cErrorBucket* GetErrorBucket() { ASSERT( mpError != 0 ); return mpError; }; - static int GetLineNumber() { return miLineNum; }; - static void IncrementLineNumber() { ++miLineNum; }; + static cErrorBucket* GetErrorBucket() + { + ASSERT(mpError != 0); + return mpError; + }; + static int GetLineNumber() + { + return miLineNum; + }; + static void IncrementLineNumber() + { + ++miLineNum; + }; // // specify whether to parse entire file for correctness checking // - static void SetParseOnly( bool f ) { mfParseOnly = f; }; - static bool ParseOnly() { return mfParseOnly; }; - + static void SetParseOnly(bool f) + { + mfParseOnly = f; + }; + static bool ParseOnly() + { + return mfParseOnly; + }; + // // genre info // - static cGenreParseInfo* GetGenreInfo(); - static void SetSection( TSTRING& strSection ); // throw( eParserHelper ) - + static cGenreParseInfo* GetGenreInfo(); + static void SetSection(TSTRING& strSection); // throw( eParserHelper ) + // // scoped attribute info // - static void PushScope( cAttrScopeInfo* pSI ); - static void PopScope(); - static bool AtTopScope(); - static cParseNamedAttrList* GetGlobalAttrList(); - static void IncrementScopeStatementCount(); - static int GetScopeStatementCount(); - static bool ScopeEmpty() { return mScopedAttrs.empty(); }; + static void PushScope(cAttrScopeInfo* pSI); + static void PopScope(); + static bool AtTopScope(); + static cParseNamedAttrList* GetGlobalAttrList(); + static void IncrementScopeStatementCount(); + static int GetScopeStatementCount(); + static bool ScopeEmpty() + { + return mScopedAttrs.empty(); + }; - static bool InsertGlobalVariable( const TSTRING& var, const TSTRING& val); //throw( eParserHelper ) + static bool InsertGlobalVariable(const TSTRING& var, const TSTRING& val); //throw( eParserHelper ) // Insert a variable into mGlobalVarTable. - static cSymbolTable& GetGlobalVarTable( void ) { return mGlobalVarTable; } - // Returns a reference to mGlobalVarTable. + static cSymbolTable& GetGlobalVarTable(void) + { + return mGlobalVarTable; + } + // Returns a reference to mGlobalVarTable. private: - - static void CleanUp(); // frees memory + static void CleanUp(); // frees memory static cSymbolTable mGlobalVarTable; // A table for all the global variable definitions. @@ -251,21 +288,20 @@ class cParserHelper // data members // static cErrorBucket* mpError; - // holds errors that the parser creates + // holds errors that the parser creates static int miLineNum; - // current line number (set in lexer) - typedef std::map< cGenre::Genre, cGenreParseInfo* > GenreContainer; - static GenreContainer mAph; // holds only genres that have been defined + // current line number (set in lexer) + typedef std::map GenreContainer; + static GenreContainer mAph; // holds only genres that have been defined // genre helpers typedef std::list ScopedAttrContainer; - static ScopedAttrContainer mScopedAttrs; - // scoped attributes - static cGenreParseInfo* pCurrentGenreInfo; - static const cGenre::Genre mDefaultGenre; // default genre for this OS + static ScopedAttrContainer mScopedAttrs; + // scoped attributes + static cGenreParseInfo* pCurrentGenreInfo; + static const cGenre::Genre mDefaultGenre; // default genre for this OS static const cGenre::Genre mAcceptedGenres[5]; // what genres we recognize for this OS. terminated with a -1 - static bool mfParseOnly; + static bool mfParseOnly; }; #endif - diff --git a/src/twparser/parserobjects.cpp b/src/twparser/parserobjects.cpp index 909c56b..8581d40 100644 --- a/src/twparser/parserobjects.cpp +++ b/src/twparser/parserobjects.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -60,19 +60,17 @@ const cFCOName& cParseRule::GetName() const return mName; } -void cParseRule::SetName( const cFCOName& name ) +void cParseRule::SetName(const cFCOName& name) { mName = name; } -cParseNamedAttrList * -cParseRule::GetAttrList() const +cParseNamedAttrList* cParseRule::GetAttrList() const { return mpAttrList; } -void -cParseRule::SetAttrList(cParseNamedAttrList *pattr) +void cParseRule::SetAttrList(cParseNamedAttrList* pattr) { mpAttrList = pattr; } @@ -81,8 +79,7 @@ cParseRule::SetAttrList(cParseNamedAttrList *pattr) // SetSpecMaskList // attaches cParseSpecMaskList to this structure /////////////////////////////////////////////////////////////////////////////// -void -cParseRule::SetSpecMaskList(cParseSpecMaskList *pmasks) +void cParseRule::SetSpecMaskList(cParseSpecMaskList* pmasks) { mpSpecMaskList = pmasks; } @@ -92,13 +89,12 @@ cParseRule::SetSpecMaskList(cParseSpecMaskList *pmasks) // GetNumSpecMasks // returns number of specmasks in list (excluding default) /////////////////////////////////////////////////////////////////////////////// -int -cParseRule::GetNumSpecMasks() const +int cParseRule::GetNumSpecMasks() const { // empty list? if (mpSpecMaskList == NULL) return 0; - + return mpSpecMaskList->mList.size(); } @@ -106,13 +102,12 @@ cParseRule::GetNumSpecMasks() const // GetNumNamedAttrs // returns number of named attributes in list /////////////////////////////////////////////////////////////////////////////// -int -cParseRule::GetNumNamedAttrs() const +int cParseRule::GetNumNamedAttrs() const { // empty list? if (mpAttrList == NULL) return 0; - + return mpAttrList->mList.size(); } @@ -121,23 +116,22 @@ cParseRule::GetNumNamedAttrs() const // dumps out all the contents of the parse node, including children /////////////////////////////////////////////////////////////////////////////// -void -cParseRule::Dump() +void cParseRule::Dump() { cDebug d("\tcParseRule::Dump()"); d.TraceDebug("name=%s\n", mName.AsString().c_str()); - d.TraceDebug("defspecmask.prop_vector=%s\n", mDefSpecMask.GetPropVectorString().c_str() ); - d.TraceDebug("defspecmask.condition=%s\n", mDefSpecMask.GetCondition().c_str() ); + d.TraceDebug("defspecmask.prop_vector=%s\n", mDefSpecMask.GetPropVectorString().c_str()); + d.TraceDebug("defspecmask.condition=%s\n", mDefSpecMask.GetCondition().c_str()); // specmasks d.TraceDebug(" numspecmasks=%d\n", GetNumSpecMasks()); - if( mpSpecMaskList ) + if (mpSpecMaskList) mpSpecMaskList->Dump(d); // named attributes d.TraceDebug(" numattrs=%d\n", GetNumNamedAttrs()); - if( mpAttrList ) + if (mpAttrList) mpAttrList->Dump(d); } @@ -146,19 +140,18 @@ cParseRule::Dump() // // constructor -cParseSpecMask::cParseSpecMask(TSTRING &condition, TSTRING &attr, iParserGenreUtil* pHelper ) // throw( eParserHelper ) - : msCondition(condition), msPV( attr ), mPropVector(), mpAttrList(NULL) +cParseSpecMask::cParseSpecMask(TSTRING& condition, TSTRING& attr, iParserGenreUtil* pHelper) // throw( eParserHelper ) + : msCondition(condition), msPV(attr), mPropVector(), mpAttrList(NULL) { - cParserUtil::CreatePropVector( msPV, mPropVector, pHelper ); + cParserUtil::CreatePropVector(msPV, mPropVector, pHelper); } cParseSpecMask::~cParseSpecMask() -{ - delete mpAttrList; +{ + delete mpAttrList; } -int -cParseSpecMask::GetNumAttrs() const +int cParseSpecMask::GetNumAttrs() const { if (mpAttrList == NULL) return 0; @@ -166,14 +159,12 @@ cParseSpecMask::GetNumAttrs() const return mpAttrList->mList.size(); } -void -cParseSpecMask::SetAttrList(cParseNamedAttrList *pattr) +void cParseSpecMask::SetAttrList(cParseNamedAttrList* pattr) { mpAttrList = pattr; } -cParseNamedAttrList * -cParseSpecMask::GetAttrList() const +cParseNamedAttrList* cParseSpecMask::GetAttrList() const { return mpAttrList; } @@ -193,11 +184,10 @@ const TSTRING& cParseSpecMask::GetCondition() const return msCondition; } -void -cParseSpecMask::Dump(cDebug &d) const +void cParseSpecMask::Dump(cDebug& d) const { - d.TraceDebug(" condition=(%s), propvector=:\n", msCondition.c_str(), msPV.c_str() ); - + d.TraceDebug(" condition=(%s), propvector=:\n", msCondition.c_str(), msPV.c_str()); + // dump list of attributes if (mpAttrList) mpAttrList->Dump(d); @@ -207,83 +197,83 @@ cParseSpecMask::Dump(cDebug &d) const // cParseSpecMaskList // -void -cParseSpecMaskList::Dump(cDebug &d) const +void cParseSpecMaskList::Dump(cDebug& d) const { - std::list::const_iterator ispec; - for (ispec = mList.begin(); ispec != mList.end(); ispec++) { + std::list::const_iterator ispec; + for (ispec = mList.begin(); ispec != mList.end(); ++ispec) + { (*ispec)->Dump(d); } } -// +// // cParseNamedAttr // // constructor -cParseNamedAttr::cParseNamedAttr( const TSTRING& name, const TSTRING& value ) - : mstrName(name), mstrValue(value), mLineNum( cParserHelper::GetLineNumber() ) -{ +cParseNamedAttr::cParseNamedAttr(const TSTRING& name, const TSTRING& value) + : mstrName(name), mstrValue(value), mLineNum(cParserHelper::GetLineNumber()) +{ // convert name to lowercase - std::transform( mstrName.begin(), mstrName.end(), mstrName.begin(), _totlower ); + std::transform(mstrName.begin(), mstrName.end(), mstrName.begin(), _totlower); } cParseNamedAttr* cParseNamedAttr::Clone() const { - cParseNamedAttr* pNew = new cParseNamedAttr( mstrName, mstrValue ); - pNew->mLineNum = mLineNum; + cParseNamedAttr* pNew = new cParseNamedAttr(mstrName, mstrValue); + pNew->mLineNum = mLineNum; return pNew; } -void cParseNamedAttr::Dump(cDebug &d) const +void cParseNamedAttr::Dump(cDebug& d) const { d.TraceDebug(" name=(%s), value=(%s)\n", mstrName.c_str(), mstrValue.c_str()); } void cParseNamedAttr::Validate() const { - if( NamesMatch( twparser::STR_PARSER_RULENAME, mstrName ) ) + if (NamesMatch(twparser::STR_PARSER_RULENAME, mstrName)) { // no checking needed } - else if( NamesMatch( twparser::STR_PARSER_EMAILTO, mstrName ) ) + else if (NamesMatch(twparser::STR_PARSER_EMAILTO, mstrName)) { // no checking needed } - else if( NamesMatch( twparser::STR_PARSER_SEVERITY, mstrName ) ) + else if (NamesMatch(twparser::STR_PARSER_SEVERITY, mstrName)) { - int iIgnore; + int iIgnore; cSeverityLimits sl; - if( ! sl.InterpretInt( mstrValue, &iIgnore ) ) - throw eParserBadSevVal( mstrValue, mLineNum ); + if (!sl.InterpretInt(mstrValue, &iIgnore)) + throw eParserBadSevVal(mstrValue, mLineNum); } - else if( NamesMatch( twparser::STR_PARSER_RECURSE, mstrName ) ) + else if (NamesMatch(twparser::STR_PARSER_RECURSE, mstrName)) { TSTRING str = mstrValue; - std::transform( str.begin(), str.end(), str.begin(), _totlower ); - - if( !NamesMatch( twparser::STR_PARSER_FALSE, str ) && !NamesMatch( twparser::STR_PARSER_TRUE, str ) ) + std::transform(str.begin(), str.end(), str.begin(), _totlower); + + if (!NamesMatch(twparser::STR_PARSER_FALSE, str) && !NamesMatch(twparser::STR_PARSER_TRUE, str)) { // must be number - int iIgnore; + int iIgnore; cRecurseDepthLimits rdl; - if( ! rdl.InterpretInt( str, &iIgnore ) ) - throw eParserUnrecognizedAttrVal( mstrValue, mLineNum ); + if (!rdl.InterpretInt(str, &iIgnore)) + throw eParserUnrecognizedAttrVal(mstrValue, mLineNum); } } else { - throw eParserUnrecognizedAttr( mstrName, mLineNum ); + throw eParserUnrecognizedAttr(mstrName, mLineNum); } } // case sensitive-matching -bool cParseNamedAttr::NamesMatch( int nString, const TSTRING& strName ) const +bool cParseNamedAttr::NamesMatch(int nString, const TSTRING& strName) const { - return ( 0 == strName.compare( TSS_GetString( cTWParser, nString ) ) ); + return (0 == strName.compare(TSS_GetString(cTWParser, nString))); } -// +// // cParseNamedAttrList // @@ -294,55 +284,51 @@ cParseNamedAttrList::~cParseNamedAttrList() } void cParseNamedAttrList::Clear() -{ - for( std::list::iterator iter = mList.begin(); iter != mList.end(); iter++ ) +{ + for (std::list::iterator iter = mList.begin(); iter != mList.end(); ++iter) { delete *iter; } mList.clear(); } -void -cParseNamedAttrList::Dump(cDebug &d) const +void cParseNamedAttrList::Dump(cDebug& d) const { // dump out each named attribute - std::list::const_iterator iattr; - for (iattr = mList.begin(); iattr != mList.end(); iattr++) { + std::list::const_iterator iattr; + for (iattr = mList.begin(); iattr != mList.end(); ++iattr) + { (*iattr)->Dump(d); } } -void cParseNamedAttrList::Add( cParseNamedAttr* const pa ) +void cParseNamedAttrList::Add(cParseNamedAttr* const pa) { - ASSERT( pa != 0 ); + ASSERT(pa != 0); pa->Validate(); // if not already in list, just put it in - constListIter iter = Find( pa ); - if( iter == mList.end() ) + constListIter iter = Find(pa); + if (iter == mList.end()) { - mList.push_back( pa ); + mList.push_back(pa); } else // set value of pa already in list { - (*iter)->SetValue( pa->GetValue() ); + (*iter)->SetValue(pa->GetValue()); } } -cParseNamedAttrList::constListIter cParseNamedAttrList::Find( const cParseNamedAttr* const pa ) +cParseNamedAttrList::constListIter cParseNamedAttrList::Find(const cParseNamedAttr* const pa) { - ASSERT( pa != 0 ); + ASSERT(pa != 0); - for( - std::list< cParseNamedAttr * >::const_iterator iter = mList.begin(); - iter != mList.end(); - iter++ - ) + for (std::list::const_iterator iter = mList.begin(); iter != mList.end(); ++iter) { - if( (*iter)->GetName() == pa->GetName() ) + if ((*iter)->GetName() == pa->GetName()) { return iter; } @@ -351,47 +337,46 @@ cParseNamedAttrList::constListIter cParseNamedAttrList::Find( const cParseNamedA return mList.end(); } -void cParseNamedAttrList::MergeNoOverwrite( const cParseNamedAttrList* const pal ) +void cParseNamedAttrList::MergeNoOverwrite(const cParseNamedAttrList* const pal) { - if( pal ) + if (pal) { // foreach attribute in pal - for( constListIter newIter = pal->mList.begin(); newIter != pal->mList.end(); newIter++ ) + for (constListIter newIter = pal->mList.begin(); newIter != pal->mList.end(); ++newIter) { // look for this attribute in this list - constListIter thisIter = Find( *newIter ); + constListIter thisIter = Find(*newIter); // if not already in list, just put it in - if( thisIter == mList.end() ) + if (thisIter == mList.end()) { - mList.push_back( (*newIter)->Clone() ); + mList.push_back((*newIter)->Clone()); } else // do not overwrite value (except for emailto) { // special case for emailto: this can have multiple values, so add the new value to the old value - if( 0 == (*thisIter)->GetName().compare( TSS_GetString( cTWParser, twparser::STR_PARSER_EMAILTO ) ) ) + if (0 == (*thisIter)->GetName().compare(TSS_GetString(cTWParser, twparser::STR_PARSER_EMAILTO))) { TSTRING tstr = (*thisIter)->GetValue(); - cParserUtil::MergeMailLists( tstr, (*newIter)->GetValue() ); - (*thisIter)->SetValue( tstr ); + cParserUtil::MergeMailLists(tstr, (*newIter)->GetValue()); + (*thisIter)->SetValue(tstr); } } } } } -const cParseNamedAttr* cParseNamedAttrList::Lookup( const TSTRING& tstrAttrName ) const +const cParseNamedAttr* cParseNamedAttrList::Lookup(const TSTRING& tstrAttrName) const { constListIter i; - for( i = mList.begin(); i != mList.end(); i++) + for (i = mList.begin(); i != mList.end(); ++i) { - if( 0 == tstrAttrName.compare( (*i)->GetName() ) ) + if (0 == tstrAttrName.compare((*i)->GetName())) { - return( *i ); + return (*i); } } - - return( NULL ); -} + return (NULL); +} diff --git a/src/twparser/parserobjects.h b/src/twparser/parserobjects.h index 969beb3..7cd3e5a 100644 --- a/src/twparser/parserobjects.h +++ b/src/twparser/parserobjects.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -64,7 +64,14 @@ class iParserGenreUtil; // INLINE FUNCTIONS //========================================================================= -#define KILL_LIST(type, name) do { for( std::list::iterator iter = mList.begin(); iter != mList.end(); iter++ ) { delete *iter; } } while(0) +#define KILL_LIST(type, name) \ + do \ + { \ + for (std::list::iterator iter = mList.begin(); iter != mList.end(); ++iter) \ + { \ + delete *iter; \ + } \ + } while (0) /////////////////////////////////////////////////////////////////////////////// @@ -83,49 +90,61 @@ class cParseNamedAttr // // ctors and dtors // - cParseNamedAttr( const TSTRING& strName, const TSTRING& strValue ); // converts strName to lower before storing + cParseNamedAttr(const TSTRING& strName, const TSTRING& strValue); // converts strName to lower before storing cParseNamedAttr* Clone() const; - - const TSTRING& GetName() const { return mstrName; }; - const TSTRING& GetValue() const { return mstrValue; }; - int GetLineNum() const { return mLineNum; }; - void SetValue( const TSTRING& str ) { mstrValue = str; }; - void Validate() const; - + const TSTRING& GetName() const + { + return mstrName; + }; + const TSTRING& GetValue() const + { + return mstrValue; + }; + int GetLineNum() const + { + return mLineNum; + }; + void SetValue(const TSTRING& str) + { + mstrValue = str; + }; + + void Validate() const; + // // debug functions // - void Dump(cDebug &d) const; // debugging routine + void Dump(cDebug& d) const; // debugging routine private: // // dont' let C++ create these - // - cParseNamedAttr( const cParseNamedAttr& rhs ); - cParseNamedAttr& operator=( const cParseNamedAttr& rhs ); - + // + cParseNamedAttr(const cParseNamedAttr& rhs); + cParseNamedAttr& operator=(const cParseNamedAttr& rhs); + // // enums // enum ValidAttrNames { - NAME_1 = twparser::STR_PARSER_RULENAME, - NAME_2 = twparser::STR_PARSER_EMAILTO, - NAME_3 = twparser::STR_PARSER_RECURSE, - NAME_4 = twparser::STR_PARSER_SEVERITY, + NAME_1 = twparser::STR_PARSER_RULENAME, + NAME_2 = twparser::STR_PARSER_EMAILTO, + NAME_3 = twparser::STR_PARSER_RECURSE, + NAME_4 = twparser::STR_PARSER_SEVERITY, MIN_NAME = NAME_1, MAX_NAME = NAME_4 }; - bool NamesMatch( int nString, const TSTRING& strName ) const; + bool NamesMatch(int nString, const TSTRING& strName) const; // // data members // - TSTRING mstrName; - TSTRING mstrValue; - int mLineNum; + TSTRING mstrName; + TSTRING mstrValue; + int mLineNum; }; @@ -137,41 +156,42 @@ class cParseNamedAttrList // // ctors and dtors // - cParseNamedAttrList() {}; + cParseNamedAttrList(){}; ~cParseNamedAttrList(); // // typedefed iters // - typedef std::list< cParseNamedAttr * >::const_iterator constListIter; - typedef std::list< cParseNamedAttr * >::const_reverse_iterator constListRevIter; - + typedef std::list::const_iterator constListIter; + typedef std::list::const_reverse_iterator constListRevIter; + // // general functionality // - void Dump( cDebug &d ) const; // dump entire list - void Add( cParseNamedAttr* const pa ); - const cParseNamedAttr* Lookup( const TSTRING& tstrAttrName ) const; - void Clear(); - void MergeNoOverwrite( const cParseNamedAttrList* const pal ); + void Dump(cDebug& d) const; // dump entire list + void Add(cParseNamedAttr* const pa); + const cParseNamedAttr* Lookup(const TSTRING& tstrAttrName) const; + void Clear(); + void MergeNoOverwrite(const cParseNamedAttrList* const pal); + private: // // private utils // - constListIter Find( const cParseNamedAttr* const pa ); + constListIter Find(const cParseNamedAttr* const pa); // // dont' let C++ create these // - cParseNamedAttrList( const cParseNamedAttrList& rhs ); - cParseNamedAttrList& operator=( const cParseNamedAttrList& rhs ); + cParseNamedAttrList(const cParseNamedAttrList& rhs); + cParseNamedAttrList& operator=(const cParseNamedAttrList& rhs); public: // // data members // - std::list< cParseNamedAttr * > mList; + std::list mList; }; @@ -179,96 +199,110 @@ class cParseNamedAttrList // parser representation of fcospecmasks // specmasks consist of sets of {condition, propvector} pairs, and also have associated // with them a list of {attributes}. -class cParseSpecMask +class cParseSpecMask { public: // // ctor and dtor // - cParseSpecMask( TSTRING &condition, TSTRING &vector, iParserGenreUtil* pHelper ); // throw( eParserHelper ) - cParseSpecMask( const cParseSpecMask& sm ) { *this = sm; }; + cParseSpecMask(TSTRING& condition, TSTRING& vector, iParserGenreUtil* pHelper); // throw( eParserHelper ) + cParseSpecMask(const cParseSpecMask& sm) + { + *this = sm; + }; ~cParseSpecMask(); // // data access // - void SetAttrList(cParseNamedAttrList *); // attach list of named attributes - cParseNamedAttrList *GetAttrList() const; - int GetNumAttrs() const; // number of named attributes - const cFCOPropVector& GetPropVector() const; // get prop vector (only used when parsing default specmasks) - const TSTRING& GetPropVectorString() const; - const TSTRING& GetCondition() const; // get condition - + void SetAttrList(cParseNamedAttrList*); // attach list of named attributes + cParseNamedAttrList* GetAttrList() const; + int GetNumAttrs() const; // number of named attributes + const cFCOPropVector& GetPropVector() const; // get prop vector (only used when parsing default specmasks) + const TSTRING& GetPropVectorString() const; + const TSTRING& GetCondition() const; // get condition + // // debug functionality // - void Dump(cDebug &d) const; // debugging routine + void Dump(cDebug& d) const; // debugging routine private: // // data members // - TSTRING msCondition; // TODO: this shouldn't be a string -- should be expression - TSTRING msPV; - cFCOPropVector mPropVector; - cParseNamedAttrList* mpAttrList; // list of named attributes associated with specmask - + TSTRING msCondition; // TODO: this shouldn't be a string -- should be expression + TSTRING msPV; + cFCOPropVector mPropVector; + cParseNamedAttrList* mpAttrList; // list of named attributes associated with specmask }; /////////////////////////////////////////////////////////////////////////////// // wrapper around list routines // we do this so yacc can have something convenient to carry around -class cParseSpecMaskList +class cParseSpecMaskList { public: - ~cParseSpecMaskList() { KILL_LIST(cParseSpecMask,mList); }; + ~cParseSpecMaskList() + { + KILL_LIST(cParseSpecMask, mList); + }; - void Dump(cDebug &d) const; // dump entire list - void Add( cParseSpecMask* const pa ) { mList.push_back( pa );}; + void Dump(cDebug& d) const; // dump entire list + void Add(cParseSpecMask* const pa) + { + mList.push_back(pa); + }; - std::list< cParseSpecMask* > mList; + std::list mList; }; // parser representation of fcospecs, which is composed of... // a rule name, a set of specmasks, a default specmask (required), and a set of named attributes -class cParseRule +class cParseRule { public: // // ctors and dtor // - cParseRule( const cParseSpecMask& defSpecMask ) :mDefSpecMask( defSpecMask ), mpAttrList(0), mpSpecMaskList(0), mName(_T("")) {} + explicit cParseRule(const cParseSpecMask& defSpecMask) + : mDefSpecMask(defSpecMask), mpAttrList(0), mpSpecMaskList(0), mName(_T("")) + { + } ~cParseRule(); // // data access // - const cFCOName& GetName() const; // rule name - void SetName( const cFCOName& name ); - cParseNamedAttrList*GetAttrList() const; // rule attributes - void SetAttrList(cParseNamedAttrList* ); - void SetSpecMaskList(cParseSpecMaskList *pmask); - // attach a list of specifiers to this rule (excluding default spec) - int GetNumSpecMasks() const; - // returns number of spec masks (excluding default rule) - int GetNumNamedAttrs() const; - // returns number of named attributes - const cParseSpecMask& GetDefSpecMask() const { return mDefSpecMask; }; + const cFCOName& GetName() const; // rule name + void SetName(const cFCOName& name); + cParseNamedAttrList* GetAttrList() const; // rule attributes + void SetAttrList(cParseNamedAttrList*); + void SetSpecMaskList(cParseSpecMaskList* pmask); + // attach a list of specifiers to this rule (excluding default spec) + int GetNumSpecMasks() const; + // returns number of spec masks (excluding default rule) + int GetNumNamedAttrs() const; + // returns number of named attributes + const cParseSpecMask& GetDefSpecMask() const + { + return mDefSpecMask; + }; // // debugging functions // - void Dump(); - + void Dump(); + private: // // debugging functions // - cParseSpecMask mDefSpecMask; // default specifier - cParseNamedAttrList* mpAttrList; // list of named attributes - cParseSpecMaskList* mpSpecMaskList; // list of specifiers - cFCOName mName; // name of fcospec + cParseSpecMask mDefSpecMask; // default specifier + cParseNamedAttrList* mpAttrList; // list of named attributes + cParseSpecMaskList* mpSpecMaskList; // list of specifiers + cFCOName mName; // name of fcospec }; @@ -278,14 +312,17 @@ class cParseRule class cParseString : public TSTRING { public: - TSTRING& operator=( const TSTRING& str ) { return TSTRING::operator=( str ); }; + TSTRING& operator=(const TSTRING& str) + { + return TSTRING::operator=(str); + }; }; -class cParseStringList : public std::list< TSTRING > +class cParseStringList : public std::list { private: - std::list< TSTRING >& operator=( const std::list< TSTRING >& str ); + std::list& operator=(const std::list& str); }; @@ -293,17 +330,28 @@ class cParseStringList : public std::list< TSTRING > class cAttrScopeInfo { public: - cAttrScopeInfo() :pAttrList(0), nStatements(0) {}; - - cParseNamedAttrList* GetAttrList() { return pAttrList; }; - void SetAttributes( cParseNamedAttrList* pL ) { pAttrList = pL; }; - void IncrementStatementCount() { nStatements++; }; - int GetStatementCount() { return nStatements; }; - + cAttrScopeInfo() : pAttrList(0), nStatements(0){}; + + cParseNamedAttrList* GetAttrList() + { + return pAttrList; + }; + void SetAttributes(cParseNamedAttrList* pL) + { + pAttrList = pL; + }; + void IncrementStatementCount() + { + nStatements++; + }; + int GetStatementCount() + { + return nStatements; + }; + private: cParseNamedAttrList* pAttrList; - int nStatements; + int nStatements; }; #endif //__PARSEROBJECTS_H - diff --git a/src/twparser/policyparser.cpp b/src/twparser/policyparser.cpp index a01d7df..8586a0d 100644 --- a/src/twparser/policyparser.cpp +++ b/src/twparser/policyparser.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,9 +46,9 @@ // STANDARD LIBRARY INCLUDES //========================================================================= -#include +#include #ifdef HAVE_WCHAR_H -# include +#include #endif #include "core/ntmbs.h" @@ -57,11 +57,11 @@ // UTIL FUNCTION PROTOTYES //========================================================================= -static std::string util_ConvertMB( const std::string& sIn ); +static std::string util_ConvertMB(const std::string& sIn); //static bool util_ReadMBCharAsSBString( std::stringstream& ss, std::string& strCh ); -static std::string convert_to_encoded_hex( char ch ); +static std::string convert_to_encoded_hex(char ch); //static std::string util_Output512Chars( const std::string& s ); - // don't want to pass debug a string over 1024, so play it safe with 512 +// don't want to pass debug a string over 1024, so play it safe with 512 //========================================================================= // PUBLIC METHOD CODE @@ -70,25 +70,23 @@ static std::string convert_to_encoded_hex( char ch ); // // constructor // -cPolicyParser::cPolicyParser( std::istream& in ) - : mParser(), mIn( in ) +cPolicyParser::cPolicyParser(std::istream& in) : mParser(), mIn(in) { } -void tw_yy_scan::output( int c ) +void tw_yy_scan::output(int c) { TOSTRINGSTREAM sstr; - TCHAR sz[2]; + TCHAR sz[2]; - sstr << TSS_GetString( cTWParser, twparser::STR_PARSER_INVALID_CHAR ); + sstr << TSS_GetString(cTWParser, twparser::STR_PARSER_INVALID_CHAR); sz[0] = (unsigned char)c; // don't want to sign extend this sz[1] = 0; sstr << sz; - - throw eParseFailed( sstr.str() ); -} + throw eParseFailed(sstr.str()); +} /////////////////////////////////////////////////////////////////////////////// @@ -96,19 +94,19 @@ void tw_yy_scan::output( int c ) // // on failure, it will throw an error /////////////////////////////////////////////////////////////////////////////// -void cPolicyParser::Check( cErrorBucket* pError ) //throw(eError); +void cPolicyParser::Check(cErrorBucket* pError) //throw(eError); { - cParserHelper::Init( pError ); - cParserHelper::SetParseOnly( true ); - - std::basic_stringstream in( ConvertMultibyte( mIn ) ); - tw_yy_scan lexer( in ); + cParserHelper::Init(pError); + cParserHelper::SetParseOnly(true); + + std::basic_stringstream in(ConvertMultibyte(mIn)); + tw_yy_scan lexer(in); // start the parsing - if ( mParser.yyparse( &lexer ) != 0 ) - throw eParseFailed( _T("") ); + if (mParser.yyparse(&lexer) != 0) + throw eParseFailed(_T("")); - cParserHelper::Finit( NULL ); + cParserHelper::Finit(NULL); } /////////////////////////////////////////////////////////////////////////////// @@ -117,18 +115,18 @@ void cPolicyParser::Check( cErrorBucket* pError ) //throw(eError); // on failure, it will throw an error (binding failed, or parse error) // on success, the list will be populated /////////////////////////////////////////////////////////////////////////////// -void cPolicyParser::Execute( cGenreSpecListVector& policy, cErrorBucket* pError ) //throw( eParserHelper ) +void cPolicyParser::Execute(cGenreSpecListVector& policy, cErrorBucket* pError) //throw( eParserHelper ) { - cParserHelper::Init( pError ); + cParserHelper::Init(pError); - std::basic_stringstream in( ConvertMultibyte( mIn ) ); - tw_yy_scan lexer( in ); + std::basic_stringstream in(ConvertMultibyte(mIn)); + tw_yy_scan lexer(in); // start the parsing - if ( mParser.yyparse( &lexer ) != 0 ) - throw eParseFailed( _T("") ); + if (mParser.yyparse(&lexer) != 0) + throw eParseFailed(_T("")); - cParserHelper::Finit( &policy ); + cParserHelper::Finit(&policy); } @@ -136,134 +134,123 @@ void cPolicyParser::Execute( cGenreSpecListVector& policy, cErrorBucket* pError // it doesn't look at any args following pszErr // Only call this with fully formatted message // Parser will ALWAYS call the narrow-char version, so special case Unicode compile -void tw_yy_scan::yyerror( const char* pszErr, ... ) //throw( eParserHelper ) +void tw_yy_scan::yyerror(const char* pszErr, ...) //throw( eParserHelper ) { - TOSTRINGSTREAM ssError; // final error string - -#ifdef _UNICODE - // passed in strings are narrow so we need to convert them to wide - wchar_t szErrorW[1024]; - size_t nWrote = ::mbstowcs( szErrorW, pszErr, strlen( pszErr ) + 1 ); - if ( nWrote == (size_t)-1 ) - throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); - ssError << szErrorW; -#else + TOSTRINGSTREAM ssError; // final error string ssError << pszErr; -#endif - - throw eParseFailed( ssError.str() ); + + throw eParseFailed(ssError.str()); } // Throw this in the display encoder? -std::string cPolicyParser::ConvertMultibyte( std::istream& in ) +std::string cPolicyParser::ConvertMultibyte(std::istream& in) { // get this file as a stringstream std::stringstream ss; - - while( true ) + + while (true) { // get next character char ch; - in.get( ch ); + in.get(ch); // check stream state - if( in.eof() ) + if (in.eof()) break; // we're done! - if( in.bad() || in.fail() ) + if (in.bad() || in.fail()) throw eParserBadCharacter(); // add next character to output buffer - ss.put( ch ); - + ss.put(ch); + // check stream state - if( ss.bad() || ss.fail() ) + if (ss.bad() || ss.fail()) throw eParserBadCharacter(); } -#ifdef _DEBUG +#ifdef DEBUG TCERR << _T("*** begin policy text ***") << std::endl; - std::cerr << ss.str() << std::endl; + std::cerr << ss.str() << std::endl; TCERR << _T("*** end policy text ***") << std::endl << std::endl; #endif // convert it to single byte escaped - std::string str = util_ConvertMB( ss.str() ); + std::string str = util_ConvertMB(ss.str()); -#ifdef _DEBUG +#ifdef DEBUG TCERR << _T("*** begin policy converted to ***") << std::endl; - std::cerr << str << std::endl; + std::cerr << str << std::endl; TCERR << _T("*** end policy converted to ***") << std::endl << std::endl; #endif return str; } -std::string convert_to_encoded_hex( char ch ) +std::string convert_to_encoded_hex(char ch) { - std::basic_stringstream< char > sstr; + std::basic_stringstream sstr; // set up stringstream - sstr.imbue( std::locale::classic() ); - sstr.setf( std::ios_base::hex, std::ios_base::basefield ); + sstr.imbue(std::locale::classic()); + sstr.setf(std::ios_base::hex, std::ios_base::basefield); // get the num_put facet - const std::num_put< char > *pnp = 0, &np = tss::GetFacet( sstr.getloc(), pnp ); - + const std::num_put*pnp = 0, &np = tss::GetFacet(sstr.getloc(), pnp); + // output the char sstr << "\\x"; - np.put( sstr, sstr, sstr.fill(), (long)(unsigned char)ch ); - + np.put(sstr, sstr, sstr.fill(), (long)(unsigned char)ch); + return sstr.str(); } -std::string util_ConvertMB( const std::string& sIn ) +std::string util_ConvertMB(const std::string& sIn) { -#if defined(__ANDROID_API__) || defined(__AROS__) - return sIn; +#if !USES_MBLEN + return sIn; #else - cDebug d( "cPolicyParser::util_ConvertMB" ); + cDebug d("cPolicyParser::util_ConvertMB"); std::string sOut; std::string::const_iterator at; - for( at = sIn.begin(); - at != sIn.end(); + for (at = sIn.begin(); at != sIn.end(); // at gets incremented when used.... - ) + ) { - int nBytes = ::mblen( (char*)&at[0], MB_CUR_MAX ); - if ( nBytes == -1 ) + int nBytes = ::mblen((char*)&at[0], MB_CUR_MAX); + if (nBytes == -1) { - d.TraceDebug( "Unrecognized Character: %c\n", *at ); - if ( (unsigned char)*at > 0x7F ) + d.TraceDebug("Unrecognized Character: %c\n", *at); + if ((unsigned char)*at > 0x7F) { - d.TraceDebug( "Normalizing.\n" ); - sOut += convert_to_encoded_hex( *(at++) ); + d.TraceDebug("Normalizing.\n"); + sOut += convert_to_encoded_hex(*(at++)); } else { - d.TraceDebug( "Incorrectly Formed, Cannot Normalize!\n" ); - std::string s( 1, *at ); - TSTRING ts = cStringUtil::StrToTstr( s ); - throw eParserBadCharacter( ts ); + d.TraceDebug("Incorrectly Formed, Cannot Normalize!\n"); + std::string s(1, *at); + TSTRING ts = cStringUtil::StrToTstr(s); + throw eParserBadCharacter(ts); } } - else if( nBytes == 0 ) + else if (nBytes == 0) { break; // done with sIn } - else if( nBytes == 1 ) + else if (nBytes == 1) { sOut += *(at++); // regular SB char } else // ( nBytes > 1 ) { // mb char -- output it as encoded bytes - while( nBytes-- > 0 ) + while (nBytes-- > 0) { - ASSERT( at != sIn.end() ); - sOut += convert_to_encoded_hex( *(at++) ); + ASSERT(at != sIn.end()); + sOut += convert_to_encoded_hex(*(at++)); } } } @@ -271,4 +258,3 @@ std::string util_ConvertMB( const std::string& sIn ) return sOut; #endif } - diff --git a/src/twparser/policyparser.h b/src/twparser/policyparser.h index 9ef6de0..636b7af 100644 --- a/src/twparser/policyparser.h +++ b/src/twparser/policyparser.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,7 +33,7 @@ // policyparser.h -- wrapper around yacc generated classes. intended to be used // as interface to parser // -// cPolicyParser: object responsible for reading policy file, and +// cPolicyParser: object responsible for reading policy file, and // generating list of FCOSpecs // @@ -61,8 +61,8 @@ #endif #ifndef YYNEWLINE -# include "twparser/yylex.h" -# include "twparser/yyparse.h" +#include "twparser/yylex.h" +#include "twparser/yyparse.h" #endif //========================================================================= @@ -70,45 +70,57 @@ //========================================================================= /////////////////////////////////////////////// -// wrapper around yy_scan +// wrapper around yy_scan // we do this so we can overload member functions class tw_yy_scan : public yy_scan { - enum { MAX_TOKEN_LENGTH = 1024 }; + enum + { + MAX_TOKEN_LENGTH = 1024 + }; + public: - tw_yy_scan( std::istream& i ) : yy_scan( MAX_TOKEN_LENGTH ), mIn(i) {}; // need to increase token length over mks default + explicit tw_yy_scan(std::istream& i) + : yy_scan(MAX_TOKEN_LENGTH), mIn(i){}; // need to increase token length over mks default + + virtual int yygetc() + { + return mIn.get(); + }; - virtual int yygetc() { return mIn.get(); }; - - virtual void yyerror( const char *pszErr, ... ); //throw( eParserHelper ) + virtual void yyerror(const char* pszErr, ...); //throw( eParserHelper ) // this is the MKS error function. But, since some operating systems (e.g. like AIX) - // don't offer a vnsprintf, so there's no way we can safely output the error + // don't offer a vnsprintf, so there's no way we can safely output the error // from the va_arg list to a string without possible buffer overflow. // So, only call this function with a fully formatted message. // NOTE: I repeat: this version ALWAYS IGNORES the va_list!! Even though it says "...", - virtual void output(int c); //throw( eParserHelper ) - // this is what lex calls when it gets to a char that it doesn't recognize. - // we throw an error. -private: - tw_yy_scan( const tw_yy_scan& ); - tw_yy_scan& operator=( const tw_yy_scan& ); + virtual void output(int c); //throw( eParserHelper ) + // this is what lex calls when it gets to a char that it doesn't recognize. + // we throw an error. +private: + tw_yy_scan(const tw_yy_scan&); + tw_yy_scan& operator=(const tw_yy_scan&); // input stream - std::istream& mIn; + std::istream& mIn; }; - + /////////////////////////////////////////////// // wrapper around yy_parse // we do this so we can overload member functions class tw_yy_parse : public yy_parse { - enum { PARSER_STATE_STACK_SIZE = 150 }; + enum + { + PARSER_STATE_STACK_SIZE = 150 + }; + public: - tw_yy_parse() : yy_parse( PARSER_STATE_STACK_SIZE ){}; // need to increase token length over mks default -private: - tw_yy_parse( const tw_yy_parse& ); - tw_yy_parse& operator=( const tw_yy_parse& ); + tw_yy_parse() : yy_parse(PARSER_STATE_STACK_SIZE){}; // need to increase token length over mks default +private: + tw_yy_parse(const tw_yy_parse&); + tw_yy_parse& operator=(const tw_yy_parse&); }; /////////////////////////////////////////////////////////////////////////////// @@ -123,23 +135,22 @@ class tw_yy_parse : public yy_parse class cPolicyParser { public: - cPolicyParser( std::istream& in ); // input source - - void Execute( cGenreSpecListVector& policy, cErrorBucket* pError ); //throw(eError); - void Check( cErrorBucket* pError ); //throw(eError); - // do the parsing -private: - cPolicyParser( const cPolicyParser& ); - cPolicyParser& operator=( const cPolicyParser& ); - - std::string ConvertMultibyte( std::istream& in ); - // turns all mb chars > 1 byte or unrecognizable chars - // into escaped hex (\xXX) - - tw_yy_parse mParser; - std::istream& mIn; + explicit cPolicyParser(std::istream& in); // input source + + void Execute(cGenreSpecListVector& policy, cErrorBucket* pError); //throw(eError); + void Check(cErrorBucket* pError); //throw(eError); + // do the parsing +private: + cPolicyParser(const cPolicyParser&); + cPolicyParser& operator=(const cPolicyParser&); + + std::string ConvertMultibyte(std::istream& in); + // turns all mb chars > 1 byte or unrecognizable chars + // into escaped hex (\xXX) + + tw_yy_parse mParser; + std::istream& mIn; }; #endif - diff --git a/src/twparser/stdtwparser.cpp b/src/twparser/stdtwparser.cpp index bb8b146..1d47e59 100644 --- a/src/twparser/stdtwparser.cpp +++ b/src/twparser/stdtwparser.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdtwparser.h" - -// eof: stdtwparser.cpp diff --git a/src/twparser/stdtwparser.h b/src/twparser/stdtwparser.h index 43d8038..e1a582e 100644 --- a/src/twparser/stdtwparser.h +++ b/src/twparser/stdtwparser.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/twparser/twparser.cpp b/src/twparser/twparser.cpp index bb73220..eeb8f93 100644 --- a/src/twparser/twparser.cpp +++ b/src/twparser/twparser.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,7 +45,7 @@ // PUBLIC METHOD CODE //========================================================================= -TSS_ImplementPackage( cTWParser ) +TSS_ImplementPackage(cTWParser) cTWParser::cTWParser() { @@ -54,6 +54,5 @@ cTWParser::cTWParser() // // TODO:BAM -- TSS_Dependency( ??? ); - TSS_REGISTER_PKG_ERRORS( twparser ) + TSS_REGISTER_PKG_ERRORS(twparser) } - diff --git a/src/twparser/twparser.h b/src/twparser/twparser.h index 3689471..f52db10 100644 --- a/src/twparser/twparser.h +++ b/src/twparser/twparser.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,18 +42,17 @@ //--Requirements -#include "core/package.h" // for: Packaging Abstraction +#include "core/package.h" // for: Packaging Abstraction //--Classes -TSS_BeginPackage( cTWParser ) - +TSS_BeginPackage(cTWParser) + TSS_DECLARE_STRINGTABLE; - - public: - cTWParser(); -TSS_EndPackage( cTWParser ) +public: +cTWParser(); -#endif //#ifndef __TWPARSER_H +TSS_EndPackage(cTWParser) +#endif //#ifndef __TWPARSER_H diff --git a/src/twparser/twparsererrors.cpp b/src/twparser/twparsererrors.cpp index d3abacc..bdf7a92 100644 --- a/src/twparser/twparsererrors.cpp +++ b/src/twparser/twparsererrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,31 +40,31 @@ #include "parserhelper.h" -TSS_BEGIN_ERROR_REGISTRATION( twparser ) +TSS_BEGIN_ERROR_REGISTRATION(twparser) // // Parser Helper // -TSS_REGISTER_ERROR( eParserHelper(), _T("Policy file parsing problem.") ); -TSS_REGISTER_ERROR( eParseFailed(), _T("Policy file parsing problem.") ); -TSS_REGISTER_ERROR( eParserRedefineVar(), _T("Read only variables cannot be assigned a value.") ); -TSS_REGISTER_ERROR( eParserUnrecognizedAttr(), _T("Unrecognized attribute name.") ); -TSS_REGISTER_ERROR( eParserUnrecognizedAttrVal(), _T("Unrecognized attribute value.") ); -TSS_REGISTER_ERROR( eParserPropChar(), _T("Unrecognized property mask in policy file.") ); -TSS_REGISTER_ERROR( eParserNoRules(), _T("No rules specified in policy file.") ); -TSS_REGISTER_ERROR( eParserNoRulesInSection(), _T("No rules specified in section.") ); -TSS_REGISTER_ERROR( eParserUseUndefVar(), _T("Undefined variable used.") ); -TSS_REGISTER_ERROR( eParserBadSevVal(), _T("Severity value outside of allowable limits.") ); -TSS_REGISTER_ERROR( eParserBadFCONameFmt(), _T("Bad objectname format.") ); -TSS_REGISTER_ERROR( eParserSectionAlreadyDefined(), _T("Section already declared.") ); -TSS_REGISTER_ERROR( eParserPointAlreadyDefined(), _T("Rule already defined as a start or stop point of another rule.") ); -TSS_REGISTER_ERROR( eParserSectionInsideBlock(), _T("Section declaration inside another block.") ); -TSS_REGISTER_ERROR( eParserRelativePath(), _T("Relative paths are not allowed in the policy file.") ); -TSS_REGISTER_ERROR( eParserIgnoringSection(), _T("Ignoring unknown section.") ); -TSS_REGISTER_ERROR( eParserNoStatementsInScope(), _T("Scoped attributes section has no statements.") ); -TSS_REGISTER_ERROR( eParserBadHex(), _T("Bad hex value in policy file.") ); -TSS_REGISTER_ERROR( eParserBadCharacter(), _T("Bad character found in policy file.") ); +TSS_REGISTER_ERROR(eParserHelper(), _T("Policy file parsing problem.")); +TSS_REGISTER_ERROR(eParseFailed(), _T("Policy file parsing problem.")); +TSS_REGISTER_ERROR(eParserRedefineVar(), _T("Read only variables cannot be assigned a value.")); +TSS_REGISTER_ERROR(eParserUnrecognizedAttr(), _T("Unrecognized attribute name.")); +TSS_REGISTER_ERROR(eParserUnrecognizedAttrVal(), _T("Unrecognized attribute value.")); +TSS_REGISTER_ERROR(eParserPropChar(), _T("Unrecognized property mask in policy file.")); +TSS_REGISTER_ERROR(eParserNoRules(), _T("No rules specified in policy file.")); +TSS_REGISTER_ERROR(eParserNoRulesInSection(), _T("No rules specified in section.")); +TSS_REGISTER_ERROR(eParserUseUndefVar(), _T("Undefined variable used.")); +TSS_REGISTER_ERROR(eParserBadSevVal(), _T("Severity value outside of allowable limits.")); +TSS_REGISTER_ERROR(eParserBadFCONameFmt(), _T("Bad objectname format.")); +TSS_REGISTER_ERROR(eParserSectionAlreadyDefined(), _T("Section already declared.")); +TSS_REGISTER_ERROR(eParserPointAlreadyDefined(), _T("Rule already defined as a start or stop point of another rule.")); +TSS_REGISTER_ERROR(eParserSectionInsideBlock(), _T("Section declaration inside another block.")); +TSS_REGISTER_ERROR(eParserRelativePath(), _T("Relative paths are not allowed in the policy file.")); +TSS_REGISTER_ERROR(eParserIgnoringSection(), _T("Ignoring unknown section.")); +TSS_REGISTER_ERROR(eParserNoStatementsInScope(), _T("Scoped attributes section has no statements.")); +TSS_REGISTER_ERROR(eParserBadHex(), _T("Bad hex value in policy file.")); +TSS_REGISTER_ERROR(eParserBadCharacter(), _T("Bad character found in policy file.")); TSS_END_ERROR_REGISTRATION() diff --git a/src/twparser/twparsererrors.h b/src/twparser/twparsererrors.h index 04d2772..2ae9810 100644 --- a/src/twparser/twparsererrors.h +++ b/src/twparser/twparsererrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( twparser ) - -#endif//__PARSERERRORS_H +TSS_DECLARE_ERROR_REGISTRATION(twparser) +#endif //__PARSERERRORS_H diff --git a/src/twparser/twparserstrings.cpp b/src/twparser/twparserstrings.cpp index 94e9bee..21f71f4 100644 --- a/src/twparser/twparserstrings.cpp +++ b/src/twparser/twparserstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,17 +39,16 @@ #include "twparser.h" #include "twparserstrings.h" -TSS_BeginStringtable( cTWParser ) - - TSS_StringEntry( twparser::STR_PARSER_INVALID_CHAR, _T("Invalid character: ") ), - TSS_StringEntry( twparser::STR_PARSER_RULENAME, _T("rulename") ), - TSS_StringEntry( twparser::STR_PARSER_EMAILTO, _T("emailto") ), - TSS_StringEntry( twparser::STR_PARSER_RECURSE, _T("recurse") ), - TSS_StringEntry( twparser::STR_PARSER_SEVERITY, _T("severity") ), - TSS_StringEntry( twparser::STR_PARSER_FALSE, _T("false") ), - TSS_StringEntry( twparser::STR_PARSER_TRUE, _T("true") ), - TSS_StringEntry( twparser::STR_PARSER_SECTION_GLOBAL, _T("GLOBAL") ), - TSS_StringEntry( twparser::STR_LINE_NUMBER, _T("Line number ") ), - TSS_StringEntry( twparser::STR_ERR2_PARSER_NO_RULES_IN_SECTION, _T("Section: ") ), +TSS_BeginStringtable(cTWParser) + + TSS_StringEntry(twparser::STR_PARSER_INVALID_CHAR, _T("Invalid character: ")), + TSS_StringEntry(twparser::STR_PARSER_RULENAME, _T("rulename")), + TSS_StringEntry(twparser::STR_PARSER_EMAILTO, _T("emailto")), + TSS_StringEntry(twparser::STR_PARSER_RECURSE, _T("recurse")), + TSS_StringEntry(twparser::STR_PARSER_SEVERITY, _T("severity")), + TSS_StringEntry(twparser::STR_PARSER_FALSE, _T("false")), TSS_StringEntry(twparser::STR_PARSER_TRUE, _T("true")), + TSS_StringEntry(twparser::STR_PARSER_SECTION_GLOBAL, _T("GLOBAL")), + TSS_StringEntry(twparser::STR_LINE_NUMBER, _T("Line number ")), + TSS_StringEntry(twparser::STR_ERR2_PARSER_NO_RULES_IN_SECTION, _T("Section: ")), -TSS_EndStringtable( cTWParser ) + TSS_EndStringtable(cTWParser) diff --git a/src/twparser/twparserstrings.h b/src/twparser/twparserstrings.h index 57b02f2..d693135 100644 --- a/src/twparser/twparserstrings.h +++ b/src/twparser/twparserstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,26 +38,18 @@ #ifndef __TWPARSERSTRINGS_H #define __TWPARSERSTRINGS_H -#include "twparser.h" // for: STRINGTABLE syntax +#include "twparser.h" // for: STRINGTABLE syntax //--Message Keys -TSS_BeginStringIds( twparser ) +TSS_BeginStringIds(twparser) STR_PARSER_INVALID_CHAR, - STR_YYERROR_LINE_NUM_FMT, - STR_PARSER_RULENAME, - STR_PARSER_EMAILTO, - STR_PARSER_RECURSE, - STR_PARSER_SEVERITY, - STR_PARSER_FALSE, - STR_PARSER_TRUE, - STR_PARSER_SECTION_GLOBAL, - STR_LINE_NUMBER, + STR_YYERROR_LINE_NUM_FMT, STR_PARSER_RULENAME, STR_PARSER_EMAILTO, STR_PARSER_RECURSE, STR_PARSER_SEVERITY, + STR_PARSER_FALSE, STR_PARSER_TRUE, STR_PARSER_SECTION_GLOBAL, STR_LINE_NUMBER, STR_ERR2_PARSER_NO_RULES_IN_SECTION -TSS_EndStringIds( twparser ) - + TSS_EndStringIds(twparser) -#endif//__PARSERSTRINGS_H +#endif //__PARSERSTRINGS_H diff --git a/src/twparser/yylex.cpp b/src/twparser/yylex.cpp index ed66a60..225b869 100644 --- a/src/twparser/yylex.cpp +++ b/src/twparser/yylex.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -478,7 +478,7 @@ static int yy_base[] = { }; -#line 152 "..\\..\\mkslexyacc\\etc\\yylex.cpp" +// #line 152 "..\\..\\mkslexyacc\\etc\\yylex.cpp" // MKS LEX prototype scanner code // Copyright 1991 by Mortice Kern Systems Inc. @@ -505,7 +505,7 @@ const int MIN_NUM_STATES = 20; #define REJECT goto yy_reject #define yymore() goto yy_more -#line 10 "tokens.l" +// #line 10 "tokens.l" #include "stdtwparser.h" @@ -515,7 +515,7 @@ const int MIN_NUM_STATES = 20; //#endif #include -#ifdef HAVE_MALLOC_H +#if HAVE_MALLOC_H && !IS_AROS #include #endif #include @@ -563,7 +563,7 @@ std::string FormatSyntaxError( char ch, const char* pszAdditionalMsg = NULL ) // saves typing #define TRACE_RETURN(x) lextrace(_T(#x)); return x -#line 178 "..\\..\\mkslexyacc\\etc\\yylex.cpp" +// #line 178 "..\\..\\mkslexyacc\\etc\\yylex.cpp" // Constructor for yy_scan. Set up tables @@ -614,10 +614,10 @@ yy_scan::~yy_scan() { if (mustfree) { mustfree = 0; - delete(yytext); - delete(state); + delete [] yytext; + delete [] state; #ifdef YY_PRESERVE - delete(save); + delete [] save; #endif } } @@ -762,7 +762,7 @@ yy_scan::yylex() int yyoldi, yyoleng; /* base i, yyleng before look-ahead */ int yyeof; /* 1 if eof has already been read */ -#line 375 "..\\..\\mkslexyacc\\etc\\yylex.cpp" +// #line 375 "..\\..\\mkslexyacc\\etc\\yylex.cpp" #ifdef YYEXIT @@ -876,43 +876,43 @@ yy_scan::yylex() YY_USER(); switch (yy_la_act[yyfmin] & 0777) { case 0: -#line 109 "tokens.l" +// #line 109 "tokens.l" { BEGIN( globals ); } break; case 1: -#line 114 "tokens.l" +// #line 114 "tokens.l" { BEGIN(INITIAL); return TWP_SECTION; } break; case 2: -#line 119 "tokens.l" +// #line 119 "tokens.l" { TRACE_RETURN(TWP_ECHO); } break; case 3: -#line 122 "tokens.l" +// #line 122 "tokens.l" { lextrace(_T("eating spaces...")); /* eat spaces */ } break; case 4: -#line 125 "tokens.l" +// #line 125 "tokens.l" { cParserHelper::IncrementLineNumber(); lextrace(_T("eating line continuation...")); /* eat line continuations */ } break; case 5: -#line 129 "tokens.l" +// #line 129 "tokens.l" { lextrace(_T("eating comment...")); } break; case 6: -#line 138 "tokens.l" +// #line 138 "tokens.l" { // we must make copy of string, otherwise another lexeme will clobber it cDebug d("\t\t\t\tlexer::string"); @@ -931,7 +931,7 @@ yy_scan::yylex() } break; case 7: -#line 155 "tokens.l" +// #line 155 "tokens.l" { // we must make copy of string, otherwise another lexeme will clobber it cDebug d("\t\t\t\tlexer::qstring"); @@ -960,19 +960,19 @@ yy_scan::yylex() } break; case 8: -#line 182 "tokens.l" +// #line 182 "tokens.l" { TRACE_RETURN(TWP_SEMICOLON); } break; case 9: -#line 183 "tokens.l" +// #line 183 "tokens.l" { TRACE_RETURN(TWP_EQUALS); } break; case 10: -#line 185 "tokens.l" +// #line 185 "tokens.l" { cParserHelper::IncrementLineNumber(); } break; case 11: -#line 186 "tokens.l" +// #line 186 "tokens.l" { std::string strError; strError = FormatSyntaxError( yytext[0], "The global section only accepts statements of the form:\n variable = value;\n" ); @@ -981,102 +981,102 @@ yy_scan::yylex() } /* catches anything that cannot be deemed a variable definition and exits. */ break; case 12: -#line 196 "tokens.l" +// #line 196 "tokens.l" { lextrace(_T("eating spaces...")); /* eat spaces */ } break; case 13: -#line 200 "tokens.l" +// #line 200 "tokens.l" { cParserHelper::IncrementLineNumber(); lextrace(_T("eating line continuation...")); /* eat line continuations */ } break; case 14: -#line 205 "tokens.l" +// #line 205 "tokens.l" { lextrace(_T("eating comment...")); } break; case 15: -#line 209 "tokens.l" +// #line 209 "tokens.l" { TRACE_RETURN(TWP_LBRACE); } break; case 16: -#line 210 "tokens.l" +// #line 210 "tokens.l" { TRACE_RETURN(TWP_RBRACE); } break; case 17: -#line 213 "tokens.l" +// #line 213 "tokens.l" { TRACE_RETURN(TWP_BANG); } break; case 18: -#line 215 "tokens.l" +// #line 215 "tokens.l" { TRACE_RETURN(TWP_RARROW); } break; case 19: -#line 216 "tokens.l" +// #line 216 "tokens.l" { TRACE_RETURN(TWP_EQUALS); } break; case 20: -#line 218 "tokens.l" +// #line 218 "tokens.l" { TRACE_RETURN(TWP_SEMICOLON); } break; case 21: -#line 219 "tokens.l" +// #line 219 "tokens.l" { TRACE_RETURN(TWP_LPAREN); } break; case 22: -#line 220 "tokens.l" +// #line 220 "tokens.l" { TRACE_RETURN(TWP_RPAREN); } break; case 23: -#line 221 "tokens.l" +// #line 221 "tokens.l" { TRACE_RETURN(TWP_COMMA); } break; case 24: -#line 222 "tokens.l" +// #line 222 "tokens.l" { TRACE_RETURN(TWP_PIPE); } break; case 25: -#line 226 "tokens.l" +// #line 226 "tokens.l" { TRACE_RETURN(TWP_DOLLAR); } break; case 26: -#line 227 "tokens.l" +// #line 227 "tokens.l" { TRACE_RETURN(TWP_OROR); } break; case 27: -#line 230 "tokens.l" +// #line 230 "tokens.l" { TRACE_RETURN(TWP_SECTION); } break; case 28: -#line 231 "tokens.l" +// #line 231 "tokens.l" { TRACE_RETURN(TWP_IFHOST); } break; case 29: -#line 232 "tokens.l" +// #line 232 "tokens.l" { TRACE_RETURN(TWP_ELSE); } break; case 30: -#line 233 "tokens.l" +// #line 233 "tokens.l" { TRACE_RETURN(TWP_ENDIF); } break; case 31: -#line 234 "tokens.l" +// #line 234 "tokens.l" { TRACE_RETURN(TWP_ERROR); } break; case 32: -#line 235 "tokens.l" +// #line 235 "tokens.l" { TRACE_RETURN(TWP_ECHO); } break; case 33: -#line 236 "tokens.l" +// #line 236 "tokens.l" { lextrace( _T( "@@end" ) ); return 0; } /* logical end of file */ break; case 34: -#line 239 "tokens.l" +// #line 239 "tokens.l" { // we must make copy of string, otherwise another lexeme will clobber it cDebug d("\t\t\t\tlexer::string"); @@ -1095,7 +1095,7 @@ yy_scan::yylex() } break; case 35: -#line 256 "tokens.l" +// #line 256 "tokens.l" { // we must make copy of string, otherwise another lexeme will clobber it cDebug d("\t\t\t\tlexer::qstring"); @@ -1121,12 +1121,12 @@ yy_scan::yylex() *mpstring = strW; -#ifdef _DEBUG +#ifdef DEBUG TSTRING strDisplay = *mpstring; cDisplayEncoder e; e.Encode( strDisplay ); d.TraceDetail("interpreted as --> <%s>\n", strDisplay.c_str()); -#endif // _DEBUG +#endif // DEBUG // attach to lval yylval.mpString = mpstring; @@ -1134,11 +1134,11 @@ yy_scan::yylex() } break; case 36: -#line 309 "tokens.l" +// #line 309 "tokens.l" { cParserHelper::IncrementLineNumber(); } break; case 37: -#line 310 "tokens.l" +// #line 310 "tokens.l" { std::string strError; strError = FormatSyntaxError( yytext[0] ); @@ -1147,7 +1147,7 @@ yy_scan::yylex() } /* catches anything else that's not in here and quits */ break; -#line 487 "..\\..\\mkslexyacc\\etc\\yylex.cpp" +// #line 487 "..\\..\\mkslexyacc\\etc\\yylex.cpp" } YY_SCANNER(); @@ -1231,7 +1231,7 @@ yy_scan::unput(int c) return c; } -#line 321 "tokens.l" +// #line 321 "tokens.l" diff --git a/src/twparser/yylex.h b/src/twparser/yylex.h index fa5e866..8ede93c 100644 --- a/src/twparser/yylex.h +++ b/src/twparser/yylex.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -38,7 +38,7 @@ #endif #define YYNEWLINE 10 -#line 1 "..\\..\\mkslexyacc\\etc\\yylex.cpp" +//#line 1 "..\\..\\mkslexyacc\\etc\\yylex.cpp" // MKS LEX prototype scanner header // Copyright 1991 by Mortice Kern Systems Inc. // All rights reserved. diff --git a/src/twparser/yyparse.cpp b/src/twparser/yyparse.cpp index 0bb7645..8d3862b 100644 --- a/src/twparser/yyparse.cpp +++ b/src/twparser/yyparse.cpp @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -30,7 +30,7 @@ // info@tripwire.org or www.tripwire.org. // /* ..\. -LC -o ..\twparser\yyparse.cpp -P ..\..\mkslexyacc\etc\yyparse.cpp -D yyparse.h policy.y */ -#line 74 "policy.y" +// #line 74 "policy.y" #include "stdtwparser.h" @@ -349,7 +349,7 @@ int yy_parse::yynrule = 55; -#line 2 "..\\..\\mkslexyacc\\etc\\yyparse.cpp" +// #line 2 "..\\..\\mkslexyacc\\etc\\yyparse.cpp" // C++ YACC parser code // Copyright 1991 by Mortice Kern Systems Inc. All rights reserved. // @@ -419,16 +419,16 @@ yy_parse::yy_parse(int sz) yy_parse::~yy_parse() { if (mustfree) { - delete stateStack; - delete valueStack; + delete [] stateStack; + delete [] valueStack; } stateStack = (short *) 0; #if YYDEBUG - delete typeStack; + delete [] typeStack; #endif } -#ifdef YACC_WINDOWS +#if 0 //YACC_WINDOWS // The initial portion of the yacc parser. // In an windows environment, it will load the desired @@ -533,7 +533,7 @@ yy_parse::yyparse(yy_scan* ps) #endif /* YACC_WINDOWS */ { -#ifdef YACC_WINDOWS +#if 0 //YACC_WINDOWS short far *yyp; // needed as res tables locked in far memory short far *yyq; #else @@ -594,7 +594,7 @@ yy_parse::yyparse(yy_scan* ps) #endif } #endif -#ifdef YACC_WINDOWS +#if 0 //YACC_WINDOWS if (yystate >= Sizeof_yypact) /* simple state */ #else /* YACC_WINDOWS */ if (yystate >= (int)sizeof yypact/(int)sizeof yypact[0]) /* simple state */ @@ -640,7 +640,7 @@ yy_parse::yyparse(yy_scan* ps) * Fell through - take default action */ -#ifdef YACC_WINDOWS +#if 0 //YACC_WINDOWS if (yystate >= Sizeof_yydef) /* simple state */ #else /* YACC_WINDOWS */ if (yystate >= (int)sizeof yydef /(int)sizeof yydef[0]) @@ -689,22 +689,22 @@ yy_parse::yyparse(yy_scan* ps) switch (yyi) { /* perform semantic action */ case YYr6: { /* statement : variable_assignment TWP_SEMICOLON */ -#line 194 "policy.y" +// #line 194 "policy.y" cParserHelper::IncrementScopeStatementCount(); } break; case YYr7: { /* statement : global_variable_assignment TWP_SEMICOLON */ -#line 195 "policy.y" +// #line 195 "policy.y" cParserHelper::IncrementScopeStatementCount(); } break; case YYr8: { /* statement : rule TWP_SEMICOLON */ -#line 196 "policy.y" +// #line 196 "policy.y" cParserHelper::IncrementScopeStatementCount(); } break; case YYr12: { /* scoped_block : TWP_LPAREN attribute_list_with_opt_trailing_comma TWP_RPAREN TWP_LBRACE */ -#line 204 "policy.y" +// #line 204 "policy.y" cDebug d("Parse::scope"); @@ -721,7 +721,7 @@ case YYr12: { /* scoped_block : TWP_LPAREN attribute_list_with_opt_trailing_c } break; case YYr13: { /* scoped_block : TWP_LPAREN attribute_list_with_opt_trailing_comma TWP_RPAREN TWP_LBRACE $12 opt_statement_list TWP_RBRACE */ -#line 218 "policy.y" +// #line 218 "policy.y" if( 0 == cParserHelper::GetScopeStatementCount() && iUserNotify::GetInstance()->GetVerboseLevel() == iUserNotify::V_VERBOSE ) { @@ -737,7 +737,7 @@ case YYr13: { /* scoped_block : TWP_LPAREN attribute_list_with_opt_trailing_c } break; case YYr14: { /* directive_block : TWP_IFHOST host_name_list */ -#line 234 "policy.y" +// #line 234 "policy.y" cDebug d("Parse::#ifhost"); @@ -763,7 +763,7 @@ case YYr14: { /* directive_block : TWP_IFHOST host_name_list */ } break; case YYr15: { /* directive_block : TWP_IFHOST host_name_list $14 opt_statement_list opt_else_host TWP_ENDIF */ -#line 257 "policy.y" +// #line 257 "policy.y" cDebug d("Parse::#endif"); cPreprocessor::PopState(); @@ -773,7 +773,7 @@ case YYr15: { /* directive_block : TWP_IFHOST host_name_list $14 opt_statemen } break; case YYr16: { /* directive_block : TWP_SECTION string */ -#line 264 "policy.y" +// #line 264 "policy.y" cDebug d("Parse::#section"); @@ -787,7 +787,7 @@ case YYr16: { /* directive_block : TWP_SECTION string */ } break; case YYr17: { /* directive_block : TWP_ERROR string */ -#line 275 "policy.y" +// #line 275 "policy.y" if( cPreprocessor::GetState() == cPreprocessor::STATE_ACCEPT && !cParserHelper::ParseOnly() ) { @@ -801,7 +801,7 @@ case YYr17: { /* directive_block : TWP_ERROR string */ } break; case YYr18: { /* directive_block : TWP_ECHO string */ -#line 286 "policy.y" +// #line 286 "policy.y" if( cPreprocessor::GetState() == cPreprocessor::STATE_ACCEPT && !cParserHelper::ParseOnly() ) { @@ -814,7 +814,7 @@ case YYr18: { /* directive_block : TWP_ECHO string */ } break; case YYr19: { /* host_name_list : host_name_list TWP_OROR host_name */ -#line 299 "policy.y" +// #line 299 "policy.y" yyval.mpStringList = yypvt[-2].mpStringList; yyval.mpStringList->push_back( *yypvt[0].mpString ); @@ -822,7 +822,7 @@ case YYr19: { /* host_name_list : host_name_list TWP_OROR host_name */ } break; case YYr20: { /* host_name_list : host_name */ -#line 304 "policy.y" +// #line 304 "policy.y" yyval.mpStringList = new cParseStringList; yyval.mpStringList->push_back( *yypvt[0].mpString ); @@ -830,7 +830,7 @@ case YYr20: { /* host_name_list : host_name */ } break; case YYr21: { /* opt_else_host : TWP_ELSE */ -#line 312 "policy.y" +// #line 312 "policy.y" cDebug d("Parse::#else"); @@ -848,7 +848,7 @@ case YYr21: { /* opt_else_host : TWP_ELSE */ } break; case YYr24: { /* variable_assignment : variable_name TWP_EQUALS multi_string */ -#line 332 "policy.y" +// #line 332 "policy.y" cDebug d("Parse::variable_assignment"); @@ -869,7 +869,7 @@ case YYr24: { /* variable_assignment : variable_name TWP_EQUALS multi_string } break; case YYr25: { /* global_variable_assignment : global_string TWP_EQUALS global_multi_string */ -#line 353 "policy.y" +// #line 353 "policy.y" cDebug d("Parse::global variable_assignment"); @@ -890,7 +890,7 @@ case YYr25: { /* global_variable_assignment : global_string TWP_EQUALS global } break; case YYr26: { /* rule : fco_name TWP_RARROW spec_masks */ -#line 374 "policy.y" +// #line 374 "policy.y" cDebug d("Parse::rule(fco_name TWP_RARROW spec_masks)"); if( cPreprocessor::GetState() == cPreprocessor::STATE_IGNORE ) @@ -927,6 +927,7 @@ case YYr26: { /* rule : fco_name TWP_RARROW spec_masks */ // add to our lists cParserHelper::GetGenreInfo()->AddStopPoint( fcoName ); cParserHelper::GetGenreInfo()->AddRule( pnode ); + delete pGU; } delete yypvt[-2].mpStringList; @@ -935,7 +936,7 @@ case YYr26: { /* rule : fco_name TWP_RARROW spec_masks */ } break; case YYr27: { /* rule : TWP_BANG fco_name */ -#line 416 "policy.y" +// #line 416 "policy.y" cDebug d("Parse::rule(!fconame)"); @@ -959,6 +960,7 @@ case YYr27: { /* rule : TWP_BANG fco_name */ // add to stop list cParserHelper::GetGenreInfo()->AddStopPoint( fcoName ); + delete pGU; } delete yypvt[0].mpStringList; @@ -966,7 +968,7 @@ case YYr27: { /* rule : TWP_BANG fco_name */ } break; case YYr28: { /* spec_masks : prop_vector opt_spec_attributes */ -#line 447 "policy.y" +// #line 447 "policy.y" if( cPreprocessor::GetState() == cPreprocessor::STATE_ACCEPT ) { @@ -978,6 +980,7 @@ case YYr28: { /* spec_masks : prop_vector opt_spec_attributes */ yypvt[0].mpAttrList->MergeNoOverwrite( cParserHelper::GetGlobalAttrList() ); yyval.mpNode = pNode; + delete pGU; } delete yypvt[-1].mpString; @@ -987,28 +990,28 @@ case YYr28: { /* spec_masks : prop_vector opt_spec_attributes */ } break; case YYr29: { /* opt_spec_attributes : TWP_LPAREN attribute_list_with_opt_trailing_comma TWP_RPAREN */ -#line 485 "policy.y" +// #line 485 "policy.y" yyval.mpAttrList = yypvt[-1].mpAttrList; } break; case YYr30: { /* opt_spec_attributes : */ -#line 489 "policy.y" +// #line 489 "policy.y" yyval.mpAttrList = new cParseNamedAttrList; } break; case YYr31: { /* attribute_list_with_opt_trailing_comma : attribute_list opt_comma */ -#line 515 "policy.y" +// #line 515 "policy.y" yyval.mpAttrList = yypvt[-1].mpAttrList; } break; case YYr32: { /* attribute_list : attribute_list TWP_COMMA attribute */ -#line 522 "policy.y" +// #line 522 "policy.y" cDebug d("Parse::attribute_list"); ASSERT( yypvt[-2].mpAttrList && yypvt[0].mpAttr ); @@ -1024,7 +1027,7 @@ case YYr32: { /* attribute_list : attribute_list TWP_COMMA attribute */ } break; case YYr33: { /* attribute_list : attribute */ -#line 535 "policy.y" +// #line 535 "policy.y" cDebug d("Parse::attribute_list"); @@ -1038,7 +1041,7 @@ case YYr33: { /* attribute_list : attribute */ } break; case YYr34: { /* attribute : attribute_name TWP_EQUALS attribute_value */ -#line 548 "policy.y" +// #line 548 "policy.y" cDebug d("Parse::attribute"); @@ -1055,7 +1058,7 @@ case YYr34: { /* attribute : attribute_name TWP_EQUALS attribute_value */ } break; case YYr37: { /* variable : TWP_DOLLAR TWP_LPAREN variable_name TWP_RPAREN */ -#line 618 "policy.y" +// #line 618 "policy.y" cDebug d( " parser::variable" ); @@ -1082,7 +1085,7 @@ case YYr37: { /* variable : TWP_DOLLAR TWP_LPAREN variable_name TWP_RPAREN */ } break; case YYr38: { /* prop_vector : multi_string */ -#line 662 "policy.y" +// #line 662 "policy.y" yyval.mpString = new cParseString; *yyval.mpString = ConcatenateStrings( yypvt[0].mpStringList ); @@ -1091,7 +1094,7 @@ case YYr38: { /* prop_vector : multi_string */ } break; case YYr39: { /* attribute_name : string */ -#line 671 "policy.y" +// #line 671 "policy.y" cDebug d(" parser::string(attribute_name)"); yyval.mpString = yypvt[0].mpString; @@ -1099,7 +1102,7 @@ case YYr39: { /* attribute_name : string */ } break; case YYr40: { /* attribute_value : multi_string */ -#line 679 "policy.y" +// #line 679 "policy.y" yyval.mpString = new cParseString; cDebug d(" parser::multi_string(attribute_value)"); @@ -1109,7 +1112,7 @@ case YYr40: { /* attribute_value : multi_string */ } break; case YYr41: { /* fco_name : multi_string */ -#line 689 "policy.y" +// #line 689 "policy.y" cDebug d(" parser::multi_string(fco_name)"); yyval.mpStringList = yypvt[0].mpStringList; @@ -1117,7 +1120,7 @@ case YYr41: { /* fco_name : multi_string */ } break; case YYr42: { /* fco_name : multi_string TWP_PIPE multi_string */ -#line 695 "policy.y" +// #line 695 "policy.y" yypvt[-2].mpStringList->push_back( _T("|") ); @@ -1129,7 +1132,7 @@ case YYr42: { /* fco_name : multi_string TWP_PIPE multi_string */ } break; case YYr43: { /* host_name : string */ -#line 710 "policy.y" +// #line 710 "policy.y" cDebug d(" parser::multi_string(host_name)"); @@ -1138,7 +1141,7 @@ case YYr43: { /* host_name : string */ } break; case YYr44: { /* variable_name : TWP_STRING */ -#line 719 "policy.y" +// #line 719 "policy.y" cDebug d(" parser::string(variable_name)"); yyval.mpString = yypvt[0].mpString; @@ -1146,7 +1149,7 @@ case YYr44: { /* variable_name : TWP_STRING */ } break; case YYr45: { /* multi_string : multi_string string */ -#line 728 "policy.y" +// #line 728 "policy.y" yyval.mpStringList->push_back( *yypvt[0].mpString ); delete yypvt[0].mpString; @@ -1154,7 +1157,7 @@ case YYr45: { /* multi_string : multi_string string */ } break; case YYr46: { /* multi_string : string */ -#line 733 "policy.y" +// #line 733 "policy.y" yyval.mpStringList = new cParseStringList; yyval.mpStringList->push_back( *yypvt[0].mpString ); @@ -1163,7 +1166,7 @@ case YYr46: { /* multi_string : string */ } break; case YYr47: { /* global_multi_string : global_multi_string global_string */ -#line 742 "policy.y" +// #line 742 "policy.y" yyval.mpStringList->push_back( *yypvt[0].mpString ); delete yypvt[0].mpString; @@ -1171,7 +1174,7 @@ case YYr47: { /* global_multi_string : global_multi_string global_string */ } break; case YYr48: { /* global_multi_string : global_string */ -#line 747 "policy.y" +// #line 747 "policy.y" yyval.mpStringList = new cParseStringList; yyval.mpStringList->push_back( *yypvt[0].mpString ); @@ -1180,7 +1183,7 @@ case YYr48: { /* global_multi_string : global_string */ } break; case YYr49: { /* string : TWP_STRING */ -#line 757 "policy.y" +// #line 757 "policy.y" cDebug d(" parser::string(normal)"); d.TraceNever("--(STRING)--> got string (%s)\n", yypvt[0].mpString); @@ -1189,7 +1192,7 @@ case YYr49: { /* string : TWP_STRING */ } break; case YYr50: { /* string : variable */ -#line 763 "policy.y" +// #line 763 "policy.y" cDebug d(" parser::string(normal)"); d.TraceNever("--(STRING)--> got string (%s)\n", yypvt[0].mpString); @@ -1198,14 +1201,14 @@ case YYr50: { /* string : variable */ } break; case YYr51: { /* global_string : TWP_GLOBAL_STRING */ -#line 772 "policy.y" +// #line 772 "policy.y" cDebug d(" parser::string(normal)"); d.TraceNever("--(STRING)--> got string (%s)\n", yypvt[0].mpString); yyval.mpString = yypvt[0].mpString; } break; -#line 343 "..\\..\\mkslexyacc\\etc\\yyparse.cpp" +// #line 343 "..\\..\\mkslexyacc\\etc\\yyparse.cpp" case YYrACCEPT: YYACCEPT; case YYrERROR: @@ -1265,7 +1268,7 @@ yyerrlabel: ; /* come here from YYERROR */ , yytp-- #endif ) { -#ifdef YACC_WINDOWS +#if 0 //YACC_WINDOWS if (*yyps >= Sizeof_yypact) /* simple state */ #else /* YACC_WINDOWS */ if (*yyps >= (int)sizeof yypact/(int)sizeof yypact[0]) @@ -1393,7 +1396,7 @@ yy_parse::yyExpandName(int num, int isrule, char * buf, int len) for (endp = buf + len - 8; *s; s++) { if (buf >= endp) { /* too large: return 0 */ - full: (void) strcpy(buf, " ...\n"); + full: (void) strncpy(buf, " ...\n", len); return 0; } else if (*s == '%') { /* nonterminal */ type = 0; @@ -1423,7 +1426,7 @@ yy_parse::yyExpandName(int num, int isrule, char * buf, int len) if ((i = strlen(cp)) + buf > endp) goto full; - (void) strcpy(buf, cp); + (void) strncpy(buf, cp, len); buf += i; } else *buf++ = *s; diff --git a/src/twparser/yyparse.h b/src/twparser/yyparse.h index 6a09190..348ad6d 100644 --- a/src/twparser/yyparse.h +++ b/src/twparser/yyparse.h @@ -1,6 +1,6 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. // @@ -133,7 +133,7 @@ typedef struct yyTypedRules_tag { /* Typed rule table */ } yyTypedRules; #endif -#ifdef YACC_WINDOWS +#if 0 // YACC_WINDOWS // include all windows prototypes, macros, constants, etc. @@ -155,7 +155,7 @@ extern HANDLE hInst; class yy_parse { protected: -#ifdef YACC_WINDOWS +#if 0 // YACC_WINDOWS // protected member function for actual scanning diff --git a/src/twprint/Makefile.am b/src/twprint/Makefile.am index 5e6ee90..6b09237 100644 --- a/src/twprint/Makefile.am +++ b/src/twprint/Makefile.am @@ -1,18 +1,23 @@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. LIBS = -ltripwire -lcryptlib @LIBS@ LDFLAGS = @LDFLAGS@ -L../../lib LN_S = @LN@ sbin_PROGRAMS = twprint +twprintdir=. twprint_SOURCES = \ stdtwprint.cpp twprint.cpp twprintcmdline.cpp twprinterrors.cpp \ twprintmain.cpp twprintstrings.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../bin/twprint +twprint_HEADERS = \ + resource.h stdtwprint.h twprint.h twprintcmdline.h \ + twprinterrors.h twprintstrings.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = ../../bin/twprint *.gcno *.gcda all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin diff --git a/src/twprint/Makefile.in b/src/twprint/Makefile.in index 4b4a64a..afaa7af 100644 --- a/src/twprint/Makefile.in +++ b/src/twprint/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(twprint_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,43 +87,117 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ sbin_PROGRAMS = twprint$(EXEEXT) subdir = src/twprint -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(twprint_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twprintdir)" PROGRAMS = $(sbin_PROGRAMS) am_twprint_OBJECTS = stdtwprint.$(OBJEXT) twprint.$(OBJEXT) \ twprintcmdline.$(OBJEXT) twprinterrors.$(OBJEXT) \ twprintmain.$(OBJEXT) twprintstrings.$(OBJEXT) twprint_OBJECTS = $(am_twprint_OBJECTS) twprint_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(twprint_SOURCES) DIST_SOURCES = $(twprint_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +HEADERS = $(twprint_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -88,7 +213,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -96,6 +221,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -107,6 +233,7 @@ LN = @LN@ LN_S = @LN@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -123,21 +250,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -167,20 +297,29 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. +twprintdir = . twprint_SOURCES = \ stdtwprint.cpp twprint.cpp twprintcmdline.cpp twprinterrors.cpp \ twprintmain.cpp twprintstrings.cpp -CLEANFILES = ../../bin/twprint +twprint_HEADERS = \ + resource.h stdtwprint.h twprint.h twprintcmdline.h \ + twprinterrors.h twprintstrings.h + +CLEANFILES = ../../bin/twprint *.gcno *.gcda all: all-am .SUFFIXES: @@ -189,15 +328,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twprint/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/twprint/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twprint/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/twprint/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -214,32 +352,53 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): install-sbinPROGRAMS: $(sbin_PROGRAMS) @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(mkdir_p) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(sbindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(sbindir)" || exit 1; \ + fi; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p \ + ; then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' \ + -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || exit $$?; \ + } \ + ; done uninstall-sbinPROGRAMS: @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' \ + `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(sbindir)" && rm -f $$files clean-sbinPROGRAMS: -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -twprint$(EXEEXT): $(twprint_OBJECTS) $(twprint_DEPENDENCIES) + +twprint$(EXEEXT): $(twprint_OBJECTS) $(twprint_DEPENDENCIES) $(EXTRA_twprint_DEPENDENCIES) @rm -f twprint$(EXEEXT) - $(CXXLINK) $(twprint_LDFLAGS) $(twprint_OBJECTS) $(twprint_LDADD) $(LIBS) + $(AM_V_CXXLD)$(CXXLINK) $(twprint_OBJECTS) $(twprint_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -248,93 +407,120 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-twprintHEADERS: $(twprint_HEADERS) + @$(NORMAL_INSTALL) + @list='$(twprint_HEADERS)'; test -n "$(twprintdir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(twprintdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(twprintdir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(twprintdir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(twprintdir)" || exit $$?; \ + done + +uninstall-twprintHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(twprint_HEADERS)'; test -n "$(twprintdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(twprintdir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + for dir in "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twprintdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -346,17 +532,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -376,18 +568,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-twprintHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: install-sbinPROGRAMS +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -406,22 +618,30 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-sbinPROGRAMS +uninstall-am: uninstall-sbinPROGRAMS uninstall-twprintHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-sbinPROGRAMS ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-sbinPROGRAMS install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-sbinPROGRAMS cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-sbinPROGRAMS \ + install-strip install-twprintHEADERS installcheck \ + installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am uninstall-sbinPROGRAMS + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-sbinPROGRAMS uninstall-twprintHEADERS + +.PRECIOUS: Makefile all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/twprint/resource.h b/src/twprint/resource.h index 8fc8ab8..81aac68 100644 --- a/src/twprint/resource.h +++ b/src/twprint/resource.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,13 +35,12 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 +# ifndef APSTUDIO_READONLY_SYMBOLS +# define _APS_NEXT_RESOURCE_VALUE 102 +# define _APS_NEXT_COMMAND_VALUE 40001 +# define _APS_NEXT_CONTROL_VALUE 1000 +# define _APS_NEXT_SYMED_VALUE 101 +# endif #endif -#endif - diff --git a/src/twprint/stdtwprint.cpp b/src/twprint/stdtwprint.cpp index 6894eb9..5a7e3a9 100644 --- a/src/twprint/stdtwprint.cpp +++ b/src/twprint/stdtwprint.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // #include "stdtwprint.h" - -// eof: stdtwprint.cpp diff --git a/src/twprint/stdtwprint.h b/src/twprint/stdtwprint.h index 141f9c1..0ffcee4 100644 --- a/src/twprint/stdtwprint.h +++ b/src/twprint/stdtwprint.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/twprint/twprint.cpp b/src/twprint/twprint.cpp index 921a4dd..add7d4d 100644 --- a/src/twprint/twprint.cpp +++ b/src/twprint/twprint.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,11 +42,11 @@ #include "stdtwprint.h" #include "twprint.h" -#include "tw/tw.h" // for cTW +#include "tw/tw.h" // for cTW #include "twprinterrors.h" #include "core/errortable.h" -TSS_ImplementPackage( cTWPrint ) +TSS_ImplementPackage(cTWPrint) //============================================================================= // cTWPrint::cTWPrint() @@ -65,8 +65,6 @@ cTWPrint::cTWPrint() // // set up dependencies // - TSS_Dependency( cTW ); - TSS_REGISTER_PKG_ERRORS ( twprint ); + TSS_Dependency(cTW); + TSS_REGISTER_PKG_ERRORS(twprint); } - -// eof: twprint.cpp diff --git a/src/twprint/twprint.h b/src/twprint/twprint.h index 635eb91..4ebf829 100644 --- a/src/twprint/twprint.h +++ b/src/twprint/twprint.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,18 +42,17 @@ //--Requirements -#include "core/package.h" // for: Packaging Abstraction +#include "core/package.h" // for: Packaging Abstraction //--Classes -TSS_BeginPackage( cTWPrint ) +TSS_BeginPackage(cTWPrint) TSS_DECLARE_STRINGTABLE; - - public: - cTWPrint(); -TSS_EndPackage( cTWPrint ) +public: +cTWPrint(); -#endif //#ifndef __TWPRINT_H +TSS_EndPackage(cTWPrint) +#endif //#ifndef __TWPRINT_H diff --git a/src/twprint/twprintcmdline.cpp b/src/twprint/twprintcmdline.cpp index 3057b09..50762fc 100644 --- a/src/twprint/twprintcmdline.cpp +++ b/src/twprint/twprintcmdline.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,22 +34,22 @@ // #include "stdtwprint.h" #include "twprintcmdline.h" -#include "twprintstrings.h" // strings specific to twprint -#include "twprintcmdline.h" // functions for the cmd line +#include "twprintstrings.h" // strings specific to twprint +#include "twprintcmdline.h" // functions for the cmd line #include "twprinterrors.h" #include "core/cmdlineparser.h" #include "core/errorgeneral.h" -#include "core/errorbucketimpl.h" // for the error table -#include "core/usernotify.h" // for notifying the user of even -#include "core/serializerimpl.h" // cSerializerImpl -#include "core/archive.h" // cArchive and friends +#include "core/errorbucketimpl.h" // for the error table +#include "core/usernotify.h" // for notifying the user of even +#include "core/serializerimpl.h" // cSerializerImpl +#include "core/archive.h" // cArchive and friends #include "tw/configfile.h" #include "tw/fcodatabasefile.h" // cFCODatabaseFile -#include "tw/fcoreport.h" // for reports +#include "tw/fcoreport.h" // for reports #include "tw/textdbviewer.h" -#include "tw/textreportviewer.h" // text report viewer +#include "tw/textreportviewer.h" // text report viewer #include "tw/twutil.h" #include "tw/headerinfo.h" #include "tw/systeminfo.h" @@ -57,14 +57,14 @@ #include "tw/dbdatasource.h" #include "tw/twstrings.h" -#include "twcrypto/keyfile.h" // cKeyFile -- used for encryption +#include "twcrypto/keyfile.h" // cKeyFile -- used for encryption #include "util/fileutil.h" #include "fco/fcogenre.h" #include "fco/genreswitcher.h" #include "fco/twfactory.h" -#include "fco/fcospeclist.h" // cFCOSpecList +#include "fco/fcospeclist.h" // cFCOSpecList #include "fco/fcopropdisplayer.h" #include "fco/signature.h" @@ -74,8 +74,8 @@ // Static functions -- /////////////////////////////////////////////////////////////////////////////// static void InitCmdLineCommon(cCmdLineParser& parser); - // A method for initializing the command line parser with arguments that - // are common to all modes of twprint. +// A method for initializing the command line parser with arguments that +// are common to all modes of twprint. //############################################################################# // cTWPrintCmdLine @@ -83,46 +83,51 @@ static void InitCmdLineCommon(cCmdLineParser& parser); // this is used to make required condition checking in the Init() functions a little more compact -#define TEST_INIT_REQUIREMENT(t, n)\ - if(! t)\ - {\ - TCERR << TSS_GetString(cTW, n) << std::endl;\ - return false;\ +#define TEST_INIT_REQUIREMENT(t, n) \ + if (!t) \ + { \ + TCERR << TSS_GetString(cTW, n) << std::endl; \ + return false; \ } // TODO: get Matt to update this with changes he made to tripwire /////////////////////////////////////////////////////////////////////////////// -// InitCmdLineCommon -- +// InitCmdLineCommon -- // Initialize the cmdlineparser with the arguments that are common -// to all modes. Other parameters must be added in the +// to all modes. Other parameters must be added in the // InitCmdLineParser method of the derived mode. /////////////////////////////////////////////////////////////////////////////// static void InitCmdLineCommon(cCmdLineParser& parser) { // help - parser.AddArg(cTWPrintCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_NONE); // mode - parser.AddArg(cTWPrintCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWPrintCmdLine::MODE_DBPRINT, TSTRING(_T("")), TSTRING(_T("print-dbfile")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWPrintCmdLine::MODE_REPORTPRINT,TSTRING(_T("")), TSTRING(_T("print-report")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWPrintCmdLine::MODE_DBPRINT, TSTRING(_T("")), TSTRING(_T("print-dbfile")), cCmdLineParser::PARAM_NONE); + parser.AddArg( + cTWPrintCmdLine::MODE_REPORTPRINT, TSTRING(_T("")), TSTRING(_T("print-report")), cCmdLineParser::PARAM_NONE); // reporting - parser.AddArg(cTWPrintCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWPrintCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); - parser.AddArg(cTWPrintCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::VERBOSE, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::SILENT, TSTRING(_T("s")), TSTRING(_T("silent")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::SILENT, TSTRING(_T("")), TSTRING(_T("quiet")), cCmdLineParser::PARAM_NONE); // config file overrides - parser.AddArg(cTWPrintCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWPrintCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); - parser.AddArg(cTWPrintCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); - + parser.AddArg(cTWPrintCmdLine::CFG_FILE, TSTRING(_T("c")), TSTRING(_T("cfgfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWPrintCmdLine::LOCAL_KEY_FILE, TSTRING(_T("L")), TSTRING(_T("local-keyfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWPrintCmdLine::SITE_KEY_FILE, TSTRING(_T("S")), TSTRING(_T("site-keyfile")), cCmdLineParser::PARAM_ONE); + // unattended operation - parser.AddArg(cTWPrintCmdLine::PASSPHRASE, TSTRING(_T("P")), TSTRING(_T("passphrase")), cCmdLineParser::PARAM_ONE); - - - parser.AddArg(cTWPrintCmdLine::HEXADECIMAL, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); + parser.AddArg(cTWPrintCmdLine::PASSPHRASE, TSTRING(_T("P")), TSTRING(_T("passphrase")), cCmdLineParser::PARAM_ONE); + + + parser.AddArg( + cTWPrintCmdLine::HEXADECIMAL, TSTRING(_T("h")), TSTRING(_T("hexadecimal")), cCmdLineParser::PARAM_NONE); // the paramters to the command line ... for now, this will take "many", even though in some // modes, this is not valid to do... @@ -131,23 +136,23 @@ static void InitCmdLineCommon(cCmdLineParser& parser) // functionality out) so I changed this to PARAM_NONE. // NOTE -- We __DO__ take "naked" parameters in print-database mode, contrary to the above comment!!! It is an error - // to add this argument here, in the "common" code between the two modes of twprint. I'm moving the PARAMS arg to + // to add this argument here, in the "common" code between the two modes of twprint. I'm moving the PARAMS arg to // twprint --print-database's "personal" initialization (below). -DRA 8/9/99 //parser.AddArg(cTWPrintCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::/*PARAM_NONE*/PARAM_MANY); - // Error for print-report!!!! + // Error for print-report!!!! parser.AddMutEx(cTWPrintCmdLine::VERBOSE, cTWPrintCmdLine::SILENT); } /////////////////////////////////////////////////////////////////////////////// -// GetMode -- processes the command line arguments and creates an appropriate +// GetMode -- processes the command line arguments and creates an appropriate // structure for the selected mode, or NULL if an error occurs /////////////////////////////////////////////////////////////////////////////// -iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) +iTWMode* cTWPrintCmdLine::GetMode(int argc, const TCHAR* const* argv) { // note -- it is assumed the executable name is the first parameter - if(argc < 2) + if (argc < 2) { TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_VERSION) << std::endl; TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; @@ -155,11 +160,11 @@ iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) return NULL; } - int mode = MODE; + int mode = MODE; const TCHAR* pcMode; - if(_tcscmp(argv[1], _T("-m")) == 0) + if (_tcscmp(argv[1], _T("-m")) == 0) { - if(argc < 3) + if (argc < 3) { TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_VERSION) << std::endl; TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; @@ -168,7 +173,7 @@ iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) return NULL; } pcMode = argv[2]; - if (_tcscmp(argv[2], _T("d")) == 0) + if (_tcscmp(argv[2], _T("d")) == 0) mode = MODE_DBPRINT; else if (_tcscmp(argv[2], _T("r")) == 0) mode = MODE_REPORTPRINT; @@ -176,7 +181,7 @@ iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) else { pcMode = argv[1]; - if (_tcscmp(argv[1], _T("--print-dbfile")) == 0) + if (_tcscmp(argv[1], _T("--print-dbfile")) == 0) mode = MODE_DBPRINT; else if (_tcscmp(argv[1], _T("--print-report")) == 0) mode = MODE_REPORTPRINT; @@ -188,20 +193,20 @@ iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) else if (_tcscmp(argv[1], _T("--help")) == 0 || _tcscmp(argv[1], _T("-?")) == 0) mode = MODE_HELP; } - - if(mode == MODE) + + if (mode == MODE) { // unknown mode switch cDebug d("cTWPrintCmdLine::GetMode"); d.TraceError(_T("Error: Bad mode switch: %s\n"), pcMode); - TCERR << TSS_GetString(cTW, tw::STR_UNKOWN_MODE_SPECIFIED) << pcMode << std::endl; + TCERR << TSS_GetString(cTW, tw::STR_UNKNOWN_MODE_SPECIFIED) << pcMode << std::endl; TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; return NULL; } iTWMode* pRtn = 0; - switch(mode) + switch (mode) { case cTWPrintCmdLine::MODE_DBPRINT: pRtn = new cTWPrintDBMode; @@ -226,14 +231,16 @@ iTWMode* cTWPrintCmdLine::GetMode( int argc, const TCHAR* const * argv ) class cTWPrintModeCommon { public: - int mVerbosity; // must be 0 <= n <= 2 - std::string mPassPhrase; // pass phrase for private key + int mVerbosity; // must be 0 <= n <= 2 + std::string mPassPhrase; // pass phrase for private key TSTRING mLocalKeyFile; TSTRING mSiteKeyFile; TSTRING mConfigFilePath; - cTWPrintModeCommon() : mVerbosity(1) {} - cTextReportViewer::ReportingLevel mReportLevel; // The level of reporting to use. + cTWPrintModeCommon() : mVerbosity(1) + { + } + cTextReportViewer::ReportingLevel mReportLevel; // The level of reporting to use. }; /////////////////////////////////////////////////////////////////////////////// @@ -242,86 +249,57 @@ class cTWPrintModeCommon static void FillOutCommonConfigInfo(cTWPrintModeCommon* pModeInfo, const cConfigFile& cf) { TSTRING str; - if(cf.Lookup(TSTRING(_T("LOCALKEYFILE")), str)) + if (cf.Lookup(TSTRING(_T("LOCALKEYFILE")), str)) pModeInfo->mLocalKeyFile = str; - if(cf.Lookup(TSTRING(_T("SITEKEYFILE")), str)) + if (cf.Lookup(TSTRING(_T("SITEKEYFILE")), str)) pModeInfo->mSiteKeyFile = str; - // + // // turn all of the file names into full paths (they're relative to the exe dir) - // + // TSTRING fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mLocalKeyFile, cSystemInfo::GetExeDir() )) + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mLocalKeyFile, cSystemInfo::GetExeDir())) pModeInfo->mLocalKeyFile = fullPath; } /////////////////////////////////////////////////////////////////////////////// -// FillOutCmdLineInfo -- fills out info common to all modes that appears on the +// FillOutCmdLineInfo -- fills out info common to all modes that appears on the // command line. /////////////////////////////////////////////////////////////////////////////// static void FillOutCmdLineInfo(cTWPrintModeCommon* pModeInfo, const cCmdLineParser& cmdLine) { cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { - case cTWPrintCmdLine::VERBOSE: - pModeInfo->mVerbosity = 2; + case cTWPrintCmdLine::VERBOSE: + pModeInfo->mVerbosity = 2; break; - case cTWPrintCmdLine::SILENT: - pModeInfo->mVerbosity = 0; + case cTWPrintCmdLine::SILENT: + pModeInfo->mVerbosity = 0; break; - case cTWPrintCmdLine::LOCAL_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mLocalKeyFile = iter.ParamAt(0); + case cTWPrintCmdLine::LOCAL_KEY_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mLocalKeyFile = iter.ParamAt(0); break; - case cTWPrintCmdLine::SITE_KEY_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - pModeInfo->mSiteKeyFile = iter.ParamAt(0); + case cTWPrintCmdLine::SITE_KEY_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mSiteKeyFile = iter.ParamAt(0); break; - case cTWPrintCmdLine::HEXADECIMAL: - cArchiveSigGen::SetHex(true); - break; - case cTWPrintCmdLine::PASSPHRASE: - { - // this bites! I have to make sure it is a narrow char string - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser -#ifdef _UNICODE - char* buf = new char[2*(wcslen(iter.ParamAt(0).c_str()) + 1)]; - wcstombs(buf, iter.ParamAt(0).c_str(), sizeof(buf)); - pModeInfo->mPassPhrase = buf; - delete [] buf; -#else - pModeInfo->mPassPhrase = iter.ParamAt(0); -#endif - } + case cTWPrintCmdLine::HEXADECIMAL: + cArchiveSigGen::SetHex(true); + break; + case cTWPrintCmdLine::PASSPHRASE: + { + // this bites! I have to make sure it is a narrow char string + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + pModeInfo->mPassPhrase = iter.ParamAt(0); + break; + } + default: break; - case cTWPrintCmdLine::REPORTLEVEL: - { - if ( iter.ParamAt(0) == _T("0")) - pModeInfo->mReportLevel = cTextReportViewer::SINGLE_LINE; - else if( iter.ParamAt(0) == _T("1") ) - pModeInfo->mReportLevel = cTextReportViewer::PARSEABLE; - else if( iter.ParamAt(0) == _T("2") ) - pModeInfo->mReportLevel = cTextReportViewer::SUMMARY_ONLY; - else if( iter.ParamAt(0) == _T("3") ) - pModeInfo->mReportLevel = cTextReportViewer::CONCISE_REPORT; - else if( iter.ParamAt(0) == _T("4") ) - pModeInfo->mReportLevel = cTextReportViewer::FULL_REPORT; - else - { - // They specified an illegal level, error. - TSTRING errStr = _T("Invalid Level: "); - errStr += iter.ParamAt(0); - throw eTWPrintInvalidReportLevel( errStr ); - } - } - //done with report-level stuff. - break; - default: - break; } } @@ -335,14 +313,17 @@ static void FillOutCmdLineInfo(cTWPrintModeCommon* pModeInfo, const cCmdLinePars //############################################################################# class cTWPrintReportMode_i : public cTWPrintModeCommon { -public: - TSTRING mReportFile; +public: + TSTRING mReportFile; + std::set mFilesToCheck; // ctor can set up some default values - cTWPrintReportMode_i() : cTWPrintModeCommon(){} + cTWPrintReportMode_i() : cTWPrintModeCommon() + { + } }; -void cTWPrintReportMode::SetConfigFile( TSTRING configFilePath ) +void cTWPrintReportMode::SetConfigFile(TSTRING configFilePath) { mpData->mConfigFilePath = configFilePath; } @@ -353,12 +334,12 @@ void cTWPrintReportMode::SetConfigFile( TSTRING configFilePath ) void cTWPrintReportMode::FillOutReportModeConfigInfo(cTWPrintReportMode_i* pModeInfo, const cConfigFile& cf) { TSTRING str; - if(cf.Lookup(TSTRING(_T("REPORTFILE")), str)) + if (cf.Lookup(TSTRING(_T("REPORTFILE")), str)) pModeInfo->mReportFile = str; - + // Find out what level of reporting we should use, use default level if none // has been specified. - if(cf.Lookup(TSTRING(_T("REPORTLEVEL")), str)) + if (cf.Lookup(TSTRING(_T("REPORTLEVEL")), str)) { if (_tcsicmp(str.c_str(), _T("0")) == 0) /*throw eTWPrintReportLevelZeroCfg( TSS_GetString( cTWPrint, twprint::STR_ERR2_REPORT_LEVEL_ZERO_CFG ) ); @@ -374,22 +355,22 @@ void cTWPrintReportMode::FillOutReportModeConfigInfo(cTWPrintReportMode_i* pMode else if (_tcsicmp(str.c_str(), _T("4")) == 0) pModeInfo->mReportLevel = cTextReportViewer::FULL_REPORT; else - { + { // They specified an illegal level, error. TSTRING errStr = _T("Invalid Level: "); errStr += str; - throw eTWPrintInvalidReportLevelCfg( errStr ); + throw eTWPrintInvalidReportLevelCfg(errStr); } } else // Use the default level of reporting, they specified none in configuration file. pModeInfo->mReportLevel = cTextReportViewer::CONCISE_REPORT; - // + // // turn all of the file names into full paths (they're relative to the exe dir) - // + // TSTRING fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mReportFile, cSystemInfo::GetExeDir() )) + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mReportFile, cSystemInfo::GetExeDir())) pModeInfo->mReportFile = fullPath; } @@ -411,12 +392,16 @@ cTWPrintReportMode::~cTWPrintReportMode() /////////////////////////////////////////////////////////////////////////////// void cTWPrintReportMode::InitCmdLineParser(cCmdLineParser& parser) { - InitCmdLineCommon( parser ); + InitCmdLineCommon(parser); - parser.AddArg(cTWPrintCmdLine::REPORT_FILE, TSTRING(_T("r")), TSTRING(_T("twrfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWPrintCmdLine::REPORT_FILE, TSTRING(_T("r")), TSTRING(_T("twrfile")), cCmdLineParser::PARAM_ONE); // multiple levels of reporting - parser.AddArg(cTWPrintCmdLine::REPORTLEVEL, TSTRING(_T("t")), TSTRING(_T("report-level")), cCmdLineParser::PARAM_ONE); + parser.AddArg( + cTWPrintCmdLine::REPORTLEVEL, TSTRING(_T("t")), TSTRING(_T("report-level")), cCmdLineParser::PARAM_ONE); + + // For the variable object list. + parser.AddArg(cTWPrintCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); } /////////////////////////////////////////////////////////////////////////////// @@ -427,7 +412,7 @@ bool cTWPrintReportMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLi // first, fill out everything with the config file info... FillOutCommonConfigInfo(mpData, cf); FillOutReportModeConfigInfo(mpData, cf); - + // TODO -- should I error or warn for (1) mutual exclustion errors or (2) unneeded cmd line // parameters? I think I should, but I won't right now. // TODO -- error at the end of Init() if I am missing any requires parameter values.. @@ -438,60 +423,70 @@ bool cTWPrintReportMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLi // now do the stuff specific to this mode... cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { - case cTWPrintCmdLine::REPORT_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mpData->mReportFile = iter.ParamAt(0); + case cTWPrintCmdLine::REPORT_FILE: + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mpData->mReportFile = iter.ParamAt(0); break; - case cTWPrintCmdLine::REPORTLEVEL: - { - if ( iter.ParamAt(0) == _T("0")) - mpData->mReportLevel = cTextReportViewer::SINGLE_LINE; - else if( iter.ParamAt(0) == _T("1") ) - mpData->mReportLevel = cTextReportViewer::PARSEABLE; - else if( iter.ParamAt(0) == _T("2") ) - mpData->mReportLevel = cTextReportViewer::SUMMARY_ONLY; - else if( iter.ParamAt(0) == _T("3") ) - mpData->mReportLevel = cTextReportViewer::CONCISE_REPORT; - else if( iter.ParamAt(0) == _T("4") ) - mpData->mReportLevel = cTextReportViewer::FULL_REPORT; - else - { - // They specified an illegal level, error. - TSTRING errStr = _T("Invalid Level: "); - errStr += iter.ParamAt(0); - throw eTWPrintInvalidReportLevel( errStr ); - } - } - //done with report-level stuff. + case cTWPrintCmdLine::REPORTLEVEL: + { + if (iter.ParamAt(0) == _T("0")) + mpData->mReportLevel = cTextReportViewer::SINGLE_LINE; + else if (iter.ParamAt(0) == _T("1")) + mpData->mReportLevel = cTextReportViewer::PARSEABLE; + else if (iter.ParamAt(0) == _T("2")) + mpData->mReportLevel = cTextReportViewer::SUMMARY_ONLY; + else if (iter.ParamAt(0) == _T("3")) + mpData->mReportLevel = cTextReportViewer::CONCISE_REPORT; + else if (iter.ParamAt(0) == _T("4")) + mpData->mReportLevel = cTextReportViewer::FULL_REPORT; + else + { + // They specified an illegal level, error. + TSTRING errStr = _T("Invalid Level: "); + errStr += iter.ParamAt(0); + throw eTWPrintInvalidReportLevel(errStr); + } break; - default: - // should I do anything, or just ignore this? - ; + } + case cTWPrintCmdLine::PARAMS: + { + // pack all of these onto the files to check list... + mpData->mFilesToCheck.clear(); + for (int i = 0; i < iter.NumParams(); i++) + { + mpData->mFilesToCheck.insert(iter.ParamAt(i)); + } + } + //done with report-level stuff. + break; + default: + // should I do anything, or just ignore this? + ; } } - + //---------------------------------------- // I require the following information: // // * local key file // * report file //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mReportFile.empty()), tw::STR_ERR_MISSING_REPORT); + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mReportFile.empty()), tw::STR_ERR_MISSING_REPORT); // check that the config file and site key file are in sync... // - if( ! mpData->mConfigFilePath.empty() ) - try + if (!mpData->mConfigFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mpData->mConfigFilePath, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mpData->mConfigFilePath, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -505,37 +500,43 @@ bool cTWPrintReportMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLi /////////////////////////////////////////////////////////////////////////////// int cTWPrintReportMode::Execute(cErrorQueue* pQueue) { - cFCOReport report; - cFCOReportHeader reportHeader; - try { - ASSERT( ! mpData->mReportFile.empty() ); + ASSERT(!mpData->mReportFile.empty()); // make sure the report file exists... cFileUtil::TestFileExists(mpData->mReportFile); - cKeyFile localKeyfile; - const cElGamalSigPublicKey* pKey; - cFCOReport report; + cKeyFile localKeyfile; + const cElGamalSigPublicKey* pKey; + cFCOReport report; + cFCOReportHeader reportHeader; - cTWUtil::OpenKeyFile( localKeyfile, mpData->mLocalKeyFile ); + cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); pKey = localKeyfile.GetPublicKey(); - if( !cTWUtil::IsObjectEncrypted( mpData->mReportFile.c_str(), cFCOReport::GetFileHeaderID(), TSS_GetString( cTW, tw::STR_ERR_REPORT_READ ) ) ) + if (!cTWUtil::IsObjectEncrypted(mpData->mReportFile.c_str(), + cFCOReport::GetFileHeaderID(), + TSS_GetString(cTW, tw::STR_ERR_REPORT_READ))) { // note (rather than warn) if the database is not encrytped - iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, TSS_GetString(cTW, tw::STR_REPORT_NOT_ENCRYPTED).c_str()); + iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, + TSS_GetString(cTW, tw::STR_REPORT_NOT_ENCRYPTED).c_str()); } // open the report... bool bDummy; - cTWUtil::ReadReport( mpData->mReportFile.c_str(), reportHeader, report, pKey, false, bDummy ); + cTWUtil::ReadReport(mpData->mReportFile.c_str(), reportHeader, report, pKey, false, bDummy); // print it - cTextReportViewer trv( reportHeader, report ); - trv.PrintTextReport( _T("-"), mpData->mReportLevel ); + cTextReportViewer trv(reportHeader, report); + if (!mpData->mFilesToCheck.empty()) + { + trv.SetObjects(mpData->mFilesToCheck); + } + + trv.PrintTextReport(_T("-"), mpData->mReportLevel); } - catch(eError& e) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); return 1; @@ -547,9 +548,9 @@ int cTWPrintReportMode::Execute(cErrorQueue* pQueue) /////////////////////////////////////////////////////////////////////////////// // GetModeUsage -- returns a mode-specific usage statement. /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWPrintReportMode::GetModeUsage() +TSTRING cTWPrintReportMode::GetModeUsage() { - return TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT ); + return TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT); } //############################################################################# @@ -558,11 +559,14 @@ TSTRING cTWPrintReportMode::GetModeUsage() class cTWPrintDBMode_i : public cTWPrintModeCommon { public: - TSTRING mDbFile; - std::vector mFilesToCheck; + TSTRING mDbFile; + std::vector mFilesToCheck; + cTextDBViewer::DbVerbosity mDbVerbosity; // ctor can set up some default values - cTWPrintDBMode_i() : cTWPrintModeCommon() {} + cTWPrintDBMode_i() : cTWPrintModeCommon(), mDbVerbosity(cTextDBViewer::VERBOSE) + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -578,7 +582,7 @@ cTWPrintDBMode::~cTWPrintDBMode() delete mpData; } -void cTWPrintDBMode::SetConfigFile( TSTRING configFilePath ) +void cTWPrintDBMode::SetConfigFile(TSTRING configFilePath) { mpData->mConfigFilePath = configFilePath; } @@ -589,29 +593,52 @@ void cTWPrintDBMode::SetConfigFile( TSTRING configFilePath ) void cTWPrintDBMode::FillOutDBModeConfigInfo(cTWPrintDBMode_i* pModeInfo, const cConfigFile& cf) { TSTRING str; - if(cf.Lookup(TSTRING(_T("DBFILE")), str)) + if (cf.Lookup(TSTRING(_T("DBFILE")), str)) pModeInfo->mDbFile = str; - - // + + if (cf.Lookup(TSTRING(_T("DBPRINTLEVEL")), str)) + { + if (_tcsicmp(str.c_str(), _T("0")) == 0) + pModeInfo->mDbVerbosity = cTextDBViewer::SUMMARY; + else if (_tcsicmp(str.c_str(), _T("1")) == 0) + pModeInfo->mDbVerbosity = cTextDBViewer::CONCISE; + else if (_tcsicmp(str.c_str(), _T("2")) == 0) + pModeInfo->mDbVerbosity = cTextDBViewer::VERBOSE; + else + { + // They specified an illegal level, error. + TSTRING errStr = _T("Invalid Level: "); + errStr += str; + throw eTWPrintInvalidDbPrintLevelCfg(errStr); + } + } + else + // Use the default level of reporting, they specified none in configuration file. + pModeInfo->mVerbosity = cTextDBViewer::VERBOSE; + + // // turn all of the file names into full paths (they're relative to the exe dir) - // + // TSTRING fullPath; - if(iFSServices::GetInstance()->FullPath( fullPath, pModeInfo->mDbFile, cSystemInfo::GetExeDir() )) + if (iFSServices::GetInstance()->FullPath(fullPath, pModeInfo->mDbFile, cSystemInfo::GetExeDir())) pModeInfo->mDbFile = fullPath; } /////////////////////////////////////////////////////////////////////////////// // InitCmdLineParser /////////////////////////////////////////////////////////////////////////////// -void cTWPrintDBMode::InitCmdLineParser( cCmdLineParser& parser ) +void cTWPrintDBMode::InitCmdLineParser(cCmdLineParser& parser) { - InitCmdLineCommon( parser ); + InitCmdLineCommon(parser); - parser.AddArg(cTWPrintCmdLine::DB_FILE, TSTRING(_T("d")), TSTRING(_T("dbfile")), cCmdLineParser::PARAM_ONE); + parser.AddArg(cTWPrintCmdLine::DB_FILE, TSTRING(_T("d")), TSTRING(_T("dbfile")), cCmdLineParser::PARAM_ONE); - // For the variable object list. - parser.AddArg(cTWPrintCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + // multiple levels of reporting + parser.AddArg( + cTWPrintCmdLine::REPORTLEVEL, TSTRING(_T("t")), TSTRING(_T("output-level")), cCmdLineParser::PARAM_ONE); + // For the variable object list. + parser.AddArg(cTWPrintCmdLine::PARAMS, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); } /////////////////////////////////////////////////////////////////////////////// @@ -622,7 +649,7 @@ bool cTWPrintDBMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) // first, fill out everything with the config file info... FillOutCommonConfigInfo(mpData, cf); FillOutDBModeConfigInfo(mpData, cf); - + // TODO -- should I error or warn for (1) mutual exclustion errors or (2) unneeded cmd line // parameters? I think I should, but I won't right now. // TODO -- error at the end of Init() if I am missing any requires parameter values.. @@ -633,47 +660,67 @@ bool cTWPrintDBMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) // now do the stuff specific to this mode... cCmdLineIter iter(cmdLine); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) + { + + case cTWPrintCmdLine::DB_FILE: { - case cTWPrintCmdLine::DB_FILE: - ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser - mpData->mDbFile = iter.ParamAt(0); + ASSERT(iter.NumParams() > 0); // should be caught by cmd line parser + mpData->mDbFile = iter.ParamAt(0); break; - case cTWPrintCmdLine::PARAMS: - { - // pack all of these onto the files to check list... - mpData->mFilesToCheck.clear(); - for(int i=0; i < iter.NumParams(); i++) - { - mpData->mFilesToCheck.push_back(iter.ParamAt(i)); - } - } - default: - // TODO: should I do anything, or just ignore this? - ; + } + case cTWPrintCmdLine::REPORTLEVEL: + { + if (iter.ParamAt(0) == _T("0")) + mpData->mDbVerbosity = cTextDBViewer::SUMMARY; + else if (iter.ParamAt(0) == _T("1")) + mpData->mDbVerbosity = cTextDBViewer::CONCISE; + else if (iter.ParamAt(0) == _T("2")) + mpData->mDbVerbosity = cTextDBViewer::VERBOSE; + else + { + // They specified an illegal level, error. + TSTRING errStr = _T("Invalid Level: "); + errStr += iter.ParamAt(0); + throw eTWPrintInvalidDbPrintLevel(errStr); + } + break; + } + case cTWPrintCmdLine::PARAMS: + { + // pack all of these onto the files to check list... + mpData->mFilesToCheck.clear(); + for (int i = 0; i < iter.NumParams(); i++) + { + mpData->mFilesToCheck.push_back(iter.ParamAt(i)); + } + } + default: + // TODO: should I do anything, or just ignore this? + ; } } - + //---------------------------------------- // I require the following information: // // * local key file // * report file //----------------------------------------- - TEST_INIT_REQUIREMENT((! mpData->mLocalKeyFile.empty()), tw::STR_ERR_MISSING_LOCAL_KEY); - TEST_INIT_REQUIREMENT((! mpData->mDbFile.empty()), tw::STR_ERR_MISSING_DB); + TEST_INIT_REQUIREMENT((!mpData->mLocalKeyFile.empty()), tw::STR_ERR_MISSING_LOCAL_KEY); + TEST_INIT_REQUIREMENT((!mpData->mDbFile.empty()), tw::STR_ERR_MISSING_DB); // check that the config file and site key file are in sync... // - if( ! mpData->mConfigFilePath.empty() ) - try + if (!mpData->mConfigFilePath.empty()) + try { - if (cTWUtil::VerifyCfgSiteKey( mpData->mConfigFilePath, mpData->mSiteKeyFile ) == false) - cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + if (cTWUtil::VerifyCfgSiteKey(mpData->mConfigFilePath, mpData->mSiteKeyFile) == false) + cTWUtil::PrintErrorMsg(eTWCfgUnencrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } - catch (eTWUtilCfgKeyMismatch& e) + catch (eTWUtilCfgKeyMismatch& e) { e.SetFatality(false); cTWUtil::PrintErrorMsg(e); @@ -688,102 +735,105 @@ bool cTWPrintDBMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) int cTWPrintDBMode::Execute(cErrorQueue* pQueue) { cDebug d("cTWPrintDBMode::Execute"); - int ret = 0; + int ret = 0; try { - ASSERT( ! mpData->mDbFile.empty() ); + ASSERT(!mpData->mDbFile.empty()); // make sure the database file exists... cFileUtil::TestFileExists(mpData->mDbFile); - cFCODatabaseFile db; - cKeyFile localKeyfile; + cFCODatabaseFile db; + cKeyFile localKeyfile; const cElGamalSigPublicKey* pKey = 0; cTWUtil::OpenKeyFile(localKeyfile, mpData->mLocalKeyFile); pKey = localKeyfile.GetPublicKey(); - if( !cTWUtil::IsObjectEncrypted( mpData->mDbFile.c_str(), cFCODatabaseFile::GetFileHeaderID(), TSS_GetString( cTW, tw::STR_ERR_DB_READ ) ) ) + if (!cTWUtil::IsObjectEncrypted( + mpData->mDbFile.c_str(), cFCODatabaseFile::GetFileHeaderID(), TSS_GetString(cTW, tw::STR_ERR_DB_READ))) { // warn if the database is not encrytped - if(iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) + if (iUserNotify::GetInstance()->GetVerboseLevel() > iUserNotify::V_SILENT) { - cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + cTWUtil::PrintErrorMsg(eTWDbNotEncrypted(_T(""), eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } } - - // open the database; note that ReadDatabase will set bEncrypted and open the + + // open the database; note that ReadDatabase will set bEncrypted and open the // key file if necessary bool bDummy; cTWUtil::ReadDatabase(mpData->mDbFile.c_str(), db, pKey, bDummy); - if( mpData->mFilesToCheck.size() > 0 ) + if (mpData->mFilesToCheck.size() > 0) { + bool details = (mpData->mDbVerbosity == cTextDBViewer::VERBOSE); //------------------------------------------------ // print specific FCOs from the database //------------------------------------------------ cTWUtil::GenreObjList listOut; - cTWUtil::ParseObjectList( listOut, mpData->mFilesToCheck ); + cTWUtil::ParseObjectList(listOut, mpData->mFilesToCheck); // now, iterate through the list of objects... // - cFCODatabaseFile::iterator dbIter( db ); - for( cTWUtil::GenreObjList::iterator genreIter = listOut.begin(); genreIter != listOut.end(); genreIter++ ) + cFCODatabaseFile::iterator dbIter(db); + for (cTWUtil::GenreObjList::iterator genreIter = listOut.begin(); genreIter != listOut.end(); ++genreIter) { - dbIter.SeekToGenre( genreIter->first ); - if( ! dbIter.Done() ) + dbIter.SeekToGenre(genreIter->first); + if (!dbIter.Done()) { - cGenreSwitcher::GetInstance()->SelectGenre( (cGenre::Genre)dbIter.GetGenre() ); - cDbDataSourceIter dsIter( &dbIter.GetDb() ); + cGenreSwitcher::GetInstance()->SelectGenre((cGenre::Genre)dbIter.GetGenre()); + cDbDataSourceIter dsIter(&dbIter.GetDb()); dsIter.SetErrorBucket(pQueue); - iFCONameTranslator* pNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre( (cGenre::Genre)dbIter.GetGenre() )->GetNameTranslator(); + iFCONameTranslator* pNT = cGenreSwitcher::GetInstance() + ->GetFactoryForGenre((cGenre::Genre)dbIter.GetGenre()) + ->GetNameTranslator(); // // iterate over all the objects in this genre.... // - for(cTWUtil::ObjList::iterator it = genreIter->second.begin(); it != genreIter->second.end(); it++) + for (cTWUtil::ObjList::iterator it = genreIter->second.begin(); it != genreIter->second.end(); ++it) { try { - cFCOName name = cTWUtil::ParseObjectName( *it ); - dsIter.SeekToFCO( name, false ); - if( (! dsIter.Done()) && (dsIter.HasFCOData()) ) + cFCOName name = cTWUtil::ParseObjectName(*it); + dsIter.SeekToFCO(name, false); + if ((!dsIter.Done()) && (dsIter.HasFCOData())) { - cTextDBViewer::OutputFCO( dsIter, dbIter.GetGenreHeader().GetPropDisplayer(), pNT, &TCOUT ); + cTextDBViewer::OutputFCO( + dsIter, dbIter.GetGenreHeader().GetPropDisplayer(), pNT, &TCOUT, details); } else { - eTWUtilObjNotInDb e( *it ); - e.SetFatality( false ); - cTWUtil::PrintErrorMsg( e ); + eTWUtilObjNotInDb e(*it); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); } } - catch( eError& e) + catch (eError& e) { - e.SetFatality( false ); - cTWUtil::PrintErrorMsg( e ); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); } } - } else { - eTWDbDoesntHaveGenre e( cGenreSwitcher::GetInstance()->GenreToString( (cGenre::Genre)genreIter->first, true ) ); - e.SetFatality( false ); - cTWUtil::PrintErrorMsg( e ); + eTWDbDoesntHaveGenre e( + cGenreSwitcher::GetInstance()->GenreToString((cGenre::Genre)genreIter->first, true)); + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); } } - } else { //------------------------------------------------ // printing the entire db //------------------------------------------------ - cTextDBViewer::PrintDB( db, _T("-") ); + cTextDBViewer::PrintDB(db, _T("-"), mpData->mDbVerbosity); } - } - catch(eError& e) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); return 1; @@ -795,13 +845,12 @@ int cTWPrintDBMode::Execute(cErrorQueue* pQueue) /////////////////////////////////////////////////////////////////////////////// // GetModeUsage -- returns a mode-specific usage statement. /////////////////////////////////////////////////////////////////////////////// -TSTRING cTWPrintDBMode::GetModeUsage() +TSTRING cTWPrintDBMode::GetModeUsage() { - return TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE ); + return TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE); } - //############################################################################# // cTWPrintHelpMode //############################################################################# @@ -809,12 +858,16 @@ TSTRING cTWPrintDBMode::GetModeUsage() class cTWPrintHelpMode_i { public: - cTWPrintHelpMode_i() {} - ~cTWPrintHelpMode_i() {} + cTWPrintHelpMode_i() + { + } + ~cTWPrintHelpMode_i() + { + } // A list of modes to output usage statements for: - std::set< TSTRING > mlModes; - std::set< TSTRING > mPrinted; + std::set mlModes; + std::set mPrinted; }; @@ -831,7 +884,7 @@ cTWPrintHelpMode::~cTWPrintHelpMode() delete mpData; } -void cTWPrintHelpMode::SetConfigFile( TSTRING configFilePath ) +void cTWPrintHelpMode::SetConfigFile(TSTRING configFilePath) { } @@ -842,11 +895,13 @@ void cTWPrintHelpMode::InitCmdLineParser(cCmdLineParser& cmdLine) { // We're only interested in one parameter, that being help. Anything else // passed to this mode should be a cmdlineparser error. - cmdLine.AddArg(cTWPrintCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true); - cmdLine.AddArg(cTWPrintCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWPrintCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWPrintCmdLine::MODE_REPORTPRINT, TSTRING(_T("r")), TSTRING(_T("print-report")), cCmdLineParser::PARAM_MANY); - cmdLine.AddArg(cTWPrintCmdLine::MODE_DBPRINT, TSTRING(_T("d")), TSTRING(_T("print-dbfile")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWPrintCmdLine::MODE, TSTRING(_T("m")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY, true); + cmdLine.AddArg(cTWPrintCmdLine::MODE_HELP, TSTRING(_T("?")), TSTRING(_T("help")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg(cTWPrintCmdLine::MODE_HELP_ALL, TSTRING(_T("")), TSTRING(_T("all")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg( + cTWPrintCmdLine::MODE_REPORTPRINT, TSTRING(_T("r")), TSTRING(_T("print-report")), cCmdLineParser::PARAM_MANY); + cmdLine.AddArg( + cTWPrintCmdLine::MODE_DBPRINT, TSTRING(_T("d")), TSTRING(_T("print-dbfile")), cCmdLineParser::PARAM_MANY); } /////////////////////////////////////////////////////////////////////////////// @@ -857,51 +912,51 @@ bool cTWPrintHelpMode::Init(const cConfigFile& cf, const cCmdLineParser& cmdLine cCmdLineIter iter(cmdLine); // Grab the arguments from the help parameter: - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { - switch(iter.ArgId()) + switch (iter.ArgId()) { - case cTWPrintCmdLine::MODE_HELP: - { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - mpData->mlModes.insert( iter.ParamAt(i) ); - } - break; - case cTWPrintCmdLine::MODE: - { - int i; - for( i = 0; i < iter.NumParams(); ++i ) - { - mpData->mlModes.insert( iter.ParamAt(i) ); - } - } - break; - // Begin ugly hack so we can allow users to enter the mode - // names with "--" prepended. We have to do this, since - // the cmdlineparser treats them as switches. - case cTWPrintCmdLine::MODE_HELP_ALL: // fall through - case cTWPrintCmdLine::MODE_REPORTPRINT: // fall through - case cTWPrintCmdLine::MODE_DBPRINT: - { - int i; - TSTRING str = iter.ActualParam(); - // Kill off the initial "--" or "-" - str.erase( 0, 1 ); - if( str.length() != 1) - str.erase( 0, 1 ); - - // push back the parameter that was actually passed. - mpData->mlModes.insert( str ); - // grab all the "parameters" following the mode/switch, since - // they may be valid modes without the "--" prepended. - for( i = 0; i < iter.NumParams(); ++i ) - mpData->mlModes.insert( iter.ParamAt(i) ); - } - break; - default: - // should I do anything, or just ignore this? - ; + case cTWPrintCmdLine::MODE_HELP: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) + mpData->mlModes.insert(iter.ParamAt(i)); + } + break; + case cTWPrintCmdLine::MODE: + { + int i; + for (i = 0; i < iter.NumParams(); ++i) + { + mpData->mlModes.insert(iter.ParamAt(i)); + } + } + break; + // Begin ugly hack so we can allow users to enter the mode + // names with "--" prepended. We have to do this, since + // the cmdlineparser treats them as switches. + case cTWPrintCmdLine::MODE_HELP_ALL: // fall through + case cTWPrintCmdLine::MODE_REPORTPRINT: // fall through + case cTWPrintCmdLine::MODE_DBPRINT: + { + int i; + TSTRING str = iter.ActualParam(); + // Kill off the initial "--" or "-" + str.erase(0, 1); + if (str.length() != 1) + str.erase(0, 1); + + // push back the parameter that was actually passed. + mpData->mlModes.insert(str); + // grab all the "parameters" following the mode/switch, since + // they may be valid modes without the "--" prepended. + for (i = 0; i < iter.NumParams(); ++i) + mpData->mlModes.insert(iter.ParamAt(i)); + } + break; + default: + // should I do anything, or just ignore this? + ; } } @@ -916,13 +971,13 @@ int cTWPrintHelpMode::Execute(cErrorQueue* pQueue) cDebug d("cTWPrintHelpMode::Execute"); // The iterator we will use to traverse the list of arguments: - std::set< TSTRING >::iterator it = mpData->mlModes.begin(); + std::set::iterator it = mpData->mlModes.begin(); // We'll want to output the version information, regardless: TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_VERSION) << std::endl; - TCOUT << TSS_GetString( cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; - if( it == mpData->mlModes.end() ) // all that was passed was --help + if (it == mpData->mlModes.end()) // all that was passed was --help { // Output a short usage statement for each mode TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_USAGE_SUMMARY); @@ -931,44 +986,44 @@ int cTWPrintHelpMode::Execute(cErrorQueue* pQueue) return 1; } - for( ; it != mpData->mlModes.end(); ++it ) + for (; it != mpData->mlModes.end(); ++it) { - if( _tcscmp( (*it).c_str(), _T("all")) == 0 ) + if (_tcscmp((*it).c_str(), _T("all")) == 0) { //Since --help all was passed, emit all help messages and return. - TCOUT<< TSS_GetString( cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT ); - TCOUT<< TSS_GetString( cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE ); + TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT); + TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE); //We're done, return return 1; } } - + //We need some subset of the usage statements. Figure out which modes have //been specified: it = mpData->mlModes.begin(); - for( ; it != mpData->mlModes.end(); ++it ) + for (; it != mpData->mlModes.end(); ++it) { - if ( _tcscmp( (*it).c_str(), _T("print-report") ) == 0 || _tcscmp( (*it).c_str(), _T("r") ) == 0) + if (_tcscmp((*it).c_str(), _T("print-report")) == 0 || _tcscmp((*it).c_str(), _T("r")) == 0) { // make sure we don't print the same help twice... - if( mpData->mPrinted.find(_T("print-report")) == mpData->mPrinted.end() ) + if (mpData->mPrinted.find(_T("print-report")) == mpData->mPrinted.end()) { - TCOUT<< TSS_GetString( cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT ); - mpData->mPrinted.insert( _T("print-report") ); + TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_REPORT); + mpData->mPrinted.insert(_T("print-report")); } } - else if( _tcscmp( (*it).c_str(), _T("print-dbfile") ) == 0 || _tcscmp( (*it).c_str(), _T("d") ) == 0) + else if (_tcscmp((*it).c_str(), _T("print-dbfile")) == 0 || _tcscmp((*it).c_str(), _T("d")) == 0) { - if( mpData->mPrinted.find(_T("print-dbfile")) == mpData->mPrinted.end() ) + if (mpData->mPrinted.find(_T("print-dbfile")) == mpData->mPrinted.end()) { - TCOUT<< TSS_GetString( cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE ); - mpData->mPrinted.insert( _T("print-dbfile") ); + TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_HELP_PRINT_DATABASE); + mpData->mPrinted.insert(_T("print-dbfile")); } } else { - cTWUtil::PrintErrorMsg( eTWPrintInvalidParamHelp( (*it), eError::NON_FATAL ) ); + cTWUtil::PrintErrorMsg(eTWPrintInvalidParamHelp((*it), eError::NON_FATAL)); TCOUT << std::endl; // emit error/warning string, this mode does not exist } @@ -977,4 +1032,3 @@ int cTWPrintHelpMode::Execute(cErrorQueue* pQueue) //Everything went okay return 1; } - diff --git a/src/twprint/twprintcmdline.h b/src/twprint/twprintcmdline.h index b75fe4b..e9de366 100644 --- a/src/twprint/twprintcmdline.h +++ b/src/twprint/twprintcmdline.h @@ -1,37 +1,37 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// // twprintcmdline.h -// +// // cTWPrintCmdLine -- holds all information on twprint's command line // iTWMode -- abstract base class for a mode of operation in tripwire #ifndef __TWPRINTCMDLINE_H @@ -47,9 +47,11 @@ class cErrorQueue; class cErrorBucket; class iTWMode; -TSS_EXCEPTION( eTWPrintInvalidParamHelp, eError ) -TSS_EXCEPTION( eTWPrintInvalidReportLevel, eError ) -TSS_EXCEPTION( eTWPrintInvalidReportLevelCfg, eError ) +TSS_EXCEPTION(eTWPrintInvalidParamHelp, eError) +TSS_EXCEPTION(eTWPrintInvalidReportLevel, eError) +TSS_EXCEPTION(eTWPrintInvalidReportLevelCfg, eError) +TSS_EXCEPTION(eTWPrintInvalidDbPrintLevel, eError) +TSS_EXCEPTION(eTWPrintInvalidDbPrintLevelCfg, eError) // Help is requested for a non-existent mode. @@ -61,9 +63,9 @@ class cTWPrintCmdLine { public: static iTWMode* GetMode(int argc, const TCHAR* const* argv); - // after the command line has been read, call this to extract the mode information - // from the command line, create an iTWMode-derived class, and return it. If this - // fails, it will print the error message to stderr and return NULL. + // after the command line has been read, call this to extract the mode information + // from the command line, create an iTWMode-derived class, and return it. If this + // fails, it will print the error message to stderr and return NULL. // constants for all the command line arguments enum CmdLineArgs @@ -71,8 +73,8 @@ class cTWPrintCmdLine HELP, // modes - MODE, // generic -m - MODE_DBPRINT, + MODE, // generic -m + MODE_DBPRINT, MODE_REPORTPRINT, MODE_HELP, MODE_HELP_ALL, @@ -91,38 +93,39 @@ class cTWPrintCmdLine REPORTLEVEL, HEXADECIMAL, - PARAMS, // the final parameters + PARAMS, // the final parameters NUM_CMDLINEARGS }; }; /////////////////////////////////////////////////////////////////////////////// -// iTWMode -- base class that contains an interface for initializing tripwire +// iTWMode -- base class that contains an interface for initializing tripwire // in a mode of operation and executing in that mode; a class is derived // from this for each mode of operation /////////////////////////////////////////////////////////////////////////////// class iTWMode { public: - virtual void InitCmdLineParser(cCmdLineParser& parser) = 0; - // call this to initialize the command line parser. All modes must override this - // method. A static function will be made to initialize the cmdline with parameters - // common to all modes. + // call this to initialize the command line parser. All modes must override this + // method. A static function will be made to initialize the cmdline with parameters + // common to all modes. virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine) = 0; - // call this to ask the mode object to initialize all of its data structures - // with the passed in information. If it returns false, it can be assumed that an error - // message was spit to stderr. + // call this to ask the mode object to initialize all of its data structures + // with the passed in information. If it returns false, it can be assumed that an error + // message was spit to stderr. virtual int Execute(cErrorQueue* pQueue) = 0; - // go to work! TODO -- I don't know how errors (or return values) should be conveyed - // I think that maybe this guy should return an int indicating the return value - virtual TSTRING GetModeUsage( void ) = 0; - // Returns a TSTRING that describes specific usage for a derived mode. - virtual cTWPrintCmdLine::CmdLineArgs GetModeID() = 0; - virtual void SetConfigFile( TSTRING configFilePath ) = 0; - - virtual ~iTWMode() {} + // go to work! TODO -- I don't know how errors (or return values) should be conveyed + // I think that maybe this guy should return an int indicating the return value + virtual TSTRING GetModeUsage(void) = 0; + // Returns a TSTRING that describes specific usage for a derived mode. + virtual cTWPrintCmdLine::CmdLineArgs GetModeID() = 0; + virtual void SetConfigFile(TSTRING configFilePath) = 0; + + virtual ~iTWMode() + { + } }; /////////////////////////////////////////////////////////////////////////////// @@ -135,17 +138,21 @@ class cTWPrintReportMode : public iTWMode cTWPrintReportMode(); virtual ~cTWPrintReportMode(); - + void FillOutReportModeConfigInfo(cTWPrintReportMode_i* pModeInfo, const cConfigFile& cf); - - virtual void InitCmdLineParser( cCmdLineParser& parser); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage(); - virtual cTWPrintCmdLine::CmdLineArgs GetModeID() { return cTWPrintCmdLine::MODE_DBPRINT; } - virtual void SetConfigFile( TSTRING configFilePath ); + + virtual void InitCmdLineParser(cCmdLineParser& parser); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWPrintCmdLine::CmdLineArgs GetModeID() + { + return cTWPrintCmdLine::MODE_DBPRINT; + } + virtual void SetConfigFile(TSTRING configFilePath); + private: - cTWPrintReportMode_i* mpData; + cTWPrintReportMode_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -159,15 +166,19 @@ class cTWPrintDBMode : public iTWMode virtual ~cTWPrintDBMode(); void FillOutDBModeConfigInfo(cTWPrintDBMode_i* pModeInfo, const cConfigFile& cf); - - virtual void InitCmdLineParser( cCmdLineParser& parser); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage(); - virtual cTWPrintCmdLine::CmdLineArgs GetModeID() { return cTWPrintCmdLine::MODE_REPORTPRINT; } - virtual void SetConfigFile( TSTRING configFilePath ); + + virtual void InitCmdLineParser(cCmdLineParser& parser); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage(); + virtual cTWPrintCmdLine::CmdLineArgs GetModeID() + { + return cTWPrintCmdLine::MODE_REPORTPRINT; + } + virtual void SetConfigFile(TSTRING configFilePath); + private: - cTWPrintDBMode_i* mpData; + cTWPrintDBMode_i* mpData; }; /////////////////////////////////////////////////////////////////////////////// @@ -179,18 +190,23 @@ class cTWPrintHelpMode : public iTWMode public: cTWPrintHelpMode(); virtual ~cTWPrintHelpMode(); - + virtual void InitCmdLineParser(cCmdLineParser& cmdLine); - virtual bool Init (const cConfigFile& cf, const cCmdLineParser& cmdLine); - virtual int Execute (cErrorQueue* pQueue); - virtual TSTRING GetModeUsage() { return _T(""); } - virtual cTWPrintCmdLine::CmdLineArgs GetModeID() { return cTWPrintCmdLine::MODE_HELP; } - virtual void SetConfigFile( TSTRING configFilePath ); + virtual bool Init(const cConfigFile& cf, const cCmdLineParser& cmdLine); + virtual int Execute(cErrorQueue* pQueue); + virtual TSTRING GetModeUsage() + { + return _T(""); + } + virtual cTWPrintCmdLine::CmdLineArgs GetModeID() + { + return cTWPrintCmdLine::MODE_HELP; + } + virtual void SetConfigFile(TSTRING configFilePath); + private: - cTWPrintHelpMode_i* mpData; + cTWPrintHelpMode_i* mpData; }; - -#endif// TWPRINTCMDLINE - +#endif // TWPRINTCMDLINE diff --git a/src/twprint/twprinterrors.cpp b/src/twprint/twprinterrors.cpp index 21c0d11..3d9d64e 100644 --- a/src/twprint/twprinterrors.cpp +++ b/src/twprint/twprinterrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,11 +41,14 @@ #include "core/errortable.h" #include "twprintcmdline.h" -TSS_BEGIN_ERROR_REGISTRATION( twprint ) +TSS_BEGIN_ERROR_REGISTRATION(twprint) -TSS_REGISTER_ERROR( eTWPrintInvalidParamHelp(), _T("Invalid mode parameter to help:") ); -TSS_REGISTER_ERROR( eTWPrintInvalidReportLevel(), _T("Invalid reporting level specified, valid levels: [0-4]") ); -TSS_REGISTER_ERROR( eTWPrintInvalidReportLevelCfg(),_T("Invalid reporting level in configuration file, must be [0-4]") ); +TSS_REGISTER_ERROR(eTWPrintInvalidParamHelp(), _T("Invalid mode parameter to help:")); +TSS_REGISTER_ERROR(eTWPrintInvalidReportLevel(), _T("Invalid reporting level specified, valid levels: [0-4]")); +TSS_REGISTER_ERROR(eTWPrintInvalidReportLevelCfg(), \ + _T("Invalid reporting level in configuration file, must be [0-4]")); +TSS_REGISTER_ERROR(eTWPrintInvalidDbPrintLevel(), _T("Invalid output level specified, valid levels: [0-2]")); +TSS_REGISTER_ERROR(eTWPrintInvalidDbPrintLevelCfg(), \ + _T("Invalid output level in configuration file, valid levels: [0-2]")); TSS_END_ERROR_REGISTRATION() - diff --git a/src/twprint/twprinterrors.h b/src/twprint/twprinterrors.h index c5b1350..58675a5 100644 --- a/src/twprint/twprinterrors.h +++ b/src/twprint/twprinterrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,7 +40,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( twprint ) - -#endif//__TWPRINTERRORS +TSS_DECLARE_ERROR_REGISTRATION(twprint) +#endif //__TWPRINTERRORS diff --git a/src/twprint/twprintmain.cpp b/src/twprint/twprintmain.cpp index 474b109..079ace4 100644 --- a/src/twprint/twprintmain.cpp +++ b/src/twprint/twprintmain.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,7 +42,7 @@ #include "core/cmdlineparser.h" #include "core/errorbucketimpl.h" #include "core/usernotifystdout.h" -#include "core/timebomb.h" +#include "core/epoch.h" #include "core/debug.h" @@ -51,14 +51,12 @@ #include "tw/twutil.h" #include "tw/twstrings.h" -#include "twprint.h" // package initialization +#include "twprint.h" // package initialization -#if IS_UNIX #include "core/unixfsservices.h" #include -#endif -#include // for auto_ptr +#include // for auto_ptr #include #include @@ -78,28 +76,28 @@ void tw_unexpected_handler() _exit(1); } -int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) +int __cdecl _tmain(int argc, const TCHAR* argv[]) { int ret = 0; - if (TimeBombExploded()) + if (CheckEpoch()) return 1; cTWInit twInit; - try + try { // set unexpected and terminate handlers // Note: we do this before Init() in case it attempts to call these handlers // TODO: move this into the Init() routine - EXCEPTION_NAMESPACE set_terminate(tw_terminate_handler); - EXCEPTION_NAMESPACE set_unexpected(tw_unexpected_handler); + EXCEPTION_NAMESPACE set_terminate(tw_terminate_handler); + EXCEPTION_NAMESPACE set_unexpected(tw_unexpected_handler); + + twInit.Init(argv[0]); + TSS_Dependency(cTWPrint); - twInit.Init( argv[0] ); - TSS_Dependency( cTWPrint ); - // init twprint strings // @@ -113,7 +111,7 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_VERSION) << std::endl; TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; TCOUT << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; - + ret = 1; goto exit; } @@ -122,7 +120,7 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) // Display the version info... // this is quick and dirty ... just the way I like it :-) -- mdb // - if (_tcscmp(argv[1], _T("--version")) == 0) + if (_tcscmp(argv[1], _T("--version")) == 0) { TCOUT << TSS_GetString(cTW, tw::STR_VERSION_LONG) << std::endl; ret = 0; @@ -130,8 +128,8 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) } // Next, set the mode... exit with error if now valid mode specified. - std::auto_ptr pMode(cTWPrintCmdLine::GetMode(argc, argv)); - if(! pMode.get()) + TW_UNIQUE_PTR pMode(cTWPrintCmdLine::GetMode(argc, argv)); + if (!pMode.get()) { // no valid mode passed; GetMode will display an appropriate string (include usage statement) ret = 1; @@ -146,28 +144,26 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) { cmdLine.Parse(argc, argv); } - catch( eError& e ) + catch (eError& e) { cTWUtil::PrintErrorMsg(e); TCERR << TSS_GetString(cTW, tw::STR_GET_HELP) << std::endl; - + ret = 1; goto exit; } - #if IS_UNIX // erase the command line // TODO: it might be a good idea to move this to cTWUtil int i; for (i = 1; i < argc; ++i) - memset((char*)argv[i], 0, strlen(argv[i])*sizeof(char)); - #endif + memset((char*)argv[i], 0, strlen(argv[i]) * sizeof(char)); cCmdLineIter iter(cmdLine); if (iter.SeekToArg(cTWPrintCmdLine::HELP)) { TCOUT << TSS_GetString(cTWPrint, twprint::STR_TWPRINT_VERSION) << std::endl; - TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; + TCOUT << TSS_GetString(cTW, tw::STR_VERSION) << std::endl; // Output a specific usage statement for this mode. TCOUT << pMode->GetModeUsage(); ret = 1; @@ -175,19 +171,19 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) } // open up the config file, possibly using the passed in path - cConfigFile config; + cConfigFile config; cErrorReporter errorReporter; - if( pMode->GetModeID() != cTWPrintCmdLine::MODE_HELP ) + if (pMode->GetModeID() != cTWPrintCmdLine::MODE_HELP) { try { //open cfg file TSTRING cfgPath; cTWUtil::OpenConfigFile(config, cmdLine, cTWPrintCmdLine::CFG_FILE, errorReporter, cfgPath); - pMode->SetConfigFile( cfgPath ); + pMode->SetConfigFile(cfgPath); } - catch(eError& error) + catch (eError& error) { cTWUtil::PrintErrorMsg(error); TCERR << TSS_GetString(cTW, tw::STR_ERR_TWCFG_CANT_READ) << std::endl; @@ -197,7 +193,7 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) } // ok, now we can initialize the mode object and have it execute - if(! pMode->Init(config, cmdLine)) + if (!pMode->Init(config, cmdLine)) { // TODO -- Init should spit out the error msg... // I don't think this error message is necessary @@ -206,9 +202,9 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) ret = 1; goto exit; } - ret = pMode->Execute( &twInit.errorQueue ); + ret = pMode->Execute(&twInit.errorQueue); - }//end try block + } //end try block catch (eError& error) { @@ -217,14 +213,14 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) ret = 1; } - catch (std::bad_alloc e) + catch (std::bad_alloc& e) { TCERR << _T("*** Fatal exception: Out of memory "); TCERR << _T("*** Exiting...\n"); ret = 1; } - catch (std::exception e) + catch (std::exception& e) { TCERR << _T("*** Fatal exception: "); std::cerr << e.what() << std::endl; @@ -245,5 +241,4 @@ int __cdecl _tmain( int argc, const TCHAR* argv[ ] ) return ret; -}//end MAIN - +} //end MAIN diff --git a/src/twprint/twprintstrings.cpp b/src/twprint/twprintstrings.cpp index 42eac57..05d0a73 100644 --- a/src/twprint/twprintstrings.cpp +++ b/src/twprint/twprintstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,50 +39,55 @@ #include "twprint.h" #include "twprintstrings.h" -TSS_BeginStringtable( cTWPrint ) - - TSS_StringEntry( twprint::STR_TWPRINT_USAGE_SUMMARY, - _T("Usage:\n") - _T("\n") - _T("Print Database: twprint [-m d|--print-dbfile] [options] [object1 [object2...]]\n") - _T("Print Report: twprint [-m r|--print-report] [options]\n") - _T("Type 'twprint [mode] --help' OR\n") - _T("'twprint --help mode [mode...]' OR\n") - _T("'twprint --help all' for extended help\n") - _T("\n") - ), +#if IS_AROS +# define VERSION_PREFIX "$VER: " +#else +# define VERSION_PREFIX "@(#)" +#endif + +TSS_BeginStringtable(cTWPrint) + + TSS_StringEntry(twprint::STR_TWPRINT_USAGE_SUMMARY, + _T("Usage:\n") + _T("\n") + _T("Print Database: twprint [-m d|--print-dbfile] [options] [object1 [object2...]]\n") + _T("Print Report: twprint [-m r|--print-report] [options] [object1 [object2...]]\n") + _T("Type 'twprint [mode] --help' OR\n") + _T("'twprint --help mode [mode...]' OR\n") + _T("'twprint --help all' for extended help\n") + _T("\n")), - TSS_StringEntry( twprint::STR_TWPRINT_HELP_PRINT_DATABASE, - _T("Print Database mode:\n") - _T(" -m d --print-dbfile\n") - _T(" -v --verbose\n") - _T(" -h --hexadecimal\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -d database --dbfile database\n") - _T(" -L localkey --local-keyfile localkey\n") - _T("[object1 [object2 ...]\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), + TSS_StringEntry(twprint::STR_TWPRINT_HELP_PRINT_DATABASE, + _T("Print Database mode:\n") + _T(" -m d --print-dbfile\n") + _T(" -v --verbose\n") + _T(" -h --hexadecimal\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -d database --dbfile database\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -t { 0|1|2 } --output-level { 0|1|2 }\n") + _T("[object1 [object2 ...]]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), - TSS_StringEntry( twprint::STR_TWPRINT_HELP_PRINT_REPORT, - _T("Print Report mode:\n") - _T(" -m r --print-report\n") - _T(" -v --verbose\n") - _T(" -h --hexadecimal\n") - _T(" -s --silent, --quiet\n") - _T(" -c cfgfile --cfgfile cfgfile\n") - _T(" -r report --twrfile report\n") - _T(" -L localkey --local-keyfile localkey\n") - _T(" -t { 0|1|2|3|4 } --report-level { 0|1|2|3|4 }\n") - _T("\n") - _T("The -v and -s options are mutually exclusive.\n") - _T("\n") - ), - - TSS_StringEntry( twprint::STR_TWPRINT_VERSION, _T("twprint: Tripwire database and report printer.\n") ), + TSS_StringEntry(twprint::STR_TWPRINT_HELP_PRINT_REPORT, + _T("Print Report mode:\n") + _T(" -m r --print-report\n") + _T(" -v --verbose\n") + _T(" -h --hexadecimal\n") + _T(" -s --silent, --quiet\n") + _T(" -c cfgfile --cfgfile cfgfile\n") + _T(" -r report --twrfile report\n") + _T(" -L localkey --local-keyfile localkey\n") + _T(" -t { 0|1|2|3|4 } --report-level { 0|1|2|3|4 }\n") + _T("[object1 [object2 ...]]\n") + _T("\n") + _T("The -v and -s options are mutually exclusive.\n") + _T("\n")), -TSS_EndStringtable( cTWPrint ) + TSS_StringEntry(twprint::STR_TWPRINT_VERSION, _T("twprint: Tripwire database and report printer.\n")), + TSS_StringEntry(twprint::STR_EMBEDDED_VERSION, _T(VERSION_PREFIX "twprint " PACKAGE_VERSION)), + TSS_EndStringtable(cTWPrint) diff --git a/src/twprint/twprintstrings.h b/src/twprint/twprintstrings.h index 2acac1f..ed8caba 100644 --- a/src/twprint/twprintstrings.h +++ b/src/twprint/twprintstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,18 +38,16 @@ #ifndef __TWPRINTSTRINGS_H #define __TWPRINTSTRINGS_H -#include "twprint.h" // for: STRINGTABLE syntax +#include "twprint.h" // for: STRINGTABLE syntax //--Message Keys -TSS_BeginStringIds( twprint ) +TSS_BeginStringIds(twprint) STR_TWPRINT_USAGE_SUMMARY, - STR_TWPRINT_HELP_PRINT_REPORT, - STR_TWPRINT_HELP_PRINT_DATABASE, - STR_TWPRINT_VERSION - -TSS_EndStringIds( twprint ) + STR_TWPRINT_HELP_PRINT_REPORT, STR_TWPRINT_HELP_PRINT_DATABASE, STR_TWPRINT_VERSION, + STR_EMBEDDED_VERSION -#endif//__TWPRINTSTRINGS_H + TSS_EndStringIds(twprint) +#endif //__TWPRINTSTRINGS_H diff --git a/src/twtest/Makefile.am b/src/twtest/Makefile.am index f7fe7c0..cedcf10 100644 --- a/src/twtest/Makefile.am +++ b/src/twtest/Makefile.am @@ -1,20 +1,25 @@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. LIBS = -ltripwire -lcryptlib @LIBS@ LDFLAGS = @LDFLAGS@ -L../../lib LN_S = @LN@ sbin_PROGRAMS = twtest + +twtestdir=. + twtest_SOURCES = \ archive_t.cpp \ +blockfile_t.cpp \ +blockrecordarray_t.cpp \ charutil_t.cpp \ cmdlineparser_t.cpp \ codeconvert_t.cpp \ configfile_t.cpp \ cryptoarchive_t.cpp \ -crytpo_t.cpp \ +crypto_t.cpp \ dbdatasource_t.cpp \ debug_t.cpp \ displayencoder_t.cpp \ @@ -48,8 +53,8 @@ genrespeclist_t.cpp \ genreswitcher_t.cpp \ growheap_t.cpp \ hashtable_t.cpp \ +hierdatabase_t.cpp \ keyfile_t.cpp \ -objectpool_t.cpp \ platform_t.cpp \ policyparser_t.cpp \ refcountobj_t.cpp \ @@ -73,8 +78,16 @@ unixfsservices_t.cpp \ usernotifystdout_t.cpp \ wchar16_t.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit -CLEANFILES = ../../bin/twtest +twtest_HEADERS = stdtest.h stringutil_t.h test.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit + +clean-local: clean-local-check +.PHONY: clean-local-check +clean-local-check: + -rm -rf ../../bin/TWTestData + -rm -f ../../bin/twtest + -rm -f *.gcno *.gcda all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin diff --git a/src/twtest/Makefile.in b/src/twtest/Makefile.in old mode 100755 new mode 100644 index 8eba23d..409d2bd --- a/src/twtest/Makefile.in +++ b/src/twtest/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(twtest_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,25 +87,29 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ sbin_PROGRAMS = twtest$(EXEEXT) subdir = src/twtest -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(twtest_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = -am__installdirs = "$(DESTDIR)$(sbindir)" -sbinPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twtestdir)" PROGRAMS = $(sbin_PROGRAMS) -am_twtest_OBJECTS = archive_t.$(OBJEXT) charutil_t.$(OBJEXT) \ +am_twtest_OBJECTS = archive_t.$(OBJEXT) blockfile_t.$(OBJEXT) \ + blockrecordarray_t.$(OBJEXT) charutil_t.$(OBJEXT) \ cmdlineparser_t.$(OBJEXT) codeconvert_t.$(OBJEXT) \ configfile_t.$(OBJEXT) cryptoarchive_t.$(OBJEXT) \ - crytpo_t.$(OBJEXT) dbdatasource_t.$(OBJEXT) debug_t.$(OBJEXT) \ + crypto_t.$(OBJEXT) dbdatasource_t.$(OBJEXT) debug_t.$(OBJEXT) \ displayencoder_t.$(OBJEXT) error_t.$(OBJEXT) \ errorbucketimpl_t.$(OBJEXT) fcocompare_t.$(OBJEXT) \ fcodatabasefile_t.$(OBJEXT) fconame_t.$(OBJEXT) \ @@ -69,40 +124,120 @@ am_twtest_OBJECTS = archive_t.$(OBJEXT) charutil_t.$(OBJEXT) \ fspropcalc_t.$(OBJEXT) fspropdisplayer_t.$(OBJEXT) \ fspropset_t.$(OBJEXT) fsspec_t.$(OBJEXT) genre_t.$(OBJEXT) \ genrespeclist_t.$(OBJEXT) genreswitcher_t.$(OBJEXT) \ - growheap_t.$(OBJEXT) hashtable_t.$(OBJEXT) keyfile_t.$(OBJEXT) \ - objectpool_t.$(OBJEXT) platform_t.$(OBJEXT) \ - policyparser_t.$(OBJEXT) refcountobj_t.$(OBJEXT) \ - resources_t.$(OBJEXT) serializer_t.$(OBJEXT) \ - serializerimpl_t.$(OBJEXT) signature_t.$(OBJEXT) \ - srefcountobj_t.$(OBJEXT) stdtest.$(OBJEXT) \ - stringencoder_t.$(OBJEXT) tasktimer_t.$(OBJEXT) \ - tchar_t.$(OBJEXT) test.$(OBJEXT) textreportviewer_t.$(OBJEXT) \ - twlocale_t.$(OBJEXT) twutil_t.$(OBJEXT) types_t.$(OBJEXT) \ + growheap_t.$(OBJEXT) hashtable_t.$(OBJEXT) \ + hierdatabase_t.$(OBJEXT) keyfile_t.$(OBJEXT) \ + platform_t.$(OBJEXT) policyparser_t.$(OBJEXT) \ + refcountobj_t.$(OBJEXT) resources_t.$(OBJEXT) \ + serializer_t.$(OBJEXT) serializerimpl_t.$(OBJEXT) \ + signature_t.$(OBJEXT) srefcountobj_t.$(OBJEXT) \ + stdtest.$(OBJEXT) stringencoder_t.$(OBJEXT) \ + tasktimer_t.$(OBJEXT) tchar_t.$(OBJEXT) test.$(OBJEXT) \ + textreportviewer_t.$(OBJEXT) twlocale_t.$(OBJEXT) \ + twutil_t.$(OBJEXT) types_t.$(OBJEXT) \ unixfsservices_t.$(OBJEXT) usernotifystdout_t.$(OBJEXT) \ wchar16_t.$(OBJEXT) twtest_OBJECTS = $(am_twtest_OBJECTS) twtest_LDADD = $(LDADD) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_@AM_V@) +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) +am__v_CC_0 = @echo " CC " $@; +am__v_CC_1 = CCLD = $(CC) LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_@AM_V@) +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) +am__v_CCLD_0 = @echo " CCLD " $@; +am__v_CCLD_1 = SOURCES = $(twtest_SOURCES) DIST_SOURCES = $(twtest_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +HEADERS = $(twtest_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -118,7 +253,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -126,6 +261,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -137,6 +273,7 @@ LN = @LN@ LN_S = @LN@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -153,21 +290,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -197,23 +337,30 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies AM_INSTALL_PROGRAM_FLAGS = -m 755 -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. +twtestdir = . twtest_SOURCES = \ archive_t.cpp \ +blockfile_t.cpp \ +blockrecordarray_t.cpp \ charutil_t.cpp \ cmdlineparser_t.cpp \ codeconvert_t.cpp \ configfile_t.cpp \ cryptoarchive_t.cpp \ -crytpo_t.cpp \ +crypto_t.cpp \ dbdatasource_t.cpp \ debug_t.cpp \ displayencoder_t.cpp \ @@ -247,8 +394,8 @@ genrespeclist_t.cpp \ genreswitcher_t.cpp \ growheap_t.cpp \ hashtable_t.cpp \ +hierdatabase_t.cpp \ keyfile_t.cpp \ -objectpool_t.cpp \ platform_t.cpp \ policyparser_t.cpp \ refcountobj_t.cpp \ @@ -272,7 +419,7 @@ unixfsservices_t.cpp \ usernotifystdout_t.cpp \ wchar16_t.cpp -CLEANFILES = ../../bin/twtest +twtest_HEADERS = stdtest.h stringutil_t.h test.h all: all-am .SUFFIXES: @@ -281,15 +428,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twtest/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/twtest/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/twtest/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/twtest/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -306,32 +452,53 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): install-sbinPROGRAMS: $(sbin_PROGRAMS) @$(NORMAL_INSTALL) - test -z "$(sbindir)" || $(mkdir_p) "$(DESTDIR)$(sbindir)" - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ - if test -f $$p \ - ; then \ - f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \ - $(INSTALL_PROGRAM_ENV) $(sbinPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \ - else :; fi; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(sbindir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(sbindir)" || exit 1; \ + fi; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p \ + ; then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' \ + -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || exit $$?; \ + } \ + ; done uninstall-sbinPROGRAMS: @$(NORMAL_UNINSTALL) - @list='$(sbin_PROGRAMS)'; for p in $$list; do \ - f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ - echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \ - rm -f "$(DESTDIR)$(sbindir)/$$f"; \ - done + @list='$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' \ + `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(sbindir)" && rm -f $$files clean-sbinPROGRAMS: -test -z "$(sbin_PROGRAMS)" || rm -f $(sbin_PROGRAMS) -twtest$(EXEEXT): $(twtest_OBJECTS) $(twtest_DEPENDENCIES) + +twtest$(EXEEXT): $(twtest_OBJECTS) $(twtest_DEPENDENCIES) $(EXTRA_twtest_DEPENDENCIES) @rm -f twtest$(EXEEXT) - $(CXXLINK) $(twtest_LDFLAGS) $(twtest_OBJECTS) $(twtest_LDADD) $(LIBS) + $(AM_V_CXXLD)$(CXXLINK) $(twtest_OBJECTS) $(twtest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -340,93 +507,120 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-twtestHEADERS: $(twtest_HEADERS) + @$(NORMAL_INSTALL) + @list='$(twtest_HEADERS)'; test -n "$(twtestdir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(twtestdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(twtestdir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(twtestdir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(twtestdir)" || exit $$?; \ + done + +uninstall-twtestHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(twtest_HEADERS)'; test -n "$(twtestdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(twtestdir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(PROGRAMS) +all-am: Makefile $(PROGRAMS) $(HEADERS) installdirs: - for dir in "$(DESTDIR)$(sbindir)"; do \ - test -z "$$dir" || $(mkdir_p) "$$dir"; \ + for dir in "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(twtestdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am @@ -438,24 +632,29 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: - -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am -clean-am: clean-generic clean-sbinPROGRAMS mostlyclean-am +clean-am: clean-generic clean-local clean-sbinPROGRAMS mostlyclean-am distclean: distclean-am -rm -f Makefile @@ -468,18 +667,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-twtestHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: install-sbinPROGRAMS +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -498,22 +717,37 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am uninstall-sbinPROGRAMS +uninstall-am: uninstall-sbinPROGRAMS uninstall-twtestHEADERS -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-sbinPROGRAMS ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-sbinPROGRAMS install-strip \ +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-local clean-sbinPROGRAMS cscopelist-am ctags ctags-am \ + distclean distclean-compile distclean-generic distclean-tags \ + distdir dvi dvi-am html html-am info info-am install \ + install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-sbinPROGRAMS install-strip install-twtestHEADERS \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am uninstall-sbinPROGRAMS + mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-sbinPROGRAMS uninstall-twtestHEADERS + +.PRECIOUS: Makefile +clean-local: clean-local-check +.PHONY: clean-local-check +clean-local-check: + -rm -rf ../../bin/TWTestData + -rm -f ../../bin/twtest + -rm -f *.gcno *.gcda + all: $(sbin_PROGRAMS) @test -d ../../bin && $(LN) -f $(sbin_PROGRAMS) ../../bin + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/twtest/archive_t.cpp b/src/twtest/archive_t.cpp index 629c0e4..7dd9565 100644 --- a/src/twtest/archive_t.cpp +++ b/src/twtest/archive_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,13 +38,14 @@ #include "core/archive.h" #include "twtest/test.h" #include "core/error.h" +#include "tw/twutil.h" #include TSS_EXCEPTION(eTestArchiveError, eError); -void TestArchive() +void TestMemoryArchive() { - // cMemoryArchive + // cMemoryArchive cMemoryArchive memarch; memarch.WriteInt32(1); @@ -52,7 +53,7 @@ void TestArchive() memarch.WriteInt32(3); memarch.WriteInt32(4); - TSTRING s = _T("Weenus"); + TSTRING s = _T("Iridogorgia"); memarch.WriteString(s); memarch.WriteInt64(1234567L); @@ -74,7 +75,7 @@ void TestArchive() TSTRING s2; memarch.ReadString(s2); - TEST(s2.compare(_T("Weenus")) == 0); + TEST(s2.compare(_T("Iridogorgia")) == 0); memarch.ReadInt64(l); TEST(l == 1234567L); @@ -82,7 +83,8 @@ void TestArchive() TEST(memarch.ReadBlob(NULL, sizeof(int16)) == sizeof(int16)); TEST(memarch.ReadBlob(NULL, 1024) == 0); - try { + try + { memarch.ReadInt32(i); throw eTestArchiveError(); } @@ -100,38 +102,74 @@ void TestArchive() memarch.MapArchive(4 * sizeof(int32) + sizeof(int32) + 6, sizeof(int64)); TEST(memarch.GetMappedOffset() == 4 * sizeof(int32) + sizeof(int32) + 6); TEST(memarch.GetMappedLength() == sizeof(int64)); -// TEST(tw_ntohll(*(int64*)memarch.GetMap()) == 1234567L); + // TEST(tw_ntohll(*(int64*)memarch.GetMap()) == 1234567L); +} +void TestLockedTemporaryArchive() +{ + TSTRING s = _T("Metallogorgia"); + bool threw = false; // cLockedTemporaryFileArchive - TSTRING lockedFileName = TEMP_DIR; - lockedFileName += _T("/inaccessable_file.bin"); + TSTRING lockedFileName = TwTestPath("inaccessable_file.bin"); cLockedTemporaryFileArchive lockedArch; - // try to create an archive using a temp file - lockedArch.OpenReadWrite(); - lockedArch.Close(); - - // this should open and lock the file -- shouldn't be able to access it - lockedArch.OpenReadWrite(lockedFileName.c_str()); - lockedArch.Seek(0, cBidirArchive::BEGINNING); + try + { + // try to create an archive using a temp file + lockedArch.OpenReadWrite(); + lockedArch.Close(); + } + catch (eError& e) + { + threw = true; + TCERR << "Error opening locked temp archive" << std::endl; + cTWUtil::PrintErrorMsg(e); + } + catch (...) + { + threw = true; + } - // shouldn't be able to see these changes - lockedArch.WriteInt32(1); - lockedArch.WriteInt32(2); - lockedArch.WriteInt32(3); - lockedArch.WriteInt32(4); - lockedArch.WriteString(s); - lockedArch.WriteInt64(1234567L); - lockedArch.WriteInt16(42); + try + { + // this should open and lock the file -- shouldn't be able to access it + lockedArch.OpenReadWrite(lockedFileName.c_str()); + lockedArch.Seek(0, cBidirArchive::BEGINNING); + + // shouldn't be able to see these changes + lockedArch.WriteInt32(1); + lockedArch.WriteInt32(2); + lockedArch.WriteInt32(3); + lockedArch.WriteInt32(4); + lockedArch.WriteString(s); + lockedArch.WriteInt64(1234567L); + lockedArch.WriteInt16(42); + + // this should delete the file + lockedArch.Close(); + } + catch (eError& e) + { + threw = true; + TCERR << "Error writing locked temp archive" << std::endl; + cTWUtil::PrintErrorMsg(e); + } + catch (...) + { + threw = true; + } - // this should delete the file - lockedArch.Close(); + TEST(!threw); +} - // cFileArchive - TSTRING fileName = TEMP_DIR; - fileName += _T("/archive_test.bin"); +void TestFileArchive() +{ + bool threw = false; + TSTRING s = _T("Acanthogorgia"); + // cFileArchive + TSTRING fileName = TwTestPath("archive_test.bin"); cFileArchive filearch; filearch.OpenReadWrite(fileName.c_str()); @@ -163,14 +201,15 @@ void TestArchive() TSTRING s3; filearch.ReadString(s3); - TEST(s3.compare(_T("Weenus")) == 0); + TEST(s3.compare(_T("Acanthogorgia")) == 0); filearch.ReadInt64(k); TEST(k == 1234567L); TEST(filearch.ReadBlob(NULL, sizeof(int16)) == sizeof(int16)); TEST(filearch.ReadBlob(NULL, 1024) == 0); // should be EOF - try { + try + { filearch.ReadInt32(j); throw eTestArchiveError(); } @@ -181,8 +220,16 @@ void TestArchive() } catch (eError& e) { - TEST(false); + threw = true; (void)e; } + + TEST(!threw); } +void RegisterSuite_Archive() +{ + RegisterTest("Archive", "MemoryArchive", TestMemoryArchive); + RegisterTest("Archive", "LockedTemporaryArchive", TestLockedTemporaryArchive); + RegisterTest("Archive", "FileArchive", TestFileArchive); +} diff --git a/src/twtest/blockfile_t.cpp b/src/twtest/blockfile_t.cpp new file mode 100644 index 0000000..1f9cf7b --- /dev/null +++ b/src/twtest/blockfile_t.cpp @@ -0,0 +1,116 @@ +// +// The developer of the original code and/or files is Tripwire, Inc. +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, +// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights +// reserved. +// +// This program is free software. The contents of this file are subject +// to the terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2 of the License, or (at your +// option) any later version. You may redistribute it and/or modify it +// only in compliance with the GNU General Public License. +// +// This program is distributed in the hope that it will be useful. +// However, this program is distributed AS-IS WITHOUT ANY +// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS +// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +// USA. +// +// Nothing in the GNU General Public License or any other license to use +// the code or files shall permit you to use Tripwire's trademarks, +// service marks, or other intellectual property without Tripwire's +// prior written consent. +// +// If you have any questions, please contact Tripwire, Inc. at either +// info@tripwire.org or www.tripwire.org. +// +// blockfile_t +#include "db/stddb.h" +#include "db/blockfile.h" +#include "db/block.h" +#include "core/archive.h" +#include "test.h" +#include "core/debug.h" + +void TestBlockFile() +{ + cDebug d("TestBlockFile"); + + std::string fileName = TwTestPath("test.bf"); + // truncate the file I am going to use... + // + cFileArchive a; + a.OpenReadWrite(fileName.c_str()); + a.Close(); + // + // open up the block file... + // + cBlockFile bf; + bf.Open(fileName, 2); // opened up with two pages +#ifdef _BLOCKFILE_DEBUG + bf.TraceContents(); +#endif + + // get a block and write something to it... + // + cBlockFile::Block* pB = bf.GetBlock(0); + TEST(pB); + static const TCHAR str1[] = _T("Block 1"); + memcpy(pB->GetData(), str1, sizeof(str1)); + pB->SetDirty(); +#ifdef _BLOCKFILE_DEBUG + bf.TraceContents(); +#endif + + // get another block... + // + pB = bf.CreateBlock(); + TEST(pB); + static const TCHAR str2[] = _T("Block 2"); + memcpy(pB->GetData(), str2, sizeof(str2)); + pB->SetDirty(); +#ifdef _BLOCKFILE_DEBUG + bf.TraceContents(); +#endif + + // get the first block we wrote... + // + pB = bf.GetBlock(0); + TEST(pB); + *pB->GetData() = _T('F'); +#ifdef _BLOCKFILE_DEBUG + bf.TraceContents(); +#endif + + // + // create a third block -- someone will have to be paged out in order for this to happen + // + pB = bf.CreateBlock(); + TEST(pB); + static const TCHAR str3[] = _T("Block 3"); + memcpy(pB->GetData(), str3, sizeof(str3)); + pB->SetDirty(); +#ifdef _BLOCKFILE_DEBUG + bf.TraceContents(); +#endif + + // + // test the guard bytes... + /* + memcpy( pB->GetData() + (cBlockFile::BLOCK_SIZE - 4), str3, sizeof(str3) ); + memcpy( pB->GetData() - 1, str3, sizeof(str3) ); + pB->AssertValid(); + */ + + bf.Close(); +} + +void RegisterSuite_BlockFile() +{ + RegisterTest("BlockFile", "Basic", TestBlockFile); +} diff --git a/src/twtest/blockrecordarray_t.cpp b/src/twtest/blockrecordarray_t.cpp new file mode 100644 index 0000000..c035e43 --- /dev/null +++ b/src/twtest/blockrecordarray_t.cpp @@ -0,0 +1,154 @@ +// +// The developer of the original code and/or files is Tripwire, Inc. +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, +// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights +// reserved. +// +// This program is free software. The contents of this file are subject +// to the terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2 of the License, or (at your +// option) any later version. You may redistribute it and/or modify it +// only in compliance with the GNU General Public License. +// +// This program is distributed in the hope that it will be useful. +// However, this program is distributed AS-IS WITHOUT ANY +// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS +// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +// USA. +// +// Nothing in the GNU General Public License or any other license to use +// the code or files shall permit you to use Tripwire's trademarks, +// service marks, or other intellectual property without Tripwire's +// prior written consent. +// +// If you have any questions, please contact Tripwire, Inc. at either +// info@tripwire.org or www.tripwire.org. +// +// blockrecordarray_t.cpp + +#include "db/stddb.h" +#include "db/blockrecordarray.h" +#include "test.h" +#include "core/debug.h" +#include "core/error.h" + +//TODO: This test needs more comprehensive validity checks +void TestBlockRecordArray() +{ + cDebug d("TestBlockRecordArray"); + + std::string fileName = TwTestPath("test2.bf"); + + cBlockFile bf; + bf.Open(fileName, 2, true); // opened up with two pages + + // make sure the file is large enough... + // + while (bf.GetNumBlocks() < 2) + { + bf.CreateBlock(); + } + + // create the record arrays and associate them with the two blocks... + // + cBlockRecordArray ra1(&bf, 0); + ra1.InitNewBlock(); + cBlockRecordArray ra2(&bf, 1); + ra2.InitNewBlock(); + + TEST(ra1.IsClassValid()); + TEST(ra2.IsClassValid()); + + TEST(ra1.Initialized()); + + // + // now, start adding and removing things from the arrays... + // + static const char data1[] = "This is data 1"; + static const char data2[] = "And here we have data 2"; + static const char data3[] = "Here is d a t a 3!"; + static const char data4[] = "Three cheers for data 4!"; + ra1.AddItem((int8*)data1, sizeof(data1), 1); + // TEST(ra1.IsItemValid(1)); + ra1.AddItem((int8*)data2, sizeof(data2), 2); + // TEST(ra1.IsItemValid(2)); + ra1.AddItem((int8*)data3, sizeof(data3), 3); + // TEST(ra1.IsItemValid(3)); + ra1.AddItem((int8*)data4, sizeof(data4), 4); + // TEST(ra1.IsItemValid(4)); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + // TODO -- try deleting the second to last and then the last thing from the array to + // see if we clean up properly. + + // delete item 2... + ra1.DeleteItem(1); + TEST(!ra1.IsItemValid(1)); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + // add a new item... + static const char data5[] = "fffiiivvveee!"; + ra1.AddItem((int8*)data5, sizeof(data5), 5); + // TEST(ra1.IsItemValid(5)); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + // delete the second to last and last items to see if we clean up properly... + // note that there are four things here at this point. + ra1.DeleteItem(2); + TEST(!ra1.IsItemValid(2)); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + ra1.DeleteItem(3); + TEST(!ra1.IsItemValid(3)); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + // delete the first item to see if that works ok.... + ra1.DeleteItem(0); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + // add a couple more just for kicks :-) + static const char data6[] = "We're looking for six"; + static const char data7[] = "All 7s go to heaven"; + ra1.AddItem((int8*)data6, sizeof(data6), 6); + ra1.AddItem((int8*)data7, sizeof(data7), 7); +#ifdef _BLOCKFILE_DEBUG + ra1.TraceContents(); +#endif + + TEST(ra1.IsClassValid()); + + // Now, we will close the file, reopen it and see if we can read it ok. + // + bf.Close(); + bf.Open(fileName, 2, false); + cBlockRecordArray ra3(&bf, 0); + ra3.InitForExistingBlock(); + d.TraceDebug("\n------ Tracing out the contents of the first block after being read back in from disk...\n\n"); +#ifdef _BLOCKFILE_DEBUG + ra3.TraceContents(); +#endif + + TEST(ra3.Initialized()); + TEST(ra3.IsClassValid()); +} + +void RegisterSuite_BlockRecordArray() +{ + RegisterTest("BlockRecordArray", "Basic", TestBlockRecordArray); +} diff --git a/src/twtest/charutil_t.cpp b/src/twtest/charutil_t.cpp index 27db91c..625460f 100644 --- a/src/twtest/charutil_t.cpp +++ b/src/twtest/charutil_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,69 +37,58 @@ #include "core/stdcore.h" -#ifdef TSS_TEST - -#include "test/utx.h" -#include "charutil.h" -#include "debug.h" -#include "errorbucketimpl.h" +#include "core/charutil.h" +#include "core/debug.h" +#include "core/errorbucketimpl.h" +#include "twtest/test.h" +#include -/////////////////////////////////////////////////////////////////////////////// -// cCharEncoderTest -/////////////////////////////////////////////////////////////////////////////// -class cCharEncoderTest +bool localeIsUtf8() { -public: + std::string locale(setlocale(LC_CTYPE, 0)); + std::transform(locale.begin(), locale.end(), locale.begin(), ::tolower); - void PrintChars( const TSTRING& str ) - { - const TCHAR* cur = str.begin(); - const TCHAR* end = str.end(); - const TCHAR* first = NULL; - const TCHAR* last = NULL; + if (locale.find("utf-8") != std::string::npos) + return true; - while( cCharUtil::PopNextChar( cur, end, first, last ) ) - { - TCOUT << _T("char length: ") << (int)(last - first) << std::endl; + if (locale.find("utf8") != std::string::npos) + return true; - TCOUT << _T("char: <"); - for( const TCHAR* at = first; at != last; at++ ) - { - if( at != first ) - TCOUT << _T(","); - TCOUT << (int)*at; - } - TCOUT << _T(">") << std::endl; - } - - TCOUT << _T("----------------------------") << std::endl; - } + return false; +} + +void CheckChars(const TSTRING& str, int length_expected = 1) +{ + TSTRING::const_iterator cur = str.begin(); + TSTRING::const_iterator end = str.end(); + TSTRING::const_iterator first, last; - /////////////////////////////////////////////////////////////////////////// - // Basic - /////////////////////////////////////////////////////////////////////////// - void Basic( tss::TestContext& ctx ) + while (cCharUtil::PopNextChar(cur, end, first, last)) { - try - { - PrintChars( _T("foo") ); - PrintChars( _T("fo\x2354") ); - } - catch( eError& e ) - { - cErrorReporter::PrintErrorMsg( e ); - ASSERT(false); - } + int length = (int)(last - first); + if (length != length_expected) + TCERR << "CheckChars on '" << str << "' : expected = " << length_expected << " | observed = " << length + << std::endl; + TEST(length == length_expected); } -}; +} -TSS_BeginTestSuiteFrom( cCharEncoderTest ) - - TSS_AddTestCase( Basic ); - -TSS_EndTestSuite( cCharEncoderTest ) +/////////////////////////////////////////////////////////////////////////// +// Basic +/////////////////////////////////////////////////////////////////////////// +void TestCharUtilBasic() +{ + CheckChars("foo"); + CheckChars("fo\x23 54"); -#endif // TSS_TEST + if (localeIsUtf8()) + CheckChars("\U0001F408", 4); //Cat emoji, if UTF-8 + else + CheckChars("\U0001F408", 1); // just a bag of bytes otherwise +} -// eof: charutil_t.cpp +void RegisterSuite_CharUtil() +{ + RegisterTest("CharUtil", "Basic", TestCharUtilBasic); +} diff --git a/src/twtest/cmdlineparser_t.cpp b/src/twtest/cmdlineparser_t.cpp index 80854c0..139568e 100644 --- a/src/twtest/cmdlineparser_t.cpp +++ b/src/twtest/cmdlineparser_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,141 +38,108 @@ //#include "tw/twutil.h" //#include "tw/twstrings.h" -const int argc1 = 9; -const TCHAR* argv1[] = -{ - _T("tripwire.exe"), - _T("-m"), - _T("Init"), - _T("-tp"), - _T("one"), - _T("two"), - _T("--verbose"), - _T("frog"), - _T("cat") -}; +const int argc1 = 9; +const TCHAR* argv1[] = { + _T("tripwire"), _T("-m"), _T("Init"), _T("-tp"), _T("one"), _T("two"), _T("--verbose"), _T("frog"), _T("cat")}; -const int argc2 = 3; -const TCHAR* argv2[] = -{ - _T("tripwire.exe"), - _T("-m"), - _T("-v") -}; +const int argc2 = 3; +const TCHAR* argv2[] = {_T("tripwire"), _T("-m"), _T("-v")}; -const int argc3 = 3; -const TCHAR* argv3[] = -{ - _T("tripwire.exe"), +const int argc3 = 3; +const TCHAR* argv3[] = { + _T("tripwire"), _T("dog"), _T("-v"), }; // test with the last param wanting 1 or 0 parameters :-) -const int argc4 = 5; -const TCHAR* argv4[] = -{ - _T("tripwire.exe"), - _T("-tp"), - _T("-v"), - _T("frog"), - _T("cat") -}; +const int argc4 = 5; +const TCHAR* argv4[] = {_T("tripwire"), _T("-tp"), _T("-v"), _T("frog"), _T("cat")}; -const int argc5 = 4; -const TCHAR* argv5[] = -{ - _T("tripwire.exe"), - _T("-tp"), - _T("-v"), - _T("frog") -}; +const int argc5 = 4; +const TCHAR* argv5[] = {_T("tripwire"), _T("-tp"), _T("-v"), _T("frog")}; +#ifdef DEBUG static void PrintCmdLine(int argc, const TCHAR** argv, cDebug d) { TSTRING str; d.TraceDebug("Testing command line:\n"); - for(int i=0; i < argc; i++) + for (int i = 0; i < argc; i++) { str += argv[i]; str += _T(" "); } d.TraceDebug(_T(">>>%s\n"), str.c_str()); } +#endif -void TestCmdLineParser() +static void test_parse(cCmdLineParser& parser, const int argc, const TCHAR** argv, bool should_throw) { - enum ArgId { ID_M, ID_TP, ID_V, ID_UNNAMED }; - - try { - cCmdLineParser p; - p.AddArg(ID_M, TSTRING(_T("m")), TSTRING(_T("mode")), cCmdLineParser::PARAM_ONE); - p.AddArg(ID_TP, TSTRING(_T("tp")), TSTRING(_T("twoparam")), cCmdLineParser::PARAM_MANY); - p.AddArg(ID_V, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); - p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); - - cDebug d("TestCmdLineParser"); - - PrintCmdLine(argc1, argv1, d); - p.Parse(argc1, argv1); - #ifdef _DEBUG - p.TraceContents(); - #endif - - PrintCmdLine(argc2, argv2, d); - p.Parse(argc2, argv2); // should fail. - #ifdef _DEBUG - p.TraceContents(); - #endif - - PrintCmdLine(argc3, argv3, d); - p.Parse(argc3, argv3); // should fail - #ifdef _DEBUG - p.TraceContents(); - #endif - - PrintCmdLine(argc4, argv4, d); - p.Parse(argc4, argv4); - #ifdef _DEBUG - p.TraceContents(); - #endif - - /* - // TODO - test mutual exclusion... - - cCmdLineParser::ErrorType et; - TSTRING errStr; - d.TraceDebug("** Making -m and -v mutually exclusive, then running on first cmd line...\n"); - p.AddMutEx(ID_M, ID_V); - p.Parse(argc1, argv1); // should fail - p.GetErrorInfo(et, errStr); - TEST(et == cCmdLineParser::ERR_MUTUAL_EXCLUSION); - d.TraceDebug(_T("Mutual exclusion test worked; here is the error string: %s\n"), errStr.c_str()); - */ - - // make the command line want one parameter - d.TraceDebug("** Changing cmd line to only want one last param...\n"); - p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); - PrintCmdLine(argc4, argv4, d); - p.Parse(argc4, argv4); // should fail - #ifdef _DEBUG - p.TraceContents(); - #endif - - PrintCmdLine(argc5, argv5, d); - p.Parse(argc5, argv5); - #ifdef _DEBUG - p.TraceContents(); - #endif - - - // TODO -- test a bunch more!!! +#ifdef DEBUG + cDebug d("test_parse"); + PrintCmdLine(argc, argv, d); +#endif + + bool threw = false; + + try + { + parser.Parse(argc, argv); } - catch (eCmdLine &e) + catch (eError& e) { - TCERR << _T("Command line error: "); - TCERR << e.GetMsg() << std::endl; - //TODO... TEST(false); + if (!should_throw) + TCERR << e.GetMsg() << std::endl; + threw = true; } + + TEST(threw == should_throw); + +#ifdef DEBUG + parser.TraceContents(); +#endif } + +void TestCmdLineParser() +{ + enum ArgId + { + ID_M, + ID_TP, + ID_V, + ID_UNNAMED + }; + + cCmdLineParser p; + p.AddArg(ID_M, TSTRING(_T("m")), TSTRING(_T("mode")), cCmdLineParser::PARAM_ONE); + p.AddArg(ID_TP, TSTRING(_T("tp")), TSTRING(_T("twoparam")), cCmdLineParser::PARAM_MANY); + p.AddArg(ID_V, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE); + p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY); + + cDebug d("TestCmdLineParser"); + + test_parse(p, argc1, argv1, false); + test_parse(p, argc2, argv2, true); + test_parse(p, argc3, argv3, true); + test_parse(p, argc4, argv4, false); + + // command line arg mutual exclusion + d.TraceDebug("** Making -m and -v mutually exclusive, then running on first cmd line...\n"); + p.AddMutEx(ID_M, ID_V); + test_parse(p, argc1, argv1, true); // should fail + + // make the command line want one parameter + d.TraceDebug("** Changing cmd line to only want one last param...\n"); + p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE); + test_parse(p, argc4, argv4, true); + + test_parse(p, argc5, argv5, false); + + // TODO -- test a bunch more!!! +} + +void RegisterSuite_CmdLineParser() +{ + RegisterTest("CmdLineParser", "Basic", TestCmdLineParser); +} diff --git a/src/twtest/codeconvert_t.cpp b/src/twtest/codeconvert_t.cpp index d31a8ba..d9c938a 100644 --- a/src/twtest/codeconvert_t.cpp +++ b/src/twtest/codeconvert_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,7 +43,7 @@ #include -bool util_IsWideCharSameAsNarrow( char ch ); +bool util_IsWideCharSameAsNarrow(char ch); bool LowASCIILooksLikeUCS2InWchart(); void TestMbToDb(); void TestDbToMb(); @@ -52,139 +52,121 @@ void TestCodeConverter() { cDebug d("TestCodeConverter()"); -#if ( !(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 ) +#if 0 //( !(HAVE_ICONV_H) && WCHAR_REP_IS_UCS2 ) // // check that rep is really UCS2 // TEST( LowASCIILooksLikeUCS2InWchart() ); #endif - + d.TraceDetail("Testing multi byte to double byte conversion.\n"); TestMbToDb(); d.TraceDetail("TestMbToDb() done.\n"); -// Took out this test as it currently throws and exception. -// We expect not to be able to convert every UCS2 to a multi-byte char. -// d.TraceDetail("Testing double byte to multi byte conversion.\n"); -// TestDbToMb(); + // Took out this test as it currently throws and exception. + // We expect not to be able to convert every UCS2 to a multi-byte char. + d.TraceDetail("Testing double byte to multi byte conversion.\n"); + TestDbToMb(); } // first last identify the lhs string // x identifies the start of the second string // start identifies the original start of the lhs string -template< class IterT > -bool Compare( IterT first, IterT last, IterT x, IterT start ) +template bool Compare(IterT first, IterT last, IterT x, IterT start) { - std::pair< IterT, IterT > - p = std::mismatch( first, - last, - x ); - - if( p.first != last ) + std::pair p = std::mismatch(first, last, x); + + if (p.first != last) { // success !! - std::cout << "*** mismatched value at: " - << (int)(p.first - start) - << ". Values are: " - << (size_t)tss::util::char_to_size(*p.first) - << " and " - << (size_t)tss::util::char_to_size(*p.second) - << std::endl; - - return Compare( p.first + 1, last, p.second + 1, start ); + std::cout << "*** mismatched value at: " << (int)(p.first - start) + << ". Values are: " << (size_t)tss::util::char_to_size(*p.first) << " and " + << (size_t)tss::util::char_to_size(*p.second) << std::endl; + + return Compare(p.first + 1, last, p.second + 1, start); } return true; } -void CompareStrings( const std::string& s1, const std::string& s2 ) +void CompareStrings(const std::string& s1, const std::string& s2) { - if( s1.length() != s2.length() ) + if (s1.length() != s2.length()) { - std::cout << "*** string lengths didn't match. Lengths were: " - << s1.length() - << " and " - << s2.length() + std::cout << "*** string lengths didn't match. Lengths were: " << s1.length() << " and " << s2.length() << std::endl; } - if( Compare( s1.begin(), s1.end(), s2.begin(), s1.begin() ) ) + if (Compare(s1.begin(), s1.end(), s2.begin(), s1.begin())) { - std::cout << "** string matched." - << std::endl; + std::cout << "** string matched." << std::endl; } } - - -void DisplayString( const std::string& s ) +void DisplayString(const std::string& s) { std::string::size_type i; - for( i = 0; i < s.length(); ++i ) + for (i = 0; i < s.length(); ++i) { - std::cout << std::hex - << std::setw(2) - << std::setfill('0') - << (size_t)(unsigned char) s[i] - << " "; + std::cout << std::hex << std::setw(2) << std::setfill('0') << (size_t)(unsigned char)s[i] << " "; } } -size_t DistanceToOne( size_t n ) +size_t DistanceToOne(size_t n) { size_t dist; - for( dist = 0; - n != 1; - dist++ ) + for (dist = 0; n != 1; dist++) { - n = ( n >> 1 ); + n = (n >> 1); } - ASSERT( n == 1 ); // n was not a power of 2! + TEST(n == 1); // n was not a power of 2! return dist; } -void ConvertAndCompareString( const std::string& s ) +void ConvertAndCompareString(const std::string& s) { std::cout << "* Converting: "; - DisplayString( s ); + DisplayString(s); std::cout << std::endl; // convert to dbchar_t string - int nWrote; + int nWrote; wc16_string ws; - ws.resize( s.length() ); - nWrote = iCodeConverter::GetInstance()->Convert( (ntdbs_t)ws.c_str(), ws.length(), s.c_str(), ws.length() ); - ASSERT( nWrote != -1 ); - ws.resize( nWrote ); + ws.resize(s.length()); + nWrote = iCodeConverter::GetInstance()->Convert((ntdbs_t)ws.c_str(), ws.length(), s.c_str(), ws.length()); + TEST(nWrote != -1); + ws.resize(nWrote); // convert back to mbchar_t string std::string s2; - s2.resize( ws.length() * MB_CUR_MAX ); - nWrote = iCodeConverter::GetInstance()->Convert( (ntmbs_t)s2.c_str(), s2.length(), ws.c_str(), ws.length() ); - ASSERT( nWrote != -1 ); - s2.resize( nWrote ); + s2.resize(ws.length() * MB_CUR_MAX); + nWrote = iCodeConverter::GetInstance()->Convert((ntmbs_t)s2.c_str(), s2.length(), ws.c_str(), ws.length()); + TEST(nWrote != -1); + s2.resize(nWrote); std::cout << "* Result : "; - DisplayString( s2 ); + DisplayString(s2); std::cout << std::endl; - CompareStrings( s, s2 ); + CompareStrings(s, s2); } -char NonZeroChar( char ch ) +char NonZeroChar(char ch) { return ch == 0 ? '0' : ch; } // mbchar_t to dbchar_t +//TestMbToDb in codeconvert_t.cpp seems to hit an infinite loop or runs verrrry long; ifdef'd" void TestMbToDb() { - TCERR << "TODO: TestMbToDb in codeconvert_t.cpp seems to hit an infinite loop or runs verrrry long; ifdef'd" << std::endl; + skip("This test is flaky & needs to be fixed/replaced; currently disabled."); + #if 0 std::string s; s.resize( 0x10000 * 2 ); // two bytes for each combination @@ -194,10 +176,10 @@ void TestMbToDb() for( size_t j = 0; j < 0x10; j++ ) { size_t first_byte = ( i & 0xFF00 ) >> 8; - ASSERT( first_byte <= 0xFF ); + TEST( first_byte <= 0xFF ); size_t second_byte = ( ( i & 0x00F0 ) >> 4 ) | j; - ASSERT( second_byte <= 0xFF ); + TEST( second_byte <= 0xFF ); s[ 2 * j ] = NonZeroChar( (char)first_byte ); s[ ( 2 * j ) + 1 ] = NonZeroChar( (char)second_byte ); @@ -220,10 +202,10 @@ void TestMbToDb() for( size_t j = 0; j < CHARS_AT_A_TIME; j++ ) { size_t first_byte = ( ( i & FIRST_BYTE_MASK ) >> DistanceToOne( CHARS_AT_A_TIME ) ); - ASSERT( first_byte <= 0xFF ); + TEST( first_byte <= 0xFF ); size_t second_byte = ( ( i & ( SECOND_BYTE_MASK << DistanceToOne( CHARS_AT_A_TIME ) ) | j ); - ASSERT( second_byte <= 0xFF ); + TEST( second_byte <= 0xFF ); s[ 2 * j ] = NonZeroChar( (char)first_byte ); s[ ( 2 * j ) + 1 ] = NonZeroChar( (char)second_byte ); @@ -234,11 +216,14 @@ void TestMbToDb() */ } - + // dbchar_t to mbchar_t void TestDbToMb() { + skip("This test fails, most likely due to not speaking UTF-16. Should fix this."); + +#if 0 wc16_string ws; wc16_string::size_type n; const wc16_string::size_type max = 0x10000; @@ -262,9 +247,10 @@ void TestDbToMb() iCodeConverter::GetInstance()->Convert( (ntdbs_t)ws2.c_str(), max - 1, s.c_str(), s.length() ); TEST( ws.compare( ws2 ) == 0 ); +#endif } - +#if 0 bool util_IsWideCharSameAsNarrow( char ch ) { cDebug d("LowASCIILooksLikeUCS2InWchart()"); @@ -305,7 +291,7 @@ bool LowASCIILooksLikeUCS2InWchart() cDebug d("LowASCIILooksLikeUCS2InWchart()"); bool fOK = true; -#if 0 // I hear this function isn't even correct... rjf +# if 0 // I hear this function isn't even correct... rjf // // save old locale @@ -335,9 +321,13 @@ bool LowASCIILooksLikeUCS2InWchart() TEST( 0 == strcmp( pOldLocale, setlocale( LC_CTYPE, NULL ) ) ); free( pOldLocale ); -#endif +# endif return fOK; } +#endif -// eof: codeconvert_t.cpp - +void RegisterSuite_CodeConvert() +{ + RegisterTest("CodeConvert", "MbToDb", TestMbToDb); + RegisterTest("CodeConvert", "DbToMb", TestDbToMb); +} diff --git a/src/twtest/configfile_t.cpp b/src/twtest/configfile_t.cpp index 98a7a64..25635bc 100644 --- a/src/twtest/configfile_t.cpp +++ b/src/twtest/configfile_t.cpp @@ -1,38 +1,38 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // /////////////////////////////////////////////////////////////////////////////// //configfile_t.cpp : a test driver for cConfigFile // -//Don't see a test driver for this module in source safe - +//Don't see a test driver for this module in source safe - //hopefully this hasn't been implemented already! -DA #include "tw/stdtw.h" @@ -47,118 +47,124 @@ using namespace std; -void TestConfigFile(void) +static void assertParse(const std::string& configLineIn, bool expectValid) { - TSTRING asConfigFileText[] = - { - _T("BRIAN=foo"), // 0 fine - _T("BRIAN=foo\nBILL=bar"), // 1 fine - _T("BRIAN=foo\r\nBILL=bar"), // 2 fine - _T("BRIAN=foo\n\n\rBILL=bar\n"),// 3 fine - _T(" WS=foo \n\n\r BILL=bar\n"), // 4 fine - _T(" WS = foo \n\n\r BILL = bar \n"), // 5 fine - _T("FOO=foo\nBAR=$(FOO)"), // 6 fine - _T("FOO=foo\nBAR=$(FO)"), // 7 undefined var - _T("FOO=foo\nBAR=$(FOO"), // 8 no r paren - _T("FOO=foo\nBAR=$(FOO "), // 9 no r paren - _T("BAR=$(FOO\n"), // 10 no r paren - _T(" VAR =foo \nWS = $(VAR)\n"), // 11 fine - _T(""), // 12 fine - _T("\n"), // 13 fine - _T("\r"), // 14 fine - _T("\r\n"), // 15 fine - _T("B=POO\nA"), // 16 no equals - _T(" B=POO \n A \r"), // 17 no equals - _T("B=POO\nB=CRAP"), // 18 redefined var - _T("DATE=CRAP"), // 19 redefine predefine var - _T("B=POO\nDATE=CRAP"), // 20 redefine predefine var - _T("A=1\nB=$(A)\nC=$(B)"), // 21 fine -- checking var sub - _T("A=$(DATE)"), // 22 fine -- checking predef var sub - _T("A=1\nB=$(A)\nC=$(DATE)"), // 23 fine -- checking predef var sub - _T("A=1\n=$(A)\nC=$(DATE)"), // 24 no key - _T("A=$(DATE)-B"), // 25 fine -- check that the '-' shows up - _T("A=$(DATE)-$(DATE)"), // 26 fine -- check that the '-' shows up - }; - - /* - TSTRING sMandatory = \ - _T("\nPOLFILE=foo") \ - _T("\nDBFILE=foo") \ - _T("\nREPORTFILE=foo") \ - _T("\nSITEKEYFILE=foo") \ - _T("\nLOCALKEYFILE=foo"); - */ - - - for( TSTRING* at = &asConfigFileText[0]; - at != &asConfigFileText[countof(asConfigFileText)]; - at++ ) + static const std::string sMandatory = "\nPOLFILE=foo" + "\nDBFILE=foo" + "\nREPORTFILE=foo" + "\nSITEKEYFILE=foo" + "\nLOCALKEYFILE=foo"; + + bool threw = false; + cConfigFile cfg; + + std::string configLine = configLineIn + sMandatory; + + try + { + cfg.ReadString(configLine); + } + catch (eConfigFileMissReqKey& e) { - cConfigFile cfg; - //*at += sMandatory; - - TCERR << _T("*** line:") << std::endl; - TCERR << *at << std::endl; - TCERR << _T("*** eol:") << std::endl; - try - { - cfg.ReadString( *at ); - } - catch( eConfigFileMissReqKey& ) - { - // ignore.... - } - catch( eConfigFile& e ) - { - int offset = ( at - asConfigFileText ); - int itemSize = sizeof( asConfigFileText[0] ); - int num = offset / itemSize; - TCERR << num << std::endl; - cTWUtil::PrintErrorMsg( e ); - } + TCERR << "Got a missing key exception, which should not happen" << std::endl; + TEST(false); + } + catch (eConfigFile& e) + { + e.SetFatality(false); + cTWUtil::PrintErrorMsg(e); + + threw = true; } -#ifdef NOT_BRIANS_TEST +#ifdef _DEBUG + TCERR << "LINE [" << configLineIn << "]" << std::endl + << "Expected = " << expectValid << std::endl + << "Threw = " << threw << std::endl; +#endif + + TEST(expectValid != threw); +} + + +void TestConfigFile(void) +{ + // should succeed + assertParse(_T("BRIAN=foo"), true); // 0 fine + assertParse(_T("BRIAN=foo\nBILL=bar"), true); // 1 fine + assertParse(_T("BRIAN=foo\r\nBILL=bar"), true); // 2 fine + assertParse(_T("BRIAN=foo\n\n\rBILL=bar\n"), true); // 3 fine + assertParse(_T(" WS=foo \n\n\r BILL=bar\n"), true); // 4 fine + assertParse(_T(" WS = foo \n\n\r BILL = bar \n"), true); // 5 fine + assertParse(_T("FOO=foo\nBAR=$(FOO)"), true); // 6 fine + + // should fail + assertParse(_T("FOO=foo\nBAR=$(FO)"), false); // 7 undefined var + assertParse(_T("FOO=foo\nBAR=$(FOO"), false); // 8 no r paren + assertParse(_T("FOO=foo\nBAR=$(FOO "), false); // 9 no r paren + assertParse(_T("BAR=$(FOO\n"), false); // 10 no r paren + + // should succeed + assertParse(_T(" VAR =foo \nWS = $(VAR)\n"), true); // 11 fine + assertParse(_T(""), true); // 12 fine + assertParse(_T("\n"), true); // 13 fine + assertParse(_T("\r"), true); // 14 fine + assertParse(_T("\r\n"), true); // 15 fine + + // should fail + assertParse(_T("B=POO\nA"), false); // 16 no equals + assertParse(_T(" B=POO \n A \r"), false); // 17 no equals + + /* This next test asserts that you can't change a variable once you've defined it. + However there's no actual code in cConfigFile to check for this, and + OST appears to work fine if you redefine a config variable, so I'm not going + to change the current behavior. Leaving this test in w/ a note for reference. + + assertParse( _T("B=POO\nB=CRAP"), false ); // 18 redefined var +*/ + assertParse(_T("DATE=CRAP"), false); // 19 redefine predefine var + assertParse(_T("B=POO\nDATE=CRAP"), false); // 20 redefine predefine var + // should succeed + assertParse(_T("A=1\nB=$(A)\nC=$(B)"), true); // 21 fine -- checking var sub + assertParse(_T("A=$(DATE)"), true); // 22 fine -- checking predef var sub + assertParse(_T("A=1\nB=$(A)\nC=$(DATE)"), true); // 23 fine -- checking predef var sub + + // should fail + assertParse(_T("A=1\n=$(A)\nC=$(DATE)"), false); // 24 no key + + // should succeed + assertParse(_T("A=$(DATE)-B"), true); // 25 fine -- check that the '-' shows up + assertParse(_T("A=$(DATE)-$(DATE)"), true); // 26 fine -- check that the '-' shows up +} + +void TestConfigFile2(void) +{ cDebug d("Testconfigfile"); d.TraceDetail("Entering...\n"); - iFSServices* pFSServices = iFSServices::GetInstance(); + //iFSServices* pFSServices = iFSServices::GetInstance(); //Define some test values for pairs to be //stored in a test config. module. I'm going to use the //values specified in the install doc. -DA - TSTRING currpath; - pFSServices->GetCurrentDir(currpath); - const TSTRING testTWROOT = currpath; - const TSTRING testTWBIN = (testTWROOT + _T("/bin/")); - const TSTRING testTWCFG = (testTWROOT + _T("/etc/")); - const TSTRING testTWMAN = (testTWROOT + _T("/man/")); - const TSTRING testTWHTML = (testTWROOT + _T("/html/")); - const TSTRING testTWDB = (testTWROOT + _T("/db/")); - const TSTRING testTWKEY = (testTWROOT + _T("/key/")); - const TSTRING testTWREPORT = (testTWROOT + _T("/report/")); - const TSTRING testTWPASSWORD = (testTWROOT + _T("/null_password")); + + //TODO maybe also test read failure when mandatory config values aren't set + //Begin tests of config. module parser: cConfigFile write_cfgmod; + //Add all the mandatory config options. + write_cfgmod.Insert(_T("POLFILE"), "test.pol"); + write_cfgmod.Insert(_T("DBFILE"), "test.twd"); + write_cfgmod.Insert(_T("REPORTFILE"), "test.twr"); + write_cfgmod.Insert(_T("SITEKEYFILE"), "site.key"); + write_cfgmod.Insert(_T("LOCALKEYFILE"), "local.key"); + //Filename for writing/reading some value pairs: - const TSTRING testfile = testTWCFG + _T("tripwire.cfg"); - - //Insert the test values into cConfigFile's hashtable: - /* - write_cfgmod.Insert( _T("TWROOT"), testTWROOT); - write_cfgmod.Insert( _T("TWBIN"), testTWBIN); - write_cfgmod.Insert( _T("TWCFG"), testTWCFG); - write_cfgmod.Insert( _T("TWMAN"), testTWMAN); - write_cfgmod.Insert( _T("TWHTML"), testTWHTML); - write_cfgmod.Insert( _T("TWDB"), testTWDB); - write_cfgmod.Insert( _T("TWKEY"), testTWKEY); - write_cfgmod.Insert( _T("TWREPORT"), testTWREPORT); - write_cfgmod.Insert( _T("TWPASSWORD"), testTWPASSWORD); - */ + const TSTRING testfile = TwTestPath("tripwire.cfg"); //Store these values on disk. TSTRING configText; - write_cfgmod.WriteString(configText); + write_cfgmod.WriteString(configText); cTWUtil::WriteConfigText(testfile.c_str(), configText, false, NULL); //Instantiate another cConfigFile object for reading back @@ -173,19 +179,24 @@ void TestConfigFile(void) catch (eError& error) { TCERR << (int)error.GetID() << std::endl << error.GetMsg() << std::endl; - ASSERT(false); + TEST(false); } //These TSTRINGS will hold info. from .Lookup: TSTRING lookup1, lookup2; - read_cfgmod.Lookup( _T("TWROOT"), lookup1); - read_cfgmod.Lookup( _T("TWDB"), lookup2); + read_cfgmod.Lookup(_T("POLFILE"), lookup1); + read_cfgmod.Lookup(_T("DBFILE"), lookup2); d.TraceDetail("First lookup's value: %s \n", lookup1.c_str()); d.TraceDetail("Second lookup's value: %s \n", lookup2.c_str()); - TEST( lookup1 == testTWROOT ); - TEST( lookup2 == testTWDB ); + TEST(lookup1 == "test.pol"); + TEST(lookup2 == "test.twd"); d.TraceDetail("Tests Passed!\n"); -#endif // NOT_BRIANS_TEST +} + +void RegisterSuite_ConfigFile() +{ + RegisterTest("ConfigFile", "Basic1", TestConfigFile); + RegisterTest("ConfigFile", "Basic2", TestConfigFile2); } diff --git a/src/twtest/crypto_t.cpp b/src/twtest/crypto_t.cpp new file mode 100644 index 0000000..c8c5ed5 --- /dev/null +++ b/src/twtest/crypto_t.cpp @@ -0,0 +1,422 @@ +// +// The developer of the original code and/or files is Tripwire, Inc. +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, +// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights +// reserved. +// +// This program is free software. The contents of this file are subject +// to the terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2 of the License, or (at your +// option) any later version. You may redistribute it and/or modify it +// only in compliance with the GNU General Public License. +// +// This program is distributed in the hope that it will be useful. +// However, this program is distributed AS-IS WITHOUT ANY +// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS +// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +// USA. +// +// Nothing in the GNU General Public License or any other license to use +// the code or files shall permit you to use Tripwire's trademarks, +// service marks, or other intellectual property without Tripwire's +// prior written consent. +// +// If you have any questions, please contact Tripwire, Inc. at either +// info@tripwire.org or www.tripwire.org. +// +/////////////////////////////////////////////////////////////////////////////// +// crypto-t.cpp -- generic crypto implementations +// + +#include "twcrypto/stdtwcrypto.h" +#include "twcrypto/crypto.h" +#include "core/archive.h" +#include "twtest/test.h" + +void TestCrypto() +{ + const int COUNT = 4000; + + const int BUFSIZE = 9000; + + std::vector source_buf(BUFSIZE); + std::vector crypt_buf(COUNT + BUFSIZE); // needs to be able to hold even number of blocks + std::vector dest_buf(COUNT); + + char* source = &source_buf[0]; + char* crypt = &crypt_buf[0]; + char* dest = &dest_buf[0]; + + memcpy(source, "I love the smell of the sheep.", 31); + + +#ifdef _IDEA_ENCRYPTION + /////////////////////////////////////////////////////////////////////////// + // IDEA test + { + memset(crypt, 0, COUNT + 1024); + memset(dest, 0, COUNT); + + cIDEA crypter; + + // we use buf for when the end of the source doesn't fall on a + // blocksize boundry. + TEST(crypter.GetBlockSizePlain() < 32); + TEST(crypter.GetBlockSizeCipher() < 32); + char buf[32]; + + // encrypt the phrase + crypter.SetKey(iCipher::ENCRYPT, cHashedKey128(_T("big cow"))); + + int i, j; + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + memcpy(buf, source + i, COUNT - i); + memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); + crypter.ProcessBlock(buf, crypt + j); + break; + } + + crypter.ProcessBlock(source + i, crypt + j); + } + + // dycrypt the phrase + crypter.SetKey(iCipher::DECRYPT, cHashedKey128(_T("big cow"))); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + } +#endif + +#ifdef _RSA_ENCRYPTION + /////////////////////////////////////////////////////////////////////////// + // RSA test + { + int i, j; + + memset(crypt, 0, COUNT + 1024); + memset(dest, 0, COUNT); + + cRSA crypter(cRSA::KEY2048); + + // we use buf for when the end of the source doesn't fall on a + // blocksize boundry. + TEST(crypter.GetBlockSizePlain() < BUFSIZE); + TEST(crypter.GetBlockSizeCipher() < BUFSIZE); + char buf[BUFSIZE]; + + cRSAPublicKey* pPublic; + cRSAPrivateKey* pPrivate; + + crypter.GenerateKeys(pPrivate, pPublic); + + // save the keys to a data stream and read back in + cRSAPublicKey* pPublic2; + cRSAPrivateKey* pPrivate2; + + TEST(pPublic->GetWriteLen() < BUFSIZE); + pPublic->Write(buf); + pPublic2 = new cRSAPublicKey(buf); + + TEST(pPrivate->GetWriteLen() < BUFSIZE); + pPrivate->Write(buf); + pPrivate2 = new cRSAPrivateKey(buf); + + // we will try encrypting to a second pair of buffers and see if all goes well + char crypt2[COUNT + BUFSIZE]; + char dest2[COUNT]; + + // encrypt the phrase + crypter.SetEncrypting(pPublic); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + memcpy(buf, source + i, COUNT - i); + memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); + crypter.ProcessBlock(buf, crypt + j); + break; + } + + crypter.ProcessBlock(source + i, crypt + j); + } + + crypter.SetEncrypting(pPublic2); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + memcpy(buf, source + i, COUNT - i); + memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); + crypter.ProcessBlock(buf, crypt2 + j); + break; + } + + crypter.ProcessBlock(source + i, crypt2 + j); + } + + // You might think this test would be valid (I did), but it is not. + // The Crypto++ lib pads input with random bytes so encrypting the + // same plaintext twice will not create the same ciphertext. + //TEST(memcmp(crypt, crypt2, crypter.GetBlockSizeCipher()) == 0); + + // dycrypt the phrase + crypter.SetDecrypting(pPrivate); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + + crypter.SetDecrypting(pPrivate2); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt2 + j, buf); + memcpy(dest2 + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt2 + j, dest2 + i); + } + + TEST(memcmp(source, dest2, COUNT) == 0); + TEST(memcmp(dest, dest2, COUNT) == 0); + + // zero out things and try signing and verifying + memset(crypt, 0, COUNT + 1024); + memset(dest, 0, COUNT); + + // sign the phrase + crypter.SetSigning(pPrivate); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + memcpy(buf, source + i, COUNT - i); + memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); + crypter.ProcessBlock(buf, crypt + j); + break; + } + + crypter.ProcessBlock(source + i, crypt + j); + } + + // verify the phrase + crypter.SetVerifying(pPublic); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + + // verify the phrase again using a local public key + cRSAPublicKey publicKey(*pPrivate); + crypter.SetVerifying(&publicKey); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + + delete pPublic; + delete pPrivate; + } +#endif + + + /////////////////////////////////////////////////////////////////////////// + // El Gamal test + { + int i, j; + + TCOUT << _T("El Gamal test\n"); + + memset(crypt, 0, COUNT + 1024); + memset(dest, 0, COUNT); + + cElGamalSig crypter(cElGamalSig::KEY512); + + // we use buf for when the end of the source doesn't fall on a + // blocksize boundry. + TEST(crypter.GetBlockSizePlain() < BUFSIZE); + TEST(crypter.GetBlockSizeCipher() < BUFSIZE); + char buf[BUFSIZE]; + + cElGamalSigPublicKey* pPublic; + cElGamalSigPrivateKey* pPrivate; + + crypter.GenerateKeys(pPrivate, pPublic); + + // save the keys to a data stream and read back in + cElGamalSigPublicKey* pPublic2; + cElGamalSigPrivateKey* pPrivate2; + + TEST(pPublic->GetWriteLen() < BUFSIZE); + pPublic->Write(buf); + pPublic2 = new cElGamalSigPublicKey(buf); + + TEST(pPrivate->GetWriteLen() < BUFSIZE); + pPrivate->Write(buf); + pPrivate2 = new cElGamalSigPrivateKey(buf); + + // we will try encrypting to a second pair of buffers and see if all goes well + //char crypt2[COUNT + BUFSIZE]; + //char dest2[COUNT]; + + // zero out things and try signing and verifying + memset(crypt, 0, COUNT + 1024); + memset(dest, 0, COUNT); + + TCOUT << _T("El Gamal Signing...\n"); + + // sign the phrase + crypter.SetSigning(pPrivate); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + memcpy(buf, source + i, COUNT - i); + memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); + crypter.ProcessBlock(buf, crypt + j); + break; + } + + crypter.ProcessBlock(source + i, crypt + j); + } + + TCOUT << _T("El Gamal Verifying...\n"); + + // verify the phrase + crypter.SetVerifying(pPublic); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + + TCOUT << _T("El Gamal Verifying with serialized key...\n"); + + // verify the phrase again using a local public key + cElGamalSigPublicKey publicKey(*pPrivate); + crypter.SetVerifying(&publicKey); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + + TCOUT << _T("El Gamal Testing altered buffer...\n"); + + try + { + crypt[4] = '\x42'; + + // verify the phrase again using a local public key + cElGamalSigPublicKey publicKey(*pPrivate); + crypter.SetVerifying(&publicKey); + + for (i = 0, j = 0;; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) + { + if (i + crypter.GetBlockSizePlain() > COUNT) + { + crypter.ProcessBlock(crypt + j, buf); + memcpy(dest + i, buf, COUNT - i); + break; + } + + crypter.ProcessBlock(crypt + j, dest + i); + } + + TEST(memcmp(source, dest, COUNT) == 0); + } + catch (eArchiveCrypto&) + { + // accept eArchiveCrypto + } + catch (eArchive&) + { + TCOUT << _T("Modified Buffer Test failed!\n"); + TEST(false); + } + + delete pPublic; + delete pPrivate; + delete pPublic2; + delete pPrivate2; + } +} + +void RegisterSuite_Crypto() +{ + RegisterTest("Crypto", "Basic", TestCrypto); +} diff --git a/src/twtest/cryptoarchive_t.cpp b/src/twtest/cryptoarchive_t.cpp index 97e80c9..c2664a0 100644 --- a/src/twtest/cryptoarchive_t.cpp +++ b/src/twtest/cryptoarchive_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,10 +41,10 @@ void TestCryptoArchive() { cDebug d("TestCryptoArchive()"); - cMemoryArchive memory(0x800000); // max size 8 meg + cMemoryArchive memory(0x800000); // max size 8 meg - const int SIZEOF_CHUNK = 7; - const int NUM_CHUNKS = 1024 * 32; // 32k + const int SIZEOF_CHUNK = 7; + const int NUM_CHUNKS = 1024 * 32; // 32k const int TEST_CHUNKSIZE = 1023 * 7; d.TraceDetail("Building test memory image of size %dK bytes\n", SIZEOF_CHUNK * NUM_CHUNKS / 1024); @@ -63,20 +63,20 @@ void TestCryptoArchive() #ifdef _IDEA_ENCRYPTION - cIDEA idea; - cHashedKey128 ideaKey(_T("puddy, puddy, puddy, poo!")); + cIDEA idea; + cHashedKey128 ideaKey(_T("puddy, puddy, puddy, poo!")); { d.TraceDetail("Encrypting using symmetric key\n"); cFileArchive outFile; - outFile.OpenReadWrite(TEMP_DIR _T("/crypted.bin")); + outFile.OpenReadWrite(TwTestPath("crypted.bin")); idea.SetKey(iCipher::ENCRYPT, ideaKey); cCryptoArchive outCrypt; outCrypt.Start(&outFile, &idea); - for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile(); ) + for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile();) { int8 buf[SIZEOF_CHUNK]; memory.ReadBlob(buf, SIZEOF_CHUNK); @@ -90,7 +90,7 @@ void TestCryptoArchive() d.TraceDetail("Decrypting using symmetric key\n"); cFileArchive inFile; - inFile.OpenRead(TEMP_DIR _T("/crypted.bin")); + inFile.OpenRead(TwTestPath("crypted.bin")); idea.SetKey(iCipher::DECRYPT, ideaKey); cCryptoArchive inCrypt; @@ -101,9 +101,8 @@ void TestCryptoArchive() { int8 buf[TEST_CHUNKSIZE]; - int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) - ? TEST_CHUNKSIZE - : NUM_CHUNKS * SIZEOF_CHUNK - index; + int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) ? TEST_CHUNKSIZE : + NUM_CHUNKS * SIZEOF_CHUNK - index; inCrypt.ReadBlob(buf, s); @@ -119,59 +118,58 @@ void TestCryptoArchive() // Testing cElGamalSigArchive { - cElGamalSig cipher(cElGamalSig::KEY1024); - cElGamalSigPrivateKey* privateKey; - cElGamalSigPublicKey* publicKey; - cipher.GenerateKeys(privateKey, publicKey); + cElGamalSig cipher(cElGamalSig::KEY1024); + cElGamalSigPrivateKey* privateKey; + cElGamalSigPublicKey* publicKey; + cipher.GenerateKeys(privateKey, publicKey); - { - // encypt using private key - d.TraceDetail("Signing using asymmetric key\n"); + { + // encypt using private key + d.TraceDetail("Signing using asymmetric key\n"); - cFileArchive outFile; - outFile.OpenReadWrite(TEMP_DIR _T("/rsacrypted.bin")); + cFileArchive outFile; + outFile.OpenReadWrite(TwTestPath("rsacrypted.bin").c_str()); - cElGamalSigArchive outCrypt; - outCrypt.SetWrite(&outFile, privateKey); + cElGamalSigArchive outCrypt; + outCrypt.SetWrite(&outFile, privateKey); - for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile(); ) - { - int8 buf[SIZEOF_CHUNK]; - memory.ReadBlob(buf, SIZEOF_CHUNK); - outCrypt.WriteBlob(buf, SIZEOF_CHUNK); - } + for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile();) + { + int8 buf[SIZEOF_CHUNK]; + memory.ReadBlob(buf, SIZEOF_CHUNK); + outCrypt.WriteBlob(buf, SIZEOF_CHUNK); + } - outCrypt.FlushWrite(); - } + outCrypt.FlushWrite(); + } - { - // decrypt using public key - d.TraceDetail("Verifying using asymmetric key\n"); + { + // decrypt using public key + d.TraceDetail("Verifying using asymmetric key\n"); - cFileArchive inFile; - inFile.OpenRead(TEMP_DIR _T("/rsacrypted.bin")); + cFileArchive inFile; + inFile.OpenRead(TwTestPath("rsacrypted.bin").c_str()); - cElGamalSigArchive inCrypt; - inCrypt.SetRead(&inFile, publicKey); + cElGamalSigArchive inCrypt; + inCrypt.SetRead(&inFile, publicKey); - int index; - for (index = 0; index < NUM_CHUNKS * SIZEOF_CHUNK; index += TEST_CHUNKSIZE) - { - int8 buf[TEST_CHUNKSIZE]; + int index; + for (index = 0; index < NUM_CHUNKS * SIZEOF_CHUNK; index += TEST_CHUNKSIZE) + { + int8 buf[TEST_CHUNKSIZE]; - int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) - ? TEST_CHUNKSIZE - : NUM_CHUNKS * SIZEOF_CHUNK - index; + int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) ? TEST_CHUNKSIZE : + NUM_CHUNKS * SIZEOF_CHUNK - index; - inCrypt.ReadBlob(buf, s); + inCrypt.ReadBlob(buf, s); - memory.MapArchive(index, s); - TEST(memcmp(buf, memory.GetMap(), s) == 0); + memory.MapArchive(index, s); + TEST(memcmp(buf, memory.GetMap(), s) == 0); + } } - } - delete privateKey; - delete publicKey; + delete privateKey; + delete publicKey; } #ifdef _RSA_ENCRYPTION @@ -180,11 +178,11 @@ void TestCryptoArchive() cRSAPublicKey* publicKey; cipher.GenerateKeys(privateKey, publicKey); - cIDEA idea; - cHashedKey128 ideaKey(_T("puddy, puddy, puddy, poo!")); + cIDEA idea; + cHashedKey128 ideaKey(_T("puddy, puddy, puddy, poo!")); - const int SIZEOF_CHUNK = 7; - const int NUM_CHUNKS = 1024 * 32; // 32k + const int SIZEOF_CHUNK = 7; + const int NUM_CHUNKS = 1024 * 32; // 32k const int TEST_CHUNKSIZE = 1023 * 7; d.TraceDetail("Building test memory image of size %dK bytes\n", SIZEOF_CHUNK * NUM_CHUNKS / 1024); @@ -206,12 +204,12 @@ void TestCryptoArchive() d.TraceDetail("Encrypting using asymmetric key\n"); cFileArchive outFile; - outFile.OpenReadWrite(TEMP_DIR _T("/rsacrypted.bin")); + outFile.OpenReadWrite(TwTestPath("rsacrypted.bin").c_str()); cRSAArchive outCrypt; outCrypt.SetWrite(&outFile, publicKey); - for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile(); ) + for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile();) { int8 buf[SIZEOF_CHUNK]; memory.ReadBlob(buf, SIZEOF_CHUNK); @@ -226,7 +224,7 @@ void TestCryptoArchive() d.TraceDetail("Decrypting using asymmetric key\n"); cFileArchive inFile; - inFile.OpenRead(TEMP_DIR _T("/rsacrypted.bin")); + inFile.OpenRead(TwTestPath("rsacrypted.bin").c_str()); cRSAArchive inCrypt; inCrypt.SetRead(&inFile, privateKey); @@ -236,9 +234,8 @@ void TestCryptoArchive() { int8 buf[TEST_CHUNKSIZE]; - int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) - ? TEST_CHUNKSIZE - : NUM_CHUNKS * SIZEOF_CHUNK - index; + int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) ? TEST_CHUNKSIZE : + NUM_CHUNKS * SIZEOF_CHUNK - index; inCrypt.ReadBlob(buf, s); @@ -252,12 +249,12 @@ void TestCryptoArchive() d.TraceDetail("Signing using asymmetric key\n"); cFileArchive outFile; - outFile.OpenReadWrite(TEMP_DIR _T("/rsacrypted.bin")); + outFile.OpenReadWrite(TwTestPath("rsacrypted.bin").c_str()); cRSAArchive outCrypt; outCrypt.SetWrite(&outFile, privateKey); - for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile(); ) + for (memory.Seek(0, cBidirArchive::BEGINNING); !memory.EndOfFile();) { int8 buf[SIZEOF_CHUNK]; memory.ReadBlob(buf, SIZEOF_CHUNK); @@ -272,7 +269,7 @@ void TestCryptoArchive() d.TraceDetail("Verifying using asymmetric key\n"); cFileArchive inFile; - inFile.OpenRead(TEMP_DIR _T("/rsacrypted.bin")); + inFile.OpenRead(TwTestPath("rsacrypted.bin").c_str()); cRSAArchive inCrypt; inCrypt.SetRead(&inFile, publicKey); @@ -282,9 +279,8 @@ void TestCryptoArchive() { int8 buf[TEST_CHUNKSIZE]; - int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) - ? TEST_CHUNKSIZE - : NUM_CHUNKS * SIZEOF_CHUNK - index; + int s = (index + TEST_CHUNKSIZE <= NUM_CHUNKS * SIZEOF_CHUNK) ? TEST_CHUNKSIZE : + NUM_CHUNKS * SIZEOF_CHUNK - index; inCrypt.ReadBlob(buf, s); @@ -299,4 +295,7 @@ void TestCryptoArchive() #endif } - +void RegisterSuite_CryptoArchive() +{ + RegisterTest("CryptoArchive", "Basic", TestCryptoArchive); +} diff --git a/src/twtest/crytpo_t.cpp b/src/twtest/crytpo_t.cpp deleted file mode 100644 index 6d30c83..0000000 --- a/src/twtest/crytpo_t.cpp +++ /dev/null @@ -1,412 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// crypto-t.cpp -- generic crypto implementations -// - -#include "twcrypto/stdtwcrypto.h" -#include "twcrypto/crypto.h" -#include "core/archive.h" -#include "twtest/test.h" - -void TestCrypto() -{ - const int COUNT = 4000; - - const int BUFSIZE = 9000; - - char source[BUFSIZE]; - char crypt[COUNT + BUFSIZE]; // needs to be able to hold even number of blocks - char dest[COUNT]; - - memcpy(source, "I love the smell of the sheep.", 31); - - -#ifdef _IDEA_ENCRYPTION - /////////////////////////////////////////////////////////////////////////// - // IDEA test - { - memset(crypt, 0, COUNT + 1024); - memset(dest, 0, COUNT); - - cIDEA crypter; - - // we use buf for when the end of the source doesn't fall on a - // blocksize boundry. - TEST(crypter.GetBlockSizePlain() < 32); - TEST(crypter.GetBlockSizeCipher() < 32); - char buf[32]; - - // encrypt the phrase - crypter.SetKey(iCipher::ENCRYPT, cHashedKey128(_T("big cow"))); - - int i, j; - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - memcpy(buf, source + i, COUNT - i); - memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); - crypter.ProcessBlock(buf, crypt + j); - break; - } - - crypter.ProcessBlock(source + i, crypt + j); - } - - // dycrypt the phrase - crypter.SetKey(iCipher::DECRYPT, cHashedKey128(_T("big cow"))); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - } -#endif - -#ifdef _RSA_ENCRYPTION - /////////////////////////////////////////////////////////////////////////// - // RSA test - { - int i, j; - - memset(crypt, 0, COUNT + 1024); - memset(dest, 0, COUNT); - - cRSA crypter(cRSA::KEY2048); - - // we use buf for when the end of the source doesn't fall on a - // blocksize boundry. - TEST(crypter.GetBlockSizePlain() < BUFSIZE); - TEST(crypter.GetBlockSizeCipher() < BUFSIZE); - char buf[BUFSIZE]; - - cRSAPublicKey* pPublic; - cRSAPrivateKey* pPrivate; - - crypter.GenerateKeys(pPrivate, pPublic); - - // save the keys to a data stream and read back in - cRSAPublicKey* pPublic2; - cRSAPrivateKey* pPrivate2; - - ASSERT(pPublic->GetWriteLen() < BUFSIZE); - pPublic->Write(buf); - pPublic2 = new cRSAPublicKey(buf); - - ASSERT(pPrivate->GetWriteLen() < BUFSIZE); - pPrivate->Write(buf); - pPrivate2 = new cRSAPrivateKey(buf); - - // we will try encrypting to a second pair of buffers and see if all goes well - char crypt2[COUNT + BUFSIZE]; - char dest2[COUNT]; - - // encrypt the phrase - crypter.SetEncrypting(pPublic); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - memcpy(buf, source + i, COUNT - i); - memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); - crypter.ProcessBlock(buf, crypt + j); - break; - } - - crypter.ProcessBlock(source + i, crypt + j); - } - - crypter.SetEncrypting(pPublic2); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - memcpy(buf, source + i, COUNT - i); - memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); - crypter.ProcessBlock(buf, crypt2 + j); - break; - } - - crypter.ProcessBlock(source + i, crypt2 + j); - } - - // You might think this test would be valid (I did), but it is not. - // The Crypto++ lib pads input with random bytes so encrypting the - // same plaintext twice will not create the same ciphertext. - //TEST(memcmp(crypt, crypt2, crypter.GetBlockSizeCipher()) == 0); - - // dycrypt the phrase - crypter.SetDecrypting(pPrivate); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - - crypter.SetDecrypting(pPrivate2); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt2 + j, buf); - memcpy(dest2 + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt2 + j, dest2 + i); - } - - TEST(memcmp(source, dest2, COUNT) == 0); - TEST(memcmp(dest, dest2, COUNT) == 0); - - // zero out things and try signing and verifying - memset(crypt, 0, COUNT + 1024); - memset(dest, 0, COUNT); - - // sign the phrase - crypter.SetSigning(pPrivate); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - memcpy(buf, source + i, COUNT - i); - memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); - crypter.ProcessBlock(buf, crypt + j); - break; - } - - crypter.ProcessBlock(source + i, crypt + j); - } - - // verify the phrase - crypter.SetVerifying(pPublic); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - - // verify the phrase again using a local public key - cRSAPublicKey publicKey(*pPrivate); - crypter.SetVerifying(&publicKey); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - - delete pPublic; - delete pPrivate; - } -#endif - - - /////////////////////////////////////////////////////////////////////////// - // El Gamal test - { - int i, j; - - TCOUT << _T("El Gamal test\n"); - - memset(crypt, 0, COUNT + 1024); - memset(dest, 0, COUNT); - - cElGamalSig crypter(cElGamalSig::KEY512); - - // we use buf for when the end of the source doesn't fall on a - // blocksize boundry. - TEST(crypter.GetBlockSizePlain() < BUFSIZE); - TEST(crypter.GetBlockSizeCipher() < BUFSIZE); - char buf[BUFSIZE]; - - cElGamalSigPublicKey* pPublic; - cElGamalSigPrivateKey* pPrivate; - - crypter.GenerateKeys(pPrivate, pPublic); - - // save the keys to a data stream and read back in - cElGamalSigPublicKey* pPublic2; - cElGamalSigPrivateKey* pPrivate2; - - ASSERT(pPublic->GetWriteLen() < BUFSIZE); - pPublic->Write(buf); - pPublic2 = new cElGamalSigPublicKey(buf); - - ASSERT(pPrivate->GetWriteLen() < BUFSIZE); - pPrivate->Write(buf); - pPrivate2 = new cElGamalSigPrivateKey(buf); - - // we will try encrypting to a second pair of buffers and see if all goes well - //char crypt2[COUNT + BUFSIZE]; - //char dest2[COUNT]; - - // zero out things and try signing and verifying - memset(crypt, 0, COUNT + 1024); - memset(dest, 0, COUNT); - - TCOUT << _T("El Gamal Signing...\n"); - - // sign the phrase - crypter.SetSigning(pPrivate); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - memcpy(buf, source + i, COUNT - i); - memset(buf + COUNT - i, 0, crypter.GetBlockSizePlain() - COUNT + i); - crypter.ProcessBlock(buf, crypt + j); - break; - } - - crypter.ProcessBlock(source + i, crypt + j); - } - - TCOUT << _T("El Gamal Verifying...\n"); - - // verify the phrase - crypter.SetVerifying(pPublic); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - - TCOUT << _T("El Gamal Verifying with serialized key...\n"); - - // verify the phrase again using a local public key - cElGamalSigPublicKey publicKey(*pPrivate); - crypter.SetVerifying(&publicKey); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - - TCOUT << _T("El Gamal Testing altered buffer...\n"); - - try - { - crypt[4] = '\x42'; - - // verify the phrase again using a local public key - cElGamalSigPublicKey publicKey(*pPrivate); - crypter.SetVerifying(&publicKey); - - for (i = 0, j = 0; ; i += crypter.GetBlockSizePlain(), j += crypter.GetBlockSizeCipher()) - { - if (i + crypter.GetBlockSizePlain() > COUNT) - { - crypter.ProcessBlock(crypt + j, buf); - memcpy(dest + i, buf, COUNT - i); - break; - } - - crypter.ProcessBlock(crypt + j, dest + i); - } - - TEST(memcmp(source, dest, COUNT) == 0); - } - catch (eArchiveCrypto&) - { - // accept eArchiveCrypto - } - catch (eArchive&) - { - TCOUT << _T("Modified Buffer Test failed!\n"); - TEST(false); - } - - delete pPublic; - delete pPrivate; - } -} - diff --git a/src/twtest/dbdatasource_t.cpp b/src/twtest/dbdatasource_t.cpp index 0f83e09..97bbc01 100644 --- a/src/twtest/dbdatasource_t.cpp +++ b/src/twtest/dbdatasource_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,261 +40,180 @@ #include "fco/fcopropset.h" #include "fco/fcoprop.h" #include "fco/fco.h" +#include "twtest/test.h" +#include "fs/fsobject.h" -static void GetNoun( TSTRING& noun ) +static void AddFile(cDbDataSourceIter& iter, const TSTRING& filename, bool with_data = false) { - static TSTRING prevNoun; - TCIN >> noun; - if( noun.compare( _T("!$") ) == 0 ) + if (iter.SeekTo(filename.c_str())) + TCOUT << "Object " << filename << " already exists!" << std::endl; + + cFCOName fname(filename); + + if (with_data) + { + iFCO* pFCO = new cFSObject(fname); + iter.AddFCO(filename, pFCO); + } + else { - noun = prevNoun; + iter.AddFCO(filename, 0); } - prevNoun = noun; + + TEST(iter.HasFCOData() == with_data); } -// -// TODO -- implement this with the prop displayer as well! -// -static void PrintFCO( const iFCO* pFCO ) +static void AddDirectory(cDbDataSourceIter& iter, const TSTRING& filename) { - TCOUT.setf(std::ios::left); - - TCOUT << "------- " << pFCO->GetName().AsString() << " -------" << std::endl; - // - // iterate over all of the properties - // - const iFCOPropSet* pPropSet = pFCO->GetPropSet(); - cFCOPropVector v = pPropSet->GetValidVector(); - for( int i=0; i < pPropSet->GetNumProps(); i++ ) - { - if( v.ContainsItem( i ) ) - { - TCOUT << "["; - TCOUT.width(2); - TCOUT << i << "]" ; - TCOUT.width(25); - TCOUT << pPropSet->GetPropName(i); - TCOUT.width(0); - TCOUT << pPropSet->GetPropAt( i )->AsString() << std::endl; - } - } - TCOUT << "--------------------------------------------" << std::endl; + if (iter.SeekTo(filename.c_str())) + TCOUT << "Object " << filename << " already exists!" << std::endl; + + iter.AddFCO(filename, 0); + iter.AddChildArray(); + + TEST(iter.CanDescend()); } +static void RemoveDirectory(cDbDataSourceIter& iter, const TSTRING& filename) +{ + TCOUT << "Removing the child of " << filename << std::endl; + if (iter.SeekTo(filename.c_str())) + { + iter.RemoveChildArray(); + iter.RemoveFCO(); + } + else + { + TCOUT << "Unable to find object " << filename << std::endl; + } +} -void TestDbDataSource() +static void RemoveFile(cDbDataSourceIter& iter, const TSTRING& filename) { - cDebug d("TestDbDataSource"); - cHierDatabase db; + TCOUT << "Removing object " << filename << std::endl; + cFCOName fname(filename); + iter.SeekToFCO(fname); - const TSTRING dbName = _T("c:/tmp/tw.db"); + if (iter.CanDescend()) + { + TCOUT << "Can't delete object; it still has children." << std::endl; + } + else + { + iter.RemoveFCOData(); + iter.RemoveFCO(); + } +} - try +static void ChDir(cDbDataSourceIter& iter, const TSTRING& filename) +{ + if (filename.compare(_T("..")) == 0) { - // TODO -- get the case sensitiveness and delimiting char out of the factory instead of iFSServices - // - TCOUT << _T("Opening database ") << dbName << std::endl; - db.Open( dbName, 5, false ); - cDbDataSourceIter iter( &db ); + if (iter.AtRoot()) + TCOUT << "At root already" << std::endl; - //////////////////////////// - // the main event loop... - //////////////////////////// - while( true ) + TCOUT << "Ascending..." << std::endl; + iter.Ascend(); + } + else + { + if (iter.SeekTo(filename.c_str())) { - TSTRING verb, noun; - TCOUT << _T(">>"); - TCIN >> verb; - // - // ok, now we switch on the command... - // - //----------------------------------------------------------------- - // quit - //----------------------------------------------------------------- - if( verb.compare( _T("quit") ) == 0 ) - { - // the quit command... - break; - } - //----------------------------------------------------------------- - // print - //----------------------------------------------------------------- - if( verb.compare( _T("print") ) == 0 ) - { - GetNoun(noun); - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.HasFCOData() ) - { - iFCO* pFCO = iter.CreateFCO(); - PrintFCO( pFCO ); - pFCO->Release(); - } - else - { - TCOUT << "Object has no data associated with it." << std::endl; - } - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // mkdir - //----------------------------------------------------------------- - else if( verb.compare( _T("mkdir") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Making a child of " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - iter.AddChildArray(); - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // mk - //----------------------------------------------------------------- - else if( verb.compare( _T("mk") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Making object " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - TCOUT << "Error: object already exists!" << std::endl; - } - else - { - iter.AddFCO( noun, 0 ); // add a null fco for now - } - } - //----------------------------------------------------------------- - // rmdir - //----------------------------------------------------------------- - // TODO -- still needs to be implemented in the iterator class! - // - /* - else if( verb.compare( _T("rmdir") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Removing the child of " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - //TODO -- check that it has an empty child - iter.DeleteChildArray(); - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - */ - //----------------------------------------------------------------- - // rm - //----------------------------------------------------------------- - else if( verb.compare( _T("rm") ) == 0 ) - { - GetNoun(noun); - TCOUT << "Removing object " << noun << std::endl; - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << "Can't delete object; it still has children." << std::endl; - } - else - { - iter.RemoveFCO(); - } - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - //----------------------------------------------------------------- - // pwd - //----------------------------------------------------------------- - else if( verb.compare( _T("pwd") ) == 0 ) - { - TCOUT << iter.GetParentName().AsString() << std::endl; - } - //----------------------------------------------------------------- - // ls - //----------------------------------------------------------------- - else if( verb.compare( _T("ls") ) == 0 ) - { - int cnt = 0; - for( iter.SeekBegin(); ! iter.Done(); iter.Next(), cnt++ ) - { - TCOUT << "[" << cnt ; - if( iter.CanDescend() ) - { - TCOUT << "]*\t" ; - } - else - { - TCOUT << "]\t" ; - } - TCOUT << iter.GetShortName() << std::endl; - } - } - //----------------------------------------------------------------- - // cd - //----------------------------------------------------------------- - else if( verb.compare( _T("cd") ) == 0 ) - { - GetNoun(noun); - if( noun.compare( _T("..") ) == 0 ) - { - if( iter.AtRoot() ) - { - TCOUT << "Can't ascend above root." << std::endl; - } - else - { - TCOUT << "Ascending..." << std::endl; - iter.Ascend(); - } - } - else - { - if( iter.SeekTo( noun.c_str() ) ) - { - if( iter.CanDescend() ) - { - TCOUT << "Descending into " << noun << std::endl; - iter.Descend(); - } - else - { - TCOUT << noun << " has no children; can't descend." << std::endl; - } - } - else - { - TCOUT << "Unable to find object " << noun << std::endl; - } - } - } + if (!iter.CanDescend()) + TCOUT << filename << " has no children; can't descend." << std::endl; - // make sure the file is still valid... - // -#ifdef _BLOCKFILE_DEBUG - db.AssertAllBlocksValid() ; -#endif + TCOUT << "Descending into " << filename << std::endl; + iter.Descend(); } + else + { + TCOUT << "Unable to find object " << filename << std::endl; + } + } +} - TCOUT << "Exiting..." << std::endl; +static void AssertData(cDbDataSourceIter& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + TEST(exists == should_have); + if (exists) + { + bool has_data = iter.HasFCOData(); + TEST(has_data == should_have); + if (has_data) + { + iFCO* pFCO = iter.CreateFCO(); + TEST(pFCO); + TCOUT << "Roundtrip FCOName = " << pFCO->GetName().AsString() << std::endl; + TSTRING expected = filename + "/"; + TEST(pFCO->GetName().AsString() == expected); + } } - catch( eError& e ) +} + +static void AssertExists(cDbDataSourceIter& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + TEST(exists == should_have); +} + +static void AssertChildren(cDbDataSourceIter& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + + if (exists) { - d.TraceError("*** Caught error: %d %s\n", e.GetID(), e.GetMsg().c_str() ); + bool has_children = iter.CanDescend(); + TEST(has_children == should_have); } } + +void TestDbDataSourceBasic() +{ + cHierDatabase db; + std::string dbpath = TwTestPath("test.db"); + db.Open(dbpath, 5, true); + cDbDataSourceIter iter(&db); + + AddFile(iter, "file1", true); + AddFile(iter, "file2", false); + AddFile(iter, "file3", false); + + AddDirectory(iter, "dir1"); + AddDirectory(iter, "dir2"); + AddDirectory(iter, "dir3"); + + AssertData(iter, "file1", true); + + ChDir(iter, "dir1"); + AddFile(iter, "dir1_file1"); + ChDir(iter, ".."); + + RemoveFile(iter, "file1"); + RemoveFile(iter, "file2"); + + AssertExists(iter, "file1", false); + AssertExists(iter, "file2", false); + AssertExists(iter, "file3", true); + + RemoveDirectory(iter, "dir2"); + + AssertExists(iter, "dir1", true); + AssertExists(iter, "dir2", false); + AssertExists(iter, "dir3", true); + + AssertChildren(iter, "dir1", true); + AssertChildren(iter, "dir3", true); + AssertChildren(iter, "file3", false); + +#ifdef DEBUG + db.AssertAllBlocksValid(); +#endif +} + +void RegisterSuite_DbDataSource() +{ + RegisterTest("DbDataSource", "Basic", TestDbDataSourceBasic); +} diff --git a/src/twtest/debug_t.cpp b/src/twtest/debug_t.cpp index 26ab5bf..633792c 100644 --- a/src/twtest/debug_t.cpp +++ b/src/twtest/debug_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,17 +48,20 @@ void TestDebug() // test debug level variation... d.TraceDebug("Setting debug level to Debug(%d)\n", cDebug::D_DEBUG); cDebug::SetDebugLevel(cDebug::D_DEBUG); - d.TraceDebug ("You should see this, as well as line 2 below, but not line 3.\n"); - d.TraceWarning ("Line 2: Warning(%d)\n", cDebug::D_WARNING); - d.TraceDetail ("Line 3: Detail(%d)\n", cDebug::D_DETAIL); - d.TraceDebug ("Restoring the debug level to %d\n", oldDebugLevel); + d.TraceDebug("You should see this, as well as line 2 below, but not line 3.\n"); + d.TraceWarning("Line 2: Warning(%d)\n", cDebug::D_WARNING); + d.TraceDetail("Line 3: Detail(%d)\n", cDebug::D_DETAIL); + d.TraceDebug("Restoring the debug level to %d\n", oldDebugLevel); cDebug::SetDebugLevel(oldDebugLevel); // testing the output source int oldOutTarget = 0; - if(cDebug::HasOutTarget(cDebug::OUT_STDOUT)) oldOutTarget |= cDebug::OUT_STDOUT; - if(cDebug::HasOutTarget(cDebug::OUT_TRACE)) oldOutTarget |= cDebug::OUT_TRACE; - if(cDebug::HasOutTarget(cDebug::OUT_FILE)) oldOutTarget |= cDebug::OUT_FILE; + if (cDebug::HasOutTarget(cDebug::OUT_STDOUT)) + oldOutTarget |= cDebug::OUT_STDOUT; + if (cDebug::HasOutTarget(cDebug::OUT_TRACE)) + oldOutTarget |= cDebug::OUT_TRACE; + if (cDebug::HasOutTarget(cDebug::OUT_FILE)) + oldOutTarget |= cDebug::OUT_FILE; cDebug::RemoveOutTarget(cDebug::OUT_STDOUT); cDebug::RemoveOutTarget(cDebug::OUT_TRACE); cDebug::RemoveOutTarget(cDebug::OUT_FILE); @@ -70,24 +73,40 @@ void TestDebug() d.TraceDebug("You should see this in stdout and trace.\n"); cDebug::RemoveOutTarget(cDebug::OUT_STDOUT); d.TraceDebug("You should see this in trace only.\n"); + + // set up an output file...use the temp file in test.h - std::string str = TEMP_DIR_N; - str += "/debug.out"; - bool bResult = false; - bResult = cDebug::SetOutputFile(str.c_str()); - //TODO... TEST(bResult); - if( !bResult) - TCERR << "SetOutputFile failed!" << std::endl; + std::string str = TwTestPath("debug.out"); + +#ifdef DEBUG + TEST(cDebug::SetOutputFile(str.c_str())); +#endif d.TraceDebug("This should be in trace and the file %s.\n", str.c_str()); // restore the out source... // TODO -- note that the original output file cannot be restored; this sucks! - if(oldOutTarget & cDebug::OUT_STDOUT) cDebug::AddOutTarget(cDebug::OUT_STDOUT); else cDebug::RemoveOutTarget(cDebug::OUT_STDOUT); - if(oldOutTarget & cDebug::OUT_TRACE) cDebug::AddOutTarget(cDebug::OUT_TRACE); else cDebug::RemoveOutTarget(cDebug::OUT_TRACE); - if(oldOutTarget & cDebug::OUT_FILE) cDebug::AddOutTarget(cDebug::OUT_FILE); else cDebug::RemoveOutTarget(cDebug::OUT_FILE); + if (oldOutTarget & cDebug::OUT_STDOUT) + cDebug::AddOutTarget(cDebug::OUT_STDOUT); + else + cDebug::RemoveOutTarget(cDebug::OUT_STDOUT); + if (oldOutTarget & cDebug::OUT_TRACE) + cDebug::AddOutTarget(cDebug::OUT_TRACE); + else + cDebug::RemoveOutTarget(cDebug::OUT_TRACE); + if (oldOutTarget & cDebug::OUT_FILE) + cDebug::AddOutTarget(cDebug::OUT_FILE); + else + cDebug::RemoveOutTarget(cDebug::OUT_FILE); d.TraceDebug("Exiting...\n"); -} +#ifndef DEBUG + TEST("Should always succeed in release builds & cDebug should do nothing"); +#endif +} +void RegisterSuite_Debug() +{ + RegisterTest("Debug", "Basic", TestDebug); +} diff --git a/src/twtest/displayencoder_t.cpp b/src/twtest/displayencoder_t.cpp index ce3bc80..ad8e372 100644 --- a/src/twtest/displayencoder_t.cpp +++ b/src/twtest/displayencoder_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,31 +37,25 @@ #include "core/stdcore.h" -#ifdef TSS_TEST - -#include "test/utx.h" -#include "displayencoder.h" -#include "debug.h" -#include "twlocale.h" -#include "errorbucketimpl.h" +#include "core/displayencoder.h" +#include "core/debug.h" +#include "core/twlocale.h" +#include "core/errorbucketimpl.h" +#include "twtest/test.h" /////////////////////////////////////////////////////////////////////////////// -// UTIL +// UTIL /////////////////////////////////////////////////////////////////////////////// -#ifdef _UNICODE - #define TSS_TCHAR_MIN WCHAR_MIN - #define TSS_TCHAR_MAX WCHAR_MAX -#else - #define TSS_TCHAR_MIN CHAR_MIN - #define TSS_TCHAR_MAX CHAR_MAX -#endif +#define TSS_TCHAR_MIN CHAR_MIN +#define TSS_TCHAR_MAX CHAR_MAX +/* template< class CharT > bool IsPrintable( const std::basic_string< CharT >& str ) { const std::ctype< CharT > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - for( std::basic_string< CharT >::const_iterator at = str.begin(); at != str.end(); at++ ) + for( std::basic_string< CharT >::const_iterator at = str.begin(); at != str.end(); ++at ) { if( ! ct.is( std::ctype_base::print, *at ) ) // if not printable return false; @@ -69,299 +63,278 @@ template< class CharT > bool IsPrintable( const std::basic_string< CharT >& str return true; } +*/ -static void util_TestUnprintable( const TSTRING& strCUnprintable ) +static void util_TestUnprintable(const TSTRING& strCUnprintable) { - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - TSTRING strEncoded = strCUnprintable; + cDisplayEncoder e(cDisplayEncoder::ROUNDTRIP); + TSTRING strEncoded = strCUnprintable; - e.Encode( strEncoded ); - TCOUT << strEncoded << std::endl; + e.Encode(strEncoded); + // TCOUT << strEncoded << std::endl; TSTRING strOut = strEncoded; - e.Decode( strOut ); + e.Decode(strOut); - ASSERT( strOut == strCUnprintable ); + TEST(strOut == strCUnprintable); } -/////////////////////////////////////////////////////////////////////////////// -// cDisplayEncoderTest -/////////////////////////////////////////////////////////////////////////////// -class cDisplayEncoderTest +/////////////////////////////////////////////////////////////////////////// +// TestCharToHex +/////////////////////////////////////////////////////////////////////////// +void test_char_to_hex(char ch, const TSTRING& expected) { -public: + TSTRING observed = cCharEncoderUtil::char_to_hex(ch); + TEST(expected == observed); +} - /////////////////////////////////////////////////////////////////////////// - // TestCharToHex - /////////////////////////////////////////////////////////////////////////// - void TestCharToHex( tss::TestContext& ctx ) - { - TCHAR ch; - TSTRING str; - const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - - // only use lowercase strings with this define - #define TSS_CHAR_TO_HEX_TEST( s ) \ - ch = 0x ## s; \ - str = cCharEncoderUtil::char_to_hex( ch ); \ - ct.tolower( str.begin(), str.end() ); \ - ASSERT( str == _T( #s ) ); - - TSS_CHAR_TO_HEX_TEST( fefe ); - TSS_CHAR_TO_HEX_TEST( 0000 ); - TSS_CHAR_TO_HEX_TEST( 1234 ); - TSS_CHAR_TO_HEX_TEST( ffff ); - TSS_CHAR_TO_HEX_TEST( 0001 ); - TSS_CHAR_TO_HEX_TEST( 543c ); - TSS_CHAR_TO_HEX_TEST( cccc ); - TSS_CHAR_TO_HEX_TEST( 9999 ); - TSS_CHAR_TO_HEX_TEST( abcd ); - } - /////////////////////////////////////////////////////////////////////////// - // TestHexToChar - /////////////////////////////////////////////////////////////////////////// - void TestHexToChar( tss::TestContext& ctx ) - { - TCHAR ch; - TSTRING str; - - // only use lowercase strings with this define - #define TSS_HEX_TO_CHAR_TEST( s ) \ - str = _T( #s ); \ - ch = cCharEncoderUtil::hex_to_char( str.begin(), str.end() ); \ - ASSERT( ch == 0x ## s ); - - TSS_HEX_TO_CHAR_TEST( fefe ); - TSS_HEX_TO_CHAR_TEST( 0000 ); - TSS_HEX_TO_CHAR_TEST( 1234 ); - TSS_HEX_TO_CHAR_TEST( ffff ); - TSS_HEX_TO_CHAR_TEST( 0001 ); - TSS_HEX_TO_CHAR_TEST( 543c ); - TSS_HEX_TO_CHAR_TEST( cccc ); - TSS_HEX_TO_CHAR_TEST( 9999 ); - TSS_HEX_TO_CHAR_TEST( abcd ); - } +void TestCharToHex() +{ + test_char_to_hex(0xfe, "fe"); + test_char_to_hex(0xff, "ff"); + test_char_to_hex(0x00, "00"); + test_char_to_hex(0x01, "01"); + test_char_to_hex(0x7f, "7f"); + test_char_to_hex(0x80, "80"); +} - ////////////////////////////////////////////////////////////////////////// - // TestStringToHex -- locale specific test -- only works in ASCII - /////////////////////////////////////////////////////////////////////////// - void TestStringToHex( tss::TestContext& ctx ) - { - TSTRING str; - const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - - // only use lowercase strings with this define - #define TSS_STRING_TO_HEX_TEST( s, n ) \ - str = cCharEncoderUtil::CharStringToHexValue( _T( #s ) ); \ - ct.tolower( str.begin(), str.end() ); \ - ASSERT( str == _T( #n ) ); - - TSS_STRING_TO_HEX_TEST( \n, 000a ); - TSS_STRING_TO_HEX_TEST( \r, 000d ); - TSS_STRING_TO_HEX_TEST( \r\n, 000d000a ); - TSS_STRING_TO_HEX_TEST( a\r\nb, 0061000d000a0062 ); - } - ////////////////////////////////////////////////////////////////////////// - // TestHexToString -- locale specific test -- only works in Unicode - /////////////////////////////////////////////////////////////////////////// - void TestHexToString( tss::TestContext& ctx ) +/////////////////////////////////////////////////////////////////////////// +// TestHexToChar +/////////////////////////////////////////////////////////////////////////// +void test_hex_to_char(const TSTRING& str, char expected, bool should_throw = false) +{ + bool threw = false; + try { - TSTRING str; - const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - - // only use lowercase strings with this define - #define TSS_HEX_TO_STRING_TEST( s, n ) \ - str = cCharEncoderUtil::HexValueToCharString( _T( #n ) ); \ - ct.tolower( str.begin(), str.end() ); \ - ASSERT( str == _T( #s ) ); - - TSS_HEX_TO_STRING_TEST( \n, 000a ); - TSS_HEX_TO_STRING_TEST( \r, 000d ); - TSS_HEX_TO_STRING_TEST( \r\n, 000d000a ); - TSS_HEX_TO_STRING_TEST( a\r\nb, 0061000d000a0062 ); + char observed = cCharEncoderUtil::hex_to_char(str.begin(), str.end()); + TEST(expected == observed); } - - ////////////////////////////////////////////////////////////////////////// - // TestUnconvertable -- locale specific test -- only works in Unicode - /////////////////////////////////////////////////////////////////////////// - void TestUnconvertable( tss::TestContext& ctx ) + catch (eError& e) { - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - TSTRING str; - TCHAR ch; - - // only use lowercase strings with this define - #define TSS_UNCONVERTABLE_TEST( n ) \ - ch = 0x ## n; \ - str = ch; \ - e.Encode( str ); \ - ct.tolower( str.begin(), str.end() ); \ - ASSERT( str == _T("\\x") _T( #n ) _T("x") ); - - TSS_UNCONVERTABLE_TEST( fefe ); - TSS_UNCONVERTABLE_TEST( 1234 ); - TSS_UNCONVERTABLE_TEST( ffff ); - TSS_UNCONVERTABLE_TEST( 1000 ); - TSS_UNCONVERTABLE_TEST( 543c ); - TSS_UNCONVERTABLE_TEST( cccc ); - TSS_UNCONVERTABLE_TEST( 9999 ); - TSS_UNCONVERTABLE_TEST( 0123 ); - TSS_UNCONVERTABLE_TEST( 0100 ); + threw = true; } - ////////////////////////////////////////////////////////////////////////// - // TestUnprintable -- locale specific test -- only works in Unicode - /////////////////////////////////////////////////////////////////////////// - void TestUnprintable( tss::TestContext& ctx ) - { - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); - TSTRING str; - TCHAR ch; - - // only use lowercase strings with this define - #define TSS_UNPRINTABLE_TEST( n ) \ - ch = 0x ## n; \ - str = ch; \ - e.Encode( str ); \ - ct.tolower( str.begin(), str.end() ); \ - ASSERT( str == _T("\\x") _T( #n ) _T("x") ); - - TSS_UNPRINTABLE_TEST( 000a ); - TSS_UNPRINTABLE_TEST( 000d ); - } + TEST(should_throw == threw); +} - ////////////////////////////////////////////////////////////////////////// - // TestQuoteAndBackSlash - /////////////////////////////////////////////////////////////////////////// - void TestQuoteAndBackSlash( tss::TestContext& ctx ) - { - cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); - TSTRING str; - - str = _T("\\"); - e.Encode( str ); - ASSERT( str == _T("\\\\") ); - - str = _T("\""); - e.Encode( str ); - ASSERT( str == _T("\\\"") ); - } - // TODO:BAM -- try multibyte now..... +void TestHexToChar() +{ + test_hex_to_char("fe", 0xfe); + test_hex_to_char("ff", 0xff); + test_hex_to_char("00", 0x00); + test_hex_to_char("01", 0x01); + test_hex_to_char("7f", 0x7f); + test_hex_to_char("80", 0x80); + + test_hex_to_char("100", 0, true); // should throw + test_hex_to_char("-01", 0, true); // should throw +} - /////////////////////////////////////////////////////////////////////////// - // Basic - /////////////////////////////////////////////////////////////////////////// - void Basic( tss::TestContext& ctx ) - { - try - { - //============================================================= - // TEST UNPRINTABLE ENCODING/ROUNDTRIP - //============================================================= - - util_TestUnprintable( _T("normal string") ); - - util_TestUnprintable( _T("return\n") ); - util_TestUnprintable( _T("ret\rurn\n") ); - util_TestUnprintable( _T("ret\rnurn\n") ); - - util_TestUnprintable( _T("bell\x08") ); - util_TestUnprintable( _T("\x08 bell") ); - util_TestUnprintable( _T("be\x08ll") ); - - util_TestUnprintable( _T("\x1F\x1F\x1F") ); - - util_TestUnprintable( _T("big\xFF") ); - util_TestUnprintable( _T("\xEE big") ); - util_TestUnprintable( _T("\xEE\xEEtwo big") ); - util_TestUnprintable( _T("small\x01") ); - util_TestUnprintable( _T("\x01\x01two small") ); - - //============================================================= - // TEST UNCONVERTABLE CHARS - //============================================================= - TSTRING strMessWithMe = _T("Mess with me..."); - for( size_t c = TSS_TCHAR_MIN; - c < TSS_TCHAR_MAX; -#ifdef _UNICODE - c += ( TSS_TCHAR_MAX / 150 ) ) -#else - c++ ) -#endif - { - if( ( c != '\0' ) ) - { - strMessWithMe += c; - } - } - util_TestUnprintable( strMessWithMe ); - - //============================================================= - // TEST \\ and \x ENCODING/ROUNDTRIP - //============================================================= - - util_TestUnprintable( _T("\\Other \\\\slashes") ); - util_TestUnprintable( _T("\\Other slashes\\\\") ); - util_TestUnprintable( _T("O\\ther slashes\\\\") ); - util_TestUnprintable( _T("\\\\\\") ); - - util_TestUnprintable( _T("\\xTricky") ); - util_TestUnprintable( _T("Tri\\xcky") ); - util_TestUnprintable( _T("Tricky\\x") ); - util_TestUnprintable( _T("\\Tricky\\\\x") ); - - - //============================================================= - // TEST UNCONVERTABLE, UNPRINTABLE, AND \\ and \" CHARS - //============================================================= - TSTRING strMessWithMe2 = _T("Mess with me..."); - for( size_t ch = TSS_TCHAR_MIN; - ch < TSS_TCHAR_MAX; -#ifdef _UNICODE - ch += ( TSS_TCHAR_MAX / 150 ) ) -#else - ch++ ) +////////////////////////////////////////////////////////////////////////// +// TestStringToHex -- locale specific test -- only works in ASCII +/////////////////////////////////////////////////////////////////////////// +void test_string_to_hex(const std::string& str, const std::string& expected) +{ + std::string observed = cCharEncoderUtil::CharStringToHexValue(str); + TEST(expected == observed); +} + +void TestStringToHex() +{ + test_string_to_hex("\n", "0a"); + test_string_to_hex("\r", "0d"); + test_string_to_hex("\r\n", "0d0a"); + test_string_to_hex("a\r\nb", "610d0a62"); +} + + +////////////////////////////////////////////////////////////////////////// +// TestHexToString -- locale specific test -- only works in Unicode +/////////////////////////////////////////////////////////////////////////// +void test_hex_to_string(const std::string& str, const std::string& expected) +{ + std::string observed = cCharEncoderUtil::HexValueToCharString(str); + TEST(expected == observed); +} + +void TestHexToString() +{ + test_hex_to_string("0a", "\n"); + test_hex_to_string("0d", "\r"); + test_hex_to_string("0d0a", "\r\n"); + test_hex_to_string("610d0a62", "a\r\nb"); +} + +#if 0 +////////////////////////////////////////////////////////////////////////// +// TestUnconvertable -- locale specific test -- only works in Unicode +/////////////////////////////////////////////////////////////////////////// +void TestUnconvertable() +{ + cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); + const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); + TSTRING str; + TCHAR ch; + + // only use lowercase strings with this define +# define TSS_UNCONVERTABLE_TEST(n) \ + ch = 0x##n; \ + str = ch; \ + e.Encode(str); \ + ct.tolower(str.begin(), str.end()); \ + TEST(str == _T("\\x") _T(#n) _T("x")); + + TSS_UNCONVERTABLE_TEST( fefe ); + TSS_UNCONVERTABLE_TEST( 1234 ); + TSS_UNCONVERTABLE_TEST( ffff ); + TSS_UNCONVERTABLE_TEST( 1000 ); + TSS_UNCONVERTABLE_TEST( 543c ); + TSS_UNCONVERTABLE_TEST( cccc ); + TSS_UNCONVERTABLE_TEST( 9999 ); + TSS_UNCONVERTABLE_TEST( 0123 ); + TSS_UNCONVERTABLE_TEST( 0100 ); +} + +////////////////////////////////////////////////////////////////////////// +// TestUnprintable -- locale specific test -- only works in Unicode +/////////////////////////////////////////////////////////////////////////// +void TestUnprintable() +{ + cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); + const std::ctype< TCHAR > *pct = 0, &ct = tss::GetFacet( std::locale(), pct ); + TSTRING str; + TCHAR ch; + + // only use lowercase strings with this define +# define TSS_UNPRINTABLE_TEST(n) \ + ch = 0x##n; \ + str = ch; \ + e.Encode(str); \ + ct.tolower(str.begin(), str.end()); \ + TEST(str == _T("\\x") _T(#n) _T("x")); + + TSS_UNPRINTABLE_TEST( 000a ); + TSS_UNPRINTABLE_TEST( 000d ); +} #endif - { - if( ( ch != '\0' ) ) - { - strMessWithMe2 += ch; - } - } - - strMessWithMe2 += _T("\r\n\t\b\\\"\\\\\\\"\v\""); - util_TestUnprintable( strMessWithMe2 ); - - // TODO:BAM -- create multibyte tests (create a mb string at random, then test it. - // make sure there are '\' and '"' in it ) - } - catch( eError& e ) + +////////////////////////////////////////////////////////////////////////// +// TestQuoteAndBackSlash +/////////////////////////////////////////////////////////////////////////// +void TestQuoteAndBackSlash() +{ + cDisplayEncoder e(cDisplayEncoder::ROUNDTRIP); + TSTRING str; + + str = _T("\\"); + e.Encode(str); + TEST(str == _T("\\\\")); + + str = _T("\""); + e.Encode(str); + TEST(str == _T("\\\"")); +} + +// TODO:BAM -- try multibyte now..... + + +/////////////////////////////////////////////////////////////////////////// +// Basic +/////////////////////////////////////////////////////////////////////////// +void TestDisplayEncoderBasic1() +{ + //============================================================= + // TEST UNPRINTABLE ENCODING/ROUNDTRIP + //============================================================= + + util_TestUnprintable(_T("normal string")); + + util_TestUnprintable(_T("return\n")); + util_TestUnprintable(_T("ret\rurn\n")); + util_TestUnprintable(_T("ret\rnurn\n")); + + util_TestUnprintable(_T("bell\x08")); + util_TestUnprintable(_T("\x08 bell")); + util_TestUnprintable(_T("be\x08ll")); + + util_TestUnprintable(_T("\x1F\x1F\x1F")); + + util_TestUnprintable(_T("big\xFF")); + util_TestUnprintable(_T("\xEE big")); + util_TestUnprintable(_T("\xEE\xEEtwo big")); + util_TestUnprintable(_T("small\x01")); + util_TestUnprintable(_T("\x01\x01two small")); +} + +void TestDisplayEncoderBasic2() +{ + //============================================================= + // TEST UNCONVERTABLE CHARS + //============================================================= + TSTRING strMessWithMe = _T("Mess with me..."); + for (size_t c = TSS_TCHAR_MIN; c < TSS_TCHAR_MAX; c++) + { + if ((c != '\0')) { - cErrorReporter::PrintErrorMsg( e ); - ASSERT(false); + strMessWithMe += c; } } -}; + util_TestUnprintable(strMessWithMe); +} + +void TestDisplayEncoderBasic3() +{ + //============================================================= + // TEST \\ and \x ENCODING/ROUNDTRIP + //============================================================= + + util_TestUnprintable(_T("\\Other \\\\slashes")); + util_TestUnprintable(_T("\\Other slashes\\\\")); + util_TestUnprintable(_T("O\\ther slashes\\\\")); + util_TestUnprintable(_T("\\\\\\")); + + util_TestUnprintable(_T("\\xTricky")); + util_TestUnprintable(_T("Tri\\xcky")); + util_TestUnprintable(_T("Tricky\\x")); + util_TestUnprintable(_T("\\Tricky\\\\x")); +} -TSS_BeginTestSuiteFrom( cDisplayEncoderTest ) +void TestDisplayEncoderBasic4() +{ + //============================================================= + // TEST UNCONVERTABLE, UNPRINTABLE, AND \\ and \" CHARS + //============================================================= + TSTRING strMessWithMe2 = _T("Mess with me..."); + for (size_t ch = TSS_TCHAR_MIN; ch < TSS_TCHAR_MAX; ch++) + { + if ((ch != '\0')) + { + strMessWithMe2 += ch; + } + } - TSS_AddTestCase( Basic ); - TSS_AddTestCase( TestHexToChar ); - TSS_AddTestCase( TestCharToHex ); - TSS_AddTestCase( TestStringToHex ); - TSS_AddTestCase( TestHexToString ); - TSS_AddTestCase( TestUnconvertable ); - TSS_AddTestCase( TestUnprintable ); - TSS_AddTestCase( TestQuoteAndBackSlash ); - -TSS_EndTestSuite( cDisplayEncoderTest ) + strMessWithMe2 += _T("\r\n\t\b\\\"\\\\\\\"\v\""); + util_TestUnprintable(strMessWithMe2); -#endif // TSS_TEST + // TODO:BAM -- create multibyte tests (create a mb string at random, then test it. + // make sure there are '\' and '"' in it ) +} -// eof: displayencoder_t.cpp +void RegisterSuite_DisplayEncoder() +{ + RegisterTest("DisplayEncoder", "Basic1", TestDisplayEncoderBasic1); + RegisterTest("DisplayEncoder", "Basic2", TestDisplayEncoderBasic2); + RegisterTest("DisplayEncoder", "Basic3", TestDisplayEncoderBasic3); + RegisterTest("DisplayEncoder", "Basic4", TestDisplayEncoderBasic4); + RegisterTest("DisplayEncoder", "CharToHex", TestCharToHex); + RegisterTest("DisplayEncoder", "HexToChar", TestHexToChar); + RegisterTest("DisplayEncoder", "StringToHex", TestStringToHex); + RegisterTest("DisplayEncoder", "HexToString", TestHexToString); + //RegisterTest("DisplayEncoder", "Unconvertable", TestUnconvertable); + //RegisterTest("DisplayEncoder", "Unprintable", TestUnprintable); + RegisterTest("DisplayEncoder", "QuoteAndBackSlash", TestQuoteAndBackSlash); +} diff --git a/src/twtest/error_t.cpp b/src/twtest/error_t.cpp index fd3a24c..03f68a2 100644 --- a/src/twtest/error_t.cpp +++ b/src/twtest/error_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,40 +34,55 @@ #include "core/stdcore.h" #include "core/error.h" +#include "core/errorgeneral.h" +#include "core/errorutil.h" #include "twtest/test.h" #include void TestError() { -//#pragma message( __FILE__ "(1) : TODO - implement this test file") - -/* + bool threw = false; try { - std::cout << "Before Exception" << std::endl; - std::cout << "Line number before throw: " << __LINE__ << std::endl; - THROW_ERROR(53, _T("This is an error!")); - std::cout << "After Exception" << std::endl; + // std::cout << "Before Exception" << std::endl; + // std::cout << "Line number before throw: " << __LINE__ << std::endl; + throw eErrorGeneral(_T("This is an error!")); + // std::cout << "After Exception" << std::endl; } - catch(eError& e) + catch (eError& e) { - TEST(e.GetErrorNum() == 53); + threw = true; TEST(_tcscmp(e.GetMsg().c_str(), _T("This is an error!")) == 0); - TCOUT << _T("Exception caught!\n\tErrorNum=") << e.GetErrorNum() << _T("\n\t") << e.GetMsg() << std::endl; + // TCOUT << _T("Exception caught!\n\nID=") << e.GetID() << _T("\n\t") << e.GetMsg() << std::endl; + } + catch (...) + { + TEST(false); } - try + TEST(threw); + + + try { - THROW_INTERNAL("error_t.cpp"); + threw = false; + throw eInternal("error_t.cpp"); } - catch(eInternal& e) + catch (eInternal& e) { - TEST(e.GetErrorNum() == eInternal::ERR_INTERNAL); - TCOUT << _T("Internal error caught!\n\tErrorNum=") << e.GetErrorNum() << _T("\n\t") << e.GetMsg() << std::endl; + threw = true; + TEST(_tcscmp(e.GetMsg().c_str(), _T("error_t.cpp")) == 0); + // TCOUT << _T("Internal error caught!\n\nID=") << e.GetID() << _T("\n\t") << e.GetMsg() << std::endl; } - catch(...) + catch (...) { TEST(false); } -*/ + + TEST(threw); +} + +void RegisterSuite_Error() +{ + RegisterTest("Error", "Basic", TestError); } diff --git a/src/twtest/errorbucketimpl_t.cpp b/src/twtest/errorbucketimpl_t.cpp index e9d8e59..b1d3870 100644 --- a/src/twtest/errorbucketimpl_t.cpp +++ b/src/twtest/errorbucketimpl_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,60 +37,67 @@ #include "core/debug.h" #include "core/archive.h" #include "core/errorgeneral.h" +#include "core/errortable.h" // test option 7 void TestErrorBucketImpl() { -/* + cDebug d("TestErrorBucketImpl"); + //This whole function is in sorry shape... TODO: Fix this DRA - d.TraceDebug("Entering...\n"); + d.TraceDebug("Entering...\n"); - cErrorReporter er; - cErrorQueue eq; + cErrorReporter er; + cErrorQueue eq; er.SetChild(&eq); -//These calls to PrintErrorMsg are broken. The code is probably old. -DRA + //These calls to PrintErrorMsg are broken. The code is probably old. -DRA // Test error reporting - cErrorReporter::PrintErrorMsg(eError(_T("This should have a single line."))); - cErrorReporter::PrintErrorMsg(eError(_T("This should have a mulitiple lines since I have") - _T(" put so much text here. But it does have a lot") - _T(" of spaces so cErrorReporter should have no") - _T(" problem breaking it up.") - )); - cErrorReporter::PrintErrorMsg(eError(_T("This has many long words: ") - _T("40chars_________________________________") - _T(" short words ") - _T("50chars___________________________________________") - _T(" short words ") - _T("90chars___________________________________________________________________________________") - _T(" short words short words short words short words ") - _T("90chars___________________________________________________________________________________") - )); - cErrorReporter::PrintErrorMsg(eError(_T("The error reporter should handle newlines.\n") - _T("Newlines should break up the text appropriately. Who knows when they will occur. Can't have them getting in the way.\n") - _T("And one last line with a big char strings: 90chars___________________________________________________________________________________ 40chars_________________________________ 50chars___________________________________________") - )); + cErrorReporter::PrintErrorMsg(eErrorGeneral(_T("This should have a single line."))); + cErrorReporter::PrintErrorMsg(eErrorGeneral(_T("This should have a mulitiple lines since I have") + _T(" put so much text here. But it does have a lot") + _T(" of spaces so cErrorReporter should have no") + _T(" problem breaking it up."))); + cErrorReporter::PrintErrorMsg(eErrorGeneral( + _T("This has many long words: ") + _T("40chars_________________________________") + _T(" short words ") + _T("50chars___________________________________________") + _T(" short words ") + _T("90chars___________________________________________________________________________________") + _T(" short words short words short words short words ") + _T("90chars___________________________________________________________________________________"))); + cErrorReporter::PrintErrorMsg(eErrorGeneral( + _T("The error reporter should handle newlines.\n") + _T("Newlines should break up the text appropriately. Who knows when they will occur. Can't have them ") + _T("getting in the way.\n") + _T("And one last line with a big char strings: ") + _T("90chars___________________________________________________________________________________ ") + _T("40chars_________________________________ 50chars___________________________________________"))); // TODO -- test the error table // TODO -- test the error filter // set some errors... - TSS_EXCEPTION( eTestErrorBucketImpl, eError ); + TSS_EXCEPTION(eTestErrorBucketImpl, eError); eTestErrorBucketImpl error1(_T("Error A")), error2(_T("Error B")), error3(_T("Error C")); - er.AddError(error1); d.TraceDebug("Adding error 0 -- Error A\n"); - er.AddError(error2); d.TraceDebug("Adding error 1 -- Error B\n"); - er.AddError(error3); d.TraceDebug("Adding error 100 -- Error C\n"); + er.AddError(error1); + d.TraceDebug("Adding error 0 -- Error A\n"); + er.AddError(error2); + d.TraceDebug("Adding error 1 -- Error B\n"); + er.AddError(error3); + d.TraceDebug("Adding error 100 -- Error C\n"); // those should have gone out to stderr; let's check the queue cErrorQueueIter i(eq); - int counter = 0; - for(i.SeekBegin(); ! i.Done(); i.Next(), counter++) + int counter = 0; + for (i.SeekBegin(); !i.Done(); i.Next(), counter++) { - switch(counter) + switch (counter) { case 0: TEST(i.GetError().GetID() == error1.GetID()); @@ -109,13 +116,14 @@ void TestErrorBucketImpl() } } - TODO - test this stuff that's commented out + //TODO - test this stuff that's commented out - TCOUT << _T("Following string should be a cArchive::ERR_OPEN_FAILED error:\n"); - TCOUT << cErrorTable::GetErrorString(cArchive::ERR_OPEN_FAILED) << std::endl; + // TCOUT << _T("Following string should be a cArchive::ERR_OPEN_FAILED error:\n"); + // TCOUT << cErrorTable::GetErrorString(cArchive::ERR_OPEN_FAILED) << std::endl; + /* This isn't going to work anymore, given that we don't have numeric errror constants // print out all error strings -#if 1 + // Look up all errors. // Note: our current error printing format limits us to 4 digit errors, so this should work for a while. int errornum; @@ -134,9 +142,12 @@ void TestErrorBucketImpl() TCOUT << _T(": ") << errorString << std::endl; } } -#endif +*/ d.TraceDebug("Leaving...\n"); -*/ } +void RegisterSuite_ErrorBucketImpl() +{ + RegisterTest("ErrorBucketImpl", "Basic", TestErrorBucketImpl); +} diff --git a/src/twtest/fcocompare_t.cpp b/src/twtest/fcocompare_t.cpp index 0c74573..9f71511 100644 --- a/src/twtest/fcocompare_t.cpp +++ b/src/twtest/fcocompare_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -35,6 +35,7 @@ #include "core/debug.h" #include "fs/fsobject.h" #include "fs/fspropcalc.h" +#include "fs/fsdatasourceiter.h" #include "twtest/test.h" #include @@ -42,40 +43,36 @@ /////////////////////////////////////////////////////////////////////////////// // PrintProps -- prints out all the valid property names and values as pairs... /////////////////////////////////////////////////////////////////////////////// -/* + static void PrintProps(const iFCO* pFCO) { - cDebug d("PrintProps"); - const iFCOPropSet* pSet = pFCO->GetPropSet(); - const cFCOPropVector& v = pSet->GetValidVector(); - - for(int i=0; iGetNumProps(); i++) + cDebug d("PrintProps"); + const iFCOPropSet* pSet = pFCO->GetPropSet(); + const cFCOPropVector& v = pSet->GetValidVector(); + + for (int i = 0; i < pSet->GetNumProps(); i++) { - if(v.ContainsItem(i)) + if (v.ContainsItem(i)) { d.TraceDebug(_T("[%d] %s\t%s\n"), i, pSet->GetPropName(i).c_str(), pSet->GetPropAt(i)->AsString().c_str()); } } } -*/ + void TestFCOCompare() { -#pragma message( __FILE__ "(1) : TODO - implement this test file") -#if 0 - - const TCHAR* FILE_NAME = TEMP_DIR _T("/dog.txt"); - const char* FILE_NAME_N = TEMP_DIR_N "/dog.txt"; + std::string filename = TwTestPath("dog.txt"); cDebug d("TestFCOCompare"); d.TraceDebug("Entering...\n"); // first, create an fco to compare with... - - TOFSTREAM fstr(FILE_NAME_N); - if(fstr.bad()) + + TOFSTREAM fstr(filename.c_str()); + if (fstr.bad()) { - d.TraceError("Unable to create test file %s!\n", FILE_NAME); + d.TraceError("Unable to create test file %s!\n", filename.c_str()); TEST(false); return; } @@ -84,12 +81,13 @@ void TestFCOCompare() fstr.close(); // create the test FCO - cFSDataSource ds; - iFCO* pFCO = ds.CreateFCO(cFCOName(FILE_NAME), 0); + cFSDataSourceIter ds; + ds.SeekToFCO(cFCOName(filename), false); + iFCO* pFCO = ds.CreateFCO(); TEST(pFCO); // measure a couple of properties, some of which will change... - cFSPropCalc propCalc; + cFSPropCalc propCalc; cFCOPropVector v(pFCO->GetPropSet()->GetValidVector().GetSize()); v.AddItem(cFSPropSet::PROP_DEV); v.AddItem(cFSPropSet::PROP_CTIME); @@ -103,55 +101,65 @@ void TestFCOCompare() PrintProps(pFCO); // first, try comparing it to itself... - cFCOCompare comp; - cFCOCompare::CompareResult result; + cFCOCompare comp; comp.SetPropsToCmp(v); - comp.Compare(pFCO, pFCO, result); - d.TraceDebug("Compare to itself is (expect true) %s\n", result.mResult == cFCOCompare::EQUAL? "true" : "false"); - TEST(result.mResult == cFCOCompare::EQUAL); + unsigned int result = comp.Compare(pFCO, pFCO); + d.TraceDebug("Compare to itself is (expect true) %s\n", result == cFCOCompare::EQUAL ? "true" : "false"); + TEST(result == cFCOCompare::EQUAL); // change the file... d.TraceDebug("Changing the file...\n"); - fstr.open(FILE_NAME_N); - if(fstr.bad()) + fstr.open(filename.c_str()); + if (fstr.bad()) { - d.TraceError("Unable to reopen %s!\n", FILE_NAME_N); + d.TraceError("Unable to reopen %s!\n", filename.c_str()); TEST(false); return; } fstr << "Meow! Meow! Meow! Meow!" << std::endl; fstr.close(); - iFCO* pFCO2 = ds.CreateFCO(cFCOName(FILE_NAME), 0); - ASSERT(pFCO2); + //need a new data source iter, otherwise the existing FCO gets updated & you get a ref to it, + // and the resulting FCOs always match. + cFSDataSourceIter ds2; + ds2.SeekToFCO(cFCOName(filename), false); + iFCO* pFCO2 = ds2.CreateFCO(); + TEST(pFCO2); pFCO2->AcceptVisitor(&propCalc); d.TraceDebug("Second FCO's properties:\n"); PrintProps(pFCO2); - comp.Compare(pFCO, pFCO2, result); - d.TraceDebug("Compare to new object is (expect false) %s\n", result.mResult == cFCOCompare::EQUAL? "true" : "false"); - TEST(result.mResult == cFCOCompare::UNEQUAL); + result = comp.Compare(pFCO, pFCO2); + d.TraceDebug("Compare to new object is (expect false) %s\n", result == cFCOCompare::EQUAL ? "true" : "false"); + TEST(result == cFCOCompare::PROPS_UNEQUAL); d.TraceDebug("Properties that differ are:\n"); - result.mPropVector.TraceContents(); + //result.mPropVector.TraceContents(); + cFSDataSourceIter ds3; + ds3.SeekToFCO(cFCOName(filename), false); // try testing properties that weren't calculated... d.TraceDebug("Comparing FCOs with different properties calculated\n"); - iFCO* pFCO3 = ds.CreateFCO(cFCOName(FILE_NAME), 0); - v = propCalc.GetPropVector(); + iFCO* pFCO3 = ds3.CreateFCO(); + v = propCalc.GetPropVector(); v.AddItem(cFSPropSet::PROP_MD5); propCalc.SetPropVector(v); pFCO3->AcceptVisitor(&propCalc); // do the compare comp.SetPropsToCmp(v); - comp.Compare(pFCO2, pFCO3, result); - TEST(result.mResult == cFCOCompare::PROPS_NOT_ALL_VALID); + result = comp.Compare(pFCO2, pFCO3); + TEST(result == cFCOCompare::PROPS_NOT_ALL_VALID); d.TraceDebug("Properties not valid are (should be %d):\n", cFSPropSet::PROP_MD5); - result.mPropVector.TraceContents(); + //result.mPropVector.TraceContents(); // release the fcos pFCO3->Release(); pFCO2->Release(); pFCO->Release(); -#endif + return; } + +void RegisterSuite_FCOCompare() +{ + RegisterTest("FCOCompare", "Basic", TestFCOCompare); +} diff --git a/src/twtest/fcodatabasefile_t.cpp b/src/twtest/fcodatabasefile_t.cpp index 3b58d8f..ea1d78c 100644 --- a/src/twtest/fcodatabasefile_t.cpp +++ b/src/twtest/fcodatabasefile_t.cpp @@ -1,39 +1,47 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // fcodatabasefile.cpp #include "tw/stdtw.h" #include "tw/fcodatabasefile.h" +#include "test.h" void TestFCODatabaseFile() { + cDebug d("TestFCODatabaseFile"); + d.TraceError("Implement this!\n"); + skip("TestFCODatabaseFile not implemented"); +} +void RegisterSuite_FCODatabaseFile() +{ + RegisterTest("FCODatabaseFile", "Basic", TestFCODatabaseFile); } diff --git a/src/twtest/fconame_t.cpp b/src/twtest/fconame_t.cpp index 551b883..6bbe174 100644 --- a/src/twtest/fconame_t.cpp +++ b/src/twtest/fconame_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,36 +43,31 @@ #include "core/archive.h" #include "fco/genreswitcher.h" -void TestFCOName() +void TestFCOName1() { -#if 0 - // the following only works w/case insensitive names - cGenreSwitcher::GetInstance()->SelectGenre( cGenre::NTFS ); -#endif - // test the relationship operator... - cFCOName above (_T("/etc")); - cFCOName extraDel (_T("/etc/")); - cFCOName below (_T("/etc/passwd")); - cFCOName same (_T("/etc/passwd")); - cFCOName unrel (_T("/var/spool/mail")); - cFCOName caseTest (_T("/etc/PASsWD")); - cFCOName caseTest2 (_T("/etc/passwd/dog")); - cFCOName test (_T("/etcc")); - - TEST(above.GetRelationship(below) == cFCOName::REL_ABOVE); - TEST(below.GetRelationship(above) == cFCOName::REL_BELOW); - TEST(below.GetRelationship(same) == cFCOName::REL_EQUAL); - TEST(unrel.GetRelationship(above) == cFCOName::REL_UNRELATED); - TEST(test.GetRelationship(above) == cFCOName::REL_UNRELATED); + cFCOName above(_T("/etc")); + cFCOName extraDel(_T("/etc/")); + cFCOName below(_T("/etc/passwd")); + cFCOName same(_T("/etc/passwd")); + cFCOName unrel(_T("/var/spool/mail")); + cFCOName caseTest(_T("/etc/PASsWD")); + cFCOName caseTest2(_T("/etc/passwd/dog")); + cFCOName test(_T("/etcc")); + + TEST(above.GetRelationship(below) == cFCOName::REL_ABOVE); + TEST(below.GetRelationship(above) == cFCOName::REL_BELOW); + TEST(below.GetRelationship(same) == cFCOName::REL_EQUAL); + TEST(unrel.GetRelationship(above) == cFCOName::REL_UNRELATED); + TEST(test.GetRelationship(above) == cFCOName::REL_UNRELATED); TEST(caseTest.GetRelationship(same) == cFCOName::REL_UNRELATED); // test the extra delimiter removal... caseTest.SetCaseSensitive(false); caseTest2.SetCaseSensitive(false); same.SetCaseSensitive(false); above.SetCaseSensitive(false); - TEST(caseTest.GetRelationship(caseTest2) == cFCOName::REL_ABOVE); - TEST(caseTest.GetRelationship(same) == cFCOName::REL_EQUAL); + TEST(caseTest.GetRelationship(caseTest2) == cFCOName::REL_ABOVE); + TEST(caseTest.GetRelationship(same) == cFCOName::REL_EQUAL); // test push() and pop() cFCOName dog(_T("/a/brown/dog")); @@ -81,13 +76,16 @@ void TestFCOName() dog.Push(_T("woof")); TEST(dog.AsString().compare(_T("/a/brown/dog/woof")) == 0); TEST(dog.GetSize() == 5); - TEST(_tcscmp(dog.Pop(),_T("woof")) == 0); - TEST(_tcscmp(dog.Pop(),_T("dog")) == 0); + TEST(_tcscmp(dog.Pop(), _T("woof")) == 0); + TEST(_tcscmp(dog.Pop(), _T("dog")) == 0); TEST(cat.GetRelationship(dog) == cFCOName::REL_BELOW); - TEST(_tcscmp(cat.Pop(),_T("cat")) == 0); + TEST(_tcscmp(cat.Pop(), _T("cat")) == 0); TEST(dog.AsString().compare(cat.AsString()) == 0); TEST(dog.GetRelationship(cat) == cFCOName::REL_EQUAL); +} +void TestFCOName2() +{ cFCOName nullName; TEST(*nullName.AsString().c_str() == 0); @@ -103,28 +101,33 @@ void TestFCOName() cFCOName copyName(stringName); TEST(_tcscmp(copyName.AsString().c_str(), _T("/a/string/name")) == 0); - TCERR << "Multiple TODO tests in fconame_t.cpp" << std::endl; -#if 0 - cFCOName name(_T("new name")); + cFCOName name(_T("/new name")); nullName = name; - //TODO... TEST(_tcscmp(nullName.AsString().c_str(), _T("new name")) == 0); - - nullName = _T("newer name"); - //TODO... TEST(_tcscmp(nullName.AsString().c_str(), _T("newer name")) == 0); + TEST(_tcscmp(nullName.AsString().c_str(), _T("/new name")) == 0); + + nullName = _T("/newer name"); + TEST(_tcscmp(nullName.AsString().c_str(), _T("/newer name")) == 0); cMemoryArchive memArc; + { cSerializerImpl ser(memArc, cSerializerImpl::S_WRITE); ser.Init(); ser.WriteObject(&charName); - stringName.SetDelimiter(_T('\\')); + + //Note: backslash delimiters aren't supported (& don't work) in OST + //stringName.SetDelimiter(_T('\\')); + ser.WriteObject(&stringName); ser.Finit(); } + memArc.Seek(0, cBidirArchive::BEGINNING); + { cSerializerImpl ser(memArc, cSerializerImpl::S_READ); - cFCOName name1, name2; + cFCOName name1, name2; + ser.Init(); ser.ReadObject(&name1); ser.ReadObject(&name2); @@ -132,12 +135,15 @@ void TestFCOName() TEST(name1.IsEqual(charName)); TEST(name2.IsEqual(stringName)); - TEST(! name1.IsCaseSensitive()); - TEST(! name2.IsCaseSensitive()); - TEST(name2.GetDelimiter() == _T('\\')); - TEST(name1.GetDelimiter() == _T('/')); + TEST(name1.IsCaseSensitive()); + TEST(name2.IsCaseSensitive()); + TEST(name2.GetDelimiter() == _T('/')); + TEST(name1.GetDelimiter() == _T('/')); } -#endif } - +void RegisterSuite_FCOName() +{ + RegisterTest("FCOName", "Basic1", TestFCOName1); + RegisterTest("FCOName", "Basic2", TestFCOName2); +} diff --git a/src/twtest/fconametbl_t.cpp b/src/twtest/fconametbl_t.cpp index a5ed4b2..14fd162 100644 --- a/src/twtest/fconametbl_t.cpp +++ b/src/twtest/fconametbl_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,13 +46,13 @@ void TestFCONameTbl() cFCONameTblNode* pNode4 = nameTbl.CreateNode(_T("def")); cFCONameTblNode* pNode5 = nameTbl.CreateNode(_T("dEf")); - TEST(*pNode1 != *pNode2); - TEST(*pNode5 != *pNode4); - TEST(*pNode1->GetLowercaseNode() == *pNode3); - TEST(*pNode2->GetLowercaseNode() == *pNode3); - TEST(*pNode3->GetLowercaseNode() == *pNode3); - TEST(*pNode4->GetLowercaseNode() == *pNode4); - TEST(*pNode5->GetLowercaseNode() == *pNode4); + TEST(*pNode1 != *pNode2); + TEST(*pNode5 != *pNode4); + TEST(*pNode1->GetLowercaseNode() == *pNode3); + TEST(*pNode2->GetLowercaseNode() == *pNode3); + TEST(*pNode3->GetLowercaseNode() == *pNode3); + TEST(*pNode4->GetLowercaseNode() == *pNode4); + TEST(*pNode5->GetLowercaseNode() == *pNode4); pNode1->Release(); @@ -61,3 +61,8 @@ void TestFCONameTbl() pNode4->Release(); pNode5->Release(); } + +void RegisterSuite_FCONameTbl() +{ + RegisterTest("FCONameTbl", "Basic", TestFCONameTbl); +} diff --git a/src/twtest/fconametranslator_t.cpp b/src/twtest/fconametranslator_t.cpp index 76d75be..ccdf4c8 100644 --- a/src/twtest/fconametranslator_t.cpp +++ b/src/twtest/fconametranslator_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,79 +39,82 @@ #include "fco/fconametranslator.h" #include "fco/genreswitcher.h" #include "fco/fconame.h" +#include "twtest/test.h" - -void TestName( const TCHAR* pchName, const TCHAR* pchGenre ); -void TestUnprintable( const TCHAR* pchName, const TCHAR* pchGenre ); +void TestName(const TCHAR* pchName, const TCHAR* pchGenre); +void TestUnprintable(const TCHAR* pchName, const TCHAR* pchGenre); void TestFCONameTranslator() { - TestName( _T("/not_quoted/tmp"), _T("FS") ); - TestName( _T("/\"quoted\"/tmp"), _T("FS") ); - TestName( _T("/tmp/\"freak\x08y\""), _T("FS") ); - TestUnprintable( _T("c:\\\"more freak\xFFy\""), _T("FS") ); - + TestName(_T("/not_quoted/tmp"), _T("FS")); + TestName(_T("/\"quoted\"/tmp"), _T("FS")); + TestName(_T("/tmp/\"freak\x08y\""), _T("FS")); + TestUnprintable(_T("c:\\\"more freak\xFFy\""), _T("FS")); } -void TestName( const TCHAR* pchName, const TCHAR* pchGenre ) +void TestName(const TCHAR* pchName, const TCHAR* pchGenre) { // // set up name translator // iFCONameTranslator* mpCurNT = NULL; - cGenre::Genre gNTFS = cGenreSwitcher::GetInstance()->StringToGenre( pchGenre ); - ASSERT( gNTFS != cGenre::GENRE_INVALID ); - mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre( gNTFS )->GetNameTranslator(); + cGenre::Genre genre = cGenreSwitcher::GetInstance()->StringToGenre(pchGenre); + TEST(genre != cGenre::GENRE_INVALID); + mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre(genre)->GetNameTranslator(); // // encode name // - cFCOName fcoName( pchName ); - TSTRING strName = mpCurNT->ToStringDisplay( fcoName, true ); + cFCOName fcoName(pchName); + TSTRING strName = mpCurNT->ToStringDisplay(fcoName, true); TCOUT << _T("from: <") << fcoName.AsString() << _T("> to:") << strName; - + // // unencode name // cFCOName fcoNameNew; - ASSERT( mpCurNT->DisplayStringToFCOName( strName, fcoNameNew ) ); + TEST(mpCurNT->DisplayStringToFCOName(strName, fcoNameNew)); TCOUT << _T("> back to: <") << fcoNameNew.AsString() << _T(">") << std::endl; - + // // check result // - ASSERT( fcoNameNew == fcoName ); + TEST(fcoNameNew == fcoName); } -void TestUnprintable( const TCHAR* pchName, const TCHAR* pchGenre ) +void TestUnprintable(const TCHAR* pchName, const TCHAR* pchGenre) { // // set up name translator // iFCONameTranslator* mpCurNT = NULL; - cGenre::Genre gNTFS = cGenreSwitcher::GetInstance()->StringToGenre( pchGenre ); - ASSERT( gNTFS != cGenre::GENRE_INVALID ); - mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre( gNTFS )->GetNameTranslator(); + cGenre::Genre genre = cGenreSwitcher::GetInstance()->StringToGenre(pchGenre); + TEST(genre != cGenre::GENRE_INVALID); + mpCurNT = cGenreSwitcher::GetInstance()->GetFactoryForGenre(genre)->GetNameTranslator(); // // encode name // - cFCOName fcoName( pchName ); - TSTRING strName = mpCurNT->ToStringDisplay( fcoName, true ); + cFCOName fcoName(pchName); + TSTRING strName = mpCurNT->ToStringDisplay(fcoName, true); TCOUT << _T("To:") << strName; - + // // unencode name // cFCOName fcoNameNew; - ASSERT( mpCurNT->DisplayStringToFCOName( strName, fcoNameNew ) ); - + TEST(mpCurNT->DisplayStringToFCOName(strName, fcoNameNew)); + // // check result // - ASSERT( fcoNameNew == fcoName ); + TEST(fcoNameNew == fcoName); } +void RegisterSuite_FCONameTranslator() +{ + RegisterTest("FCONameTranslator", "Basic", TestFCONameTranslator); +} diff --git a/src/twtest/fcopropimpl_t.cpp b/src/twtest/fcopropimpl_t.cpp index 1dc7a2d..55ea288 100644 --- a/src/twtest/fcopropimpl_t.cpp +++ b/src/twtest/fcopropimpl_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,42 +33,78 @@ #include "fco/stdfco.h" #include "fco/fcopropimpl.h" #include "core/debug.h" +#include "twtest/test.h" -void TestFCOPropImpl() +void TestNumeric() { - cDebug d("TestFCOPropImpl"); + cDebug d("TestNumeric"); d.TraceDebug("Entering...\n"); // print the enum key: - d.TraceDebug("Output key:%d True\n%d False\n%d Wrong Type\n%d Unsupported\n", - iFCOProp::CMP_TRUE,iFCOProp::CMP_FALSE,iFCOProp::CMP_WRONG_PROP_TYPE,iFCOProp::CMP_UNSUPPORTED); + d.TraceDebug("Output key:%d True\n%d False\n%d Wrong Type\n%d Unsupported\n", + iFCOProp::CMP_TRUE, + iFCOProp::CMP_FALSE, + iFCOProp::CMP_WRONG_PROP_TYPE, + iFCOProp::CMP_UNSUPPORTED); // test string rep - cFCOPropInt64 pi64; + cFCOPropInt64 pi64; cFCOPropUint64 pui64, pui64b; pi64.SetValue(-456); pui64.SetValue(456); pui64b.SetValue(333); d.TraceDebug(_T("property int64 = (should be -456) %s\n"), pi64.AsString().c_str()); + TEST(pi64.AsString() == "-456"); + // test a few operators d.TraceDebug("-456 < 456 (uint cmp to int should fail)= %d\n", pi64.Compare(&pui64, iFCOProp::OP_LT)); + TEST(iFCOProp::CMP_WRONG_PROP_TYPE == pi64.Compare(&pui64, iFCOProp::OP_LT)); + cFCOPropInt64 p2i64; p2i64.SetValue(4); + d.TraceDebug("-456 < 4 = %d\n", pi64.Compare(&p2i64, iFCOProp::OP_LT)); + TEST(iFCOProp::CMP_TRUE == pi64.Compare(&p2i64, iFCOProp::OP_LT)); + d.TraceDebug("4 == 456 = %d\n", p2i64.Compare(&pi64, iFCOProp::OP_EQ)); + TEST(iFCOProp::CMP_FALSE == p2i64.Compare(&pi64, iFCOProp::OP_EQ)); + d.TraceDebug("333ui64 == 456ui64 = %d\n", pui64.Compare(&pui64b, iFCOProp::OP_EQ)); + TEST(iFCOProp::CMP_FALSE == p2i64.Compare(&pi64, iFCOProp::OP_EQ)); +} + +void TestStrings() +{ + cDebug d("TestStrings"); cFCOPropTSTRING pt1; cFCOPropTSTRING pt2; pt1.SetValue(TSTRING(_T("bar"))); pt2.SetValue(TSTRING(_T("foo"))); + cFCOPropInt64 pi64; + pi64.SetValue(8675309); + d.TraceDebug(_T("property TSTRING = (should be \"bar\") %s\n"), pt1.AsString().c_str()); + TEST(pt1.AsString() == "bar"); + d.TraceDebug(_T("property TSTRING = (should be \"foo\") %s\n"), pt2.AsString().c_str()); + TEST(pt2.AsString() == "foo"); + d.TraceDebug("bar == foo = %d\n", pt1.Compare(&pt2, iFCOProp::OP_EQ)); + TEST(iFCOProp::CMP_FALSE == pt1.Compare(&pt2, iFCOProp::OP_EQ)); + d.TraceDebug("bar == bar = %d\n", pt1.Compare(&pt1, iFCOProp::OP_EQ)); + TEST(iFCOProp::CMP_TRUE == pt1.Compare(&pt1, iFCOProp::OP_EQ)); + d.TraceDebug("bar == 456 = %d\n", pt1.Compare(&pi64, iFCOProp::OP_EQ)); + TEST(iFCOProp::CMP_WRONG_PROP_TYPE == pt1.Compare(&pi64, iFCOProp::OP_EQ)); d.TraceDebug("Leaving...\n"); return; } +void RegisterSuite_FCOPropImpl() +{ + RegisterTest("FCOPropImpl", "Numeric", TestNumeric); + RegisterTest("FCOPropImpl", "Strings", TestStrings); +} diff --git a/src/twtest/fcopropvector_t.cpp b/src/twtest/fcopropvector_t.cpp index d281683..088d9ad 100644 --- a/src/twtest/fcopropvector_t.cpp +++ b/src/twtest/fcopropvector_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,15 +37,15 @@ #include "twtest/test.h" #endif -static bool init (cFCOPropVector &testV); -static bool addRemove (cFCOPropVector &test1, cFCOPropVector &test2, cDebug& d); -static bool objManip (cFCOPropVector &testV, cDebug& d); +static bool init(cFCOPropVector& testV); +static void addRemove(cFCOPropVector& test1, cFCOPropVector& test2, cDebug& d); +static void objManip(cFCOPropVector& testV, cDebug& d); void TestFCOPropVector() { //Local Variables for main test function - bool testout; + bool testout; cDebug d("TestFCOPropVector()"); d.TraceDetail("Entering...\n"); @@ -64,20 +64,20 @@ void TestFCOPropVector() //First, test set initialization is correct. d.TraceDetail("\nTesting vector initialization...\n"); - TEST(testout = (init (test1)) & (init(test2)) & (init(test3))); + TEST(testout = (init(test1)) & (init(test2)) & (init(test3))); if (testout) d.TraceDetail("success.\n"); - else { + else + { test1.check(d); test2.check(d); test3.check(d); } //Test ability to add and remove - TCERR << "TODO: addRemove test in fcopropvector_t.cpp" << std::endl; - // TEST(testout = addRemove (test1, test2, d)); - // d.TraceDetail("Add/Remove over all tests is %i \n", testout); - + addRemove(test1, test2, d); + d.TraceDetail("Add/Remove over all tests is %i \n", testout); + // test clear. d.TraceDetail("Testing Clear()\n"); d.TraceDetail("Filling with numbers...\n"); @@ -93,93 +93,40 @@ void TestFCOPropVector() d.TraceDetail("Clear Test Done.\n"); //test operators - TEST(testout = objManip(test1, d)); - if (testout) - d.TraceDetail("Object manipulation tests are successful\n"); - else - d.TraceDetail("Object manipulation tests are not successful\n"); + objManip(test1, d); - return; -}//end TestPropVector + return; +} -static bool init (cFCOPropVector &testV) +static bool init(cFCOPropVector& testV) { - int range = testV.GetSize()-1; - - for (int i=1; i<=range; ++i) + int range = testV.GetSize() - 1; + + for (int i = 1; i <= range; ++i) { if (testV.ContainsItem(i)) return false; } //end for return true; -} //end init +} + -static bool addRemove (cFCOPropVector &test1, cFCOPropVector &test2, cDebug& d) +static void addRemove(cFCOPropVector& test1, cFCOPropVector& test2, cDebug& d) { - int var1 = 0 , var2 = 64, var3 = 2; - bool local=true, out=true; - - /* - bool loopvar = true; - int menu, var; - cFCOPropVector testV; - testV.SetSize(64); - while (loopvar) - { + int var1 = 0, var2 = 64, var3 = 2; - d.TraceAlways("\nChoose an operation to test:\n"); - d.TraceAlways("\t1)Add an item to vector.\n"); - d.TraceAlways("\t2)Remove an item from vector. \n"); - d.TraceAlways("\t3)Check vector for item. \n"); - d.TraceAlways("\t4)Display vector information \n"); - d.TraceAlways("\t5)Stop add/remove tests. \n"); - d.TraceAlways("Your choice [1-5]: "); - cin>>menu; - d.TraceAlways("\n"); - - switch (menu) - { - case 1: - d.TraceAlways("Item to add: "); - cin>> var; - d.TraceAlways("%i \n", testV.AddItem(var)); - break; - case 2: - d.TraceAlways("Item to remove: "); - cin>>var; - d.TraceAlways("%i \n", testV.RemoveItem(var)); - break; - case 3: - d.TraceAlways("Item to check: "); - cin>>var; - if (testV.ContainsItem(var)) - d.TraceAlways("\nItem present\n"); - else - d.TraceAlways("\nItem not present\n"); - break; - case 4: - testV.check(d); - break; - case 5: - loopvar = false; - break; - default: - d.TraceAlways("Not a valid menu option\n"); - break; - }//end switch - out &= local; //Keep track of results. - }//end while - */ - test1.AddItem(var1); - TEST(local &= test1.ContainsItem(var1)); //hopefully this is true! - TEST(local &= !test1.ContainsItem(var3)); + TEST(test1.ContainsItem(var1)); //hopefully this is true! + TEST(!test1.ContainsItem(var3)); + test2.SetSize(var2); - TEST(local &= (test2.GetSize() == ((var2/32)+1)*32)); - TEST(local &= (test1 != test2)); + TEST((test2.GetSize() == ((var2 / 32) + 1) * 32)); + TEST((test1 != test2)); + test1.RemoveItem(var1); test2.SetSize(test1.GetSize()); - TEST(local &= (test1 == test2)); + TEST(test1 == test2); + test1.AddItem(var3); test2 |= test1; d.TraceDetail("\nmMask should be 4!\n"); @@ -187,22 +134,19 @@ static bool addRemove (cFCOPropVector &test1, cFCOPropVector &test2, cDebug& d) test2.RemoveItem(var3); d.TraceDetail("\nmMask should be 0! \n"); test2.check(d); +} - out &= local; //and-ing of results. - return out; -}//end addRemove - -static bool objManip (cFCOPropVector &testV, cDebug& d) +static void objManip(cFCOPropVector& testV, cDebug& d) { cFCOPropVector test1, test2 = testV; - bool out = true; /*testV.check(d); test2.check(d);*/ - TEST(out &= (testV == test2)); //test operator = , == + // test operator = , == + TEST(testV == test2) test2.AddItem(1); - TEST(out &= (testV != test2)); //test operator != + TEST(testV != test2); // test operator != /*testV.check(d); test2.check(d);*/ @@ -212,14 +156,14 @@ static bool objManip (cFCOPropVector &testV, cDebug& d) testV |= test2; //test operator |= testV.check(d); - test1 = testV | test2; //test operator | + test1 = testV | test2; //test operator | test1.check(d); - TEST(out&= (test1 == testV)); + TEST(test1 == testV); test2.RemoveItem(1); - testV = (test2 & test1);//test operator & + testV = (test2 & test1); //test operator & testV.check(d); - TEST(out&= !(test1 == testV)); + TEST(!(test1 == testV)); // test operator ^ cFCOPropVector v1, v2, v3; @@ -231,11 +175,13 @@ static bool objManip (cFCOPropVector &testV, cDebug& d) v3.AddItem(1); v3.AddItem(4); TEST((v1 ^ v2) == v3); + // try with larger sizes... v2.SetSize(40); v2.Clear(); v2.AddItem(3); TEST((v1 ^ v2) == v3); + v2.AddItem(38); v1.SetSize(40); v1.Clear(); @@ -246,6 +192,9 @@ static bool objManip (cFCOPropVector &testV, cDebug& d) v3.AddItem(1); v3.AddItem(3); TEST((v1 ^ v2) == v3); +} - return out; -}//end objManip +void RegisterSuite_FCOPropVector() +{ + RegisterTest("FCOPropVector", "Basic", TestFCOPropVector); +} diff --git a/src/twtest/fcoreport_t.cpp b/src/twtest/fcoreport_t.cpp index 28fbc6c..d3f5a17 100644 --- a/src/twtest/fcoreport_t.cpp +++ b/src/twtest/fcoreport_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -42,6 +42,7 @@ #include "core/errorbucketimpl.h" #include "fco/fcospecattr.h" #include "fco/fcospechelper.h" +#include "fs/fs.h" #include // we use this instead of TraceContents() so we can test the report iterators. @@ -51,18 +52,18 @@ static void TraceReport(const cFCOReport& r, cDebug& d) r.GetErrorQueue()->TraceContents(); cFCOReportGenreIter genreIter(r); - int genreCount = 0; + int genreCount = 0; for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next(), ++genreCount) { d.TraceDebug("> Genre [%d]:\n", genreCount); cFCOReportSpecIter specIter(genreIter); - int specCount = 0; - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next(), ++specCount) + int specCount = 0; + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next(), ++specCount) { d.TraceDebug(">>> Spec [%d]:\n", specCount); - ASSERT(specIter.GetSpec()); + TEST(specIter.GetSpec()); specIter.GetSpec()->TraceContents(); specIter.GetAttr()->TraceContents(); specIter.GetErrorQueue()->TraceContents(); @@ -74,8 +75,8 @@ static void TraceReport(const cFCOReport& r, cDebug& d) // trace out changed files cFCOReportChangeIter changeIter(specIter); - int changeCtr = 0; - for(changeIter.SeekBegin(); ! changeIter.Done(); changeIter.Next(), changeCtr++) + int changeCtr = 0; + for (changeIter.SeekBegin(); !changeIter.Done(); changeIter.Next(), changeCtr++) { d.TraceDebug(">>>>> Changed fco [%d]\n", changeCtr); d.TraceDebug(">>>>> Old FCO:\n"); @@ -88,18 +89,18 @@ static void TraceReport(const cFCOReport& r, cDebug& d) } } + void TestFCOReport() { cDebug d("TestFCOReport"); - - cFCOSpecImpl* pSpec = new cFCOSpecImpl(_T("/etc"), NULL, new cFCOSpecStopPointSet); - cFCOSpecAttr* pAttr = new cFCOSpecAttr; - cFSObject* addedFCO = new cFSObject(cFCOName(_T("/etc/added_file"))); - cFSObject* removedFCO = new cFSObject(cFCOName(_T("/etc/removed_file"))); - cFSObject* changedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); - cFSObject* oldChangedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); - cFSObject* newChangedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); + cFCOSpecImpl* pSpec = new cFCOSpecImpl(_T("/etc"), NULL, new cFCOSpecStopPointSet); + cFCOSpecAttr* pAttr = new cFCOSpecAttr; + cFSObject* addedFCO = new cFSObject(cFCOName(_T("/etc/added_file"))); + cFSObject* removedFCO = new cFSObject(cFCOName(_T("/etc/removed_file"))); + cFSObject* changedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); + cFSObject* oldChangedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); + cFSObject* newChangedFCO = new cFSObject(cFCOName(_T("/etc/changed_file"))); cFCOPropVector changedPropVector; //Calculate the time taken to generate the test report: @@ -108,15 +109,15 @@ void TestFCOReport() //time_t time_begin = time(dummy_arg); { - cFCOReport report; + cFCOReport report; changedPropVector.AddItem(cFSPropSet::PROP_SIZE); pSpec->SetStartPoint(cFCOName(_T("/etc"))); pAttr->SetName(_T("/etc")); pAttr->SetSeverity(53); - report.AddSpec(0x00020001, pSpec, pAttr); // TODO:bam - change these - cFCOReportSpecIter it(report, 0x00020001); // to use cFS::Genre + report.AddSpec(cFS::GenreID(), pSpec, pAttr); + cFCOReportSpecIter it(report, cFS::GenreID()); it.GetAddedSet()->Insert(addedFCO); it.GetRemovedSet()->Insert(removedFCO); report.AddChangedFCO(it, oldChangedFCO, newChangedFCO, changedPropVector); @@ -129,8 +130,9 @@ void TestFCOReport() d.TraceDebug("Before serializing report:\n"); TraceReport(report, d); { + std::string filepath = TwTestPath("tmp.twr"); cFileArchive outFile; - outFile.OpenReadWrite(_T("tmp.twr")); + outFile.OpenReadWrite(filepath.c_str()); cSerializerImpl outSer(outFile, cSerializerImpl::S_WRITE); outSer.Init(); @@ -140,7 +142,7 @@ void TestFCOReport() outFile.Close(); cFileArchive inFile; - inFile.OpenRead(_T("tmp.twr")); + inFile.OpenRead(filepath.c_str()); cSerializerImpl inSer(inFile, cSerializerImpl::S_READ); cFCOReport inReport; @@ -167,6 +169,9 @@ void TestFCOReport() newChangedFCO->Release(); d.TraceDebug("Leaving...\n"); - return; } +void RegisterSuite_FCOReport() +{ + RegisterTest("FCOReport", "Basic", TestFCOReport); +} diff --git a/src/twtest/fcosetimpl_t.cpp b/src/twtest/fcosetimpl_t.cpp index ff81058..cdf8932 100644 --- a/src/twtest/fcosetimpl_t.cpp +++ b/src/twtest/fcosetimpl_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,7 +43,7 @@ static void PrintIter(const iFCOIter* pIter, cDebug& d) { TSTRING str; - for(; ! pIter->Done(); pIter->Next()) + for (; !pIter->Done(); pIter->Next()) { str += pIter->FCO()->GetName().AsString().c_str(); str += _T(" "); @@ -75,18 +75,20 @@ void TestFCOSetImpl() pFCO3->Release(); // let's iterate over the fcos - cIterProxy pit(set.GetIter()); + iFCOIter* pIter = set.GetIter(); + cIterProxy pit(pIter); pit->SeekBegin(); PrintIter(pit, d); + // lookup a specific fco cIterProxy pit2(set.Lookup(cFCOName(_T("fco2")))); - if(! (iFCOIter*)pit2) + if (!(iFCOIter*)pit2) { d.TraceError("Lookup failed for fco2!\n"); TEST(false); } - + d.TraceDebug("Iterating from fco2 to end...\n"); PrintIter(pit2, d); @@ -101,7 +103,7 @@ void TestFCOSetImpl() // ...and then remove it d.TraceDebug("Removing fco3\n"); cIterProxy pit3(set.Lookup(cFCOName(_T("fco3")))); - if(! (iFCOIter*)pit3) + if (!(iFCOIter*)pit3) { d.TraceError("Lookup failed for fco3!\n"); TEST(false); @@ -113,10 +115,14 @@ void TestFCOSetImpl() // test operator= cFCOSetImpl set2; set2 = set; - pit = set2.GetIter(); + + pIter->DestroyIter(); + pIter = set2.GetIter(); + pit = pIter; d.TraceDebug("Made a new set and set it equal to the first with operator=; printing out...\n"); PrintIter(pit, d); + // test IsEmpty set.Clear(); TEST(set.IsEmpty()); @@ -127,8 +133,8 @@ void TestFCOSetImpl() PrintIter(pit, d); // test serialization - cFCOSetImpl set3; - cMemoryArchive a; + cFCOSetImpl set3; + cMemoryArchive a; cSerializerImpl writeSer(a, cSerializerImpl::S_WRITE); writeSer.Init(); set2.Write(&writeSer); @@ -142,9 +148,13 @@ void TestFCOSetImpl() pit = set3.GetIter(); PrintIter(pit, d); + pIter->DestroyIter(); d.TraceDebug("Leaving...\n"); return; - } +void RegisterSuite_FCOSetImpl() +{ + RegisterTest("FCOSetImpl", "Basic", TestFCOSetImpl); +} diff --git a/src/twtest/fcospec_t.cpp b/src/twtest/fcospec_t.cpp index 80d73aa..0a37377 100644 --- a/src/twtest/fcospec_t.cpp +++ b/src/twtest/fcospec_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,19 +34,21 @@ #include "fco/stdfco.h" #include "fco/fcospec.h" #include "core/debug.h" +#include "twtest/test.h" #include using namespace std; void TestFCOSpec() { - cout << "Begin\tTestFCOSpec" << endl; // all it seems I can test here is that the default mask works const iFCOSpecMask* pDefMask = iFCOSpecMask::GetDefaultMask(); - ASSERT(pDefMask->GetName().compare(TSTRING(_T("Default"))) == 0); - iFCO* pf1 = (iFCO*)0xbad, *pf2 = (iFCO*)0xcab; - ASSERT( pDefMask->Accept(pf1) && pDefMask->Accept(pf2) ); + TEST(pDefMask->GetName().compare(TSTRING(_T("Default"))) == 0); + iFCO *pf1 = (iFCO*)0xbad, *pf2 = (iFCO*)0xcab; + TEST(pDefMask->Accept(pf1) && pDefMask->Accept(pf2)); +} - cout << "End\tTestFCOSpec" << endl; - return; +void RegisterSuite_FCOSpec() +{ + RegisterTest("FCOSpec", "Basic", TestFCOSpec); } diff --git a/src/twtest/fcospecattr_t.cpp b/src/twtest/fcospecattr_t.cpp index e0c4861..0f560ab 100644 --- a/src/twtest/fcospecattr_t.cpp +++ b/src/twtest/fcospecattr_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,6 +36,7 @@ #include "twtest/test.h" #include "core/archive.h" #include "core/serializerimpl.h" +#include "twtest/test.h" static void TraceSpecAttr(const cFCOSpecAttr* pAttr, cDebug d) { @@ -44,36 +45,43 @@ static void TraceSpecAttr(const cFCOSpecAttr* pAttr, cDebug d) d.TraceDebug("Email addresses:\n"); cFCOSpecAttrEmailIter i(*pAttr); - for(i.SeekBegin(); ! i.Done(); i.Next()) + for (i.SeekBegin(); !i.Done(); i.Next()) { d.TraceDebug(_T("\t%s\n"), i.EmailAddress().c_str()); } } + void TestFCOSpecAttr() { cDebug d("TestFCOSpecAttr"); + d.TraceDebug("Entering\n"); cFCOSpecAttr* pAttr = new cFCOSpecAttr; - pAttr->SetName (_T("My Name")); d.TraceDebug("Setting Name = My Name\n"); - pAttr->SetSeverity (53); d.TraceDebug("Setting Severity = 53\n"); - pAttr->AddEmail (_T("dog@bark.com")); d.TraceDebug("Adding email = dog@bark.com\n"); - pAttr->AddEmail (_T("cow@moo.com")); d.TraceDebug("Adding email = cow@moo.com\n"); - pAttr->AddEmail (_T("cat@meow.com")); d.TraceDebug("Adding email = cat@meow.com\n"); + pAttr->SetName(_T("My Name")); + d.TraceDebug("Setting Name = My Name\n"); + pAttr->SetSeverity(53); + d.TraceDebug("Setting Severity = 53\n"); + pAttr->AddEmail(_T("dog@bark.com")); + d.TraceDebug("Adding email = dog@bark.com\n"); + pAttr->AddEmail(_T("cow@moo.com")); + d.TraceDebug("Adding email = cow@moo.com\n"); + pAttr->AddEmail(_T("cat@meow.com")); + d.TraceDebug("Adding email = cat@meow.com\n"); // trace contents... TraceSpecAttr(pAttr, d); // test serialization... d.TraceDebug("Testing Serialization; next output should be the same as the previous\n"); - cMemoryArchive a; + cMemoryArchive a; cSerializerImpl s(a, cSerializerImpl::S_WRITE); s.Init(); pAttr->Write(&s); s.Finit(); a.Seek(0, cBidirArchive::BEGINNING); - cFCOSpecAttr* pNew = new cFCOSpecAttr; + cFCOSpecAttr* pNew = new cFCOSpecAttr; cSerializerImpl s2(a, cSerializerImpl::S_READ); s2.Init(); pNew->Read(&s2); @@ -82,6 +90,13 @@ void TestFCOSpecAttr() // trace contents... TraceSpecAttr(pNew, d); + TEST(*pAttr == *pNew); + pNew->Release(); pAttr->Release(); } + +void RegisterSuite_FCOSpecAttr() +{ + RegisterTest("FCOSpecAttr", "Basic", TestFCOSpecAttr); +} diff --git a/src/twtest/fcospechelper_t.cpp b/src/twtest/fcospechelper_t.cpp index 409f06f..7cc03bd 100644 --- a/src/twtest/fcospechelper_t.cpp +++ b/src/twtest/fcospechelper_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -46,64 +46,75 @@ void TestFCOSpecHelper() // test the start and stop point fringe cases... d.TraceDebug("Testing start and stop point stuff...\n"); cFCOSpecStopPointSet* pSet3 = new cFCOSpecStopPointSet; - pSet3->SetStartPoint(cFCOName(_T("/etc"))); d.TraceDebug("*** Added start point /etc\n"); - pSet3->Add(cFCOName(_T("/etc/dog/bark"))); d.TraceDebug("*** Added stop point /etc/dog/bark\n"); - pSet3->Add(cFCOName(_T("/etc/dog/pant"))); d.TraceDebug("*** Added stop point /etc/dog/pant\n\n"); - pSet3->Add(cFCOName(_T("/etc/cat/meow"))); d.TraceDebug("*** Added stop point /etc/cat/meow\n"); - pSet3->TraceContents(); - pSet3->Add(cFCOName(_T("/etc/dog"))); d.TraceDebug("*** Added stop point /etc/dog\n"); - pSet3->Add(cFCOName(_T("/etc/cat/purr"))); d.TraceDebug("*** Added stop point /etc/cat/purr\n"); - pSet3->Add(cFCOName(_T("/etc/cat/purr/loud"))); d.TraceDebug("*** Added stop point /etc/cat/purr/loud\n"); - pSet3->TraceContents(); - pSet3->Add(cFCOName(_T("/etc/dog"))); d.TraceDebug("*** Added stop point /etc/dog\n"); + pSet3->SetStartPoint(cFCOName(_T("/etc"))); + d.TraceDebug("*** Added start point /etc\n"); + pSet3->Add(cFCOName(_T("/etc/dog/bark"))); + d.TraceDebug("*** Added stop point /etc/dog/bark\n"); + pSet3->Add(cFCOName(_T("/etc/dog/pant"))); + d.TraceDebug("*** Added stop point /etc/dog/pant\n\n"); + pSet3->Add(cFCOName(_T("/etc/cat/meow"))); + d.TraceDebug("*** Added stop point /etc/cat/meow\n"); + pSet3->TraceContents(); + pSet3->Add(cFCOName(_T("/etc/dog"))); + d.TraceDebug("*** Added stop point /etc/dog\n"); + pSet3->Add(cFCOName(_T("/etc/cat/purr"))); + d.TraceDebug("*** Added stop point /etc/cat/purr\n"); + pSet3->Add(cFCOName(_T("/etc/cat/purr/loud"))); + d.TraceDebug("*** Added stop point /etc/cat/purr/loud\n"); + pSet3->TraceContents(); + pSet3->Add(cFCOName(_T("/etc/dog"))); + d.TraceDebug("*** Added stop point /etc/dog\n"); try { - pSet3->Add(cFCOName(_T("/var/spool"))); d.TraceDebug("*** Added stop point /var/spool\n"); + pSet3->Add(cFCOName(_T("/var/spool"))); + d.TraceDebug("*** Added stop point /var/spool\n"); } - catch(eError& e) + catch (eError& e) { d.TraceDebug(_T("Caught exception : %s\n"), e.GetMsg().c_str()); } try { - pSet3->SetStartPoint(cFCOName(_T("/var"))); d.TraceDebug("*** Added start point /var\n"); + pSet3->SetStartPoint(cFCOName(_T("/var"))); + d.TraceDebug("*** Added start point /var\n"); } - catch(eError& e) + catch (eError& e) { d.TraceDebug(_T("Caught exception : %s\n"), e.GetMsg().c_str()); } try { - pSet3->SetStartPoint(cFCOName(_T("/"))); d.TraceDebug("*** Added start point /\n"); + pSet3->SetStartPoint(cFCOName(_T("/"))); + d.TraceDebug("*** Added start point /\n"); } - catch(eError& e) + catch (eError& e) { d.TraceDebug(_T("Caught exception : %s\n"), e.GetMsg().c_str()); } - pSet3->TraceContents(); + pSet3->TraceContents(); // test SpecContainsFCO() cFCOSpecStopPointSet* pSet4 = new cFCOSpecStopPointSet; pSet4->SetStartPoint(cFCOName(_T("/etc"))); pSet4->Add(cFCOName(_T("/etc/dog"))); pSet4->Add(cFCOName(_T("/etc/cat/meow"))); - TEST( pSet4->ContainsFCO( cFCOName(_T("/etc/frog")))); - TEST( pSet4->ContainsFCO( cFCOName(_T("/etc/cat/paw")))); - TEST(! pSet4->ContainsFCO( cFCOName(_T("/etc/dog")))); - TEST(! pSet4->ContainsFCO( cFCOName(_T("/var/spool/mail")))); - TEST(! pSet4->ContainsFCO( cFCOName(_T("/etc/dog/bark")))); + TEST(pSet4->ContainsFCO(cFCOName(_T("/etc/frog")))); + TEST(pSet4->ContainsFCO(cFCOName(_T("/etc/cat/paw")))); + TEST(!pSet4->ContainsFCO(cFCOName(_T("/etc/dog")))); + TEST(!pSet4->ContainsFCO(cFCOName(_T("/var/spool/mail")))); + TEST(!pSet4->ContainsFCO(cFCOName(_T("/etc/dog/bark")))); // test the All Children Stop Points case cFCOSpecNoChildren noChildren; noChildren.SetStartPoint(cFCOName(_T("/etc"))); - TEST( noChildren.ContainsFCO( cFCOName(_T("/etc")))); - TEST(! noChildren.ContainsFCO( cFCOName(_T("/etc/frog")))); + TEST(noChildren.ContainsFCO(cFCOName(_T("/etc")))); + TEST(!noChildren.ContainsFCO(cFCOName(_T("/etc/frog")))); // TODO -- test Compare() // test serialization - // test serialization - cMemoryArchive a; + // test serialization + cMemoryArchive a; cSerializerImpl s(a, cSerializerImpl::S_WRITE); s.Init(); s.WriteObjectDynCreate(pSet3); @@ -111,17 +122,17 @@ void TestFCOSpecHelper() s.Finit(); a.Seek(0, cBidirArchive::BEGINNING); - iFCOSpecHelper* pHelp1, *pHelp2; + iFCOSpecHelper *pHelp1, *pHelp2; cSerializerImpl s2(a, cSerializerImpl::S_READ); s2.Init(); pHelp1 = (iFCOSpecHelper*)s2.ReadObjectDynCreate(); pHelp2 = (iFCOSpecHelper*)s2.ReadObjectDynCreate(); s2.Finit(); - TEST(pHelp1->Compare(pSet3) == iFCOSpecHelper::CMP_EQ); - TEST(pHelp2->Compare(&noChildren) == iFCOSpecHelper::CMP_EQ); - TEST(pHelp1->Compare(&noChildren) != iFCOSpecHelper::CMP_EQ); - TEST(pHelp2->Compare(pSet3) != iFCOSpecHelper::CMP_EQ); + TEST(pHelp1->Compare(pSet3) == iFCOSpecHelper::CMP_EQ); + TEST(pHelp2->Compare(&noChildren) == iFCOSpecHelper::CMP_EQ); + TEST(pHelp1->Compare(&noChildren) != iFCOSpecHelper::CMP_EQ); + TEST(pHelp2->Compare(pSet3) != iFCOSpecHelper::CMP_EQ); delete pSet3; @@ -129,3 +140,8 @@ void TestFCOSpecHelper() delete pHelp1; delete pHelp2; } + +void RegisterSuite_FCOSpecHelper() +{ + RegisterTest("FCOSpecHelper", "Basic", TestFCOSpecHelper); +} diff --git a/src/twtest/fcospeclist_t.cpp b/src/twtest/fcospeclist_t.cpp index 8eac699..8a88be9 100644 --- a/src/twtest/fcospeclist_t.cpp +++ b/src/twtest/fcospeclist_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,48 +51,48 @@ void TestFCOSpecList() TEST(specList.IsEmpty()); cFCOSpecStopPointSet* pStopPts = new cFCOSpecStopPointSet; - iFCOSpec* pSpec = new cFCOSpecImpl(_T("s1"), NULL, pStopPts); + iFCOSpec* pSpec = new cFCOSpecImpl(_T("s1"), NULL, pStopPts); pSpec->SetStartPoint(cFCOName(_T("AAA"))); pStopPts->Add(cFCOName(_T("AAA/SSS"))); specList.Add(pSpec); - pSpec->Release(); // the list now owns the spec. + pSpec->Release(); // the list now owns the spec. cFCOSpecStopPointSet* pStopPts2 = new cFCOSpecStopPointSet; - pSpec = new cFCOSpecImpl(_T("s2"), NULL, pStopPts2); + pSpec = new cFCOSpecImpl(_T("s2"), NULL, pStopPts2); pSpec->SetStartPoint(cFCOName(_T("AAA"))); pStopPts2->Add(cFCOName(_T("AAA/TTT"))); specList.Add(pSpec); - pSpec->Release(); // the list now owns the spec. + pSpec->Release(); // the list now owns the spec. pSpec = new cFCOSpecImpl(_T("s3"), NULL, new cFCOSpecStopPointSet); pSpec->SetStartPoint(cFCOName(_T("AAA"))); specList.Add(pSpec); - cFCOSpecImpl* pTestSpec = new cFCOSpecImpl(_T("test"), NULL, new cFCOSpecStopPointSet); + cFCOSpecImpl* pTestSpec = new cFCOSpecImpl(_T("test"), NULL, new cFCOSpecStopPointSet); pTestSpec->SetStartPoint(cFCOName(_T("AAA"))); // Test Lookup() iFCOSpec* pTmp; - TEST((pTmp = specList.Lookup(pSpec)) == pSpec); + TEST((pTmp = specList.Lookup(pSpec)) == pSpec); pTmp->Release(); - TEST((pTmp = specList.Lookup(pTestSpec)) == pSpec); + TEST((pTmp = specList.Lookup(pTestSpec)) == pSpec); pTmp->Release(); // Test iterator and Insert() order cFCOSpecListCanonicalIter itr(specList); TEST(itr.Spec()->GetName().compare(_T("s3")) == 0); - + pTestSpec->Release(); pSpec->Release(); iFCOSpec* pPrev = NULL; - int i; + int i; for (itr.SeekBegin(), i = 0; !itr.Done(); itr.Next(), ++i) { - switch (i) + switch (i) { case 0: pPrev = itr.Spec(); @@ -106,10 +106,10 @@ void TestFCOSpecList() cFCOSpecListAddedIter itra(specList); TEST(itra.Spec()->GetName().compare(_T("s1")) == 0); - + for (itra.SeekBegin(), i = 0; !itra.Done(); itra.Next(), ++i) { - switch (i) + switch (i) { case 0: TEST(itra.Spec()->GetName().compare(_T("s1")) == 0); @@ -127,14 +127,14 @@ void TestFCOSpecList() } // test serialization - cMemoryArchive a; + cMemoryArchive a; cSerializerImpl s(a, cSerializerImpl::S_WRITE); s.Init(); specList.Write(&s); s.Finit(); a.Seek(0, cBidirArchive::BEGINNING); - cFCOSpecList newSpecList; + cFCOSpecList newSpecList; cSerializerImpl s2(a, cSerializerImpl::S_READ); s2.Init(); newSpecList.Read(&s2); @@ -142,7 +142,7 @@ void TestFCOSpecList() // now to compare the two spec lists... cFCOSpecListCanonicalIter itr1(specList), itr2(newSpecList); - for( itr1.SeekBegin(), itr2.SeekBegin(); ! itr1.Done(); itr1.Next(), itr2.Next() ) + for (itr1.SeekBegin(), itr2.SeekBegin(); !itr1.Done(); itr1.Next(), itr2.Next()) { TEST(iFCOSpecUtil::FCOSpecEqual(*itr1.Spec(), *itr2.Spec())); } @@ -152,7 +152,7 @@ void TestFCOSpecList() d.TraceDebug("Testing removal...\n"); cFCOSpecListAddedIter ai(specList); ai.SeekBegin(); - while(! ai.Done()) + while (!ai.Done()) { d.TraceDebug(_T("Removing spec %s\n"), ai.Spec()->GetName().c_str()); ai.Remove(); @@ -164,3 +164,7 @@ void TestFCOSpecList() return; } +void RegisterSuite_FCOSpecList() +{ + RegisterTest("FCOSpecList", "Basic", TestFCOSpecList); +} diff --git a/src/twtest/fcospecutil_t.cpp b/src/twtest/fcospecutil_t.cpp index e9d142e..a5b59fa 100644 --- a/src/twtest/fcospecutil_t.cpp +++ b/src/twtest/fcospecutil_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,10 +44,10 @@ void TestFcoSpecUtil() cDebug d("TestFcoSpecUtil()"); // first check the equality operator... - cFCOSpecStopPointSet* pSet1 = new cFCOSpecStopPointSet; - cFCOSpecStopPointSet* pSet2 = new cFCOSpecStopPointSet; - cFCOSpecImpl* pSpec1 = new cFCOSpecImpl(_T("Spec1"), NULL, pSet1); - cFCOSpecImpl* pSpec2 = new cFCOSpecImpl(_T("Spec2"), NULL, pSet2); + cFCOSpecStopPointSet* pSet1 = new cFCOSpecStopPointSet; + cFCOSpecStopPointSet* pSet2 = new cFCOSpecStopPointSet; + cFCOSpecImpl* pSpec1 = new cFCOSpecImpl(_T("Spec1"), NULL, pSet1); + cFCOSpecImpl* pSpec2 = new cFCOSpecImpl(_T("Spec2"), NULL, pSet2); pSpec1->SetStartPoint(cFCOName(_T("Dog"))); pSpec2->SetStartPoint(cFCOName(_T("Dog"))); @@ -63,23 +63,25 @@ void TestFcoSpecUtil() cFCOName removedName = iter.StopPoint(); iter.Remove(); pSet1->Add(cFCOName(_T("Dog/Scratch"))); - TEST(! iFCOSpecUtil::FCOSpecEqual(*pSpec1, *pSpec2)); - - pSet1->Add(removedName); - TEST(! iFCOSpecUtil::FCOSpecEqual(*pSpec1, *pSpec2)); + TEST(!iFCOSpecUtil::FCOSpecEqual(*pSpec1, *pSpec2)); + pSet1->Add(removedName); + TEST(!iFCOSpecUtil::FCOSpecEqual(*pSpec1, *pSpec2)); - // TODO -- implement a more appropriate less-than test -/* pSpec1->SetStartPoint(cFCOName(_T("Dog"))); - pSpec2->AddStopPoint(cFCOName(_T("Howl"))); - TEST(! iFCOSpecUtil::FCOSpecEqual (*pSpec1, *pSpec2)); - TEST( iFCOSpecUtil::FCOSpecLessThan(*pSpec1, *pSpec2)); - pSpec1->AddStopPoint(cFCOName(_T("Howm"))); - TEST( iFCOSpecUtil::FCOSpecLessThan(*pSpec2, *pSpec1)); -*/ + pSpec1->SetStartPoint(cFCOName(_T("Dog"))); + pSet2->Add(cFCOName(_T("Dog/Howl"))); + TEST(!iFCOSpecUtil::FCOSpecEqual(*pSpec1, *pSpec2)); + TEST(iFCOSpecUtil::FCOSpecLessThan(*pSpec1, *pSpec2)); + pSet1->Add(cFCOName(_T("Dog/Howm"))); + TEST(iFCOSpecUtil::FCOSpecLessThan(*pSpec2, *pSpec1)); pSpec1->Release(); pSpec2->Release(); d.TraceDebug("Leaving..\n"); } + +void RegisterSuite_FcoSpecUtil() +{ + RegisterTest("FcoSpecUtil", "Basic", TestFcoSpecUtil); +} diff --git a/src/twtest/file_t.cpp b/src/twtest/file_t.cpp index 7783dfa..8c1decc 100644 --- a/src/twtest/file_t.cpp +++ b/src/twtest/file_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,42 +38,220 @@ #include void TestFile() -{ - - TSTRING fileName = TEMP_DIR; - fileName += _T("/file_test.bin"); +{ + TSTRING fileName = TwTestPath("file_test.bin"); //Create a temporary file for testing: FILE* testStream; - testStream = _tfopen( fileName.c_str(), _T("w+b")); - TSTRING testString( _T("This is a test") ); - int iTestStringLength = testString.length(); + testStream = _tfopen(fileName.c_str(), _T("w+b")); + TEST(testStream); + + TSTRING testString(_T("This is a test")); + int iTestStringLength = testString.length(); //Write some data to the stream... - fwrite( testString.c_str(), sizeof(TCHAR), iTestStringLength, testStream ); - fclose( testStream ); + fwrite(testString.c_str(), sizeof(TCHAR), iTestStringLength, testStream); + fclose(testStream); //Open the file again, for reading only this time. - testStream = _tfopen( fileName.c_str(), _T("rb") ); + testStream = _tfopen(fileName.c_str(), _T("rb")); + TEST(testStream); +} + +//////////////////////////////////////////////////////////////////////// - cFile fTempFile; - //Try attaching one of our file objects to the stream. -//TODO: fTempFile.AttachRead( testStream ); +void testDosAsPosix(const std::string& in, const std::string& expected) +{ + TEST(expected == cDosPath::AsPosix(in)); +} + +void TestDosAsPosix() +{ + testDosAsPosix("c:\\foo", "/dev/c/foo"); + testDosAsPosix("c:\\foo\\bar\\baz.txt", "/dev/c/foo/bar/baz.txt"); + testDosAsPosix("c:/foo/bar/baz.txt", "/dev/c/foo/bar/baz.txt"); + + testDosAsPosix("c:\\", "/dev/c/"); + testDosAsPosix("c:", "/dev/c"); - //Try reading something from the file object - TCHAR buffer[40]; - TCHAR buffer2[40]; + testDosAsPosix("foo.txt", "foo.txt"); + testDosAsPosix("bar\\foo.txt", "bar/foo.txt"); + testDosAsPosix("bar/foo.txt", "bar/foo.txt"); + + testDosAsPosix("/foo/bar/baz.txt", "/foo/bar/baz.txt"); +} - fTempFile.Read( buffer, sizeof(TCHAR) * iTestStringLength ); - fTempFile.Close(); - testStream = _tfopen( fileName.c_str(), _T("a+b") ); -//TODO: fTempFile.AttachReadWrite( testStream ); +void testDosAsNative(const std::string& in, const std::string& expected) +{ + TEST(expected == cDosPath::AsNative(in)); +} + +void TestDosAsNative() +{ + testDosAsNative("/dev/c/foo", "c:\\foo"); + testDosAsNative("/dev/c/", "c:\\"); + testDosAsNative("/dev/c", "c:\\"); + + testDosAsNative("/foo/bar/baz", "/foo/bar/baz"); +} - //Now try writing something to the stream. - fTempFile.Write( testString.c_str(), sizeof(TCHAR) * iTestStringLength ); - fTempFile.Rewind(); - fTempFile.Read( buffer2, sizeof(TCHAR) * iTestStringLength * 2 ); +void testDosIsAbsolute(const std::string& in, bool expected) +{ + TEST(expected == cDosPath::IsAbsolutePath(in)); } +void TestDosIsAbsolute() +{ + testDosIsAbsolute("C:\\", true); + testDosIsAbsolute("C:", true); + testDosIsAbsolute("C:\\foo", true); + testDosIsAbsolute("C:\\foo\\bar\\baz.txt", true); + + testDosIsAbsolute("/foo", true); + + testDosIsAbsolute("foo.txt", false); + testDosIsAbsolute("bar\\foo.txt", false); + testDosIsAbsolute("bar/foo.txt", false); +} + +void testDosBackupName(const std::string& in, const std::string& expected) +{ + TEST(expected == cDosPath::BackupName(in)); +} + +void TestDosBackupName() +{ + testDosBackupName("C:\\12345678.123", "C:\\12345678"); + testDosBackupName("C:\\12345678", "C:\\12345678"); + testDosBackupName("C:\\1.123", "C:\\1_123"); + testDosBackupName("C:\\1", "C:\\1"); + + testDosBackupName("C:\\FOO\\12345678.123", "C:\\FOO\\12345678"); + testDosBackupName("C:\\FOO.BAR\\1234.123", "C:\\FOO.BAR\\1234_123"); +} + + +//////////////////////////////////////////////////////////////////////// +void testArosAsPosix(const std::string& in, const std::string& expected) +{ + TEST(expected == cArosPath::AsPosix(in)); +} + +void TestArosAsPosix() +{ + testArosAsPosix("DH0:", "/DH0/"); + testArosAsPosix("DH0:Foo", "/DH0/Foo"); + testArosAsPosix("DH0:Foo/Bar", "/DH0/Foo/Bar"); + + testArosAsPosix("/DH0/Foo/Bar", "/DH0/Foo/Bar"); + + testArosAsPosix("Foo", "Foo"); + testArosAsPosix("Foo/Bar", "Foo/Bar"); +} + +void testArosAsNative(const std::string& in, const std::string& expected) +{ + TEST(expected == cArosPath::AsNative(in)); +} + +void TestArosAsNative() +{ + testArosAsNative("/DH0", "DH0:"); + testArosAsNative("/DH0/Foo", "DH0:Foo"); + testArosAsNative("/DH0/Foo/Bar", "DH0:Foo/Bar"); + + testArosAsNative("DH0:Foo/Bar", "DH0:Foo/Bar"); + + testArosAsNative("Foo", "Foo"); + testArosAsNative("Foo/Bar", "Foo/Bar"); +} + +void testArosIsAbsolute(const std::string& in, bool expected) +{ + TEST(expected == cArosPath::IsAbsolutePath(in)); +} + +void TestArosIsAbsolute() +{ + testArosIsAbsolute("DH0:", true); + testArosIsAbsolute("DH0:Foo", true); + testArosIsAbsolute("DH0:Foo/bar", true); + + testArosIsAbsolute("/DH0/Foo/bar", true); + + testArosIsAbsolute("Foo/bar", false); + testArosIsAbsolute("Foo", false); +} + + +//////////////////////////////////////////////////////////////////////// +void testRedoxAsPosix(const std::string& in, const std::string& expected) +{ + TEST(expected == cRedoxPath::AsPosix(in)); +} + +void TestRedoxAsPosix() +{ + testRedoxAsPosix("file:/", "/file/"); + testRedoxAsPosix("file:/Foo", "/file/Foo"); + testRedoxAsPosix("file:/Foo/Bar", "/file/Foo/Bar"); + + testRedoxAsPosix("/file/Foo/Bar", "/file/Foo/Bar"); + + testRedoxAsPosix("Foo", "Foo"); + testRedoxAsPosix("Foo/Bar", "Foo/Bar"); +} + +void testRedoxAsNative(const std::string& in, const std::string& expected) +{ + TEST(expected == cRedoxPath::AsNative(in)); +} + +void TestRedoxAsNative() +{ + testRedoxAsNative("/file", "file:/"); + testRedoxAsNative("/file/Foo", "file:/Foo"); + testRedoxAsNative("/file/Foo/Bar", "file:/Foo/Bar"); + + testRedoxAsNative("file:/Foo/Bar", "file:/Foo/Bar"); + + testRedoxAsNative("Foo", "Foo"); + testRedoxAsNative("Foo/Bar", "Foo/Bar"); +} + +void testRedoxIsAbsolute(const std::string& in, bool expected) +{ + TEST(expected == cRedoxPath::IsAbsolutePath(in)); +} + +void TestRedoxIsAbsolute() +{ + testRedoxIsAbsolute("file:", true); + testRedoxIsAbsolute("file:/Foo", true); + testRedoxIsAbsolute("file:/Foo/bar", true); + + testRedoxIsAbsolute("/file/Foo/bar", true); + + testRedoxIsAbsolute("Foo/bar", false); + testRedoxIsAbsolute("Foo", false); +} + + +void RegisterSuite_File() +{ + RegisterTest("File", "Basic", TestFile); + RegisterTest("File", "DosAsPosix", TestDosAsPosix); + RegisterTest("File", "DosAsNative", TestDosAsNative); + RegisterTest("File", "DosIsAbsolute", TestDosIsAbsolute); + RegisterTest("File", "DosBackupName", TestDosBackupName); + + RegisterTest("File", "ArosAsPosix", TestArosAsPosix); + RegisterTest("File", "ArosAsNative", TestArosAsNative); + RegisterTest("File", "ArosIsAbsolute", TestArosIsAbsolute); + + RegisterTest("File", "RedoxAsPosix", TestRedoxAsPosix); + RegisterTest("File", "RedoxAsNative", TestRedoxAsNative); + RegisterTest("File", "RedoxIsAbsolute", TestRedoxIsAbsolute); +} diff --git a/src/twtest/fileheader_t.cpp b/src/twtest/fileheader_t.cpp index c561cb2..6a3e4fb 100644 --- a/src/twtest/fileheader_t.cpp +++ b/src/twtest/fileheader_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -52,29 +52,29 @@ void TestFileHeader() TEST(id != id_null); { - cSerializerImpl ser(memarch, cSerializerImpl::S_WRITE); - - ser.Init(); - id.Write(&ser); - id_dup.Write(&ser); - id_null.Write(&ser); - ser.Finit(); + cSerializerImpl ser(memarch, cSerializerImpl::S_WRITE); + + ser.Init(); + id.Write(&ser); + id_dup.Write(&ser); + id_null.Write(&ser); + ser.Finit(); } memarch.Seek(0, cBidirArchive::BEGINNING); { - cSerializerImpl ser(memarch, cSerializerImpl::S_READ); - cFileHeaderID id_read; - - ser.Init(); - id_read.Read(&ser); - TEST(id_read == id); - id_read.Read(&ser); - TEST(id_read == id_dup); - id_read.Read(&ser); - TEST(id_read == id_null); - ser.Finit(); + cSerializerImpl ser(memarch, cSerializerImpl::S_READ); + cFileHeaderID id_read; + + ser.Init(); + id_read.Read(&ser); + TEST(id_read == id); + id_read.Read(&ser); + TEST(id_read == id_dup); + id_read.Read(&ser); + TEST(id_read == id_null); + ser.Finit(); } memarch.Seek(0, cBidirArchive::BEGINNING); @@ -89,40 +89,45 @@ void TestFileHeader() TEST(header1.GetID() == cFileHeaderID(_T("myheader"))); header1.SetEncoding(cFileHeader::SYM_ENCRYPTION); TEST(header1.GetEncoding() == cFileHeader::SYM_ENCRYPTION); - + header2.SetID(id); TEST(header2.GetID() == id); header2.SetEncoding(cFileHeader::COMPRESSED); header2.GetBaggage().WriteBlob("abc123", 6); { - cSerializerImpl ser(memarch, cSerializerImpl::S_WRITE); - - ser.Init(); - header1.Write(&ser); - header2.Write(&ser); - ser.Finit(); + cSerializerImpl ser(memarch, cSerializerImpl::S_WRITE); + + ser.Init(); + header1.Write(&ser); + header2.Write(&ser); + ser.Finit(); } memarch.Seek(0, cBidirArchive::BEGINNING); { - cSerializerImpl ser(memarch, cSerializerImpl::S_READ); - cFileHeader header_read; - - ser.Init(); - header_read.Read(&ser); - TEST(header_read.GetID() == header1.GetID()); - TEST(header_read.GetEncoding() == header1.GetEncoding()); - TEST(header_read.GetBaggage().Length() == 0); - header_read.Read(&ser); - TEST(header_read.GetID() == header2.GetID()); - TEST(header_read.GetEncoding() == header2.GetEncoding()); - TEST(header_read.GetBaggage().Length() != 0); - ser.Finit(); - - char buf[6]; - header_read.GetBaggage().ReadBlob(buf, 6); - TEST(memcmp(buf, "abc123", 6) == 0); + cSerializerImpl ser(memarch, cSerializerImpl::S_READ); + cFileHeader header_read; + + ser.Init(); + header_read.Read(&ser); + TEST(header_read.GetID() == header1.GetID()); + TEST(header_read.GetEncoding() == header1.GetEncoding()); + TEST(header_read.GetBaggage().Length() == 0); + header_read.Read(&ser); + TEST(header_read.GetID() == header2.GetID()); + TEST(header_read.GetEncoding() == header2.GetEncoding()); + TEST(header_read.GetBaggage().Length() != 0); + ser.Finit(); + + char buf[6]; + header_read.GetBaggage().ReadBlob(buf, 6); + TEST(memcmp(buf, "abc123", 6) == 0); } } + +void RegisterSuite_FileHeader() +{ + RegisterTest("FileHeader", "Basic", TestFileHeader); +} diff --git a/src/twtest/fileutil_t.cpp b/src/twtest/fileutil_t.cpp index e478fc0..267e1ef 100644 --- a/src/twtest/fileutil_t.cpp +++ b/src/twtest/fileutil_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,6 +38,8 @@ #include "util/stdutil.h" #include "util/fileutil.h" #include "core/debug.h" +#include "test.h" +#include using namespace std; @@ -47,17 +49,29 @@ using namespace std; void TestFileUtil() { + TSTRING source = TwTestPath("copy_src"); + + //Create a temporary file for testing: + FILE* testStream; + testStream = _tfopen(source.c_str(), _T("w+b")); + TEST(testStream); - TSTRING source, dest; + TSTRING testString(_T("This is a test")); + int iTestStringLength = testString.length(); - source = _T("/etc/hosts"); - dest = _T("/tmp/dest"); - bool blah = cFileUtil::Copy(source, dest); - (void)blah; + //Write some data to the stream... + fwrite(testString.c_str(), sizeof(TCHAR), iTestStringLength, testStream); + fclose(testStream); + TSTRING dest = TwTestPath("copy_dest"); -// TCOUT << _T("<") << wstr3 << _T(">") << std::endl; - + TEST(cFileUtil::Copy(source, dest)); + unlink(dest.c_str()); + unlink(source.c_str()); } +void RegisterSuite_FileUtil() +{ + RegisterTest("FileUtil", "Basic", TestFileUtil); +} diff --git a/src/twtest/fsdatasourceiter_t.cpp b/src/twtest/fsdatasourceiter_t.cpp index 7eb57d7..290ac15 100644 --- a/src/twtest/fsdatasourceiter_t.cpp +++ b/src/twtest/fsdatasourceiter_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,83 +36,92 @@ #include "core/debug.h" #include "twtest/test.h" #include "fco/fco.h" +#include "fco/twfactory.h" +#include "core/errorbucketimpl.h" -/* -static void PrintDb( cHierDatabase::iterator iter, cDebug d, bool bFirst = true ) +namespace { - if( ! bFirst ) - { - iter.Descend(); - } - d.TraceDebug( "-- Processing directory %s\n", iter.GetCwd().c_str() ); +int num_processed = 0; + +void util_ProcessDir(iFCODataSourceIter* pIter) +{ + TEST(!pIter->Done()); + TEST(pIter->CanDescend()); + if (!pIter->CanDescend()) + return; - for( iter.SeekBegin(); ! iter.Done(); iter.Next() ) + pIter->Descend(); + + for (pIter->SeekBegin(); !pIter->Done(); pIter->Next()) { - d.TraceDebug( "Processing entry %s\n", iter.GetName().c_str() ); - if( iter.CanDescend() ) + iFCO* pFCO = pIter->CreateFCO(); + if (pFCO) { - d.TraceDebug( ">>Descending...\n" ); - PrintDb(iter, d, false); + num_processed++; + pFCO->Release(); + + if (pIter->CanDescend()) + { + TW_UNIQUE_PTR pCopy(pIter->CreateCopy()); + util_ProcessDir(pCopy.get()); + } + } + else + { + fail("CreateFCO failure"); } } - - d.TraceDebug( "-- Done Processing directory %s\n", iter.GetCwd().c_str() ); } -*/ -static void PrintIter( cFSDataSourceIter iter, cDebug& d ) +void util_ProcessDir(const cFCOName& name) { - // - //debug stuff - // - - if( ! iter.CanDescend() ) - { - d.TraceError( "Iterator cannot descend; returning!\n"); - return; - } - iter.Descend(); - iter.TraceContents(); + //Create a cFSDataSourceIter the same way we do in DB gen / IC + TW_UNIQUE_PTR pDSIter(iTWFactory::GetInstance()->CreateDataSourceIter()); + + cErrorQueue errorQueue; + pDSIter->SetErrorBucket(&errorQueue); - for( iter.SeekBegin(); ! iter.Done(); iter.Next() ) + pDSIter->SeekToFCO(name, false); // false means don't generate my peers... + if (!pDSIter->Done()) { - iFCO* pFCO = iter.CreateFCO(); - if( pFCO ) + iFCO* pFCO = pDSIter->CreateFCO(); + if (pFCO) { - pFCO->TraceContents(); + num_processed++; pFCO->Release(); + + if (pDSIter->CanDescend()) + { + TW_UNIQUE_PTR pCopy(pDSIter->CreateCopy()); + util_ProcessDir(pCopy.get()); + } } else { - d.TraceError( "*** Create of FCO failed!\n"); - } - if( iter.CanDescend() ) - { - d.TraceDebug( ">>Descending...\n" ); - PrintIter(iter, d); + fail("CreateFCO failure"); } } + + TEST(0 == errorQueue.GetNumErrors()); + TEST(0 < num_processed); } +} // namespace + + +////////////////////////////////////// + void TestFSDataSourceIter() { - cFSDataSourceIter iter; - cDebug d("TestFSDataSourceIter"); - try - { - // go to my temp directory and iterate over everything! - iter.SeekToFCO( cFCOName(_T("/tmp")) ); - // - // print out everything below the iterator - // - PrintIter( iter, d ); - } - catch( eError& e ) - { - d.TraceError( "*** Caught exception %d %s\n", e.GetID(), e.GetMsg().c_str() ); - TEST( false ); - } -} + cDebug d("TestFSDataSourceIter"); + cFCOName base(TwTestDir()); + util_ProcessDir(base); +} + +void RegisterSuite_FSDataSourceIter() +{ + RegisterTest("FSDataSourceIter", "Basic", TestFSDataSourceIter); +} diff --git a/src/twtest/fsobject_t.cpp b/src/twtest/fsobject_t.cpp index bc17e42..7df10b9 100644 --- a/src/twtest/fsobject_t.cpp +++ b/src/twtest/fsobject_t.cpp @@ -1,39 +1,68 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // fsobject_t -- the file system object test driver #include "fs/stdfs.h" #include "fs/fsobject.h" +#include "fs/fspropcalc.h" +#include "test.h" +#include void TestFSObject() { - return; + cDebug d("TestFSObject"); + + cFCOName path(TwTestPath("fsobject")); + std::ofstream fstr(path.AsString().c_str()); + if (fstr.bad()) + { + d.TraceError("Unable to create test file %s!\n", path.AsString().c_str()); + TEST(false); + } + fstr.close(); + + cFSObject obj(path); + + cFSPropCalc propCalc; + cFCOPropVector v(obj.GetPropSet()->GetValidVector().GetSize()); + for (int x = 0; x < cFSPropSet::PROP_NUMITEMS; x++) + v.AddItem(x); + propCalc.SetPropVector(v); + + obj.AcceptVisitor(&propCalc); + + TEST(obj.GetPropSet()->GetNumProps() == cFSPropSet::PROP_NUMITEMS); +} + +void RegisterSuite_FSObject() +{ + RegisterTest("FSObject", "Basic", TestFSObject); } diff --git a/src/twtest/fspropcalc_t.cpp b/src/twtest/fspropcalc_t.cpp index 8bff266..65787b1 100644 --- a/src/twtest/fspropcalc_t.cpp +++ b/src/twtest/fspropcalc_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,58 +33,69 @@ #include "fs/stdfs.h" #include "fs/fspropcalc.h" #include "core/debug.h" +#include "core/archive.h" +#include "core/fsservices.h" #include "fco/fcopropset.h" #include "fs/fspropset.h" +#include "fs/fsdatasourceiter.h" #include "twtest/test.h" #include "fco/fco.h" +#include +#include +#include +#include + /////////////////////////////////////////////////////////////////////////////// // PrintProps -- prints out all the valid property names and values as pairs... /////////////////////////////////////////////////////////////////////////////// -/* + static void PrintProps(const iFCO* pFCO) { - cDebug d("PrintProps"); - const iFCOPropSet* pSet = pFCO->GetPropSet(); - const cFCOPropVector& v = pSet->GetValidVector(); - - for(int i=0; iGetNumProps(); i++) + cDebug d("PrintProps"); + const iFCOPropSet* pSet = pFCO->GetPropSet(); + const cFCOPropVector& v = pSet->GetValidVector(); + + for (int i = 0; i < pSet->GetNumProps(); i++) { - if(v.ContainsItem(i)) + if (v.ContainsItem(i)) { - d.TraceDebug("[%d] %s\t%s\n", i, pSet->GetPropName(i), pSet->GetPropAt(i)->AsString().c_str()); + d.TraceDebug("[%d] %s\t%s\n", i, pSet->GetPropName(i).c_str(), pSet->GetPropAt(i)->AsString().c_str()); } } } -*/ - void TestFSPropCalc() { -#pragma message( __FILE__ "(1) : TODO - implement this test file") -#if 0 - cDebug d("TestFSPropCalc"); - cFSDataSource ds; + cDebug d("TestFSPropCalc"); + cFSDataSourceIter ds; + TSTRING foo_bin = TwTestPath("foo.bin"); - iFSServices* pFSServices = iFSServices::GetInstance(); - bool bCaseSensitive = pFSServices->IsCaseSensitive(); + //iFSServices* pFSServices = iFSServices::GetInstance(); // oh boy! I finally get to test property calculation! d.TraceDebug("Creating FCO c:\\temp\\foo.bin\n"); + std::ofstream fstr(foo_bin.c_str()); + if (fstr.bad()) + { + d.TraceError("Unable to create test file %s!\n", foo_bin.c_str()); + TEST(false); + } + fstr.close(); + cFileArchive arch; - int ret; - ret = arch.OpenReadWrite(TEMP_DIR _T("/foo.bin"), true); - TEST(ret); + arch.OpenReadWrite(foo_bin.c_str(), true); arch.WriteBlob("\x1\x2\x3\x4\x5\x6\x7\x8\x9\x0", 10); arch.Close(); - + // get the fco but none of its children... - iFCO* pFCO = ds.CreateFCO(cFCOName(TEMP_DIR _T("/foo.bin")), 0); - ASSERT(pFCO); + ds.SeekToFCO(cFCOName(foo_bin), false); + iFCO* pFCO = ds.CreateFCO(); + TEST(pFCO); // create the calculator and set some properties to calculate... - cFSPropCalc propCalc; + cFSPropCalc propCalc; cFCOPropVector v(pFCO->GetPropSet()->GetValidVector().GetSize()); v.AddItem(cFSPropSet::PROP_DEV); v.AddItem(cFSPropSet::PROP_CTIME); @@ -108,11 +119,10 @@ void TestFSPropCalc() propCalc.SetCollisionAction(iFCOPropCalc::PROP_LEAVE); pFCO->AcceptVisitor(&propCalc); - + // test only calculating unevaluated props... d.TraceDebug("invalidating PROP_MD5 in fco, and changing the file. \n\tAll should remain the same except md5.\n"); - ret = arch.OpenReadWrite(TEMP_DIR _T("/foo.bin"), true); - TEST(ret); + arch.OpenReadWrite(foo_bin.c_str(), true); arch.WriteString(_T("Bark Bark Bark\n")); arch.Close(); @@ -126,6 +136,29 @@ void TestFSPropCalc() // release the fco pFCO->Release(); -#endif + return; } + +void TestGetSymLinkStr() +{ + std::string file = TwTestPath("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); + std::string link = TwTestPath("linky"); + + int fd = creat(file.c_str(), 0777); + TEST(fd >= 0); + close(fd); + + unlink(link.c_str()); + TEST(0 == symlink(file.c_str(), link.c_str())); + + cMemoryArchive arch(1024 * 1024); + TEST(cFSPropCalc::GetSymLinkStr(link, arch, 8)); + TEST(arch.Length() == (int64)file.size()); +} + +void RegisterSuite_FSPropCalc() +{ + RegisterTest("FSPropCalc", "Basic", TestFSPropCalc); + RegisterTest("FSPropCalc", "GetSymLinkStr", TestGetSymLinkStr); +} diff --git a/src/twtest/fspropdisplayer_t.cpp b/src/twtest/fspropdisplayer_t.cpp index 9fa1b56..9ce9193 100644 --- a/src/twtest/fspropdisplayer_t.cpp +++ b/src/twtest/fspropdisplayer_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -54,45 +54,45 @@ void TestFSPropDisplayer() void cTestFSPropDisplayer::Test() { - char i; + char i; cDebug d("TestFSPropDisplayer"); cFSPropDisplayer* pPD = new cFSPropDisplayer(); - for( i = 0; i < 26; i++ ) + for (i = 0; i < 26; i++) { TCHAR c; c = i + 'a'; - pPD->AddUsernameMapping( i, TSTRING( 5, c ) ); + pPD->AddUsernameMapping(i, TSTRING(5, c)); c = i + 'A'; - pPD->AddGroupnameMapping( i, TSTRING( 5, c ) ); + pPD->AddGroupnameMapping(i, TSTRING(5, c)); } cFSPropDisplayer* pPDNew = new cFSPropDisplayer(); - for( i = 1; i < 26; i++ ) + for (i = 1; i < 26; i++) { TCHAR c; c = i + 'a'; - pPDNew->AddUsernameMapping( i, TSTRING( 10, c ) ); + pPDNew->AddUsernameMapping(i, TSTRING(10, c)); c = i + 'A'; - pPDNew->AddGroupnameMapping( i, TSTRING( 10, c ) ); + pPDNew->AddGroupnameMapping(i, TSTRING(10, c)); } - pPDNew->Merge( pPD ); + pPDNew->Merge(pPD); + - /* //////////////////////// // write pd cFileArchive outFile; - outFile.OpenReadWrite(_T("c:\\tmp\\tmp.pd")); + outFile.OpenReadWrite(TwTestPath("tmp.pd").c_str()); cSerializerImpl outSer(outFile, cSerializerImpl::S_WRITE); outSer.Init(); - - pPD->Write( &outSer ); + + pPD->Write(&outSer); outSer.Finit(); outFile.Close(); @@ -101,33 +101,41 @@ void cTestFSPropDisplayer::Test() //////////////////////// // read pd cFileArchive inFile; - inFile.OpenRead(_T("c:\\tmp\\tmp.pd")); + inFile.OpenRead(TwTestPath("tmp.pd").c_str()); cSerializerImpl inSer(inFile, cSerializerImpl::S_READ); - - cFSPropDisplayer* pPDNew = new cFSPropDisplayer(); + + cFSPropDisplayer* pPDRead = new cFSPropDisplayer(); inSer.Init(); - - pPDNew->Read( &inSer ); + + pPDRead->Read(&inSer); inSer.Finit(); - */ - + + TEST(*pPD == *pPDRead); + TSTRING strRet; - for( i = 0; i < 26; i++ ) + for (i = 0; i < 26; i++) { - if( pPDNew->GetUsername( i, strRet ) ) - d.TraceDebug( "username for uid %d: <%s>\n", i, strRet.c_str() ); + if (pPDNew->GetUsername(i, strRet)) + d.TraceDebug("username for uid %d: <%s>\n", i, strRet.c_str()); else - d.TraceDebug( "no username for uid %d\n", i ); - - if( pPDNew->GetGroupname( i, strRet ) ) - d.TraceDebug( "groupname for gid %d: <%s>\n", i, strRet.c_str() ); + d.TraceDebug("no username for uid %d\n", i); + + if (pPDNew->GetGroupname(i, strRet)) + d.TraceDebug("groupname for gid %d: <%s>\n", i, strRet.c_str()); else - d.TraceDebug( "no groupname for gid %d\n", i ); + d.TraceDebug("no groupname for gid %d\n", i); d.TraceDebug("\n"); } + delete pPD; + delete pPDNew; + delete pPDRead; return; } +void RegisterSuite_FSPropDisplayer() +{ + RegisterTest("FSPropDisplayer", "Basic", TestFSPropDisplayer); +} diff --git a/src/twtest/fspropset_t.cpp b/src/twtest/fspropset_t.cpp index 6ad5803..d2d66bf 100644 --- a/src/twtest/fspropset_t.cpp +++ b/src/twtest/fspropset_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,16 +38,15 @@ /////////////////////////////////////////////////////////////////////////////// // PrintPropVector -- function that prints the contents of a cFCOPropVector -// TODO: We might want to add this functionality to the property vector some -// day... /////////////////////////////////////////////////////////////////////////////// static void PrintPropVector(const cFCOPropVector& v, cDebug& d) { TOSTRINGSTREAM stream; - for(int i=0; i + /////////////////////////////////////////////////////////////////////////////// // PrintFCOTree -- recursively prints an fco's name and all of it's children's /////////////////////////////////////////////////////////////////////////////// @@ -64,48 +66,60 @@ static void PrintFCOTree(const iFCO* pFCO, cDebug d, int depth) } */ -void TestFCOSpecImpl() +void TestFCOSpecImpl1() { - cDebug d("TestFCOSpecImpl"); + cDebug d("TestFCOSpecImpl1"); d.TraceDebug("Entering...\n"); - //********************* - // - // TODO -- As of tripwire 2.1, this needs to be updated! - // 28 Jan 99 mdb - // - //********************* - ASSERT( false ); -/* - cFSDataSource dataSrc; - iFSServices* pFSS = iFSServices::GetInstance(); - + cFSDataSourceIter dataSrc; // test AllChildStopPoint fcos... - d.TraceDebug("Now testing a spec whose start point is the only thing it maps to (%s)\n", TEMP_DIR); - cFCOSpecImpl* pSpec2 = new cFCOSpecImpl(TEMP_DIR, &dataSrc, new cFCOSpecNoChildren); - pSpec2->SetStartPoint(cFCOName(TEMP_DIR)); - iFCO* pFCO = pSpec2->CreateFCO(pSpec2->GetStartPoint(), iFCODataSource::CHILDREN_ALL); - PrintFCOTree(pFCO, d, 0); + d.TraceDebug("Now testing a spec whose start point is the only thing it maps to (%s)\n", TwTestDir().c_str()); + cFCOSpecImpl* pSpec = new cFCOSpecImpl(TwTestDir(), &dataSrc, new cFCOSpecNoChildren); + pSpec->SetStartPoint(cFCOName(TwTestDir())); + + dataSrc.SeekToFCO(pSpec->GetStartPoint(), false); + TEST(!dataSrc.Done()); + iFCO* pFCO = dataSrc.CreateFCO(); + TEST(pFCO); + //PrintFCOTree(pFCO, d, 0); pFCO->Release(); + pSpec->Release(); +} + +void TestFCOSpecImpl2() +{ + cDebug d("TestFCOSpecImpl2"); + d.TraceDebug("Entering...\n"); + + if (-1 == access("/etc", F_OK)) + skip("/etc not found/accessible"); + + cFSDataSourceIter dataSrc; + // create an FSSpec and set up some start and stop points... - cFCOSpecStopPointSet* pSet = new cFCOSpecStopPointSet; - cFCOSpecImpl* pSpec = new cFCOSpecImpl(_T("Test FSSpec"), &dataSrc, pSet); - pSpec->SetStartPoint(cFCOName(_T("d:/code"))); - pSet->Add(cFCOName(_T("d:/code/open gl"))); - pSet->Add(cFCOName(_T("d:/code/pclient"))); - - // create all the fcos... - pFCO = pSpec->CreateFCO(pSpec->GetStartPoint(), iFCODataSource::CHILDREN_ALL); - ASSERT(pFCO); - PrintFCOTree(pFCO, d, 0); + cFCOSpecStopPointSet* pSet = new cFCOSpecStopPointSet; + cFCOSpecImpl* pSpec = new cFCOSpecImpl(_T("Test FSSpec"), &dataSrc, pSet); + pSpec->SetStartPoint(cFCOName(_T("/etc"))); + pSet->Add(cFCOName(_T("/etc/open gl"))); + pSet->Add(cFCOName(_T("/etc/pclient"))); + + dataSrc.SeekToFCO(pSpec->GetStartPoint(), false); + TEST(!dataSrc.Done()); + iFCO* pFCO = dataSrc.CreateFCO(); + TEST(pFCO); + //PrintFCOTree(pFCO, d, 0); + pFCO->Release(); // TODO -- test Clone(), copy ctor, operator= pSpec->Release(); - return; -*/ } +void RegisterSuite_FCOSpecImpl() +{ + RegisterTest("FCOSpecImpl", "Basic1", TestFCOSpecImpl1); + RegisterTest("FCOSpecImpl", "Basic2", TestFCOSpecImpl2); +} diff --git a/src/twtest/genre_t.cpp b/src/twtest/genre_t.cpp index e8dd325..25baa8f 100644 --- a/src/twtest/genre_t.cpp +++ b/src/twtest/genre_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,38 +36,28 @@ #include "fco/stdfco.h" #include "fco/genreswitcher.h" #include "twtest/test.h" +#include "fs/fs.h" -#ifdef _CPPRTTI -#include "fs/fsfactory.h" -#include "ntfs/ntfsfactory.h" -#endif - -void TestGenreSwitcher() +void TestGenre() { -#pragma message( __FILE__ "(1) : TODO - implement this test file") -#if 0 - cDebug d("TestGenreSwitcher"); + cDebug d("TestGenre"); d.TraceDebug("Entering...\n"); - // normally we use the cGenreSwitcher::GetInstance() interface - // to get access the class singleton. But for testing purposes - // we will put have one reside on the stack. - cGenreSwitcher genreSwitcher; + TEST(cGenreSwitcher::GetInstance()->StringToGenre(cGenreSwitcher::GetInstance()->GenreToString(cFS::GenreID())) == + cFS::GenreID()); - TEST(genreSwitcher.CurrentGenre() == cGenre::GENRE_INVALID); + //TODO: GenreToString() dies w/ GENRE_INVALID. Figure out if this should be changed. + // + //TEST(cGenreSwitcher::GetInstance()->StringToGenre(cGenreSwitcher::GetInstance()->GenreToString(cGenre::GENRE_INVALID)) == cGenre::GENRE_INVALID); - genreSwitcher.SelectGenre(cGenre::FS); - TEST(genreSwitcher.CurrentGenre() == cGenre::FS); - #ifdef _CPPRTTI - TEST(typeid(*iTWFactory::GetInstance()) == typeid(cFSFactory)); - #endif - genreSwitcher.SelectGenre(cGenre::NTFS); - TEST(genreSwitcher.CurrentGenre() == cGenre::NTFS); - #ifdef _CPPRTTI - TEST(typeid(*iTWFactory::GetInstance()) == typeid(cNTFSFactory)); - #endif + TEST(cGenreSwitcher::GetInstance()->StringToGenre(_T("fs")) == cFS::GenreID()); + TEST(cGenreSwitcher::GetInstance()->StringToGenre(_T("none of the above")) == cGenre::GENRE_INVALID); d.TraceDebug("All tests passed.\n"); -#endif //#if 0 +} + +void RegisterSuite_Genre() +{ + RegisterTest("Genre", "Basic", TestGenre); } diff --git a/src/twtest/genrespeclist_t.cpp b/src/twtest/genrespeclist_t.cpp index d7b839b..551087a 100644 --- a/src/twtest/genrespeclist_t.cpp +++ b/src/twtest/genrespeclist_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,25 +37,23 @@ #include "fco/genrespeclist.h" #include "twtest/test.h" #include "fco/fcospecimpl.h" +#include "fs/fs.h" void TestGenreSpecList() { -#pragma message( __FILE__ "(1) : TODO - implement this test file") -#if 0 - cDebug d("TestGenreSpecList"); d.TraceDebug("Entering...\n"); - // cGenreSpecListPair + // cGenreSpecListPair cGenreSpecListPair gslPair; TEST(gslPair.GetGenre() == cGenre::GENRE_INVALID); - gslPair.SetGenre(cGenre::FS); - TEST(gslPair.GetGenre() == cGenre::FS); + gslPair.SetGenre(cFS::GenreID()); + TEST(gslPair.GetGenre() == cFS::GenreID()); - cFCOSpecList speclist; - cFCOSpecImpl* fsSpec = new cFCOSpecImpl(_T("test fsspce name"), NULL); + cFCOSpecList speclist; + cFCOSpecImpl* fsSpec = new cFCOSpecImpl(_T("test fsspce name"), NULL); speclist.Add(fsSpec); fsSpec->Release(); @@ -91,6 +89,10 @@ void TestGenreSpecList() TEST(gslVector.at(2).GetSpecList().Lookup(fsSpec)->GetName() == gslPair3.GetSpecList().Lookup(fsSpec)->GetName()); d.TraceDebug("All tests passed.\n"); -#endif } + +void RegisterSuite_GenreSpecList() +{ + RegisterTest("GenreSpecList", "Basic", TestGenreSpecList); +} diff --git a/src/twtest/genreswitcher_t.cpp b/src/twtest/genreswitcher_t.cpp index a8a58c2..ae43142 100644 --- a/src/twtest/genreswitcher_t.cpp +++ b/src/twtest/genreswitcher_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,26 +33,36 @@ // genreswitcher_t.h // +#include + #include "fco/stdfco.h" #include "fco/genreswitcher.h" #include "twtest/test.h" +#include "fs/fs.h" -void TestGenre() -{ - TCERR << "TODO: genreswitcher_t.cpp test ifdef'd due to unhandled exception" << std::endl; +#include "fs/fsfactory.h" -#if 0 - cDebug d("TestGenre"); +void TestGenreSwitcher() +{ + cDebug d("TestGenreSwitcher"); d.TraceDebug("Entering...\n"); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(cGenreSwitcher::GetInstance()->GenreToString(0x00020001)) == 0x00020001); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(cGenreSwitcher::GetInstance()->GenreToString(0x00010001)) == 0x00010001); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(cGenreSwitcher::GetInstance()->GenreToString(0x00010002)) == 0x00010002); + cGenreSwitcher* genreSwitcher = cGenreSwitcher::GetInstance(); + + TEST(genreSwitcher->CurrentGenre() == cFS::GenreID()); + + // can't switch to invalid genre + //genreSwitcher->SelectGenre(cGenre::GENRE_INVALID); + //TEST(genreSwitcher->CurrentGenre() == cGenre::GENRE_INVALID); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(_T("fs")) == 0x00020001); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(_T("NT file system")) == 0x00010001); - TEST(cGenreSwitcher::GetInstance()->StringToGenre(_T("none of the above")) == cGenre::GENRE_INVALID); + genreSwitcher->SelectGenre(cFS::GenreID()); + TEST(genreSwitcher->CurrentGenre() == cFS::GenreID()); + TEST(typeid(*iTWFactory::GetInstance()) == typeid(cFSFactory)); d.TraceDebug("All tests passed.\n"); -#endif +} + +void RegisterSuite_GenreSwitcher() +{ + RegisterTest("GenreSwitcher", "Basic", TestGenreSwitcher); } diff --git a/src/twtest/growheap_t.cpp b/src/twtest/growheap_t.cpp index 8178eab..343c3f0 100644 --- a/src/twtest/growheap_t.cpp +++ b/src/twtest/growheap_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,56 +44,62 @@ using namespace std; void TestGrowHeap() { const int initSize = 0x4000; - const int growBy = 0x4000; - cGrowHeap gh( initSize, growBy, _T("growheap_t.cpp") ); - + const int growBy = 0x4000; + cGrowHeap gh(initSize, growBy, _T("growheap_t.cpp")); + // report initial state - TCOUT << _T("Initial size: ") << initSize << endl; + /* TCOUT << _T("Initial size: ") << initSize << endl; TCOUT << _T("Growby: ") << growBy << endl; TCOUT << _T("Initial Growheap memory usage: ") << gh.TotalMemUsage() << endl << endl; - +*/ const int growFactor = 5; // how much to enlarge requests each time // make it odd so we can see if the growheap // rounds to the alignment size - for( size_t size = 1; size < growBy; size *= growFactor ) + for (size_t size = 1; size < growBy; size *= growFactor) { // allocate memory - TCOUT << _T("Allocing by ") << size << endl; - void* p = gh.Malloc( size ); - TEST( p != NULL ); - + //TCOUT << _T("Allocing by ") << size << endl; + void* p = gh.Malloc(size); + TEST(p != NULL); + // access memory with ints - if( size > sizeof(int) ) + if (size > sizeof(int)) { // read from memory - TCOUT << _T("Reading an int from memory...") << endl; - int* pi = static_cast< int* >( p ); - int i = *pi; + //TCOUT << _T("Reading an int from memory...") << endl; + int* pi = static_cast(p); + int i = *pi; // write to memory - TCOUT << _T("Writing an int to memory...") << endl; + //TCOUT << _T("Writing an int to memory...") << endl; *pi = i; } - + // access memory with doubles - if( size > sizeof(double) ) + if (size > sizeof(double)) { // read from memory - TCOUT << _T("Reading a double from memory...") << endl; - double* pd = static_cast< double* >( p ); - double d = *pd; + //TCOUT << _T("Reading a double from memory...") << endl; + double* pd = static_cast(p); + double d = *pd; // write to memory - TCOUT << _T("Writing a double to memory...") << endl; + //TCOUT << _T("Writing a double to memory...") << endl; *pd = d; } // report total usage - TCOUT << _T("Growheap memory usage: ") << gh.TotalMemUsage() << endl << endl; + //TCOUT << _T("Growheap memory usage: ") << gh.TotalMemUsage() << endl << endl; } + TEST(gh.TotalMemUsage() > 0); + // free memory gh.Clear(); - TEST( gh.TotalMemUsage() == 0 ); + TEST(gh.TotalMemUsage() == 0); +} + +void RegisterSuite_GrowHeap() +{ + RegisterTest("GrowHeap", "Basic", TestGrowHeap); } - diff --git a/src/twtest/hashtable_t.cpp b/src/twtest/hashtable_t.cpp index 4db455f..5b77ea7 100644 --- a/src/twtest/hashtable_t.cpp +++ b/src/twtest/hashtable_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,41 +43,32 @@ using namespace std; -void HashTest1(); -void HashTest2(); - -void TestHashTable(void) -{ - HashTest1(); - HashTest2(); -} - void HashTest1() { - //Test the Hash table with Key = TSTRING + //Test the Hash table with Key = TSTRING cHashTable htable; - cDebug d("TestHashTable()::Test1"); + cDebug d("TestHashTable()::Test1"); d.TraceDetail("Entering ...\n"); //return val for all function calls. bool ret = true; //test data - TSTRING string = _T("test string"); - TSTRING string2 = _T("another test string"); - TSTRING string3 = _T("yet another test string"); - void* data_ptr = NULL; - void* data_ptr2 = NULL; - void* data_ptr3 = NULL; - void* test_lookup = NULL; - - int var = 32; - int var2 = 33; - int* test = &var; + TSTRING string = _T("test string"); + TSTRING string2 = _T("another test string"); + TSTRING string3 = _T("yet another test string"); + void* data_ptr = NULL; + void* data_ptr2 = NULL; + void* data_ptr3 = NULL; + void* test_lookup = NULL; + + int var = 32; + int var2 = 33; + int* test = &var; int* test2 = &var2; - data_ptr = test; + data_ptr = test; data_ptr2 = test2; //Test insert and lookup. @@ -104,13 +95,13 @@ void HashTest1() // test iteration cHashTableIter iter(htable); d.TraceDebug("Testing the iterator:\n"); - for(iter.SeekBegin(); ! iter.Done(); iter.Next()) + for (iter.SeekBegin(); !iter.Done(); iter.Next()) { d.TraceDebug(_T("Key=%s\tValue=%d\n"), iter.Key().c_str(), iter.Val()); } // get statistics -#ifdef _DEBUG +#ifdef DEBUG htable.TraceDiagnostics(); #endif @@ -123,7 +114,7 @@ void HashTest1() TEST(htable.Clear()); ret &= htable.IsEmpty(); TEST(htable.IsEmpty()); -/* + /* //Test the Hash table with arbitrary key @@ -163,7 +154,7 @@ void HashTest1() ret &= htable2.IsEmpty(); TEST(htable2.IsEmpty()); -*/ +*/ return; } @@ -173,7 +164,7 @@ void HashTest2() d.TraceDebug("entering...\n"); { - cHashTable tbl; + cHashTable tbl; // test insert and lookup TEST(tbl.Insert(_T("foo"), _T("foo")) == false); @@ -213,8 +204,13 @@ void HashTest2() TEST(tbl.Remove(_T("b"))); TEST(tbl.IsEmpty() == true); - } d.TraceDebug("PASSED!\n"); } + +void RegisterSuite_HashTable() +{ + RegisterTest("HashTable", "Basic 1", HashTest1); + RegisterTest("HashTable", "Basic 2", HashTest2); +} diff --git a/src/twtest/hierdatabase_t.cpp b/src/twtest/hierdatabase_t.cpp new file mode 100644 index 0000000..e352158 --- /dev/null +++ b/src/twtest/hierdatabase_t.cpp @@ -0,0 +1,211 @@ +// +// The developer of the original code and/or files is Tripwire, Inc. +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, +// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights +// reserved. +// +// This program is free software. The contents of this file are subject +// to the terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2 of the License, or (at your +// option) any later version. You may redistribute it and/or modify it +// only in compliance with the GNU General Public License. +// +// This program is distributed in the hope that it will be useful. +// However, this program is distributed AS-IS WITHOUT ANY +// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS +// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License +// for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +// USA. +// +// Nothing in the GNU General Public License or any other license to use +// the code or files shall permit you to use Tripwire's trademarks, +// service marks, or other intellectual property without Tripwire's +// prior written consent. +// +// If you have any questions, please contact Tripwire, Inc. at either +// info@tripwire.org or www.tripwire.org. +// +// hierdatabase_t +#include "db/stddb.h" +#include "db/hierdatabase.h" +#include "test.h" +#include "core/error.h" + + +static const TSTRING g_block_data = "Hello World Hello World Hello World Hello World"; + + +static void AddFile(cHierDatabase::iterator& iter, const TSTRING& filename, bool with_data = false) +{ + if (iter.SeekTo(filename.c_str())) + TCOUT << "Object " << filename << " already exists!" << std::endl; + + iter.CreateEntry(filename); + + if (with_data) + { + iter.SetData((int8*)g_block_data.c_str(), g_block_data.length() + 1); + } + + TEST(iter.HasData() == with_data); +} + +static void AddDirectory(cHierDatabase::iterator& iter, const TSTRING& filename) +{ + if (iter.SeekTo(filename.c_str())) + TCOUT << "Object " << filename << " already exists!" << std::endl; + + iter.CreateEntry(filename); + iter.CreateChildArray(); + + TEST(iter.CanDescend()); +} + +static void RemoveDirectory(cHierDatabase::iterator& iter, const TSTRING& filename) +{ + TCOUT << "Removing the child of " << filename << std::endl; + if (iter.SeekTo(filename.c_str())) + { + iter.DeleteChildArray(); + iter.DeleteEntry(); + } + else + { + TCOUT << "Unable to find object " << filename << std::endl; + } +} + +static void RemoveFile(cHierDatabase::iterator& iter, const TSTRING& filename) +{ + TCOUT << "Removing object " << filename << std::endl; + if (iter.SeekTo(filename.c_str())) + { + if (iter.CanDescend()) + { + TCOUT << "Can't delete object; it still has children." << std::endl; + } + else + { + iter.RemoveData(); + iter.DeleteEntry(); + } + } + else + { + TCOUT << "Unable to find object " << filename << std::endl; + } +} + +static void ChDir(cHierDatabase::iterator& iter, const TSTRING& filename) +{ + if (filename.compare(_T("..")) == 0) + { + if (iter.AtRoot()) + TCOUT << "At root already" << std::endl; + + TCOUT << "Ascending..." << std::endl; + iter.Ascend(); + } + else + { + if (iter.SeekTo(filename.c_str())) + { + if (!iter.CanDescend()) + TCOUT << filename << " has no children; can't descend." << std::endl; + + TCOUT << "Descending into " << filename << std::endl; + iter.Descend(); + } + else + { + TCOUT << "Unable to find object " << filename << std::endl; + } + } +} + +static void AssertData(cHierDatabase::iterator& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + TEST(exists == should_have); + + if (exists) + { + bool has_data = iter.HasData(); + TEST(has_data == should_have); + + if (has_data) + { + int32 dummyLength; + TSTRING read_str((TCHAR*)iter.GetData(dummyLength)); + TEST(read_str == g_block_data); + } + } +} + +static void AssertExists(cHierDatabase::iterator& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + TEST(exists == should_have); +} + +static void AssertChildren(cHierDatabase::iterator& iter, const TSTRING& filename, bool should_have) +{ + bool exists = iter.SeekTo(filename.c_str()); + + if (exists) + { + bool has_children = iter.CanDescend(); + TEST(has_children == should_have); + } +} + +void TestHierDatabaseBasic() +{ + cHierDatabase db; + db.Open(_T("test.db"), 5, true); + cHierDatabase::iterator iter(&db); + + AddFile(iter, "file1", true); + AddFile(iter, "file2", false); + AddFile(iter, "file3", false); + + AddDirectory(iter, "dir1"); + AddDirectory(iter, "dir2"); + AddDirectory(iter, "dir3"); + + AssertData(iter, "file1", true); + + ChDir(iter, "dir1"); + AddFile(iter, "dir1_file1"); + ChDir(iter, ".."); + + RemoveFile(iter, "file1"); + RemoveFile(iter, "file2"); + + AssertExists(iter, "file1", false); + AssertExists(iter, "file2", false); + AssertExists(iter, "file3", true); + + RemoveDirectory(iter, "dir2"); + + AssertExists(iter, "dir1", true); + AssertExists(iter, "dir2", false); + AssertExists(iter, "dir3", true); + + AssertChildren(iter, "dir1", true); + AssertChildren(iter, "dir3", true); + AssertChildren(iter, "file3", false); + +#ifdef DEBUG + db.AssertAllBlocksValid(); +#endif +} + +void RegisterSuite_HierDatabase() +{ + RegisterTest("HierDatabase", "Basic", TestHierDatabaseBasic); +} diff --git a/src/twtest/keyfile_t.cpp b/src/twtest/keyfile_t.cpp index fd03d3f..23fc7a2 100644 --- a/src/twtest/keyfile_t.cpp +++ b/src/twtest/keyfile_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -70,9 +70,9 @@ void TestKeyFile() { cElGamalSig elGamal(*keyfile.GetPublicKey()); - ASSERT(elGamal.GetBlockSizePlain() < 9000); - ASSERT(elGamal.GetBlockSizeCipher() < 9000); - std::string s = "haybaby"; + TEST(elGamal.GetBlockSizePlain() < 9000); + TEST(elGamal.GetBlockSizeCipher() < 9000); + std::string s = "haybaby"; cPrivateKeyProxy key; TEST(key.AquireKey(keyfile, (int8*)s.data(), 7)); elGamal.SetSigning(key.GetKey()); @@ -83,11 +83,11 @@ void TestKeyFile() d.TraceDebug("Decrypting...\n"); { cElGamalSig elGamal(*keyfile.GetPublicKey()); - char recovered_text[9000]; + char recovered_text[9000]; elGamal.SetVerifying(keyfile.GetPublicKey()); elGamal.ProcessBlock(ciphertext, recovered_text); - + TEST(memcmp(recovered_text, plaintext, elGamal.GetBlockSizePlain()) == 0); } @@ -103,33 +103,38 @@ void TestKeyFile() TEST(keyfile2.KeysLoaded()); cElGamalSig elGamal(*keyfile2.GetPublicKey()); - char recovered_text[9000]; + char recovered_text[9000]; elGamal.SetVerifying(keyfile2.GetPublicKey()); elGamal.ProcessBlock(ciphertext, recovered_text); - + TEST(memcmp(recovered_text, plaintext, elGamal.GetBlockSizePlain()) == 0); + delete [] pMem; } // save to and read from disk d.TraceDebug("Read/Write to file...\n"); { - keyfile.WriteFile(TEMP_DIR _T("/keyfile.key")); + keyfile.WriteFile(TwTestPath("keyfile.key").c_str()); cKeyFile keyfile2; TEST(!keyfile2.KeysLoaded()); - keyfile2.ReadFile(TEMP_DIR _T("/keyfile.key")); + keyfile2.ReadFile(TwTestPath("keyfile.key").c_str()); TEST(keyfile2.KeysLoaded()); cElGamalSig elGamal(*keyfile2.GetPublicKey()); - char recovered_text[9000]; + char recovered_text[9000]; elGamal.SetVerifying(keyfile2.GetPublicKey()); elGamal.ProcessBlock(ciphertext, recovered_text); - + TEST(memcmp(recovered_text, plaintext, elGamal.GetBlockSizePlain()) == 0); } return; } +void RegisterSuite_KeyFile() +{ + RegisterTest("KeyFile", "Basic", TestKeyFile); +} diff --git a/src/twtest/objectpool_t.cpp b/src/twtest/objectpool_t.cpp deleted file mode 100644 index b29225e..0000000 --- a/src/twtest/objectpool_t.cpp +++ /dev/null @@ -1,114 +0,0 @@ -// -// The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, -// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights -// reserved. -// -// This program is free software. The contents of this file are subject -// to the terms of the GNU General Public License as published by the -// Free Software Foundation; either version 2 of the License, or (at your -// option) any later version. You may redistribute it and/or modify it -// only in compliance with the GNU General Public License. -// -// This program is distributed in the hope that it will be useful. -// However, this program is distributed AS-IS WITHOUT ANY -// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS -// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License -// for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// Nothing in the GNU General Public License or any other license to use -// the code or files shall permit you to use Tripwire's trademarks, -// service marks, or other intellectual property without Tripwire's -// prior written consent. -// -// If you have any questions, please contact Tripwire, Inc. at either -// info@tripwire.org or www.tripwire.org. -// -/////////////////////////////////////////////////////////////////////////////// -// objectpool_t - -#include "core/stdcore.h" -#include "core/objectpool.h" -#include "core/debug.h" -#include "twtest/test.h" - - -// this is the struct we will use for testing purposes -struct cDog -{ - int i; - char c; - double d; - cDog() : i(53), c('f'), d(3.14) { cDebug d("cDog::cDog"); d.TraceDebug("Dog ctor...\n"); } - ~cDog() { cDebug d("cDog::~cDog"); d.TraceDebug("Dog dtor...\n"); } -}; - - -void TestObjectPool() -{ - int k, j; - cDebug d("TestObjectPool"); - - // first, just try the growing properties of the pool - cObjectPoolBase pool(10, 5); - d.TraceDebug("object size = 10, chunk size = 5\n"); - for(k=0; k < 12; k++) - { - d.TraceDebug("Allocating...\n"); - pool.Alloc(); - } - d.TraceDebug("Removing everything...\n"); - pool.Clear(); - - // test the template class - cObjectPool dogPool(3); - std::list lDog; - for(j=0; j < 7; j++) - { - lDog.push_back(dogPool.New()); - } - - std::list::iterator i; - for( i = lDog.begin(); i != lDog.end(); i++) - { - d.TraceDebug("dog contents: %d %c %lf\n", (*i)->i, (*i)->c, (*i)->d); - dogPool.Delete(*i); - } - lDog.clear(); - - // now, do some random insertions and deletions... - std::vector vAlloced; - for(k=0; k < 1000; k++) - { - if(rand() % 3 > 0 ) - { - // alloc - void* pNew = pool.Alloc(); - d.TraceDebug("Allocating %p\n", pNew); - vAlloced.push_back(pNew); - } - else - { - // free - int randval = rand(); - int vsize = vAlloced.size(); - if (vsize) - { - int idx = randval % vsize; - std::vector::iterator vi = vAlloced.begin() + idx; - void* pGone = *vi; - d.TraceDebug("Removing %p\n", pGone); - pool.Free(pGone); - vAlloced.erase(vi); - } - } - } - - d.TraceDebug("Leaving...\n"); -} - diff --git a/src/twtest/platform_t.cpp b/src/twtest/platform_t.cpp index bf8cf2d..f3dfbef 100644 --- a/src/twtest/platform_t.cpp +++ b/src/twtest/platform_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,6 +39,10 @@ #include "twtest/test.h" #include "core/error.h" +#if HAVE_SYS_UTSNAME_H +#include +#endif + using namespace std; ///////////////////////////////////////////////////////// @@ -50,8 +54,7 @@ void TestSizes(); ///////////////////////////////////////////////////////// // TEMPLATIZED UTIL FUNCTION PROTOTYPES ///////////////////////////////////////////////////////// -template< class E, class T > -bool CanBeRepresentedAs( E e, T t ); +template bool CanBeRepresentedAs(E e, T t); ///////////////////////////////////////////////////////// // TEMPLATIZED UTIL CLASSES DECLARATIONS @@ -59,61 +62,63 @@ bool CanBeRepresentedAs( E e, T t ); // Constructing this class will write to a memory location // offset by ALIGN_SIZE. If it chokes, you'll get a bus error -template -class AlignMe +template class AlignMe { - public: - AlignMe(); - private: - byte a[sizeof(int64)+ALIGN_SIZE]; // we want to be able to access a int64 at address [ALIGN_SIZE] -}; - -///////////////////////////////////////////////////////// -// MAIN TEST FUNCTION -///////////////////////////////////////////////////////// +public: + AlignMe(); -void TestPlatform() -{ - TestAlignment(); - TestSizes(); -} +private: + byte a[sizeof(int64) + ALIGN_SIZE]; // we want to be able to access a int64 at address [ALIGN_SIZE] +}; ///////////////////////////////////////////////////////// // TEMPLATIZED UTIL CLASSES IMPLEMENTATIONS ///////////////////////////////////////////////////////// -template -AlignMe::AlignMe() +template AlignMe::AlignMe() { - TCOUT << _T("Testing alignment of size ") << ALIGN_SIZE << std::endl; +// HP-UX does not play your silly alignment games, at least unless you +// first invoke something called "allow_unaligned_data_access()", which +// apparently incurs a substantial perf penalty. Luckily we don't appear +// to have any need for that behavior, which begs the question of why +// this test exists in the first place. +// -bcox +#if (!IS_HPUX && !IS_SOLARIS) //Turns out Solaris SPARC is unhappy with this test too, btw + //TCOUT << _T("Testing alignment of size ") << ALIGN_SIZE << std::endl; // access a double in the byte array to see if it is aligned. if it isn't and the CPU // can't handle it, you'll get a bus error - - // this should choke if the CPU can't + + // this should choke if the CPU can't // handle misaligned memory access int32* pi = (int32*)&a[ALIGN_SIZE]; - TCOUT << _T("Testing alignment of an int32...") << std::endl; - TCOUT << _T("Reading...") << std::endl; + //TCOUT << _T("Testing alignment of an int32...") << std::endl; + //TCOUT << _T("Reading...") << std::endl; int32 i = *pi; // access memory for read - TCOUT << _T("Read succeeded.") << std::endl; - TCOUT << _T("Writing...") << std::endl; + //TCOUT << _T("Read succeeded.") << std::endl; + //TCOUT << _T("Writing...") << std::endl; *pi = i; // access memory for write TCOUT << _T("Write succeeded.") << std::endl; - // this should choke if the CPU can't + + // this should choke if the CPU can't // handle misaligned memory access int64* pb = (int64*)&a[ALIGN_SIZE]; - TCOUT << _T("Testing alignment of an int64...") << std::endl; - TCOUT << _T("Reading...") << std::endl; + //TCOUT << _T("Testing alignment of an int64...") << std::endl; + //TCOUT << _T("Reading...") << std::endl; int64 I = *pb; // access memory for read - TCOUT << _T("Read succeeded") << std::endl; - TCOUT << _T("Writing...") << std::endl; + //TCOUT << _T("Read succeeded") << std::endl; + //TCOUT << _T("Writing...") << std::endl; *pb = I; // access memory for write - TCOUT << _T("Write succeeded.") << std::endl; - - TCOUT << _T("Alignment of ") << ALIGN_SIZE << _T(" ") << ( ALIGN_SIZE == 1 ? _T("byte") : _T("bytes") ) << _T(" is OK") << std::endl - << _T("=========================================\n"); + //TCOUT << _T("Write succeeded.") << std::endl; + + + /*TCOUT << _T("Alignment of ") << ALIGN_SIZE << _T(" ") << ( ALIGN_SIZE == 1 ? _T("byte") : _T("bytes") ) << _T(" is OK") << std::endl + << _T("=========================================\n"); */ + + TEST("Aligned"); // The actual test is not bus erroring up above; this just tells the framework we tested something. + +#endif } @@ -123,103 +128,196 @@ AlignMe::AlignMe() void TestAlignment() { - // - - - - - - - - - - - - - - - - - - - - - - + // - - - - - - - - - - - - - - - - - - - - - - // empirically determine byte alignment -- see AlignMe definition - // The last AlignMe to be successfully constructed - // - - - - - - - - - - - - - - - - - - - - - - + // The last AlignMe to be successfully constructed + // - - - - - - - - - - - - - - - - - - - - - - - TCOUT << _T("Testing for byte alignment\n") - << _T("=========================================\n"); + // TCOUT << _T("Testing for byte alignment\n") + // << _T("=========================================\n"); AlignMe<128> a128; - AlignMe<64> a64; - AlignMe<32> a32; - AlignMe<16> a16; - AlignMe<8> a8; - AlignMe<4> a4; - AlignMe<2> a2; - AlignMe<1> a1; - - // - - - - - - - - - - - - - - - - - - - - - - - // test a misaligned memory access -- if this + AlignMe<64> a64; + AlignMe<32> a32; + AlignMe<16> a16; + AlignMe<8> a8; + AlignMe<4> a4; + AlignMe<2> a2; + AlignMe<1> a1; + + // - - - - - - - - - - - - - - - - - - - - - - + // test a misaligned memory access -- if this // chokes, your CPU can't handle such accesses // (if it works, your CPU may still not handle - // such accesses: it may have handled the + // such accesses: it may have handled the // hardware interrupt that might have occured. - // - - - - - - - - - - - - - - - - - - - - - - - byte a[sizeof(int32)+sizeof(byte)]; + // - - - - - - - - - - - - - - - - - - - - - - + byte a[sizeof(int32) + sizeof(byte)]; // this should be fine a[0] = 0xAB; - - TCOUT << _T("=========================================\n") + + /* TCOUT << _T("=========================================\n") << _T("About to test memory access off by 1 byte\n") << _T("If you do not see a confirmation after this line, the test choked") - << std::endl; + << std::endl; */ - // this should choke if the CPU can't - // handle misaligned memory access + // this should choke if the CPU can't + // handle misaligned memory access int32* pi = (int32*)&a[1]; - *pi = *pi; // misaligned access (read and write) - + *pi = *pi; // misaligned access (read and write) + TCOUT << _T("Misaligned access OK.") << std::endl; + TEST("Misaligned ok"); //again, the test is not exploding up above - // - - - - - - - - - - - - - - - - - - - - - - + // - - - - - - - - - - - - - - - - - - - - - - // make sure our BYTE_ALIGN value is correct -- // OK, if the above test failed, then comment it out and try this one. // if it works, then our BYTE_ALIGN value is large enough - // - - - - - - - - - - - - - - - - - - - - - - - - byte b[2*sizeof(BYTE_ALIGN)]; + // - - - - - - - - - - - - - - - - - - - - - - + + byte b[2 * sizeof(BYTE_ALIGN)]; // this should be fine b[0] = 0xAB; - TCOUT << _T("=========================================\n") + /* TCOUT << _T("=========================================\n") << _T("About to test memory access off by ") << BYTE_ALIGN << _T(" ") << ( BYTE_ALIGN == 1 ? _T("byte") : _T("bytes") ) << std::endl << _T("If you do not see a confirmation after this line, the test choked") << std::endl; - - // this should choke if the CPU can't - // handle misaligned memory access - pi = (int32*)&b[BYTE_ALIGN]; +*/ + // this should choke if the CPU can't + // handle misaligned memory access + pi = (int32*)&b[BYTE_ALIGN]; *pi = *pi; // aligned (hopefully) access (read and write) - - TCOUT << _T("Aligned access OK. BYTE_ALIGN value of ") << BYTE_ALIGN << _T(" is good.") << std::endl; + + /* TCOUT << _T("Aligned access OK. BYTE_ALIGN value of ") << BYTE_ALIGN << _T(" is good.") << std::endl; TCOUT << _T("=========================================\n"); + TEST("BYTE_ALIGN ok"); // yet again, the test is not falling over a couple of lines up. */ } +// Not sure this is a super valuable test, since it just verifies that builtin integer types +// work the way we think they do. void TestSizes() { - /* - ASSERT( CanBeRepresentedAs( char(), char() ) ); - ASSERT( CanBeRepresentedAs( char(), unsigned char() ) ); - ASSERT( CanBeRepresentedAs( unsigned char(), char() ) ); - ASSERT( CanBeRepresentedAs( unsigned char(), unsigned char() ) ); - ASSERT( CanBeRepresentedAs( signed char(), char() ) ); - ASSERT( CanBeRepresentedAs( char(), signed char() ) ); - ASSERT( CanBeRepresentedAs( signed char(), signed char() ) ); - ASSERT( CanBeRepresentedAs( signed char(), unsigned char() ) ); - ASSERT( CanBeRepresentedAs( char(), signed char() ) ); - */ + TEST(CanBeRepresentedAs(int8(), int8())); + TEST(!CanBeRepresentedAs(int8(), uint8())); + TEST(!CanBeRepresentedAs(uint8(), int8())); + TEST(CanBeRepresentedAs(uint8(), uint8())); + + TEST(CanBeRepresentedAs(int8(), int16())); + TEST(CanBeRepresentedAs(int16(), int32())); + TEST(CanBeRepresentedAs(int32(), int64())); + + TEST(CanBeRepresentedAs(uint8(), uint16())); + TEST(CanBeRepresentedAs(uint16(), uint32())); + TEST(CanBeRepresentedAs(uint32(), uint64())); } - + ///////////////////////////////////////////////////////// // TEMPLATIZED UTIL FUNCTION IMPEMENTATIONS -///////////////////////////////////////////////////////// +///////////////////////////////////////////////////////// -template< class E, class T > -bool CanBeRepresentedAs( E e, T t ) +template bool CanBeRepresentedAs(E e, T t) { - ASSERT( std::numeric_limits< E >::is_specialized ); - ASSERT( std::numeric_limits< T >::is_specialized ); + ASSERT(std::numeric_limits::is_specialized); + ASSERT(std::numeric_limits::is_specialized); bool fReturn = true; - fReturn &= ( std::numeric_limits< E >::min() >= std::numeric_limits< T >::min() ); - fReturn &= ( std::numeric_limits< E >::max() <= std::numeric_limits< T >::max() ); + fReturn &= (std::numeric_limits::min() >= std::numeric_limits::min()); + fReturn &= (std::numeric_limits::max() <= std::numeric_limits::max()); return fReturn; } + + +//////////////////////////// + +#if IS_LINUX +const TSTRING expected_os("Linux"); +#elif IS_DARWIN +const TSTRING expected_os("Darwin"); +#elif IS_CYGWIN +const TSTRING expected_os("Cygwin"); +#elif IS_DOS_DJGPP +const TSTRING expected_os("FreeDOS"); // This will likely fail for other DOS flavors +#elif IS_ANDROID +const TSTRING expected_os("Android"); +#elif IS_DRAGONFLYBSD +const TSTRING expected_os("DragonFly"); +#elif IS_MIDNIGHTBSD +const TSTRING expected_os("MidnightBSD"); +#elif IS_FREEBSD +const TSTRING expected_os("FreeBSD"); +#elif IS_NETBSD +const TSTRING expected_os("NetBSD"); +#elif IS_MIRBSD +const TSTRING expected_os("MirBSD"); +#elif IS_BITRIG +const TSTRING expected_os("Bitrig"); +#elif IS_LIBERTYBSD +const TSTRING expected_os("LibertyBSD"); +#elif IS_OPENBSD +const TSTRING expected_os("OpenBSD"); +#elif IS_SOLARIS +const TSTRING expected_os("SunOS"); +#elif IS_AIX +const TSTRING expected_os("AIX"); +#elif IS_HPUX +const TSTRING expected_os("HP-UX"); +#elif IS_IRIX +const TSTRING expected_os("IRIX"); +#elif IS_OSF1 +const TSTRING expected_os("Tru64"); +#elif IS_MINIX +const TSTRING expected_os("Minix"); +#elif IS_HURD +const TSTRING expected_os("GNU"); +#elif IS_HAIKU +const TSTRING expected_os("Haiku"); +#elif IS_SYLLABLE +const TSTRING expected_os("Syllable"); +#elif IS_SKYOS +const TSTRING expected_os("SkyOS"); +#elif IS_SORTIX +const TSTRING expected_os("Sortix"); +#elif IS_MINT +const TSTRING expected_os("MiNT"); +#elif IS_AROS +const TSTRING expected_os("AROS"); +#elif IS_RTEMS +const TSTRING expected_os("RTEMS"); +#elif IS_RISCOS +const TSTRING expected_os("RISC OS"); +#elif IS_RISCOS +const TSTRING expected_os("Redox"); +#elif IS_QNX +const TSTRING expected_os("QNX"); +#else +const TSTRING expected_os("?!?!?"); +#endif + +void TestPlatformDetection() +{ +#if HAVE_SYS_UTSNAME_H + struct utsname os_info; + TEST(uname(&os_info) == 0); + + TSTRING observed_os(os_info.sysname); + + if (observed_os != expected_os) + TCERR << "Expected OS: " << expected_os << " | Observed OS: " << observed_os << std::endl; + + TEST(observed_os == expected_os); +#endif +} + +void RegisterSuite_Platform() +{ + RegisterTest("Platform", "Alignment", TestAlignment); + RegisterTest("Platform", "Sizes", TestSizes); + RegisterTest("Platform", "PlatformDetection", TestPlatformDetection); +} diff --git a/src/twtest/policyparser_t.cpp b/src/twtest/policyparser_t.cpp index d1f4fb3..a72eab7 100644 --- a/src/twtest/policyparser_t.cpp +++ b/src/twtest/policyparser_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -44,52 +44,82 @@ #include "fs/fspropset.h" #include "fco/fcospeclist.h" #include "twtest/test.h" +#include "util/fileutil.h" + #include +#include // helper class that checks output of each fcospec -class cPolicyParserTester { +class cPolicyParserTester +{ public: - static bool VerifyNameAndStartPoint(iFCOSpec *pfsspec, TSTRING &name); + static bool VerifyNameAndStartPoint(iFCOSpec* pfsspec, TSTRING& name); }; -void TestPolicyParser() +TSTRING get_test_file_dir() { - cDebug d("TestPolicyParser()"); + if (cFileUtil::IsDir("../src/parser/testfiles")) + return "../src/parser/testfiles"; + + if (cFileUtil::IsDir("src/parser/testfiles")) + return "src/parser/testfiles"; + + return ""; +} + +void test_policy_file(const std::string& polfile) +{ + cDebug::AddOutTarget(cDebug::OUT_STDOUT); - // - // file: pol.txt - // - try - { - cDebug::AddOutTarget(cDebug::OUT_STDOUT); + TSTRING pol_path = get_test_file_dir(); + pol_path.append("/"); + pol_path.append(polfile); - std::ifstream in; - in.open( "../twparser/testfiles/pol.txt" ); - if( ! in.good() ) - throw eParserHelper( _T("couldn't open test file") ); + if (-1 == access(pol_path.c_str(), F_OK)) + skip("policy parser test file not found/accessible"); - cPolicyParser parser( in ); + std::ifstream in; + in.open(pol_path.c_str()); + if (!in.good()) + throw eParserHelper(_T("couldn't open test file")); - cGenreSpecListVector policy; - cErrorQueue errorQ; - cErrorReporter errorR; - cErrorTracer errorT; + cPolicyParser parser(in); - // set up an error bucket that will spit things to stderr - errorT.SetChild( &errorR ); - errorQ.SetChild( &errorT ); + cGenreSpecListVector policy; + cErrorQueue errorQ; + cErrorReporter errorR; + cErrorTracer errorT; - parser.Execute( policy, &errorQ ); + // set up an error bucket that will spit things to stderr + errorT.SetChild(&errorR); + errorQ.SetChild(&errorT); - return; - } - catch(eError& e) - { - TCERR << (int)e.GetID() << " : " << e.GetMsg().c_str() << std::endl; - return; - } + parser.Execute(policy, &errorQ); + TEST("No exceptions thrown in cPolicyParser::Execute"); + TCERR << "Parsed policy test file " << polfile << std::endl; return; } - + +void TestPolicyParser() +{ + cDebug d("TestPolicyParser()"); + + test_policy_file("pol.txt"); + + TCERR << "TestPolicyParser: Parser needs work to be able to test more than one policy" << std::endl; + + // test_policy_file("directives.txt"); //fails unless you substitute your hostname for 'your_host' in this file + + // TODO: test currently segfaults if you create more than one policy parser in a process. (Not a real world scenario). + + /* test_policy_file("poleasy.txt"); + test_policy_file("polhard.txt"); + test_policy_file("polruleattr.txt"); */ +} + +void RegisterSuite_PolicyParser() +{ + RegisterTest("PolicyParser", "Basic", TestPolicyParser); +} diff --git a/src/twtest/refcountobj_t.cpp b/src/twtest/refcountobj_t.cpp index ea9ec18..66a8b3e 100644 --- a/src/twtest/refcountobj_t.cpp +++ b/src/twtest/refcountobj_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -33,13 +33,14 @@ #include "core/stdcore.h" #include "core/refcountobj.h" #include "core/debug.h" +#include "test.h" class cRefCountTestObj : public cRefCountObj { public: cRefCountTestObj(); - virtual void Release(); + virtual void Release() const; void AddChild(cRefCountTestObj* pChild); @@ -47,7 +48,7 @@ class cRefCountTestObj : public cRefCountObj virtual ~cRefCountTestObj(); std::list mChildren; - int8* mpSomeMem; + int8* mpSomeMem; }; cRefCountTestObj::cRefCountTestObj() @@ -66,15 +67,15 @@ cRefCountTestObj::~cRefCountTestObj() mChildren.pop_front(); } - delete mpSomeMem; + delete [] mpSomeMem; } void cRefCountTestObj::AddChild(cRefCountTestObj* pChild) { mChildren.push_back(pChild); } - -void cRefCountTestObj::Release() + +void cRefCountTestObj::Release() const { cRefCountObj::Release(); } @@ -88,7 +89,7 @@ class cRefCountTestObjList ~cRefCountTestObjList(); void Add(cRefCountTestObj* pNewObj); - + std::list mList; }; @@ -98,7 +99,7 @@ cRefCountTestObjList::cRefCountTestObjList() cRefCountTestObjList::~cRefCountTestObjList() { - while(!mList.empty()) + while (!mList.empty()) { mList.front()->Release(); mList.pop_front(); @@ -119,7 +120,7 @@ void TestRefCountObj() db.TraceAlways("Entering...\n"); - // Note the following test of Reference counted objects containing + // Note the following test of Reference counted objects containing // copies of themselves failed. Perhaps someday we will upgrade the // reference counting interface to allow this type of structure. /* @@ -157,11 +158,20 @@ void TestRefCountObj() } } - ASSERT(cRefCountObj::objectCounter == 0); - ASSERT(cRefCountObj::referenceCounter == 0); +#ifdef DEBUG + //These fields only exist in debug builds + TEST(cRefCountObj::objectCounter == 0); + TEST(cRefCountObj::referenceCounter == 0); +#else + TEST("This test can only make useful assertions in debug builds"); +#endif db.TraceAlways("Done...\n"); return; } +void RegisterSuite_RefCountObj() +{ + RegisterTest("RefCountObj", "Basic", TestRefCountObj); +} diff --git a/src/twtest/resources_t.cpp b/src/twtest/resources_t.cpp index 94332cf..7b31e96 100644 --- a/src/twtest/resources_t.cpp +++ b/src/twtest/resources_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,60 +41,55 @@ #include -TSS_BeginPackage( cTestResources ) +TSS_BeginPackage(cTestResources) TSS_DECLARE_STRINGTABLE; - public: - - cTestResources() : mnCount( 10 ) - { - } - - size_t Count() const { - return mnCount; - } +public: +cTestResources() : mnCount(10) +{ +} - size_t Count( size_t nCount ) { - return mnCount = nCount; - } +size_t Count() const +{ + return mnCount; +} - private: - size_t mnCount; +size_t Count(size_t nCount) +{ + return mnCount = nCount; +} -TSS_EndPackage( cTestResources ) +private: +size_t mnCount; -TSS_BeginStringIds( test ) - IDS_TEST1 = 1, - IDS_TEST2, - IDS_TEST3, - IDS_INVALID -TSS_EndStringIds( test ) +TSS_EndPackage(cTestResources) -TSS_BeginStringtable( cTestResources ) - TSS_StringEntry( test::IDS_TEST1, _T("Test String 1") ), - TSS_StringEntry( test::IDS_TEST2, _T("Test String 2") ), - TSS_StringEntry( test::IDS_TEST3, _T("Test String 3") ) -TSS_EndStringtable( cTestResources ) + TSS_BeginStringIds(test) IDS_TEST1 = 1, + IDS_TEST2, IDS_TEST3, + IDS_INVALID TSS_EndStringIds(test) + TSS_BeginStringtable(cTestResources) + TSS_StringEntry(test::IDS_TEST1, _T("Test String 1")), + TSS_StringEntry(test::IDS_TEST2, _T("Test String 2")), + TSS_StringEntry(test::IDS_TEST3, _T("Test String 3")) TSS_EndStringtable(cTestResources) -TSS_ImplementPackage( cTestResources ) + TSS_ImplementPackage(cTestResources) -void TestResources() + void TestResources() { - TSS_Package( cTestResources ).Count( 20 ); - - TCOUT << _T("Package::Count(") << TSS_Package( cTestResources ).Count() << _T(")\n" ) << std::endl; - - TCOUT << TSS_GetString( cTestResources, test::IDS_TEST1 ) << std::endl; - TCOUT << TSS_GetString( cTestResources, test::IDS_TEST2 ) << std::endl; - TCOUT << TSS_GetString( cTestResources, test::IDS_TEST3 ) << std::endl; - TCOUT << TSS_GetString( cTestResources, test::IDS_INVALID ) << std::endl; - - + TSS_Package(cTestResources).Count(20); + + TEST(TSS_Package(cTestResources).Count() == 20); + TEST(TSS_GetString(cTestResources, test::IDS_TEST1) == _T("Test String 1")); + TEST(TSS_GetString(cTestResources, test::IDS_TEST2) == _T("Test String 2")); + TEST(TSS_GetString(cTestResources, test::IDS_TEST3) == _T("Test String 3")); + TEST(TSS_GetString(cTestResources, test::IDS_INVALID) == _T("")); + TEST(TSS_GetString(cTestResources, 42) == _T("")); } - -// eof: tss.resources_t.cpp - +void RegisterSuite_Resources() +{ + RegisterTest("Resources", "Basic", TestResources); +} diff --git a/src/twtest/serializer_t.cpp b/src/twtest/serializer_t.cpp index abd10d1..3a14184 100644 --- a/src/twtest/serializer_t.cpp +++ b/src/twtest/serializer_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,11 +38,12 @@ #include "core/stdcore.h" #include "core/serializer.h" #include "core/serializable.h" +#include "test.h" -// The reading and writing functionality of the serializer is tested in +// The reading and writing functionality of the serializer is tested in // serializerimpl_t.cpp, so there's very little to be done here. -// Let's make a minimal test object just to make sure the interface is +// Let's make a minimal test object just to make sure the interface is // working properly... and then instantiate it. The actual implementation // will be tested in serializerimpl_t.cpp class cSerTestObject : public iTypedSerializable @@ -53,11 +54,15 @@ class cSerTestObject : public iTypedSerializable cSerTestObject(); // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0) {} - virtual void Write(iSerializer* pSerializer) const {} + virtual void Read(iSerializer* pSerializer, int32 version = 0) + { + } + virtual void Write(iSerializer* pSerializer) const + { + } private: - int mDummy; + int mDummy; }; IMPLEMENT_TYPEDSERIALIZABLE(cSerTestObject, _T("cSerTestObject"), 0, 1) @@ -70,4 +75,12 @@ cSerTestObject::cSerTestObject() void TestSerializer() { cSerTestObject test_obj; + + TEST(std::string(test_obj.GetType().AsString()) == std::string("cSerTestObject")); + TEST(test_obj.Version() == 1); +} + +void RegisterSuite_Serializer() +{ + RegisterTest("Serializer", "Basic", TestSerializer); } diff --git a/src/twtest/serializerimpl_t.cpp b/src/twtest/serializerimpl_t.cpp index b461c6f..f6deb84 100644 --- a/src/twtest/serializerimpl_t.cpp +++ b/src/twtest/serializerimpl_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,10 +47,10 @@ class cSerializerTestObject : public iTypedSerializable cSerializerTestObject(); // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) - bool CheckValid(); + bool CheckValid(); private: int mNumber; @@ -73,7 +73,7 @@ bool cSerializerTestObject::CheckValid() return false; int i; - for (i=0; i<20; i++) + for (i = 0; i < 20; i++) if (mData[i] != 69) return false; @@ -97,7 +97,6 @@ void cSerializerTestObject::Read(iSerializer* pSerializer, int32 version) pSerializer->ReadBlob(mData, 20); pSerializer->ReadString(mString); mNumber = number; - } void cSerializerTestObject::Write(iSerializer* pSerializer) const @@ -119,33 +118,33 @@ void TestSerializerImpl() // writing { cFileArchive file; - file.OpenReadWrite(TEMP_DIR _T("/tmp.bin")); + file.OpenReadWrite(TwTestPath("tmp.bin").c_str()); cSerializerImpl serializer(file, cSerializerImpl::S_WRITE); serializer.Init(); - + cSerializerTestObject testobj; testobj.Write(&serializer); - db.TraceAlways(" Writeing object 1...\n"); + db.TraceAlways(" Writing object 1...\n"); serializer.WriteObject(&testobj); - db.TraceAlways(" Writeing object 2...\n"); + db.TraceAlways(" Writing object 2...\n"); serializer.WriteObject(&testobj); - db.TraceAlways(" Writeing object 3...\n"); + db.TraceAlways(" Writing object 3...\n"); serializer.WriteObject(&testobj); - db.TraceAlways(" Writeing object 4...\n"); + db.TraceAlways(" Writing object 4...\n"); serializer.WriteObject(&testobj); - + serializer.Finit(); } // reading { cFileArchive file; - file.OpenRead(TEMP_DIR _T("/tmp.bin")); + file.OpenRead(TwTestPath("tmp.bin").c_str()); cSerializerImpl serializer(file, cSerializerImpl::S_READ); serializer.Init(); @@ -178,3 +177,7 @@ void TestSerializerImpl() return; } +void RegisterSuite_SerializerImpl() +{ + RegisterTest("SerializerImpl", "Basic", TestSerializerImpl); +} diff --git a/src/twtest/signature_t.cpp b/src/twtest/signature_t.cpp index a02a2ec..f047cbf 100644 --- a/src/twtest/signature_t.cpp +++ b/src/twtest/signature_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -43,67 +43,79 @@ using namespace std; -void TestSignature() +std::string getTestFile() +{ + // Create a file for which we know the signatures + // + //% siggen ~/signature_test.bin + //crc : AAAAAAAAAAy + //md5 : B/Y8ttBnlyw/NPCUu353ao + //crc32 : B1kP9v + //sha : Oia1aljHD793tfj7M55tND+3OG/ + //haval : BL6bFSo0EP5zf8lGSueeed + + static TSTRING sigFileName; + + if (sigFileName.empty()) + { + sigFileName = TwTestPath("signature_test.bin"); + + cFileArchive fileArc; + fileArc.OpenReadWrite(sigFileName.c_str()); + fileArc.WriteBlob("\x1\x2\x3\x4\x5\x6\x7\x8\x9\x0", 10); + fileArc.Close(); + } + + return sigFileName; +} + + +void TestSignatureBasic() { // Signature usage example (?) - cCRC32Signature crcSig; - cDebug d("TestSignature"); + cCRC32Signature crcSig; + cDebug d("TestSignature1"); - byte abData[ 64 ]; - int i; - for( i = 0; i < 64; i++ ) - abData[i] = static_cast< byte >( rand() ); + byte abData[64]; + int i; + for (i = 0; i < 64; i++) + abData[i] = static_cast(rand()); crcSig.Init(); - crcSig.Update( &abData[0], 32 ); - crcSig.Update( &abData[32], 32 ); + crcSig.Update(&abData[0], 32); + crcSig.Update(&abData[32], 32); crcSig.Finit(); - TCOUT << _T("new way: ") << crcSig.AsString() << endl; cMemoryArchive arch; - arch.WriteBlob( &abData[0], 32 ); - arch.WriteBlob( &abData[32], 32 ); - arch.Seek( 0, cBidirArchive::BEGINNING ); + arch.WriteBlob(&abData[0], 32); + arch.WriteBlob(&abData[32], 32); + arch.Seek(0, cBidirArchive::BEGINNING); cCRC32Signature crc; - cArchiveSigGen asg; - asg.AddSig( &crc ); - asg.CalculateSignatures( arch ); - - TCOUT << _T("old way: ") << crc.AsString() << endl; + cArchiveSigGen asg; + asg.AddSig(&crc); + asg.CalculateSignatures(arch); + TEST(crc.AsStringHex() == crcSig.AsStringHex()); +} - // Note: The following causes an ASSERT() in iSignature::Compare(), as it should, but - // we don't want asserts to occur in a working test suite! +// Note: The following causes an ASSERT() in iSignature::Compare(), as it should, but +// we don't want asserts to occur in a working test suite! // TEST(nullSig.Compare(&checksumSig, iFCOProp::OP_EQ) == iFCOProp::CMP_WRONG_PROP_TYPE); - - // Create a file for which we know the signatures - // - //% siggen ~/signature_test.bin - //crc : AAAAAAAAAAy - //md5 : B/Y8ttBnlyw/NPCUu353ao - //crc32 : B1kP9v - //sha : Oia1aljHD793tfj7M55tND+3OG/ - //haval : BL6bFSo0EP5zf8lGSueeed - - TSTRING sigFileName = TEMP_DIR; - sigFileName += TSTRING( _T("/signature_test.bin") ); - +void TestChecksum() +{ + TSTRING sigFileName = getTestFile(); cFileArchive fileArc; - fileArc.OpenReadWrite(sigFileName.c_str()); - fileArc.WriteBlob("\x1\x2\x3\x4\x5\x6\x7\x8\x9\x0", 10); - fileArc.Close(); - - + cDebug d("TestChecksum"); // test begins here // general signature & archive variables - byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; - int cbRead; + int cbRead; + - // test checksum cChecksumSignature check1, check2; d.TraceDetail("Testing checksum.\n"); @@ -113,10 +125,9 @@ void TestSignature() check1.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - check1.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + check1.Update(abBuf, cbRead); + } while (cbRead == cbToRead); check1.Finit(); fileArc.Close(); @@ -125,10 +136,9 @@ void TestSignature() check2.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - check2.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + check2.Update(abBuf, cbRead); + } while (cbRead == cbToRead); check2.Finit(); fileArc.Close(); @@ -138,7 +148,7 @@ void TestSignature() // test write capabilities { - cMemoryArchive sigArchive; + cMemoryArchive sigArchive; cSerializerImpl writeSer(sigArchive, cSerializerImpl::S_WRITE); check1.Write(&writeSer); sigArchive.Seek(0, cBidirArchive::BEGINNING); @@ -146,8 +156,19 @@ void TestSignature() check2.Read(&readSer); TEST(check1.Compare(&check2, iFCOProp::OP_EQ) == iFCOProp::CMP_TRUE); } +} + +void TestCRC32() +{ + TSTRING sigFileName = getTestFile(); + cFileArchive fileArc; + cDebug d("TestCRC32"); + + // general signature & archive variables + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; + const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; + int cbRead; - // test CRC32 cCRC32Signature crc1, crc2; d.TraceDetail("Testing CRC32.\n"); @@ -157,10 +178,9 @@ void TestSignature() crc1.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - crc1.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + crc1.Update(abBuf, cbRead); + } while (cbRead == cbToRead); crc1.Finit(); fileArc.Close(); @@ -169,10 +189,9 @@ void TestSignature() crc2.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - crc2.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + crc2.Update(abBuf, cbRead); + } while (cbRead == cbToRead); crc2.Finit(); fileArc.Close(); @@ -183,7 +202,7 @@ void TestSignature() // test write capabilities { - cMemoryArchive sigArchive; + cMemoryArchive sigArchive; cSerializerImpl writeSer(sigArchive, cSerializerImpl::S_WRITE); crc1.Write(&writeSer); sigArchive.Seek(0, cBidirArchive::BEGINNING); @@ -191,7 +210,18 @@ void TestSignature() crc2.Read(&readSer); TEST(crc1.Compare(&crc2, iFCOProp::OP_EQ) == iFCOProp::CMP_TRUE); } +} + +void TestMD5() +{ + TSTRING sigFileName = getTestFile(); + cFileArchive fileArc; + cDebug d("TestMD5"); + // general signature & archive variables + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; + const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; + int cbRead; // test MD5 cMD5Signature md51, md52; @@ -202,10 +232,9 @@ void TestSignature() md51.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - md51.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + md51.Update(abBuf, cbRead); + } while (cbRead == cbToRead); md51.Finit(); fileArc.Close(); @@ -214,10 +243,9 @@ void TestSignature() md52.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - md52.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + md52.Update(abBuf, cbRead); + } while (cbRead == cbToRead); md52.Finit(); fileArc.Close(); @@ -228,7 +256,7 @@ void TestSignature() // test write capabilities { - cMemoryArchive sigArchive; + cMemoryArchive sigArchive; cSerializerImpl writeSer(sigArchive, cSerializerImpl::S_WRITE); md51.Write(&writeSer); sigArchive.Seek(0, cBidirArchive::BEGINNING); @@ -236,7 +264,18 @@ void TestSignature() md52.Read(&readSer); TEST(md51.Compare(&md52, iFCOProp::OP_EQ) == iFCOProp::CMP_TRUE); } +} + +void TestSHA1() +{ + TSTRING sigFileName = getTestFile(); + cFileArchive fileArc; + cDebug d("TestSHA1"); + // general signature & archive variables + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; + const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; + int cbRead; // test SHA cSHASignature sha1, sha2; @@ -247,10 +286,9 @@ void TestSignature() sha1.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - sha1.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + sha1.Update(abBuf, cbRead); + } while (cbRead == cbToRead); sha1.Finit(); fileArc.Close(); @@ -259,10 +297,9 @@ void TestSignature() sha2.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - sha2.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + sha2.Update(abBuf, cbRead); + } while (cbRead == cbToRead); sha2.Finit(); fileArc.Close(); @@ -273,7 +310,7 @@ void TestSignature() // test write capabilities { - cMemoryArchive sigArchive; + cMemoryArchive sigArchive; cSerializerImpl writeSer(sigArchive, cSerializerImpl::S_WRITE); sha1.Write(&writeSer); sigArchive.Seek(0, cBidirArchive::BEGINNING); @@ -281,8 +318,19 @@ void TestSignature() sha2.Read(&readSer); TEST(sha1.Compare(&sha2, iFCOProp::OP_EQ) == iFCOProp::CMP_TRUE); } +} + +void TestHAVAL() +{ + TSTRING sigFileName = getTestFile(); + cFileArchive fileArc; + cDebug d("TestHAVAL"); + + // general signature & archive variables + byte abBuf[iSignature::SUGGESTED_BLOCK_SIZE]; + const int cbToRead = iSignature::SUGGESTED_BLOCK_SIZE; + int cbRead; - // test HAVAL cHAVALSignature haval1, haval2; d.TraceDetail("Testing HAVAL.\n"); @@ -292,10 +340,9 @@ void TestSignature() haval1.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - haval1.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + haval1.Update(abBuf, cbRead); + } while (cbRead == cbToRead); haval1.Finit(); fileArc.Close(); @@ -304,10 +351,9 @@ void TestSignature() haval2.Init(); do { - cbRead = fileArc.ReadBlob( abBuf, cbToRead ); - haval2.Update( abBuf, cbRead ); - } - while ( cbRead == cbToRead ); + cbRead = fileArc.ReadBlob(abBuf, cbToRead); + haval2.Update(abBuf, cbRead); + } while (cbRead == cbToRead); haval2.Finit(); fileArc.Close(); @@ -318,34 +364,40 @@ void TestSignature() // test write capabilities { - cMemoryArchive sigArchive; + cMemoryArchive sigArchive; cSerializerImpl writeSer(sigArchive, cSerializerImpl::S_WRITE); haval1.Write(&writeSer); sigArchive.Seek(0, cBidirArchive::BEGINNING); cSerializerImpl readSer(sigArchive, cSerializerImpl::S_READ); - md52.Read(&readSer); + haval2.Read(&readSer); TEST(haval1.Compare(&haval2, iFCOProp::OP_EQ) == iFCOProp::CMP_TRUE); } - +} + +void TestArchiveSigGen() +{ + TSTRING sigFileName = getTestFile(); + cFileArchive fileArc; + cDebug d("TestArchiveSigGen"); // test cArchiveSigGen - cArchiveSigGen asgtest; + cArchiveSigGen asgtest; cCRC32Signature crc3; - cMD5Signature md53; - cSHASignature sha3; + cMD5Signature md53; + cSHASignature sha3; cHAVALSignature haval3; d.TraceDetail("Testing cArchiveSigGen\n"); - - asgtest.AddSig( &crc3 ); - asgtest.AddSig( &md53 ); - asgtest.AddSig( &sha3 ); - asgtest.AddSig( &haval3 ); - + + asgtest.AddSig(&crc3); + asgtest.AddSig(&md53); + asgtest.AddSig(&sha3); + asgtest.AddSig(&haval3); + // calculate the signatures fileArc.OpenRead(sigFileName.c_str()); - fileArc.Seek( 0, cBidirArchive::BEGINNING ); - - asgtest.CalculateSignatures( fileArc ); + fileArc.Seek(0, cBidirArchive::BEGINNING); + + asgtest.CalculateSignatures(fileArc); // compare to known values TEST(crc3.AsString().compare(_T("B1kP9v")) == 0); @@ -356,9 +408,87 @@ void TestSignature() TEST(sha3.AsStringHex().compare(_T("e89ad5a9631c3efdded7e3ecce79b4d0fedce1bf")) == 0); TEST(haval3.AsString().compare(_T("BL6bFSo0EP5zf8lGSueeed")) == 0); TEST(haval3.AsStringHex().compare(_T("4be9b152a3410fe737fc9464ae79e79d")) == 0); - - fileArc.Close(); - return; + fileArc.Close(); +} + +void assertMD5(const std::string& source, const std::string& expectedHex) +{ + // Signature usage example (?) + cMD5Signature md5Sig; + + md5Sig.Init(); + md5Sig.Update((const byte*)source.c_str(), source.length()); + md5Sig.Finit(); + + TEST(md5Sig.AsStringHex() == expectedHex); +} + +void assertSHA1(const std::string& source, const std::string& expectedHex) +{ + // Signature usage example (?) + cSHASignature shaSig; + + shaSig.Init(); + shaSig.Update((const byte*)source.c_str(), source.length()); + shaSig.Finit(); + + TEST(shaSig.AsStringHex() == expectedHex); } + +void TestRFC1321() +{ + // All MD5 test cases from RFC 1321, appendix A.5 + // https://www.ietf.org/rfc/rfc1321.txt + + assertMD5("", "d41d8cd98f00b204e9800998ecf8427e"); + assertMD5("a", "0cc175b9c0f1b6a831c399e269772661"); + assertMD5("abc", "900150983cd24fb0d6963f7d28e17f72"); + assertMD5("message digest", "f96b697d7cb7938d525a2f31aaf161d0"); + assertMD5("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"); + assertMD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f"); + assertMD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "57edf4a22be3c955ac49da2e2107b67a"); +} + +void TestRFC3174() +{ + // SHA1 test cases from RFC 3174, section 7.3 + // https://www.ietf.org/rfc/rfc3174.txt + // plus BSD libmd test cases + // https://opensource.apple.com/source/libmd/libmd-3/Makefile + // + // TODO: Compare against NIST test vectors for extra pedanticity + // http://csrc.nist.gov/groups/STM/cavp/secure-hashing.html + + assertSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"); + assertSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); + + assertSHA1("a", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8"); + assertSHA1("0123456701234567012345670123456701234567012345670123456701234567", + "e0c094e867ef46c350ef54a7f59dd60bed92ae83"); + + assertSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + assertSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"); + assertSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3"); + assertSHA1("abcdefghijklmnopqrstuvwxyz", "32d10c7b8cf96570ca04ce37f2a19d84240d3a89"); + assertSHA1("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "761c457bf73b14d27e9e9265c46f4b4dda11f940"); + assertSHA1("12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "50abf5706a150990a08b2c5ea40fa0e585554732"); +} + + +void RegisterSuite_Signature() +{ + RegisterTest("Signature", "Basic", TestSignatureBasic); + RegisterTest("Signature", "Checksum", TestChecksum); + RegisterTest("Signature", "CRC32", TestCRC32); + RegisterTest("Signature", "MD5", TestMD5); + RegisterTest("Signature", "SHA1", TestSHA1); + RegisterTest("Signature", "HAVAL", TestHAVAL); + RegisterTest("Signature", "ArchiveSigGen", TestArchiveSigGen); + RegisterTest("Signature", "RFC1321", TestRFC1321); + RegisterTest("Signature", "RFC3174", TestRFC3174); +} diff --git a/src/twtest/srefcountobj_t.cpp b/src/twtest/srefcountobj_t.cpp index c2f586b..624f293 100644 --- a/src/twtest/srefcountobj_t.cpp +++ b/src/twtest/srefcountobj_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,6 +40,7 @@ #include "core/debug.h" #include "core/archive.h" #include "core/srefcountobj.h" +#include "twtest/test.h" class cSerRefCountObjTest : public iSerRefCountObj { @@ -52,12 +53,11 @@ class cSerRefCountObjTest : public iSerRefCountObj ~cSerRefCountObjTest(); // iSerializable interface - virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) - virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) + virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) + virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) private: int mDummyData; - }; IMPLEMENT_SERREFCOUNT(cSerRefCountObjTest, _T("cSerRefCountObjTest"), 0, 1); @@ -89,16 +89,13 @@ void cSerRefCountObjTest::Write(iSerializer* pSerializer) const } - //////////////////////////////////////////////////////////////////////////////// void TestSerRefCountObj() { - TCERR << "TODO: TestSerRefCountObj ifdef'd due to internal error" << std::endl; -#if 0 // first, we need to register the object with the serializer class... cSerializerImpl::RegisterSerializableRefCt(CLASS_TYPE(cSerRefCountObjTest), cSerRefCountObjTest::Create); - + cSerRefCountObjTest* pObj1 = new cSerRefCountObjTest; cSerRefCountObjTest* pObj2 = new cSerRefCountObjTest; pObj1->AddRef(); @@ -108,7 +105,7 @@ void TestSerRefCountObj() cMemoryArchive memarchive; { - cSerializerImpl serializer(memarchive, cSerializerImpl::S_WRITE); + cSerializerImpl serializer(memarchive, cSerializerImpl::S_WRITE); serializer.Init(); serializer.WriteObjectDynCreate(pObj1); serializer.WriteObjectDynCreate(pObj2); @@ -124,7 +121,7 @@ void TestSerRefCountObj() { memarchive.Seek(0, cBidirArchive::BEGINNING); - cSerializerImpl serializer(memarchive, cSerializerImpl::S_READ); + cSerializerImpl serializer(memarchive, cSerializerImpl::S_READ); serializer.Init(); pObj1 = static_cast(serializer.ReadObjectDynCreate()); pObj2 = static_cast(serializer.ReadObjectDynCreate()); @@ -133,9 +130,9 @@ void TestSerRefCountObj() serializer.Finit(); } - ASSERT(pObj1 == pObj3); - ASSERT(pObj1 == pObj4); - ASSERT(pObj1 != pObj2); + TEST(pObj1 == pObj3); + TEST(pObj1 == pObj4); + TEST(pObj1 != pObj2); pObj1->Release(); pObj2->Release(); @@ -143,6 +140,9 @@ void TestSerRefCountObj() pObj4->Release(); return; -#endif } +void RegisterSuite_SerRefCountObj() +{ + RegisterTest("SerRefCountObj", "Basic", TestSerRefCountObj); +} diff --git a/src/twtest/stdtest.cpp b/src/twtest/stdtest.cpp index 483df60..8559247 100644 --- a/src/twtest/stdtest.cpp +++ b/src/twtest/stdtest.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,5 +36,3 @@ // // #include "stdtest.h" - -// eof: stdtest.cpp diff --git a/src/twtest/stdtest.h b/src/twtest/stdtest.h index 291a3fc..7339e7a 100644 --- a/src/twtest/stdtest.h +++ b/src/twtest/stdtest.h @@ -1,33 +1,32 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // #include "core/stdcore.h" - diff --git a/src/twtest/stringencoder_t.cpp b/src/twtest/stringencoder_t.cpp index 2f0852c..b289751 100644 --- a/src/twtest/stringencoder_t.cpp +++ b/src/twtest/stringencoder_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,6 +39,7 @@ #include "util/stdutil.h" #include "util/stringencoder.h" +#include "twtest/test.h" //========================================================================= // STANDARD LIBRARY INCLUDES @@ -56,7 +57,7 @@ using namespace std; // UTIL FUNCTION PROTOTYES //========================================================================= -void OutputString( TSTRING& str ); +void OutputString(TSTRING& str); //========================================================================= // FUNCTION CODE @@ -64,29 +65,35 @@ void OutputString( TSTRING& str ); void TestStringEncoder() { - TSTRING str = _T("this is a non-quoted string"); - TSTRING strQ = _T("here's a quote:\"and a slash:\\ "); - TSTRING strJQ = _T("\""); - TSTRING strJS = _T("\\"); + TSTRING str = _T("this is a non-quoted string"); + TSTRING strQ = _T("here's a quote:\"and a slash:\\ "); + TSTRING strJQ = _T("\""); + TSTRING strJS = _T("\\"); TSTRING strWeird = _T("\\\"\"\\\"\\\\\"\"\"\""); - OutputString( str ); - OutputString( strQ ); - OutputString( strJQ ); - OutputString( strJS ); - OutputString( strWeird ); + OutputString(str); + OutputString(strQ); + OutputString(strJQ); + OutputString(strJS); + OutputString(strWeird); } //========================================================================= // UTIL FUNCTION CODE //========================================================================= -void OutputString( TSTRING& str ) +void OutputString(TSTRING& str) { cQuoteEncoder qe; - TCOUT << _T("Plain string: <") << str << _T(">") << endl; + /* TCOUT << _T("Plain string: <") << str << _T(">") << endl; TCOUT << _T("Encoded string: <") << qe.Encode( str ) << _T(">") << endl; - TCOUT << _T("Decoded string: <") << qe.Unencode( str ) << _T(">") << endl << endl ; + TCOUT << _T("Decoded string: <") << qe.Unencode( str ) << _T(">") << endl << endl ; */ + + TEST(str == qe.Unencode(qe.Encode(str))); } +void RegisterSuite_StringEncoder() +{ + RegisterTest("StringEncoder", "Basic", TestStringEncoder); +} diff --git a/src/core/stringutil_t.h b/src/twtest/stringutil_t.h similarity index 59% rename from src/core/stringutil_t.h rename to src/twtest/stringutil_t.h index 64aefca..1751978 100644 --- a/src/core/stringutil_t.h +++ b/src/twtest/stringutil_t.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,77 +39,70 @@ */ #ifndef __STRINGUTIL_T_H -#define __STRINGUTIL_T_H - -#include "ntmbs.h" +# define __STRINGUTIL_T_H -#if USING_NTDBS_STUFF -#include "ntdbs.h" -#endif // USING_NTDBS_STUFF +#include "core/ntmbs.h" +#include "core/ntdbs.h" //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Char traits for WCHAR16 (aka dbchar_t) and NTMBCS (mctype_t) //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -inline -void TestStringUtil() +inline void TestStringUtil() { -#if USING_NTDBS_STUFF cDebug db("Test std::char_traits"); db.TraceAlways("Entering...\n"); tss::dbstring a; tss::dbstring b; - std::string c; // Control String + std::string c; // Control String -//#if !IS_UNIX // need to get the L"" stuff working + static char NTMBS1[] = {65, 66, 67, 68, 0}; + static dbchar_t NTDBS1[] = {65, 66, 67, 68, 0}; + static dbchar_t NTDBS2[] = {40, 66, 67, 68, 0}; + // static dbchar_t NTDBS0[] = { 65, 66, 67, 68, 0, 0 }; - static char NTMBS1[] = { 65, 66, 67, 68, 0 }; - static dbchar_t NTDBS1[] = { 65, 66, 67, 68, 0 }; - static dbchar_t NTDBS2[] = { 40, 66, 67, 68, 0 }; - static dbchar_t NTDBS0[] = { 65, 66, 67, 68, 0, 0 }; + c.assign(NTMBS1); + a.assign(NTDBS1); - c.assign( NTMBS1 ); - a.assign( NTDBS1 ); + TEST(c == NTMBS1); + TEST(a == NTDBS1); - TEST( c == NTMBS1 ); - TEST( a == NTDBS1 ); + a.resize(0); + b.resize(0); - a.resize( 0 ); - b.resize( 0 ); + TEST(a.empty()); + TEST(b.empty()); - TEST( a.empty() ); - TEST( b.empty() ); + a.assign(NTDBS1); + TEST(a.size() == 4); + TEST(std::equal(a.begin(), a.end(), NTDBS1)); + TEST(b.size() == 0); - a.assign( NTDBS1 ); - TEST( a.size() == 4); - TEST( std::equal( a.begin(), a.end(), NTDBS1 ) ); - TEST( b.size() == 0) ; - - a.resize( 3 ); - TEST( a.c_str() != b.c_str() ); - TEST( std::equal( a.begin(), a.end(), NTDBS1 ) ); - TEST( std::equal( b.begin(), b.end(), NTDBS1 ) ); + a.resize(3); + TEST(a.c_str() != b.c_str()); + TEST(std::equal(a.begin(), a.end(), NTDBS1)); + TEST(std::equal(b.begin(), b.end(), NTDBS1)); a = NTDBS2; b = a; - TEST( a == b ); - TEST( a.size() == b.size() ); - - TEST( a[0] == b[0] ); - TEST( a[1] == b[1] ); - TEST( a[2] == b[2] ); - TEST( a[3] == b[3] ); + TEST(a == b); + TEST(a.size() == b.size()); + + TEST(a[0] == b[0]); + TEST(a[1] == b[1]); + TEST(a[2] == b[2]); + TEST(a[3] == b[3]); const tss::dbstring a1 = a; const tss::dbstring b1 = b; - TEST( a1[0] == b1[0] ); - TEST( a1[1] == b1[1] ); - TEST( a1[2] == b1[2] ); - TEST( a1[3] == b1[3] ); + TEST(a1[0] == b1[0]); + TEST(a1[1] == b1[1]); + TEST(a1[2] == b1[2]); + TEST(a1[3] == b1[3]); -#if 0 +# if 0 try { TEST( a[4] > 0 ); @@ -119,17 +112,16 @@ void TestStringUtil() { ; } -#endif +# endif //--Test Reference Counting - tss::dbstring x( NTDBS1 ); + tss::dbstring x(NTDBS1); tss::dbstring ref = x; - TEST( x.c_str() == ref.c_str() ); - TEST( x == ref ); - TEST( std::equal( x.begin(), x.end(), ref.begin() ) ); - TEST( x.size() == ref.size() ); + TEST(x == ref); + TEST(std::equal(x.begin(), x.end(), ref.begin())); + TEST(x.size() == ref.size()); /////////////////////////// @@ -146,29 +138,37 @@ void TestStringUtil() //wc16_string TstrToWstr( const TSTRING& tstr ); // test Null assignments - singleStr = cStringUtil::TstrToStr( tStrNull ); + singleStr = cStringUtil::TstrToStr(tStrNull); TEST(singleStr.length() == 0); - tStr = cStringUtil::StrToTstr( singleStrNull ); + tStr = cStringUtil::StrToTstr(singleStrNull); TEST(tStr.length() == 0); - tStr = cStringUtil::WstrToTstr( wc16StrNull ); + tStr = cStringUtil::WstrToTstr(wc16StrNull); TEST(tStr.length() == 0); - wc16StrNull = cStringUtil::TstrToWstr( tStrNull ); + wc16StrNull = cStringUtil::TstrToWstr(tStrNull); TEST(wc16StrNull.length() == 0); // test copying some text around singleStr = "123456789"; - tStr.erase(); tStr = cStringUtil::StrToTstr( singleStr ); + tStr.erase(); + tStr = cStringUtil::StrToTstr(singleStr); TEST(tStr.length() == 9); - wc16Str.resize(0); wc16Str = cStringUtil::TstrToWstr( tStr ); + wc16Str.resize(0); + wc16Str = cStringUtil::TstrToWstr(tStr); TEST(wc16Str.length() == 9); - singleStr.erase(); singleStr = cStringUtil::TstrToStr( tStr ); + singleStr.erase(); + singleStr = cStringUtil::TstrToStr(tStr); TEST(singleStr.length() == 9); - tStr.erase(); tStr = cStringUtil::WstrToTstr( wc16Str ); + tStr.erase(); + tStr = cStringUtil::WstrToTstr(wc16Str); TEST(tStr.length() == 9); db.TraceAlways("Done...\n"); -#endif // USING_NTDBS_STUFF } -#endif//__STRINGUTIL_T_H +#endif //__STRINGUTIL_T_H + +void RegisterSuite_StringUtil() +{ + RegisterTest("StringUtil", "Basic", TestStringUtil); +} diff --git a/src/twtest/tasktimer_t.cpp b/src/twtest/tasktimer_t.cpp index 617e54f..1cac9d3 100644 --- a/src/twtest/tasktimer_t.cpp +++ b/src/twtest/tasktimer_t.cpp @@ -1,40 +1,63 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // // tasktimer_t -- test driver for cTaskTimer #include "core/stdcore.h" +#include "test.h" +#include "core/tasktimer.h" +#include -#if IS_UNIX void TestTaskTimer() { + cTaskTimer timer("unit testing"); + + TEST(!timer.IsRunning()); + TEST(0 == timer.GetTotalTime()); + TEST(0 == timer.GetNumTimesStarted()); + + for (int counter = 0; counter < 5; counter++) + { + timer.Start(); + TEST(timer.IsRunning()); + sleep(1); + timer.Stop(); + TEST(!timer.IsRunning()); + } + + TEST(!timer.IsRunning()); + TEST(5 <= timer.GetTotalTime()); + TEST(5 == timer.GetNumTimesStarted()); } -#endif // IS_UNIX/WIN32 +void RegisterSuite_TaskTimer() +{ + RegisterTest("TaskTimer", "Basic", TestTaskTimer); +} diff --git a/src/twtest/tchar_t.cpp b/src/twtest/tchar_t.cpp index 9d1e0a5..bfffa4a 100644 --- a/src/twtest/tchar_t.cpp +++ b/src/twtest/tchar_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,78 +39,83 @@ #include "core/debug.h" #endif +#include "test.h" + TSTRING test_wost(int, const TSTRING&); -void test_wist(const TSTRING&, cDebug& d); +void test_wist(const TSTRING&, cDebug& d); void TestTCHAR() { + TCERR + << "TODO: Right now this test mostly verifies that STL string & file classes work, which is not overly useful." + << std::endl; + cDebug d("TestTCHAR()"); d.TraceDetail("Entering...\n"); //Testing TCOUT: - TCOUT<< _T("Simple test of TSTRING (and TCOUT) :\n\n"); - TCERR<< _T("This should show up on cerr"); + TCOUT << _T("Simple test of TSTRING (and TCOUT) :\n\n"); + TCERR << _T("This should show up on cerr") << std::endl; TSTRING pString; pString = _T("Hi Mom!"); - d.TraceDetail("%s \n", pString.c_str() ); + d.TraceDetail("%s \n", pString.c_str()); d.TraceDetail("Isn't this cool?\n\n"); - + //Begin fun tests of string streams: TSTRINGSTREAM wst; - //can I declare it? + //can I declare it? TSTRING str; - str = _T("Kiteman"); + str = _T("Kiteman"); TSTRING test1 = _T("word"); d.TraceDetail("Testing TOSTRINGSTREAM with TSTRING:\n"); TOSTRINGSTREAM ost(_T("test up")); - ost<>parse) - d.TraceDetail("%s \n", parse.c_str() ); + TSTRING parse; + while (wist >> parse) + d.TraceDetail("%s \n", parse.c_str()); } +void RegisterSuite_TCHAR() +{ + RegisterTest("TCHAR", "Basic", TestTCHAR); +} diff --git a/src/twtest/test.cpp b/src/twtest/test.cpp index 07023ce..7bfb9b7 100644 --- a/src/twtest/test.cpp +++ b/src/twtest/test.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,15 +39,9 @@ #include "core/core.h" #include "db/db.h" #include "twcrypto/twcrypto.h" - -#ifdef PARSER_PRESENT -#include "parser/parser.h" -#endif - +#include "twparser/twparser.h" #include "tw/tw.h" #include "fco/fco.h" - - #include "fs/fs.h" #include "util/util.h" @@ -55,6 +49,7 @@ #include "core/debug.h" #include "core/error.h" #include "core/twlocale.h" +#include "core/fsservices.h" #include "test.h" #include "core/errorbucketimpl.h" #include "tw/twinit.h" @@ -65,200 +60,365 @@ #include "db/blockfile.h" #include "db/blockrecordarray.h" #include "db/hierdatabase.h" +#include "config.h" +#include +#include + +// Known test suites +void RegisterSuite_Archive(); +void RegisterSuite_BlockFile(); +void RegisterSuite_BlockRecordArray(); +void RegisterSuite_CharUtil(); +void RegisterSuite_CmdLineParser(); +void RegisterSuite_CodeConvert(); +void RegisterSuite_ConfigFile(); +void RegisterSuite_CryptoArchive(); +void RegisterSuite_Crypto(); +void RegisterSuite_DbDataSource(); +void RegisterSuite_Debug(); +void RegisterSuite_DisplayEncoder(); +void RegisterSuite_Error(); +void RegisterSuite_ErrorBucketImpl(); +void RegisterSuite_FCOCompare(); +void RegisterSuite_FCODatabaseFile(); +void RegisterSuite_FCOName(); +void RegisterSuite_FCONameTbl(); +void RegisterSuite_FCONameTranslator(); +void RegisterSuite_FCOPropImpl(); +void RegisterSuite_FCOPropVector(); +void RegisterSuite_FCOReport(); +void RegisterSuite_FCOSetImpl(); +void RegisterSuite_FCOSpec(); +void RegisterSuite_FCOSpecAttr(); +void RegisterSuite_FCOSpecHelper(); +void RegisterSuite_FCOSpecList(); +void RegisterSuite_FcoSpecUtil(); +void RegisterSuite_File(); +void RegisterSuite_FileHeader(); +void RegisterSuite_FileUtil(); +void RegisterSuite_FSDataSourceIter(); +void RegisterSuite_FSObject(); +void RegisterSuite_FSPropCalc(); +void RegisterSuite_FSPropDisplayer(); +void RegisterSuite_FSPropSet(); +void RegisterSuite_FCOSpecImpl(); +void RegisterSuite_GenreSwitcher(); +void RegisterSuite_GenreSpecList(); +void RegisterSuite_Error(); +void RegisterSuite_GrowHeap(); +void RegisterSuite_HashTable(); +void RegisterSuite_HierDatabase(); +void RegisterSuite_KeyFile(); +void RegisterSuite_Platform(); +void RegisterSuite_PolicyParser(); +void RegisterSuite_RefCountObj(); +void RegisterSuite_Resources(); +void RegisterSuite_Serializer(); +void RegisterSuite_SerializerImpl(); +void RegisterSuite_Signature(); +void RegisterSuite_SerRefCountObj(); +void RegisterSuite_StringEncoder(); +void RegisterSuite_StringUtil(); +void RegisterSuite_TaskTimer(); +void RegisterSuite_TCHAR(); +void RegisterSuite_TextReportViewer(); +void RegisterSuite_TWLocale(); +void RegisterSuite_TWUtil(); +void RegisterSuite_Types(); +void RegisterSuite_UnixFSServices(); +void RegisterSuite_UserNotifyStdout(); +void RegisterSuite_Wchar16(); -// the test routines -void TestFCOName(); -void TestFCOTest(); -void TestFCOSetImpl(); -void TestFCOSpec(); -void TestFCOPropVector(); -void TestFileHeader(); -void TestFSPropSet(); -void TestFSDataSource(); -void TestFCOSpecImpl(); -void TestFSPropCalc(); -void TestFCOPropImpl(); -void TestFCOCompare(); -//void TestTripwire(); -void TestFCOSetUtil(); -void TestWin32FSServices(); -void TestFCOSpecList(); -void TestFCOReport(); -void TestArchive(); -void TestSerializer(); -void TestSerializerImpl(); -void TestRefCountObj(); -void TestSignature(); -void TestSerRefCountObj(); -#if IS_UNIX -void TestUnixFSServices(); -#endif -//void TestFCODatabase(); -void TestError(); -void TestDebug(); -void TestFcoSpecUtil(); -void TestTypes(); -void TestTCHAR(); -void TestErrorBucketImpl(); -void TestHashTable(); -//void TestTextReportViewer(); -void TestFCONameTbl(); -void TestConfigFile(); - -#ifdef PARSER_PRESENT -void TestPolicyParser(); -#endif//PARSER_PRESENT - -void TestFCOSpecHelper(); -void TestCrypto(); -void TestCryptoArchive(); -void TestFCOSpecAttr(); -void TestCmdLineParser(); -void TestTaskTimer(); -void TestObjectPool(); -void TestKeyFile(); -void TestFCOSetCached(); -void TestTWUtil(); -void TestFSPropDisplayer(); -void TestFSPropDisplayer(); -void TestGenre(); -void TestFSDataSourceIter(); -void TestGenerateDb(); -//void TestHierDatabaseInteractive(); -void TestGenreSwitcher(); -void TestDbDataSource(); -void TestGenreSpecList(); -void TestIntegrityCheck(); -void TestFCODatabaseFile(); -void TestWchar16(); -void TestStringEncoder(); -#ifdef TSS_TEST -void TestDisplayEncoder(); -#endif -void TestGrowHeap(); -void TestPlatform(); -//void TestBlockFile(); -//void TestBlockRecordArray(); -//void TestHierDatabaseInteractive(); -void TestTWLocale(); -void TestFileUtil(); -void TestFCONameTranslator(); -void TestCodeConverter(); /// This is easier than all the (cpp) files and declarations -#include "core/stringutil_t.h" +#include "stringutil_t.h" + +#if IS_AROS +# define VERSION_PREFIX "$VER: " +#else +# define VERSION_PREFIX "@(#)" +#endif + +const char* STR_EMBEDDED_VERSION = _T(VERSION_PREFIX "twtest " PACKAGE_VERSION); + void Usage() { - TCERR << _T("Usage: test {all | testid [testid ...]}\n") + TCERR << _T("Usage: twtest {all | list | help | version | testid [testid ...]}\n") _T("\n") - _T("Ex: test 1 2 3 12\n") - _T("(runs test id's 1, 2, 3, and 12)\n\n"); + _T("Ex: twtest foo bar/baz\n") + _T("(runs suite foo and test bar/baz)\n\n"); +} + +void Version() +{ + TCOUT << "twtest " << PACKAGE_VERSION << std::endl; } -const int MAX_TEST_ID = 100; +static int ran_count = 0; +static int failed_count = 0; +static int skipped_count = 0; +static int macro_count = 0; -static void Test(int testID) +static std::vector error_strings; +static std::vector skipped_strings; + +class skip_exception : public std::runtime_error { - switch (testID) +public: + skip_exception(const std::string& reason) : std::runtime_error(reason) { - case 1: TestArchive(); break; - case 2: TestCmdLineParser(); break; - case 3: TestCrypto(); break; - case 4: TestCryptoArchive(); break; - case 5: TestDebug(); break; - case 6: TestError(); break; - case 7: TestErrorBucketImpl(); break; - //case 8: TestFCOCompare(); break; - //case 9: TestFCODatabase(); break; - //case 11: TestFCOErrorQueue(); break; - case 12: TestFCOName(); break; - case 13: TestFCONameTbl(); break; - case 14: TestFCOPropVector(); break; - case 15: TestFCOPropImpl(); break; - case 16: TestFCOReport(); break; - //case 17: TestFCOSetCached(); break; - case 18: TestFCOSetImpl(); break; - //case 19: TestFCOSetUtil(); break; - case 20: TestFCOSpecAttr(); break; - case 21: TestFCOSpecHelper(); break; - case 22: TestFCOSpecList(); break; - case 23: TestFcoSpecUtil(); break; - case 24: TestFileHeader(); break; - //case 25: TestFSDataSource(); break; - case 26: TestFSPropSet(); break; - //case 27: TestFSPropCalc(); break; - case 28: TestFCOSpecImpl(); break; - case 29: TestHashTable(); break; - case 30: TestObjectPool(); break; - case 31: TestRefCountObj(); break; - case 32: TestSerializerImpl(); break; - case 33: TestSerRefCountObj(); break; - case 34: TestSignature(); break; - case 35: TestTaskTimer(); break; - //case 36: TestTripwire(); break; - //case 37: TestTextReportViewer(); break; - case 39: TestSerRefCountObj(); break; - case 40: TestError(); break; - //case 41: TestFCODatabase(); break; - case 42: TestHashTable(); break; - case 43: TestTCHAR(); break; - #if IS_UNIX - case 44: TestUnixFSServices(); break; - #endif - case 46: TestConfigFile(); break; -#ifdef PARSER_PRESENT - case 47: TestPolicyParser(); break; -#endif//PARSER_PRESENT - case 48: TestKeyFile(); break; - case 49: TestTWUtil(); break; - case 50: TestFSPropDisplayer(); break; - case 52: TestGenre(); break; - case 53: TestFSDataSourceIter(); break; - //case 54: TestGenerateDb(); break; - //case 55: TestHierDatabaseInteractive(); break; - case 56: TestGenreSwitcher(); break; - case 57: TestDbDataSource(); break; - case 58: TestGenreSpecList(); break; - //case 59: TestIntegrityCheck(); break; - case 65: TestWchar16(); break; - case 66: TestStringEncoder(); break; -#ifdef TSS_TEST - case 67: TestDisplayEncoder(); break; -#endif - case 69: TestGrowHeap(); break; - case 70: TestPlatform(); break; - //case 71: TestBlockFile(); break; - //case 72: TestBlockRecordArray(); break; - //case 73: TestHierDatabaseInteractive(); break; - case 74: TestFileUtil(); break; - case 75: TestTWLocale(); break; - case 76: TestFCONameTranslator(); break; - case 77: TestStringUtil(); break; - case 78: TestCodeConverter(); break; + } +}; + +void skip(const std::string& reason) +{ + throw skip_exception(reason); +} + +void fail(const std::string& reason) +{ + throw std::runtime_error(reason); +} + +void CountMacro() +{ + macro_count++; +} + +///////////////////////// + +static TestMap tests; + +void RegisterTest(const std::string& suite, const std::string testName, TestPtr testPtr) +{ + tests[suite][testName] = testPtr; +} + + +static void RunTest(const std::string& suiteName, const std::string& testName, TestPtr testPtr) +{ + try + { + if (testPtr) + { + ran_count++; + int pre_count = macro_count; + testPtr(); + if (macro_count > pre_count) + TCERR << "PASSED" << std::endl; + else + skip("Test did not make any TEST assertions"); + } + return; + } + catch (skip_exception& e) + { + TCERR << "SKIPPED: " << e.what() << std::endl; + + std::stringstream sstr; + sstr << "Test " << suiteName << "/" << testName << ": " << e.what(); + skipped_strings.push_back(sstr.str()); + + skipped_count++; + } + catch (eError& error) + { + TCERR << "FAILED: "; + cTWUtil::PrintErrorMsg(error); + + std::stringstream sstr; + sstr << "Test " << suiteName << "/" << testName << ": " << error.GetMsg(); + error_strings.push_back(sstr.str()); + + failed_count++; + } + catch (std::exception& e) + { + TCERR << "FAILED: " << e.what() << std::endl; + + std::stringstream sstr; + sstr << "Test " << suiteName << "/" << testName << ": " << e.what(); + error_strings.push_back(sstr.str()); + + failed_count++; + } + catch (...) + { + TCERR << "FAILED: " << std::endl; + + std::stringstream sstr; + sstr << "Test " << suiteName << "/" << testName << ": "; + error_strings.push_back(sstr.str()); } } + +static void RunTestSuite(const std::string& suiteName, SuiteMap suite) +{ + SuiteMap::const_iterator itr; + for (itr = suite.begin(); itr != suite.end(); ++itr) + { + TCERR << "----- Running test: " << suiteName << "/" << itr->first << " -----" << std::endl << std::endl; + RunTest(suiteName, itr->first, itr->second); + TCERR << std::endl << "----- Finished test: " << suiteName << "/" << itr->first << " -----" << std::endl; + } +} + +static void RunAllTests() +{ + TestMap::const_iterator itr; + for (itr = tests.begin(); itr != tests.end(); ++itr) + { + TCERR << std::endl << "===== Starting test suite: " << itr->first << " =====" << std::endl; + RunTestSuite(itr->first, itr->second); + TCERR << "===== Finished test suite: " << itr->first << " =====" << std::endl; + } +} + +static void ListTests() +{ + TestMap::const_iterator itr; + for (itr = tests.begin(); itr != tests.end(); ++itr) + { + std::string suiteName = itr->first; + SuiteMap suite = itr->second; + + TCERR << suiteName << std::endl; + SuiteMap::const_iterator itr; + for (itr = suite.begin(); itr != suite.end(); ++itr) + { + TCERR << " " << suiteName << "/" << itr->first << std::endl; + } + } +} + +static void RunTest(const std::string& to_run) +{ + std::string::size_type pos = to_run.find_first_of("/"); + if (pos == std::string::npos) + { + RunTestSuite(to_run, tests[to_run]); + } + else + { + std::string suite = to_run.substr(0, pos); + std::string testName = to_run.substr(pos + 1); + RunTest(suite, testName, tests[suite][testName]); + } +} + +static void RegisterSuites() +{ + RegisterSuite_Archive(); + RegisterSuite_BlockFile(); + RegisterSuite_BlockRecordArray(); + RegisterSuite_CharUtil(); + RegisterSuite_CmdLineParser(); + RegisterSuite_CodeConvert(); + RegisterSuite_ConfigFile(); + RegisterSuite_CryptoArchive(); + RegisterSuite_Crypto(); + RegisterSuite_DbDataSource(); + RegisterSuite_Debug(); + RegisterSuite_DisplayEncoder(); + RegisterSuite_Error(); + RegisterSuite_ErrorBucketImpl(); + RegisterSuite_FCOCompare(); + RegisterSuite_FCODatabaseFile(); + RegisterSuite_FCOName(); + RegisterSuite_FCONameTbl(); + RegisterSuite_FCONameTranslator(); + RegisterSuite_FCOPropImpl(); + RegisterSuite_FCOPropVector(); + RegisterSuite_FCOReport(); + RegisterSuite_FCOSetImpl(); + RegisterSuite_FCOSpec(); + RegisterSuite_FCOSpecAttr(); + RegisterSuite_FCOSpecHelper(); + RegisterSuite_FCOSpecList(); + RegisterSuite_FcoSpecUtil(); + RegisterSuite_File(); + RegisterSuite_FileHeader(); + RegisterSuite_FileUtil(); + RegisterSuite_FSDataSourceIter(); + RegisterSuite_FSObject(); + RegisterSuite_FSPropCalc(); + RegisterSuite_FSPropDisplayer(); + RegisterSuite_FSPropSet(); + RegisterSuite_FCOSpecImpl(); + RegisterSuite_GenreSwitcher(); + RegisterSuite_GenreSpecList(); + RegisterSuite_Error(); + RegisterSuite_GrowHeap(); + RegisterSuite_HashTable(); + RegisterSuite_HierDatabase(); + RegisterSuite_KeyFile(); + RegisterSuite_Platform(); + RegisterSuite_PolicyParser(); + RegisterSuite_RefCountObj(); + RegisterSuite_Resources(); + RegisterSuite_Serializer(); + RegisterSuite_SerializerImpl(); + RegisterSuite_Signature(); + RegisterSuite_SerRefCountObj(); + RegisterSuite_StringEncoder(); + RegisterSuite_StringUtil(); + RegisterSuite_TaskTimer(); + RegisterSuite_TCHAR(); + RegisterSuite_TextReportViewer(); + RegisterSuite_TWLocale(); + RegisterSuite_TWUtil(); + RegisterSuite_Types(); + RegisterSuite_UnixFSServices(); + RegisterSuite_UserNotifyStdout(); + RegisterSuite_Wchar16(); +} + + +std::string TwTestDir() +{ + static std::string dir; + + if (dir.empty()) + { + iFSServices::GetInstance()->GetCurrentDir(dir); + dir.append("/TWTestData"); + TCERR << "Using test directory: " << dir << std::endl; + mkdir(dir.c_str(), 0777); + } + + return dir; +} + +std::string TwTestPath(const std::string& child) +{ + std::stringstream sstr; + sstr << TwTestDir(); + if (child[0] != '/') + sstr << '/'; + sstr << child; + return sstr.str(); +} + /////////////////////////////////////////////////////////////////////////////// // cTest /////////////////////////////////////////////////////////////////////////////// -TSS_ImplementPackage( cTest ) +TSS_ImplementPackage(cTest) -cTest::cTest() + cTest::cTest() { - TSS_Dependency( cCore ); - TSS_Dependency( cDb ); - TSS_Dependency( cTWCrypto ); -#ifdef PARSER_PRESENT - TSS_Dependency( cParser ); -#endif//PARSER_PRESENT - TSS_Dependency( cTW ); - TSS_Dependency( cFCO ); - TSS_Dependency( cFS ); - TSS_Dependency( cUtil ); - -// no erros excluivly for test package -// TSS_REGISTER_PKG_ERRORS( test ) + TSS_Dependency(cCore); + TSS_Dependency(cDb); + TSS_Dependency(cTWCrypto); + TSS_Dependency(cTWParser); + TSS_Dependency(cTW); + TSS_Dependency(cFCO); + TSS_Dependency(cFS); + TSS_Dependency(cUtil); + + // no erros excluivly for test package + // TSS_REGISTER_PKG_ERRORS( test ) } /////////////////////////////////////////////////////////////////////////////// @@ -279,58 +439,118 @@ void tw_unexpected_handler() int _tmain(int argc, TCHAR** argv) { +#ifdef _DEBUG std::cout << "Test: Init" << std::endl; + std::cout << "Test: Setup" << std::endl; + std::cout << "Test: argc - " << argc << std::endl; + std::cout << "Test: *argv - " << argv[0] << std::endl; +#endif - try + try { - std::cout << "Test: Setup" << std::endl; - std::cout << "Test: argc - " << argc << std::endl; - std::cout << "Test: *argv - " << argv[0] << std::endl; - EXCEPTION_NAMESPACE set_terminate(tw_terminate_handler); EXCEPTION_NAMESPACE set_unexpected(tw_unexpected_handler); + if (argc < 2) + { + Usage(); + return 0; + } + cTWInit twInit; - twInit.Init( argv[0] ); + twInit.Init(argv[0]); // set up the debug output cDebug::AddOutTarget(cDebug::OUT_STDOUT); //cDebug::SetDebugLevel(cDebug::D_NEVER); cDebug::SetDebugLevel(cDebug::D_DETAIL); //cDebug::SetDebugLevel(cDebug::D_DEBUG); - - int i; - if (argc < 2) + RegisterSuites(); + std::string arg1 = argv[1]; + + + if (arg1 == "all" || arg1 == "--all") + { + RunAllTests(); + } + else if (arg1 == "list" || arg1 == "--list") + { + ListTests(); + return 0; + } + else if (arg1 == "help" || arg1 == "--help" || arg1 == "-?") + { Usage(); - else if (_tcsicmp(argv[1], _T("all")) == 0) - // run all the tests - for (i = 1; i <= MAX_TEST_ID; ++i) - Test(i); + return 0; + } + else if (arg1 == "version" || arg1 == "--version") + { + Version(); + return 0; + } else - for (i = 1; i < argc; ++i) - Test(_ttoi(argv[i])); // Note: if atoi returns 0, Test() will handle it fine. - - } + { + for (int i = 1; i < argc; ++i) + RunTest(argv[i]); + } + } catch (eError& error) - { + { cTWUtil::PrintErrorMsg(error); ASSERT(false); + return 1; + } + catch (std::exception& error) + { + TCERR << "Caught std::exception: " << error.what() << std::endl; + ASSERT(false); + return 1; } catch (...) - { + { TCERR << _T("Unhandled exception caught!"); ASSERT(false); + return 1; } - // make sure all the refrence counted objects have been destroyed + // make sure all the reference counted objects have been destroyed // this test always fails because of the static cFCONameTbl //TEST(cRefCountObj::AllRefCountObjDestoryed() == true); - // force user to hit - - return 1; -} + if (!ran_count) + { + std::cout << "Ran 0 unit tests. The specified group/test names may be incorrect (names are case sensitive).\n"; + return 1; + } + std::cout << std::endl + << "Ran " << ran_count << " unit tests with " << failed_count << " failures, " << skipped_count + << " skipped." << std::endl; + std::cout << "(total test assertions: " << macro_count << ")" << std::endl; + if (failed_count) + { + std::cout << std::endl << "Failures: " << std::endl; + std::vector::iterator itr; + for (itr = error_strings.begin(); itr != error_strings.end(); ++itr) + { + std::cout << "\t" << *itr << std::endl; + } + } + + if (skipped_count) + { + std::cout << std::endl << "Skipped: " << std::endl; + std::vector::iterator itr; + for (itr = skipped_strings.begin(); itr != skipped_strings.end(); ++itr) + { + std::cout << "\t" << *itr << std::endl; + } + } + std::cout << std::endl; + + + return failed_count ? -1 : 0; +} diff --git a/src/twtest/test.h b/src/twtest/test.h index 83c36bd..0c43423 100644 --- a/src/twtest/test.h +++ b/src/twtest/test.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,43 +48,49 @@ #include "core/debug.h" #endif -#if IS_UNIX #include +#include + using namespace std; -#endif -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Dependencies -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #include "core/package.h" -TSS_BeginPackage( cTest ) +TSS_BeginPackage(cTest) + + public : cTest(); -public: - cTest(); +TSS_EndPackage(cTest) -TSS_EndPackage( cTest ) + void CountMacro(); /////////////////////////////////////////////////////////////////////////////// -// TEST() -- Works like ASSERT() but it also breaks during release mode +// TEST() -- throw a std::runtime error if test condition is false. +// +#define TEST(exp) \ + CountMacro(); \ + if (!(exp)) \ + { \ + std::cerr << "TEST(" << #exp << ") failure, file " << __FILE__ << " line " << __LINE__ << std::endl; \ + throw std::runtime_error(#exp); \ + } -#if IS_UNIX +/////////////////////////////////////////////////////////////////////////////// -#define TEST(exp) if (!(exp)) \ - { \ - std::cerr<<"TEST(" << #exp << ") failure, file " << __FILE__ << " line " << __LINE__ << std::endl; \ - exit(-1); \ - } -#endif +std::string TwTestDir(); +std::string TwTestPath(const std::string& child); -/////////////////////////////////////////////////////////////////////////////// -// Platform dependancies +typedef void (*TestPtr)(); +typedef std::map SuiteMap; +typedef std::map TestMap; -#if IS_UNIX -#define TEMP_DIR _T("/tmp") -#define TEMP_DIR_N "/tmp" -#endif +void RegisterTest(const std::string& suite, const std::string testName, TestPtr testPtr); -#endif // __TEST_H +void skip(const std::string& reason); +void fail(const std::string& reason); + +#endif // __TEST_H diff --git a/src/twtest/textreportviewer_t.cpp b/src/twtest/textreportviewer_t.cpp index dfa13da..8642dac 100644 --- a/src/twtest/textreportviewer_t.cpp +++ b/src/twtest/textreportviewer_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,6 +36,7 @@ #include "tw/stdtw.h" #include #include +#include #include "tw/fcoreport.h" #include "fco/fcospecimpl.h" @@ -56,10 +57,10 @@ #include "tw/fcoreportutil.h" #include "tw/headerinfo.h" -#ifdef FIXED_TRV_TEST_SUITE +//#ifdef FIXED_TRV_TEST_SUITE -void MakeFile( TSTRING& fcoNameMakeMe ); -void MakeDir( const TCHAR* const lpszDirName ); +void MakeFile(TSTRING& fcoNameMakeMe); +void MakeDir(const TCHAR* const lpszDirName); // we use this instead of TraceContents() so we can test the report iterators. static void TraceReport(const cFCOReport& r, cDebug& d) @@ -68,31 +69,31 @@ static void TraceReport(const cFCOReport& r, cDebug& d) r.GetErrorQueue()->TraceContents(); cFCOReportGenreIter genreIter(r); - int genreCount = 0; + int genreCount = 0; for (genreIter.SeekBegin(); !genreIter.Done(); genreIter.Next()) { d.TraceDebug("> Genre [%d]:\n", genreCount); cFCOReportSpecIter specIter(genreIter); - int ct = 0; + int ct = 0; - for(specIter.SeekBegin(); ! specIter.Done(); specIter.Next(), ct++) + for (specIter.SeekBegin(); !specIter.Done(); specIter.Next(), ct++) { d.TraceDebug(">>> Spec [%d]:\n", ct); - ASSERT(specIter.GetSpec()); + TEST(specIter.GetSpec()); specIter.GetSpec()->TraceContents(); specIter.GetErrorQueue()->TraceContents(); d.TraceDebug(">>> Added Files:\n"); specIter.GetAddedSet()->TraceContents(); d.TraceDebug(">>> Removed Files:\n"); - specIter.GetRemovedSet()->TraceContents (); + specIter.GetRemovedSet()->TraceContents(); // trace out changed files cFCOReportChangeIter changeIter(specIter); - int changeCtr = 0; - for(changeIter.SeekBegin(); ! changeIter.Done(); changeIter.Next(), changeCtr++) + int changeCtr = 0; + for (changeIter.SeekBegin(); !changeIter.Done(); changeIter.Next(), changeCtr++) { d.TraceDebug(">>>>> Changed fco [%d]\n", changeCtr); d.TraceDebug(">>>>> Old FCO:\n"); @@ -105,8 +106,29 @@ static void TraceReport(const cFCOReport& r, cDebug& d) } } +/* + // + // basic functionality + // + void DisplayReportAndHaveUserUpdateIt( const TSTRING& edName, ReportingLevel level = FULL_REPORT ); //throw (eFSServices, eTextReportViewer, eInternal); + // outputs the given report to a temp file, opens an editor, has + // the user view changes to the database, and, by selecting FCO entries, + // chooses which changes to write to the database. Unchecked entries + // are removed from the report + // edName is the name of the editor to use to update the report + + virtual void PrintTextReport( const TSTRING& strFilename, ReportingLevel level = FULL_REPORT ); //throw (eTextReportViewer); + // if strFilename is "-", will print to TCOUT + virtual void PrintTextReport( TOSTREAM& ostr, ReportingLevel level = FULL_REPORT ); //throw (eTextReportViewer); + // prints the report to the specified ostream + */ + + void TestTextReportViewer() { + skip("TestTextReportViewer needs to be cleaned up & fixed, currently disabled"); + +#if 0 cFCOReport report; cFCOReportGenreIter genreIter(report); cFCOReportSpecIter specIter(genreIter); @@ -119,7 +141,7 @@ void TestTextReportViewer() try { iFSServices* pFSServices = iFSServices::GetInstance(); - ASSERT( pFSServices ); + TEST( pFSServices ); TSTRING fcoNameTempDir; pFSServices->GetTempDirName( fcoNameTempDir ); @@ -127,9 +149,9 @@ void TestTextReportViewer() fcoNameSpec1 = fcoNameTempDir += _T("SPEC1/"); fcoNameSpec2 = fcoNameTempDir += _T("SPEC2/"); - pFSServices->Mkdir( fcoNameTempDir ); - pFSServices->Mkdir( fcoNameSpec1.AsString() ); - pFSServices->Mkdir( fcoNameSpec2.AsString() ); + mkdir( fcoNameTempDir.c_str(), 0777 ); + mkdir( fcoNameSpec1.AsString().c_str(), 0777 ); + mkdir( fcoNameSpec2.AsString().c_str(), 0777 ); fcoNameTempFile = fcoNameTempDir += _T("twtempXXXXXX"); pFSServices->MakeTempFilename( fcoNameTempFile ); @@ -137,12 +159,12 @@ void TestTextReportViewer() catch(eFSServices& /* e */) { // TODO: properly handle error - ASSERT( false ); + TEST( false ); } - + // need two prop calcs because..... // if cFSPropCalc::VisitFSObject succeeds, cFSPropCalc stores the FCO in - // an internal set (why, I don't know), and the cFCOSet ASSERTs that the same + // an internal set (why, I don't know), and the cFCOSet TESTs that the same // FCO isn't inserted more than once. But since we visit changed FCOs twice // in this test routine, we need two calcs. Make sense? Oh, well. cFSPropCalc* pPropCalc = new cFSPropCalc; @@ -153,7 +175,7 @@ void TestTextReportViewer() cFCOSpecImpl* pSpec = new cFCOSpecImpl( fcoNameSpec1.AsString(), NULL, pStopPts); cFCOSpecAttr* pAttr = new cFCOSpecAttr; - + cFCOPropVector v; for( int i = 0; i < 32; i++ ) v.AddItem( i ); @@ -161,7 +183,6 @@ void TestTextReportViewer() pPropCalc->SetPropVector(v); pPropCalc2->SetPropVector(v); - TSTRING fcoNameMakeMe; fcoNameMakeMe = fcoNameSpec1.AsString() + _T("/added_fileXXXXXX"); MakeFile( fcoNameMakeMe ); @@ -172,9 +193,10 @@ void TestTextReportViewer() // MakeTempFile can't handle strings with escaped quotes, so we'll have to do this ourselves fcoNameMakeMe = fcoNameSpec1.AsString() + _T("/\"quoted\\_and_backslashed_file1\""); //TOFSTREAM file1( fcoNameMakeMe.c_str() ); - //ASSERT( file1 ); + //TEST( file1 ); //file1.close(); + cFSObject* addedFCO2 = new cFSObject( cFCOName(fcoNameMakeMe) ); //pPropCalc->VisitFSObject( *addedFCO2 ); @@ -182,7 +204,7 @@ void TestTextReportViewer() // MakeTempFile can't handle strings with escaped quotes, so we'll have to do this ourselves fcoNameMakeMe = fcoNameSpec1.AsString() + _T("/quoted_file\"2\"XXXXXX"); //TOFSTREAM file2( fcoNameMakeMe.c_str() ); - //ASSERT( file2 ); + //TEST( file2 ); //file2.close(); cFSObject* addedFCO3 = new cFSObject( cFCOName(fcoNameMakeMe) ); @@ -199,6 +221,7 @@ void TestTextReportViewer() MakeFile( fcoNameMakeMe ); cFSObject* removedFCO2 = new cFSObject( cFCOName(fcoNameMakeMe) ); pPropCalc->VisitFSObject( *removedFCO2 ); + pSpec->SetStartPoint( fcoNameSpec1 ); pAttr->SetName( fcoNameSpec1.AsString() ); @@ -207,7 +230,9 @@ void TestTextReportViewer() report.AddSpec(0x00020001, pSpec, pAttr, &specIter); // TODO:bam - use cFS::Genre pAttr->Release(); - + TEST(specIter.GetAddedSet()); + TEST(specIter.GetRemovedSet()); + specIter.GetAddedSet()->Insert(addedFCO); specIter.GetAddedSet()->Insert(addedFCO2); specIter.GetAddedSet()->Insert(addedFCO3); @@ -234,6 +259,7 @@ void TestTextReportViewer() changedPropVector1.AddItem(cFSPropSet::PROP_UID); report.AddChangedFCO(specIter, oldChangedFCO, newChangedFCO, changedPropVector1); + // make changed FCO2 cFCOPropVector changedPropVector2; @@ -280,7 +306,7 @@ void TestTextReportViewer() specIter.GetAddedSet()->Insert(addedFCO5); specIter.GetRemovedSet()->Insert(removedFCO5); - + // make changed FCO3 cFCOPropVector changedPropVector3; @@ -321,14 +347,13 @@ void TestTextReportViewer() specIter.Next(); //specIter.GetErrorQueue()->AddError(2, "this is an \"/etc2\" spec error",NULL); - d.TraceDebug(_T("\n======================================================\nStart PrintTextReport...\n======================================================\n\n\n")); TSTRING tstrEmpty( _T("") ); cFCOReportHeader rhi; cFCOReportUtil::FinalizeReport( report ); - cTextReportViewer trv; - trv.DisplayReportAndHaveUserUpdateIt( rhi, report, _T("") ); + cTextReportViewer trv(rhi, report); + trv.DisplayReportAndHaveUserUpdateIt( _T("") ); // test writing of USID cFileArchive outFile; @@ -354,20 +379,20 @@ void TestTextReportViewer() d.TraceDebug("Read in serialized report:\n"); //TraceReport(inReport, d); - trv.PrintTextReport( rhi, inReport, TSTRING( TEMP_DIR _T( "/test2.txt" ) ) ); + trv.PrintTextReport(TSTRING( TwTestPath("test2.txt" ) ) ); //TODO: this does not work any more //trv.LaunchEditorOnFile( TSTRING( TEMP_DIR _T("/test2.txt") ), _T("") ); // look at results - trv.PrintTextReport( rhi, report, fcoNameTempFile ); + trv.PrintTextReport(fcoNameTempFile ); //TODO: this does not work any more //cTextReportViewer::LaunchEditorOnFile( fcoNameTempFile, _T("") ); iFSServices* pFSServices = iFSServices::GetInstance(); - ASSERT( pFSServices ); + TEST( pFSServices ); pFSServices->FileDelete( addedFCO->GetName().AsString() ); pFSServices->FileDelete( addedFCO2->GetName().AsString() ); pFSServices->FileDelete( addedFCO3->GetName().AsString() ); @@ -382,8 +407,8 @@ void TestTextReportViewer() pFSServices->FileDelete( fcoNameTempFile ); // don't remove TEMP_DIR since other people may be using it - pFSServices->Rmdir( fcoNameSpec1.AsString() ); - pFSServices->Rmdir( fcoNameSpec2.AsString() ); + rmdir( fcoNameSpec1.AsString().c_str() ); + rmdir( fcoNameSpec2.AsString().c_str() ); pSpec->Release(); pSpec2->Release(); @@ -404,58 +429,54 @@ void TestTextReportViewer() newChangedFCO3->Release(); oldChangedFCO4->Release(); newChangedFCO4->Release(); +#endif return; } -void MakeFile( TSTRING& strNameMakeMe ) +void MakeFile(TSTRING& strNameMakeMe) { try { - iFSServices* pFSServices = iFSServices::GetInstance(); ASSERT( pFSServices ); - pFSServices->MakeTempFilename( strNameMakeMe ); + iFSServices* pFSServices = iFSServices::GetInstance(); + TEST(pFSServices); + pFSServices->MakeTempFilename(strNameMakeMe); std::string strA; - for( TSTRING::iterator i = strNameMakeMe.begin(); i != strNameMakeMe.end(); i++ ) + for (TSTRING::iterator i = strNameMakeMe.begin(); i != strNameMakeMe.end(); ++i) { - char ach[4]; - ASSERT( MB_CUR_MAX <= 4 ); + char ach[6]; + TEST(MB_CUR_MAX <= 6); - int n = wctomb( ach, *i ); - ASSERT( n != -1 ); - - for( int j = 0; j < n; j++ ) + int n = wctomb(ach, *i); + TEST(n != -1); + + for (int j = 0; j < n; j++) strA += ach[j]; } - TOFSTREAM file( strA.c_str() ); - ASSERT( file ); + TOFSTREAM file(strA.c_str()); + TEST(file); file.close(); } - catch( eFSServices e ) + catch (eFSServices e) { - ASSERT( false ); + TEST(false); } - catch( ... ) + catch (...) { - ASSERT( false ); + TEST(false); } } -void MakeDir( const TCHAR* const lpszDirName ) +void MakeDir(const TCHAR* const lpszDirName) { - try - { - iFSServices* pFSServices = iFSServices::GetInstance(); - TSTRING newdir(lpszDirName); - - pFSServices->Mkdir( newdir ); - } - catch( eFSServices e ) - { - ASSERT( false ); - } + TEST(0 == mkdir(lpszDirName, 0777)) } -#endif //FIXED_TRV_TEST_SUITE +//#endif //FIXED_TRV_TEST_SUITE +void RegisterSuite_TextReportViewer() +{ + RegisterTest("TextReportViewer", "Basic", TestTextReportViewer); +} diff --git a/src/twtest/twlocale_t.cpp b/src/twtest/twlocale_t.cpp index 3899662..dc629e7 100644 --- a/src/twtest/twlocale_t.cpp +++ b/src/twtest/twlocale_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,6 +40,7 @@ #include "core/stdcore.h" #include "core/debug.h" #include "core/twlocale.h" +#include "test.h" void TestAtoi(); void TestItoa(); @@ -47,181 +48,59 @@ void TestFlags(); void TestRoundtrip(); void TestHex(); -#define ASSERT_THAT_IT_THROWS( x, error ) \ - try \ - { \ - x; \ - ASSERT( false ); \ - } catch( error& ) {} - -void TestTWLocale() -{ -#ifdef DOESNTWORK - TestHex(); - TestAtoi(); - TestItoa(); - TestFlags(); - TestRoundtrip(); -#endif//NOTDONE -} - -#ifdef DOESNTWORK - -void TestAtoi() -{ - // - // setup - // - int32 n; - TSTRING str = _T("123456"); - - // - // Try formatting with our default locale - // - cTWLocale::InitGlobalLocale(); - n = cTWLocale::FormatNumber( str ); - ASSERT( n == 123456 ); - - // - // Try formatting with "" locale - // - std::locale::global( std::locale("") ); - n = cTWLocale::FormatNumber( str ); - ASSERT( n == 123456 ); - - // - // Try formatting with "C" locale - // - std::locale::global( std::locale("") ); - n = cTWLocale::FormatNumber( str ); - ASSERT( n == 123456 ); -} +#define ASSERT_THAT_IT_THROWS(x, error) \ + try \ + { \ + x; \ + TEST(false); \ + } \ + catch (error&) \ + { \ + } void TestItoa() { - // - // can't do ASSERT( str == _T("123456") ) - // because locale may turn it into "123,465" or whatever - // - - // - // setup - // - int32 n = 123456; - TSTRING str; - - // - // Try formatting with our default locale - // - cTWLocale::InitGlobalLocale(); - cTWLocale::FormatNumber( n, str ); - TCOUT << str << std::endl; - - // - // Try formatting with "" locale - // - std::locale::global( std::locale("") ); - cTWLocale::FormatNumber( n, str ); - TCOUT << str << std::endl; - - // - // Try formatting with "C" locale - // - std::locale::global( std::locale("") ); - cTWLocale::FormatNumber( n, str ); - TCOUT << str << std::endl; + try + { + // + // can't do ASSERT( str == _T("123456") ) + // because locale may turn it into "123,465" or whatever + // + + // + // setup + // + int32 n = 123456; + TSTRING str; + + // + // Try formatting with our default locale + // + cTWLocale::InitGlobalLocale(); + cTWLocale::FormatNumber(n, str); + TEST(str == "123456"); + + // + // Try formatting with "" locale + // + std::locale::global(std::locale("")); + cTWLocale::FormatNumber(n, str); + TEST(str == "123,456"); + + // + // Try formatting with "C" locale + // + std::locale::global(std::locale("")); + cTWLocale::FormatNumber(n, str); + TEST(str == "123,456"); + } + catch (const std::runtime_error& e) + { + skip("Skipping test due to configuration issue w/ 'C' locale"); + } } -void TestRoundtrip() +void RegisterSuite_TWLocale() { - // - // init - // - cTWLocale::InitGlobalLocale(); - - // - // atoitoa - // - TSTRING strIn = _T("123456"); - TSTRING strOut; - strOut = cTWLocale::FormatNumber( cTWLocale::FormatNumber( strIn ), strOut ); - // don't know if string will be the same due to possible changes in formatting from locale - // ASSERT( strOut == strIn ); <---- can't do this ^^^ - ASSERT( 123456 == cTWLocale::FormatNumber( strOut ) ); - - - // - // itoatoi - // - int32 nIn = 654321; - int32 nOut; - nOut = cTWLocale::FormatNumber( cTWLocale::FormatNumber( nIn, strIn ) ); - ASSERT( nOut == nIn ); -} - - -void TestFlags() -{ - // - // init - // - cTWLocale::InitGlobalLocale(); - - // - // hex - // - TSTRING str = _T("FF"); - int n = cTWLocale::FormatNumber( str, std::ios_base::hex ); - ASSERT( n == 0xFF ); - - // - // bad number for dec - // - ASSERT_THAT_IT_THROWS( cTWLocale::FormatNumberAsHex( str ), eError ); - - // - // oct - // - TSTRING strOct = _T("0712"); - n = cTWLocale::FormatNumber( strOct, std::ios_base::oct ); - ASSERT( n == 0712 ); - - // - // oct again - // - strOct = _T("00712"); - n = cTWLocale::FormatNumber( strOct, std::ios_base::oct ); - ASSERT( n == 0712 ); - - // - // oct again again - // - strOct = _T("712"); - n = cTWLocale::FormatNumber( strOct, std::ios_base::oct ); - ASSERT( n == 0712 ); - - // - // try bad oct - // - ASSERT_THAT_IT_THROWS( cTWLocale::FormatNumber( _T("99"), std::ios_base::oct ), eError ); -} - - -void TestHex() -{ - TSTRING str; - - str = cTWLocale::FormatNumberAsHex( 0x1234 ); - ASSERT( str == _T("1234") ); - - str = cTWLocale::FormatNumberAsHex( 16 ); - ASSERT( str == _T("10") ); - - str = cTWLocale::FormatNumberAsHex( 0x12344321 ); - ASSERT( str == _T("12344321") ); - - str = cTWLocale::FormatNumberAsHex( 0xFFFFFFFF ); - ASSERT( str == _T("FFFFFFFF") || str == _T("ffffffff") ); + RegisterTest("TWLocale", "Itoa", TestItoa); } -#endif//DOESNTWORK - diff --git a/src/twtest/twutil_t.cpp b/src/twtest/twutil_t.cpp index c96e4e4..18a2002 100644 --- a/src/twtest/twutil_t.cpp +++ b/src/twtest/twutil_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -34,23 +34,18 @@ #include "tw/stdtw.h" #include "tw/twutil.h" +#include "util/fileutil.h" #include "twtest/test.h" #include - - -#if IS_UNIX //#include #include #include -#endif -std::string WideToNarrow( const TSTRING& strWide ); +std::string WideToNarrow(const TSTRING& strWide); void TestTWUtil() { -#pragma message( __FILE__ "(1) : TODO - implement this test file") -#if 0 // TODO: we should test more than the file exists stuff, but that // is all I need to do for right now. cDebug d("TestTWUtil"); @@ -61,78 +56,63 @@ void TestTWUtil() d.TraceAlways("Testing FileExists() and FileWritable()\n"); // assuming the current dir is writable, this test should succeed - TEST(cTWUtil::FileWritable(_T("afilethatdoesnotexist.tmp")) == true); - - TSTRING tmpDir = TEMP_DIR; - tmpDir += _T("/fileexistdir"); - TSTRING tmpFN = tmpDir; - tmpFN += _T("/fileexiststest.tmp"); + TEST(cFileUtil::FileWritable(_T("afilethatdoesnotexist.tmp")) == true); - // make a subdir in the TEMP_DIR - #if IS_UNIX - _tmkdir(tmpDir.c_str(), 0700); - #else - _tmkdir(tmpDir.c_str()); - #endif + TSTRING tmpDir = TwTestPath("fileexistdir"); + TSTRING tmpFN = TwTestPath("fileexiststest.tmp"); - _tchmod(tmpDir.c_str(), 0700); + // make a subdir in the TEMP_DIR + mkdir(tmpDir.c_str(), 0700); + chmod(tmpDir.c_str(), 0700); // make sure file is not there - _tchmod(tmpFN.c_str(), 0777); - _tunlink(tmpFN.c_str()); + chmod(tmpFN.c_str(), 0777); + unlink(tmpFN.c_str()); // make sure exists tests false, writable is true // and checking writable should not create the file - TEST(cTWUtil::FileExists(tmpFN) == false); - TEST(cTWUtil::FileWritable(tmpFN) == true) - TEST(cTWUtil::FileExists(tmpFN) == false); + TEST(cFileUtil::FileExists(tmpFN) == false); + TEST(cFileUtil::FileWritable(tmpFN) == true) + TEST(cFileUtil::FileExists(tmpFN) == false); + +#if IS_AROS + bool is_root = (65534 == getuid()); //AROS doesn't really have users, & posixy fns use this pseudo value. +#else + bool is_root = (0 == getuid()); +#endif // make the dir read only and make sure write tests false - #if IS_UNIX // windows fails this test, perhaps because I am an administrator? - _tchmod(tmpDir.c_str(), 0500); - TEST(cTWUtil::FileWritable(tmpFN) == false); - _tchmod(tmpDir.c_str(), 0700); - #endif + // windows fails this test, perhaps because I am an administrator? + // chmod(tmpDir.c_str(), 0500); + // TODO - is this valid now that we don't use /tmp? + // TEST(cFileUtil::FileWritable(tmpFN) == is_root); + // chmod(tmpDir.c_str(), 0700); // create the file { - std::ofstream ostr(WideToNarrow(tmpFN).c_str()); - ostr << "Hey there.\n"; + std::ofstream ostr(WideToNarrow(tmpFN).c_str()); + ostr << "Hey there.\n"; } // test a read only file - _tchmod(tmpFN.c_str(), 0400); - TEST(cTWUtil::FileWritable(tmpFN) == false); + chmod(tmpFN.c_str(), 0400); + TEST(cFileUtil::FileWritable(tmpFN) == is_root); // test a writable file - _tchmod(tmpFN.c_str(), 0666); - TEST(cTWUtil::FileWritable(tmpFN) == true); + chmod(tmpFN.c_str(), 0666); + TEST(cFileUtil::FileWritable(tmpFN) == true); // delete the test file and dir - _tunlink(tmpFN.c_str()); - _tunlink(tmpDir.c_str()); -#endif + unlink(tmpFN.c_str()); + unlink(tmpDir.c_str()); } -std::string WideToNarrow( const TSTRING& strWide ) +std::string WideToNarrow(const TSTRING& strWide) { -#ifdef _UNICODE - std::string strA; - for( TSTRING::const_iterator i = strWide.begin(); i != strWide.end(); i++ ) - { - char ach[4]; - ASSERT( MB_CUR_MAX <= 4 ); - - int n = wctomb( ach, *i ); - ASSERT( n != -1 ); - - for( int j = 0; j < n; j++ ) - strA += ach[j]; - } - - return strA; -#else return strWide; -#endif } +void RegisterSuite_TWUtil() +{ + RegisterTest("TWUtil", "Basic", TestTWUtil); +} diff --git a/src/twtest/types_t.cpp b/src/twtest/types_t.cpp index 22f578c..d1a564b 100644 --- a/src/twtest/types_t.cpp +++ b/src/twtest/types_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,14 +39,19 @@ // TestTypes() -- this will simply make sure that all the types are defined properly for the current build void TestTypes() { - TEST(sizeof(int8) == 1); - TEST(sizeof(uint8) == 1); - TEST(sizeof(int16) == 2); - TEST(sizeof(uint16) == 2); - TEST(sizeof(int32) == 4); - TEST(sizeof(uint32) == 4); - TEST(sizeof(int64) == 8); - TEST(sizeof(uint64) == 8); - TEST(sizeof(float32) == 4); - TEST(sizeof(float64) == 8); + TEST(sizeof(int8) == 1); + TEST(sizeof(uint8) == 1); + TEST(sizeof(int16) == 2); + TEST(sizeof(uint16) == 2); + TEST(sizeof(int32) == 4); + TEST(sizeof(uint32) == 4); + TEST(sizeof(int64) == 8); + TEST(sizeof(uint64) == 8); + TEST(sizeof(float32) == 4); + TEST(sizeof(float64) == 8); +} + +void RegisterSuite_Types() +{ + RegisterTest("Types", "Basic", TestTypes); } diff --git a/src/twtest/unixfsservices_t.cpp b/src/twtest/unixfsservices_t.cpp index 001ad5e..a572c12 100644 --- a/src/twtest/unixfsservices_t.cpp +++ b/src/twtest/unixfsservices_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -38,172 +38,185 @@ #include "core/archive.h" #include "fco/fconame.h" -#if IS_UNIX - #ifndef __TEST_H #include "twtest/test.h" #endif +#include + using namespace std; + +std::string makeTestFile(const std::string& filename) +{ + TSTRING testfile = TwTestPath(filename); + cFileArchive filearch; + filearch.OpenReadWrite(testfile.c_str()); + filearch.Seek(0, cBidirArchive::BEGINNING); + filearch.WriteString(_T("This is a test")); + filearch.Close(); + + return testfile; +} + //Tests the functions that are currently implemented in win32fsservices. -void TestUnixFSServices() +void TestReadDir() { - cDebug d("TestUnixFSServices"); + cDebug d("TestReadDir"); // d.RemoveOutTarget(cDebug::OUT_STDOUT); - try - { - iFSServices* pFSServices = iFSServices::GetInstance(); + iFSServices* pFSServices = iFSServices::GetInstance(); - // working primarily with the temp dir. - cFCOName name(_T("/tmp")); // dies here + // working primarily with the temp dir. + cFCOName name(TwTestDir()); - // Check to make sure /tmp is a dir - //TEST(pFSServices->GetFileType(name) == cFSStatArgs::TY_DIR); - - // get directory contents (test readdir) - std::vector v; - pFSServices->ReadDir(name.AsString(), v); + // Check to make sure test dir is a dir + //TEST(pFSServices->GetFileType(name) == cFSStatArgs::TY_DIR); - { - d.TraceDebug("name: %d entries\n", v.size()); + // get directory contents (test readdir) + std::vector v; + pFSServices->ReadDir(name.AsString(), v); - std::vector ::iterator p; - int n = 0; - for (p = v.begin(); p != v.end(); p++) { - d.TraceDetail(" %s\n", p->c_str()); - n++; - } + { + d.TraceDebug("name: %d entries\n", v.size()); - TEST(n == v.size()); + std::vector::iterator p; + size_t n = 0; + for (p = v.begin(); p != v.end(); ++p) + { + d.TraceDetail(" %s\n", p->c_str()); + n++; } - //Test the Stat method - cFSStatArgs stat; - - //TO DO: use archive to create this file - TSTRING testfile = "/tmp/tmp.tmp"; - cFileArchive filearch; - filearch.OpenReadWrite(testfile.c_str()); - filearch.Seek(0, cBidirArchive::BEGINNING); - filearch.WriteString(_T("This is a test")); - filearch.Close(); - - pFSServices->Stat(testfile, stat); - - //print out the information returned by Stat - d.TraceDetail("Information returned by Stat: \n"); - d.TraceDetail("Group ID : %-5d \n", stat.gid); - //d.TraceDetail("Last access time: %d \n", stat.atime); - d.TraceDetail("Last inode change: %d \n", stat.ctime); - d.TraceDetail("Last modified: %d \n", stat.mtime); - d.TraceDetail("Major/minor device nums: %d \n", stat.dev); - d.TraceDetail("Inode # of file : %d \n", stat.ino); - d.TraceDetail("Mode bits: %d \n", stat.mode); - d.TraceDetail("Num links: %d \n", stat.nlink); - d.TraceDetail("Major/minor dev if special: %d \n", stat.rdev); - d.TraceDetail("File size: %d \n", stat.size); - d.TraceDetail("User ID: %d \n", stat.uid); - - //Test GetCurrentDir: - TSTRING currpath; - pFSServices->GetCurrentDir(currpath); - d.TraceDetail("GetCurrentDir returned %s\n", currpath.c_str()); - //TEST(currpath == _T("~")); - //they should both be ~!! - - //Test MakeTempFilename - TSTRING _template(_T("twtempXXXXXX")); - pFSServices->MakeTempFilename(_template); - d.TraceDetail("Testing MakeTempFilename: \n"); - d.TraceDetail("%s \n", _template.c_str() ); - - //Test ChangeDir - d.TraceDetail("Testing ChangeDir: (should be /usr)\n"); - TSTRING newdir(_T("/usr")); - pFSServices->ChangeDir(newdir); - pFSServices->GetCurrentDir(currpath); - d.TraceDetail("%s \n", currpath.c_str() ); - //Did we get there?? - - //Test Mkdir: - d.TraceDetail("Testing Mkdir: \n"); - TSTRING makedir(_T("/tmp/tw_mkdir")); - pFSServices->Mkdir(makedir); // throws on error - - //Test Rmdir - d.TraceDetail("Testing Rmdir:\n"); - TEST( pFSServices->Rmdir(makedir) ); - - // Test GetMachineName - d.TraceDetail("Testing GetMachineName:\n"); - TSTRING uname; - pFSServices->GetMachineName(uname); - d.TraceDetail("GetMachineName returned: %s\n", uname.c_str()); - - // Test GetHostID - d.TraceDetail("Testing GetHostID:\n"); - TSTRING hostid; - pFSServices->GetHostID(hostid); - d.TraceDetail("GetHostID returned: %s\n", hostid.c_str()); - - // Test GetCurrentUserName - d.TraceDetail("Testing GetCurrentUserName:\n"); - TSTRING username; - TEST( pFSServices->GetCurrentUserName(username) ); - d.TraceDetail("GetCurrentUserName returned: %s\n", username.c_str()); - - TCERR << "TODO: unixfsservices_t.cpp, Test GetIPAddress segfaults mysteriously." << std::endl; - // Test GetIPAddress - /*d.TraceDetail("Testing GetIPAddress:\n"); - uint32 *ipaddr; - TEST( pFSServices->GetIPAddress( *ipaddr ) ); - d.TraceDetail("GetIPAddress returned: %d\n", ipaddr); - */ - // test GetExecutableFilename - d.TraceDetail("Testing GetExecutableFilename: \n"); - TSTRING filename = _T("sh"); - TSTRING fullpath = _T("/bin/"); - TEST(pFSServices->GetExecutableFilename(fullpath, filename)); - filename = _T("/bin/sh"); - TEST(pFSServices->GetExecutableFilename(fullpath, filename)); - - // test Rename - d.TraceDetail("Testing Rename:\n"); - TSTRING newtestfile = _T("/tmp/new.tmp"); - TEST( pFSServices->Rename( testfile, newtestfile ) ); - - // test GetOwnerForFile - d.TraceDetail("Testing GetOwnerForFile:\n"); - TSTRING ownername; - TEST( pFSServices->GetOwnerForFile( newtestfile, ownername ) ); - d.TraceDetail("GetOwnerForFile returned owner %s.\n", ownername.c_str()); - - // test GetGroupForFile - d.TraceDetail("Testing GetGroupForFile:\n"); - TSTRING groupname; - TEST( pFSServices->GetGroupForFile( newtestfile, groupname ) ); - d.TraceDetail("GetGroupForFile returned group %s.\n", groupname.c_str()); - - // test FileDelete - d.TraceDetail("Testing FileDelete:\n"); - TEST( pFSServices->FileDelete( newtestfile ) ); - - - - }//end try block - catch (eError& e) - { - d.TraceError("Exception caught: %s\n", e.GetMsg().c_str()); + TEST(n == v.size()); } +} +void TestStat() +{ + //Test the Stat method + cFSStatArgs stat; + + std::string testfile = makeTestFile("stat.tmp"); + + iFSServices::GetInstance()->Stat(testfile, stat); + + TEST("Stat() did not throw"); + /* + cDebug d("TestStat"); + //print out the information returned by Stat + d.TraceDetail("Information returned by Stat: \n"); + d.TraceDetail("Group ID : %-5d \n", stat.gid); + //d.TraceDetail("Last access time: %d \n", stat.atime); + d.TraceDetail("Last inode change: %d \n", stat.ctime); + d.TraceDetail("Last modified: %d \n", stat.mtime); + d.TraceDetail("Major/minor device nums: %d \n", stat.dev); + d.TraceDetail("Inode # of file : %d \n", stat.ino); + d.TraceDetail("Mode bits: %d \n", stat.mode); + d.TraceDetail("Num links: %d \n", stat.nlink); + d.TraceDetail("Major/minor dev if special: %d \n", stat.rdev); + d.TraceDetail("File size: %d \n", stat.size); + d.TraceDetail("User ID: %d \n", stat.uid); +*/ } -#endif // IS_UNIX +void TestGetCurrentDir() +{ + TSTRING currpath; + iFSServices::GetInstance()->GetCurrentDir(currpath); + TEST("GetCurrentDir() did not throw"); + //d.TraceDetail("GetCurrentDir returned %s\n", currpath.c_str()); + //TEST(currpath == _T("~")); + //they should both be ~!! +} +void TestMakeTempFilename() +{ + TSTRING _template(_T("twtempXXXXXX")); + iFSServices::GetInstance()->MakeTempFilename(_template); + TEST("MakeTempFilename() did not throw"); +} + +void TestGetMachineName() +{ + TSTRING uname; + iFSServices::GetInstance()->GetMachineName(uname); + TEST("GetMachineName() did not throw"); +} + +void TestGetHostID() +{ + TSTRING hostid; + iFSServices::GetInstance()->GetHostID(hostid); + TEST("GetHostID() did not throw:"); +} + +void TestGetCurrentUserName() +{ +#if !IS_SKYOS // SkyOS breaks on this, for as-yet-unknown reasons + TSTRING username; + bool success = iFSServices::GetInstance()->GetCurrentUserName(username); + if (!success) + skip("GetCurrentUserName test skipped, usually caused by system configuration problems"); + + TEST("GetCurrentUserName() did not throw"); +#endif +} + +void TestGetIPAddress() +{ + uint32 ipaddr; + bool success = iFSServices::GetInstance()->GetIPAddress(ipaddr); + if (!success) + skip("GetIPAddress test skipped, usually caused by hostname/IP configuration problems"); + + TEST("GetIPAddress() did not throw"); +} + +void TestGetExecutableFilename() +{ + if (-1 == access("/bin/sh", F_OK)) + skip("/bin/sh not found/accessible"); + + TSTRING filename = _T("sh"); + TSTRING fullpath = _T("/bin/"); + TEST(iFSServices::GetInstance()->GetExecutableFilename(fullpath, filename)); + + filename = _T("/bin/sh"); + TEST(iFSServices::GetInstance()->GetExecutableFilename(fullpath, filename)); +} + +void TestRename() +{ + std::string testfile = makeTestFile("rename_from"); + + TSTRING newtestfile = TwTestPath("rename_to"); + TEST(iFSServices::GetInstance()->Rename(testfile, newtestfile)); +} + +void TestFileDelete() +{ + std::string to_rm = makeTestFile("to_rm"); + + TEST(iFSServices::GetInstance()->FileDelete(to_rm)); +} + +void RegisterSuite_UnixFSServices() +{ + RegisterTest("UnixFSServices", "ReadDir", TestReadDir); + RegisterTest("UnixFSServices", "Stat", TestStat); + RegisterTest("UnixFSServices", "GetCurrentDir", TestGetCurrentDir); + RegisterTest("UnixFSServices", "MakeTempFilename", TestMakeTempFilename); + RegisterTest("UnixFSServices", "GetMachineName", TestGetMachineName); + RegisterTest("UnixFSServices", "GetHostID", TestGetHostID); + RegisterTest("UnixFSServices", "GetCurrentUserName", TestGetCurrentUserName); + RegisterTest("UnixFSServices", "GetIPAddress", TestGetIPAddress); + RegisterTest("UnixFSServices", "GetExecutableFilename", TestGetExecutableFilename); + RegisterTest("UnixFSServices", "Rename", TestRename); + RegisterTest("UnixFSServices", "FileDelete", TestFileDelete); +} diff --git a/src/twtest/usernotifystdout_t.cpp b/src/twtest/usernotifystdout_t.cpp index edcbffc..ddb6b75 100644 --- a/src/twtest/usernotifystdout_t.cpp +++ b/src/twtest/usernotifystdout_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,5 +41,10 @@ void TestUserNotifyStdout() { cDebug d("TestUserNotifyStdout"); d.TraceError("Implement this!\n"); - TEST(false); + skip("TestUserNotifyStdout unimplemented"); +} + +void RegisterSuite_UserNotifyStdout() +{ + RegisterTest("UserNotifyStdout", "Basic", TestUserNotifyStdout); } diff --git a/src/twtest/wchar16_t.cpp b/src/twtest/wchar16_t.cpp index 2107a54..5361600 100644 --- a/src/twtest/wchar16_t.cpp +++ b/src/twtest/wchar16_t.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -51,11 +51,11 @@ void TestWchar16() wc16_string b(a); TEST(b.empty()); -//#if !IS_UNIX // need to get the L"" stuff working + //#if !IS_UNIX // need to get the L"" stuff working - static WCHAR16 STRING1[] = { 65, 66, 67, 68, 0 }; - static WCHAR16 STRING2[] = { 40, 66, 67, 68, 0 }; - static WCHAR16 STRING0[] = { 65, 66, 67, 68, 0, 0 }; + static WCHAR16 STRING1[] = {65, 66, 67, 68, 0}; + static WCHAR16 STRING2[] = {40, 66, 67, 68, 0}; + static WCHAR16 STRING0[] = {65, 66, 67, 68, 0, 0}; a = STRING1; TEST(a.length() == 4); @@ -75,16 +75,16 @@ void TestWchar16() b.resize(5); TEST(memcmp(b.data(), STRING0, 5 * sizeof(WCHAR16)) == 0); - a = STRING1; - b = a; + a = STRING1; + b = a; a[0] = 40; TEST(a.length() == 4); TEST(memcmp(a.data(), STRING2, 4 * sizeof(WCHAR16)) == 0); TEST(b.length() == 4); TEST(memcmp(b.data(), STRING1, 4 * sizeof(WCHAR16)) == 0); - - a = STRING1; - b = a; + + a = STRING1; + b = a; a[0] = 40; TEST(a.length() == 4); TEST(memcmp(a.data(), STRING2, 4 * sizeof(WCHAR16)) == 0); @@ -120,7 +120,12 @@ void TestWchar16() TEST(memcmp(a.data(), STRING1, 4) == 0); b.swapbytes(); TEST(memcmp(b.data(), STRING1, 4) == 0); -//#endif // IS_UNIX + //#endif // IS_UNIX db.TraceAlways("Done...\n"); } + +void RegisterSuite_Wchar16() +{ + RegisterTest("Wchar16", "Basic", TestWchar16); +} diff --git a/src/util/Makefile.am b/src/util/Makefile.am index 8a4b234..bd39842 100644 --- a/src/util/Makefile.am +++ b/src/util/Makefile.am @@ -1,13 +1,18 @@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libutil.a +libutil_adir = . libutil_a_SOURCES = \ fileutil.cpp stdutil.cpp stringencoder.cpp \ util.cpp utilerrors.cpp utilstrings.cpp -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +libutil_a_HEADERS = fileutil.h miscutil.h stdutil.h \ + stringencoder.h util.h utilerrors.h utilstrings.h + +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit +CLEANFILES = *.gcno *.gcda all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libutil_a_OBJECTS) diff --git a/src/util/Makefile.in b/src/util/Makefile.in index 5f2b124..96f23e3 100644 --- a/src/util/Makefile.in +++ b/src/util/Makefile.in @@ -1,8 +1,8 @@ -# Makefile.in generated by automake 1.8.5 from Makefile.am. +# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004 Free Software Foundation, Inc. +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -14,17 +14,68 @@ @SET_MAKE@ -SOURCES = $(libutil_a_SOURCES) -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ -top_builddir = ../.. +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -INSTALL = @INSTALL@ install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c @@ -36,43 +87,122 @@ POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : +build_triplet = @build@ host_triplet = @host@ +target_triplet = @target@ subdir = src/util -DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.in + $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(libutil_a_HEADERS) \ + $(am__DIST_COMMON) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) -AR = ar ARFLAGS = cru +AM_V_AR = $(am__v_AR_@AM_V@) +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) +am__v_AR_0 = @echo " AR " $@; +am__v_AR_1 = libutil_a_AR = $(AR) $(ARFLAGS) libutil_a_LIBADD = am_libutil_a_OBJECTS = fileutil.$(OBJEXT) stdutil.$(OBJEXT) \ stringencoder.$(OBJEXT) util.$(OBJEXT) utilerrors.$(OBJEXT) \ utilstrings.$(OBJEXT) libutil_a_OBJECTS = $(am_libutil_a_OBJECTS) -DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = am__depfiles_maybe = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) +AM_V_CXX = $(am__v_CXX_@AM_V@) +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) +am__v_CXX_0 = @echo " CXX " $@; +am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) +am__v_CXXLD_0 = @echo " CXXLD " $@; +am__v_CXXLD_1 = SOURCES = $(libutil_a_SOURCES) DIST_SOURCES = $(libutil_a_SOURCES) +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libutil_adir)" +HEADERS = $(libutil_a_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/mkinstalldirs DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ -AMDEP_FALSE = @AMDEP_FALSE@ -AMDEP_TRUE = @AMDEP_TRUE@ AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ @@ -88,7 +218,7 @@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ # This gets rid of the -I. so INCLUDES must be more explicit +DEFS = @DEFS@ # This gets rid of the -I. so AM_CPPFLAGS must be more explicit DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ @@ -96,6 +226,7 @@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ +INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ @@ -107,6 +238,7 @@ LN = @LN@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ OBJEXT = @OBJEXT@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ @@ -123,21 +255,24 @@ STRIP = @STRIP@ VERSION = @VERSION@ YACC = @YACC@ YFLAGS = @YFLAGS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ -am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ -am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ -am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ -am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ +builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ @@ -167,19 +302,28 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = foreign no-dependencies -INCLUDES = -I.. +AM_CPPFLAGS = -I$(srcdir)/.. noinst_LIBRARIES = libutil.a +libutil_adir = . libutil_a_SOURCES = \ fileutil.cpp stdutil.cpp stringencoder.cpp \ util.cpp utilerrors.cpp utilstrings.cpp +libutil_a_HEADERS = fileutil.h miscutil.h stdutil.h \ + stringencoder.h util.h utilerrors.h utilstrings.h + +CLEANFILES = *.gcno *.gcda all: all-am .SUFFIXES: @@ -188,15 +332,14 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ - cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ - && exit 0; \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/util/Makefile'; \ - cd $(top_srcdir) && \ - $(AUTOMAKE) --foreign src/util/Makefile -.PRECIOUS: Makefile + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/util/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/util/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -213,13 +356,15 @@ $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) -libutil.a: $(libutil_a_OBJECTS) $(libutil_a_DEPENDENCIES) - -rm -f libutil.a - $(libutil_a_AR) libutil.a $(libutil_a_OBJECTS) $(libutil_a_LIBADD) - $(RANLIB) libutil.a + +libutil.a: $(libutil_a_OBJECTS) $(libutil_a_DEPENDENCIES) $(EXTRA_libutil_a_DEPENDENCIES) + $(AM_V_at)-rm -f libutil.a + $(AM_V_AR)$(libutil_a_AR) libutil.a $(libutil_a_OBJECTS) $(libutil_a_LIBADD) + $(AM_V_at)$(RANLIB) libutil.a mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -228,91 +373,121 @@ distclean-compile: -rm -f *.tab.c .cpp.o: - $(CXXCOMPILE) -c -o $@ $< + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: - $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` -uninstall-info-am: - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ + $(AM_V_CXX)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +install-libutil_aHEADERS: $(libutil_a_HEADERS) + @$(NORMAL_INSTALL) + @list='$(libutil_a_HEADERS)'; test -n "$(libutil_adir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(libutil_adir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(libutil_adir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(libutil_adir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(libutil_adir)" || exit $$?; \ + done + +uninstall-libutil_aHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(libutil_a_HEADERS)'; test -n "$(libutil_adir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(libutil_adir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$tags $$unique; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - tags=; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) ' { files[$$0] = 1; } \ - END { for (i in files) print i; }'`; \ - test -z "$(CTAGS_ARGS)$$tags$$unique" \ +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$tags $$unique + $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ - && cd $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) $$here + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) - @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ - topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ - list='$(DISTFILES)'; for file in $$list; do \ - case $$file in \ - $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ - $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ - esac; \ + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ - dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ - if test "$$dir" != "$$file" && test "$$dir" != "."; then \ - dir="/$$dir"; \ - $(mkdir_p) "$(distdir)$$dir"; \ - else \ - dir=''; \ - fi; \ if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ - cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ - cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ - test -f $(distdir)/$$file \ - || cp -p $$d/$$file $(distdir)/$$file \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am -all-am: Makefile $(LIBRARIES) +all-am: Makefile $(LIBRARIES) $(HEADERS) installdirs: + for dir in "$(DESTDIR)$(libutil_adir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done install: install-am install-exec: install-exec-am install-data: install-data-am @@ -323,16 +498,23 @@ install-am: all-am installcheck: installcheck-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - `test -z '$(STRIP)' || \ - echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi mostlyclean-generic: clean-generic: + -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: - -rm -f $(CONFIG_CLEAN_FILES) + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -352,18 +534,38 @@ dvi-am: html: html-am +html-am: + info: info-am info-am: -install-data-am: +install-data-am: install-libutil_aHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: install-exec-am: +install-html: install-html-am + +install-html-am: + install-info: install-info-am +install-info-am: + install-man: +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + installcheck-am: maintainer-clean: maintainer-clean-am @@ -382,23 +584,31 @@ ps: ps-am ps-am: -uninstall-am: uninstall-info-am +uninstall-am: uninstall-libutil_aHEADERS + +.MAKE: install-am install-strip -.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ - clean-noinstLIBRARIES ctags distclean distclean-compile \ - distclean-generic distclean-tags distdir dvi dvi-am html \ - html-am info info-am install install-am install-data \ - install-data-am install-exec install-exec-am install-info \ - install-info-am install-man install-strip installcheck \ - installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-info-am +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ + clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ + distclean-compile distclean-generic distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-libutil_aHEADERS \ + install-man install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ + ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-libutil_aHEADERS + +.PRECIOUS: Makefile all: $(noinst_LIBRARIES) $(AR) ru ../../lib/libtripwire.a $(libutil_a_OBJECTS) $(RANLIB) ../../lib/libtripwire.a + # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: diff --git a/src/util/fileutil.cpp b/src/util/fileutil.cpp index 1b9368f..3b9a5fa 100644 --- a/src/util/fileutil.cpp +++ b/src/util/fileutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -45,14 +45,12 @@ #include "core/file.h" #include "core/errorbucketimpl.h" -#include // for the FileExists() stuff +#include // for the FileExists() stuff -#if IS_UNIX #include #include #include #include -#endif /////////////////////////////////////////////////////////////////////////////// @@ -60,9 +58,9 @@ /////////////////////////////////////////////////////////////////////////////// void cFileUtil::TestFileExists(const TSTRING& fileName) { - if(! cFileUtil::FileExists(fileName)) + if (!cFileUtil::FileExists(fileName)) { - TSTRING filenameText = TSS_GetString( cCore, core::STR_ERROR_FILENAME ); + TSTRING filenameText = TSS_GetString(cCore, core::STR_ERROR_FILENAME); filenameText.append(fileName); filenameText.append(1, _T('\n')); filenameText.append(iFSServices::GetInstance()->GetErrString()); @@ -76,9 +74,9 @@ void cFileUtil::TestFileExists(const TSTRING& fileName) /////////////////////////////////////////////////////////////////////////////// void cFileUtil::TestFileWritable(const TSTRING& fileName) { - if(! cFileUtil::FileWritable(fileName)) + if (!cFileUtil::FileWritable(fileName)) { - TSTRING filenameText = TSS_GetString( cCore, core::STR_ERROR_FILENAME); + TSTRING filenameText = TSS_GetString(cCore, core::STR_ERROR_FILENAME); filenameText.append(fileName); filenameText.append(1, _T('\n')); filenameText.append(iFSServices::GetInstance()->GetErrString()); @@ -92,9 +90,9 @@ void cFileUtil::TestFileWritable(const TSTRING& fileName) /////////////////////////////////////////////////////////////////////////////// void cFileUtil::TestFileReadable(const TSTRING& fileName) { - if(! cFileUtil::FileReadable(fileName)) + if (!cFileUtil::FileReadable(fileName)) { - TSTRING filenameText = TSS_GetString( cCore, core::STR_ERROR_FILENAME); + TSTRING filenameText = TSS_GetString(cCore, core::STR_ERROR_FILENAME); filenameText.append(fileName); filenameText.append(1, _T('\n')); filenameText.append(iFSServices::GetInstance()->GetErrString()); @@ -106,33 +104,33 @@ void cFileUtil::TestFileReadable(const TSTRING& fileName) /////////////////////////////////////////////////////////////////////////////// // IsDir /////////////////////////////////////////////////////////////////////////////// -bool cFileUtil::IsDir( const TSTRING& fileName ) +bool cFileUtil::IsDir(const TSTRING& fileName) { cFSStatArgs s; try { - iFSServices::GetInstance()->Stat( fileName, s ); + iFSServices::GetInstance()->Stat(fileName, s); } - catch( eFSServices ) + catch (eFSServices) { return false; } - - return( s.mFileType == cFSStatArgs::TY_DIR ); + + return (s.mFileType == cFSStatArgs::TY_DIR); } -bool cFileUtil::IsRegularFile( const TSTRING& fileName ) +bool cFileUtil::IsRegularFile(const TSTRING& fileName) { cFSStatArgs s; try { - iFSServices::GetInstance()->Stat( fileName, s); + iFSServices::GetInstance()->Stat(fileName, s); } - catch( eFSServices ) + catch (eFSServices) { return false; } - return (s.mFileType == cFSStatArgs::TY_FILE ); + return (s.mFileType == cFSStatArgs::TY_FILE); } /////////////////////////////////////////////////////////////////////////////// @@ -140,7 +138,7 @@ bool cFileUtil::IsRegularFile( const TSTRING& fileName ) /////////////////////////////////////////////////////////////////////////////// bool cFileUtil::FileExists(const TSTRING& fileName) { - return((_taccess(fileName.c_str(), F_OK) == 0) && !cFileUtil::IsDir(fileName)); + return ((_taccess(fileName.c_str(), F_OK) == 0) && !cFileUtil::IsDir(fileName)); } /////////////////////////////////////////////////////////////////////////////// @@ -148,9 +146,9 @@ bool cFileUtil::FileExists(const TSTRING& fileName) /////////////////////////////////////////////////////////////////////////////// bool cFileUtil::FileReadable(const TSTRING& fileName) { - // TODO:BAM on Win32 systems, _taccess doesn't check DACL, + // TODO:BAM on Win32 systems, _taccess doesn't check DACL, // so all files are really readable - return( _taccess( fileName.c_str(), R_OK ) == 0 ); + return (_taccess(fileName.c_str(), R_OK) == 0); } /////////////////////////////////////////////////////////////////////////////// @@ -158,11 +156,11 @@ bool cFileUtil::FileReadable(const TSTRING& fileName) /////////////////////////////////////////////////////////////////////////////// bool cFileUtil::FileWritable(const TSTRING& fileName) { - // if the file does not exist, but could be + // if the file does not exist, but could be // created then return true if (_taccess(fileName.c_str(), F_OK) != 0) { - // After some other attempts to see if we could create + // After some other attempts to see if we could create // the file, it became easier to just to create the file // and check for failure. int fh; @@ -175,9 +173,9 @@ bool cFileUtil::FileWritable(const TSTRING& fileName) return true; } - else // file exists; make sure it is writable and not a dir + else // file exists; make sure it is writable and not a dir { - return((_taccess(fileName.c_str(), W_OK) == 0) && !cFileUtil::IsDir(fileName)); + return ((_taccess(fileName.c_str(), W_OK) == 0) && !cFileUtil::IsDir(fileName)); } } @@ -206,10 +204,15 @@ bool cFileUtil::BackupFile(const TSTRING& filename, bool printWarningOnFailure) // if this assert goes off, you didn't check that the file was writeable // before calling BackupFile(). ASSERT(false); - throw eFileWrite(filename, iFSServices::GetInstance()->GetErrString() ); + throw eFileWrite(filename, iFSServices::GetInstance()->GetErrString()); } +#if IS_DOS_DJGPP + TSTRING backup_filename = cDosPath::BackupName(cDosPath::AsNative(filename)); +#else TSTRING backup_filename = filename; +#endif + backup_filename += iFSServices::GetInstance()->GetStandardBackupExtension(); // remove the backup file if it exists. We ingore the return value from @@ -219,17 +222,16 @@ bool cFileUtil::BackupFile(const TSTRING& filename, bool printWarningOnFailure) // back up the file, preserving permissions and ownership, if possible if (cFileUtil::Copy(filename.c_str(), backup_filename.c_str()) == false) { - if (printWarningOnFailure && - iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL) + if (printWarningOnFailure && iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL) { TSTRING estr; - estr.assign(TSS_GetString( cUtil, util::STR_ERR2_BACKUP_FAILED1)); + estr.assign(TSS_GetString(cUtil, util::STR_ERR2_BACKUP_FAILED1)); estr.append(filename); - estr.append(TSS_GetString( cUtil, util::STR_ERR2_BACKUP_FAILED2)); + estr.append(TSS_GetString(cUtil, util::STR_ERR2_BACKUP_FAILED2)); estr.append(backup_filename); - estr.append(TSS_GetString( cUtil, util::STR_ERR2_BACKUP_FAILED3)); + estr.append(TSS_GetString(cUtil, util::STR_ERR2_BACKUP_FAILED3)); - cErrorReporter::PrintErrorMsg(eFileUtilBackup(estr, eError::NON_FATAL|eError::SUPRESS_THIRD_MSG)); + cErrorReporter::PrintErrorMsg(eFileUtilBackup(estr, eError::NON_FATAL | eError::SUPRESS_THIRD_MSG)); } } return true; @@ -237,19 +239,20 @@ bool cFileUtil::BackupFile(const TSTRING& filename, bool printWarningOnFailure) bool cFileUtil::Copy(const TSTRING& src_path, const TSTRING& dest_path) { -#if IS_UNIX - - enum { BUF_SIZE = 4096 }; + enum + { + BUF_SIZE = 4096 + }; int8 buf[BUF_SIZE]; - int nBytesRead; + int nBytesRead; cFile srcFile, destFile; srcFile.Open(src_path.c_str()); // Create destination file. We'll fix the permissions later. - destFile.Open(dest_path.c_str(), cFile::OPEN_WRITE|cFile::OPEN_CREATE); - - for (int i = srcFile.GetSize(); i > 0; ) + destFile.Open(dest_path.c_str(), cFile::OPEN_WRITE | cFile::OPEN_CREATE); + + for (int i = srcFile.GetSize(); i > 0;) { nBytesRead = srcFile.Read(buf, BUF_SIZE); destFile.Write(buf, nBytesRead); @@ -261,15 +264,11 @@ bool cFileUtil::Copy(const TSTRING& src_path, const TSTRING& dest_path) // restore permissions and ownership // don't worry if it fails. it's not mission-critical. - chmod( dest_path.c_str(), srcStat.st_mode ); - chown( dest_path.c_str(), srcStat.st_uid, srcStat.st_gid ); + chmod(dest_path.c_str(), srcStat.st_mode); + chown(dest_path.c_str(), srcStat.st_uid, srcStat.st_gid); srcFile.Close(); destFile.Close(); -#endif - return true; } - - diff --git a/src/util/fileutil.h b/src/util/fileutil.h index f0591fc..3272c84 100644 --- a/src/util/fileutil.h +++ b/src/util/fileutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -37,8 +37,8 @@ #include "core/error.h" -TSS_EXCEPTION( eFileUtil, eError ); -TSS_EXCEPTION( eFileUtilBackup, eFileUtil ); +TSS_EXCEPTION(eFileUtil, eError); +TSS_EXCEPTION(eFileUtilBackup, eFileUtil); //----------------------------------------------------------------------------- // cFileUtil @@ -54,24 +54,24 @@ class cFileUtil //------------------------------------------------------------------------- // File properties //------------------------------------------------------------------------- - - static void TestFileExists(const TSTRING& fileName); //throw eError(); + + static void TestFileExists(const TSTRING& fileName); //throw eError(); // tests whether or not the file exists; throws eError suitable for cTWUtil::PrintErrorMsg() - static void TestFileWritable(const TSTRING& fileName); //throw eError(); + static void TestFileWritable(const TSTRING& fileName); //throw eError(); // tests whether or not the named file can be written to; throws eError suitable for cTWUtil::PrintErrorMsg() - static void TestFileReadable(const TSTRING& fileName); //throw eError(); + static void TestFileReadable(const TSTRING& fileName); //throw eError(); // tests whether or not the named file can be read from; throws eError suitable for cTWUtil::PrintErrorMsg() - static bool FileExists(const TSTRING& fileName); - // tests whether or not the file exists - static bool FileWritable(const TSTRING& fileName); - // tests whether or not the named file can be written to - // if the file does not exist, but can be created this function will return true + static bool FileExists(const TSTRING& fileName); + // tests whether or not the file exists + static bool FileWritable(const TSTRING& fileName); + // tests whether or not the named file can be written to + // if the file does not exist, but can be created this function will return true static bool FileReadable(const TSTRING& fileName); - // tests whether or not the named file can be read from - static bool IsDir( const TSTRING& fileName ); - // returns true if file is a dir - static bool IsRegularFile( const TSTRING& fileName ); - // returns true if file is a regular file + // tests whether or not the named file can be read from + static bool IsDir(const TSTRING& fileName); + // returns true if file is a dir + static bool IsRegularFile(const TSTRING& fileName); + // returns true if file is a regular file //------------------------------------------------------------------------- // File backup mechanism @@ -83,14 +83,12 @@ class cFileUtil // An eFileWrite will be thrown if the file is not writable. // This is because we don't want to overwrite read-only files, which would happen // if we were just renamed the file to a backup filename. - + //------------------------------------------------------------------------- // File copy mechanism //------------------------------------------------------------------------- static bool Copy(const TSTRING& src, const TSTRING& dest); // throw eFile() // copies the file from src to dest, preserving permissions. - }; #endif //__FILEUTIL_H - diff --git a/src/util/miscutil.h b/src/util/miscutil.h index dd1f69d..dab4bda 100644 --- a/src/util/miscutil.h +++ b/src/util/miscutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -47,4 +47,3 @@ class cMiscUtil }; #endif //__MISCUTIL_H - diff --git a/src/util/stdutil.cpp b/src/util/stdutil.cpp index 7d53ebd..e0b3aba 100644 --- a/src/util/stdutil.cpp +++ b/src/util/stdutil.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,6 +36,3 @@ // #include "stdutil.h" - - -// eof: stdutil.cpp diff --git a/src/util/stdutil.h b/src/util/stdutil.h index 2189466..cd1fb73 100644 --- a/src/util/stdutil.h +++ b/src/util/stdutil.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -36,4 +36,3 @@ // #include "core/stdcore.h" - diff --git a/src/util/stringencoder.cpp b/src/util/stringencoder.cpp index 22d72a2..6b97ab0 100644 --- a/src/util/stringencoder.cpp +++ b/src/util/stringencoder.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -48,14 +48,14 @@ // cCharEncoder ////////////////////////////////////////////////////////////////////////////// -void cCharEncoder::EncodeChar( TSTRING::const_iterator& i, TSTRING& strToAppendTo ) +void cCharEncoder::EncodeChar(TSTRING::const_iterator& i, TSTRING& strToAppendTo) { - if( *i == mchEncodeMe ) + if (*i == mchEncodeMe) { strToAppendTo += mchEncoded1; strToAppendTo += mchEncoded2; } - else if( *i == mchEncoded1 ) + else if (*i == mchEncoded1) { strToAppendTo += mchEncoded1; strToAppendTo += mchEncoded1; @@ -66,86 +66,85 @@ void cCharEncoder::EncodeChar( TSTRING::const_iterator& i, TSTRING& strToAppendT } } -TCHAR cCharEncoder::DecodeChar( TSTRING::const_iterator& i, TSTRING::const_iterator& end ) +TCHAR cCharEncoder::DecodeChar(TSTRING::const_iterator& i, TSTRING::const_iterator& end) { - ASSERT( i != end ); + ASSERT(i != end); - if( *i == mchEncodeMe ) + if (*i == mchEncodeMe) { - ASSERT( false ); + ASSERT(false); return _T('\0'); } - else if( *i == mchEncoded1 ) + else if (*i == mchEncoded1) { - if( ++i == end ) + if (++i == end) { - ASSERT( false ); + ASSERT(false); return _T('\0'); } else { - if( *i == mchEncoded1 ) - return mchEncoded1 ; - else if( *i == mchEncoded2 ) - return mchEncodeMe ; + if (*i == mchEncoded1) + return mchEncoded1; + else if (*i == mchEncoded2) + return mchEncodeMe; else { - ASSERT( false ); + ASSERT(false); return _T('\0'); } } } else - return ( *i ); + return (*i); } ////////////////////////////////////////////////////////////////////////////// // cStringEncoder ////////////////////////////////////////////////////////////////////////////// -TSTRING& cStringEncoder::Encode( TSTRING& inAndOut ) +TSTRING& cStringEncoder::Encode(TSTRING& inAndOut) { TSTRING strOut; - Encode( inAndOut, strOut ); + Encode(inAndOut, strOut); inAndOut = strOut; return inAndOut; } -TSTRING& cStringEncoder::Encode( const TSTRING& in, TSTRING& out ) +TSTRING& cStringEncoder::Encode(const TSTRING& in, TSTRING& out) { out.erase(); // // assume that out will approximately be the size of in // - out.reserve( in.length() ); + out.reserve(in.length()); - for( TSTRING::const_iterator i = in.begin(); i != in.end(); i++ ) - ce.EncodeChar( i, out ); + for (TSTRING::const_iterator i = in.begin(); i != in.end(); ++i) + ce.EncodeChar(i, out); return out; } -TSTRING& cStringEncoder::Unencode( TSTRING& inAndOut ) +TSTRING& cStringEncoder::Unencode(TSTRING& inAndOut) { TSTRING strOut; - Unencode( inAndOut, strOut ); + Unencode(inAndOut, strOut); inAndOut = strOut; return inAndOut; } -TSTRING& cStringEncoder::Unencode( const TSTRING& in, TSTRING& out ) +TSTRING& cStringEncoder::Unencode(const TSTRING& in, TSTRING& out) { out.erase(); // // assume that out will approximately be the size of in // - out.reserve( in.length() ); + out.reserve(in.length()); TSTRING::const_iterator end = in.end(); - for( TSTRING::const_iterator i = in.begin(); i != end; i++ ) - out += ce.DecodeChar( i, end ); - + for (TSTRING::const_iterator i = in.begin(); i != end; ++i) + out += ce.DecodeChar(i, end); + return out; } - diff --git a/src/util/stringencoder.h b/src/util/stringencoder.h index 6eb419c..931378f 100644 --- a/src/util/stringencoder.h +++ b/src/util/stringencoder.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -58,16 +58,16 @@ class cCharEncoder { public: - cCharEncoder( TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2 ); + cCharEncoder(TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2); - void EncodeChar( TSTRING::const_iterator& i, TSTRING& strToAppendTo ); - TCHAR DecodeChar( TSTRING::const_iterator& i, TSTRING::const_iterator& end ); - TCHAR GetEncodeChar(); + void EncodeChar(TSTRING::const_iterator& i, TSTRING& strToAppendTo); + TCHAR DecodeChar(TSTRING::const_iterator& i, TSTRING::const_iterator& end); + TCHAR GetEncodeChar(); private: cCharEncoder(); - cCharEncoder( const cCharEncoder& ); - cCharEncoder& operator=( const cCharEncoder& ); + cCharEncoder(const cCharEncoder&); + cCharEncoder& operator=(const cCharEncoder&); TCHAR mchEncodeMe; TCHAR mchEncoded1; @@ -80,22 +80,22 @@ class cCharEncoder class cStringEncoder { public: - cStringEncoder( TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2 ); + cStringEncoder(TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2); - TSTRING& Encode( TSTRING& inAndOut ); - TSTRING& Encode( const TSTRING& in, TSTRING& out ); - // returns reference to out + TSTRING& Encode(TSTRING& inAndOut); + TSTRING& Encode(const TSTRING& in, TSTRING& out); + // returns reference to out - TSTRING& Unencode( TSTRING& inAndOut ); - TSTRING& Unencode( const TSTRING& in, TSTRING& out ); - // returns reference to out + TSTRING& Unencode(TSTRING& inAndOut); + TSTRING& Unencode(const TSTRING& in, TSTRING& out); + // returns reference to out - TCHAR GetEncodeChar(); + TCHAR GetEncodeChar(); private: cStringEncoder(); - cStringEncoder( const cStringEncoder& ); - cStringEncoder& operator=( const cStringEncoder& ); + cStringEncoder(const cStringEncoder&); + cStringEncoder& operator=(const cStringEncoder&); cCharEncoder ce; }; @@ -109,9 +109,10 @@ class cQuoteEncoder : public cStringEncoder { public: cQuoteEncoder(); + private: - cQuoteEncoder( const cQuoteEncoder& ); - cQuoteEncoder& operator=( const cQuoteEncoder& ); + cQuoteEncoder(const cQuoteEncoder&); + cQuoteEncoder& operator=(const cQuoteEncoder&); }; @@ -120,30 +121,28 @@ class cQuoteEncoder : public cStringEncoder //========================================================================= -inline cCharEncoder::cCharEncoder( TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2 ) - : mchEncodeMe( chEncodeMe ), mchEncoded1( chEncoded1 ), mchEncoded2( chEncoded2 ) +inline cCharEncoder::cCharEncoder(TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2) + : mchEncodeMe(chEncodeMe), mchEncoded1(chEncoded1), mchEncoded2(chEncoded2) { } -inline TCHAR cCharEncoder::GetEncodeChar() -{ - return mchEncodeMe; +inline TCHAR cCharEncoder::GetEncodeChar() +{ + return mchEncodeMe; } -inline cStringEncoder::cStringEncoder( TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2 ) - : ce( chEncodeMe, chEncoded1, chEncoded2 ) +inline cStringEncoder::cStringEncoder(TCHAR chEncodeMe, TCHAR chEncoded1, TCHAR chEncoded2) + : ce(chEncodeMe, chEncoded1, chEncoded2) { } -inline TCHAR cStringEncoder::GetEncodeChar() -{ - return ce.GetEncodeChar(); +inline TCHAR cStringEncoder::GetEncodeChar() +{ + return ce.GetEncodeChar(); } -inline cQuoteEncoder::cQuoteEncoder() - : cStringEncoder( _T('\"'), _T('\\'), _T('\"') ) +inline cQuoteEncoder::cQuoteEncoder() : cStringEncoder(_T('\"'), _T('\\'), _T('\"')) { } #endif //__STRINGENCODER_H - diff --git a/src/util/util.cpp b/src/util/util.cpp index 9ea5874..8b9d573 100644 --- a/src/util/util.cpp +++ b/src/util/util.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,12 +39,12 @@ #include "util.h" #include "utilerrors.h" -TSS_ImplementPackage( cUtil ) +TSS_ImplementPackage(cUtil) cUtil::cUtil() { - TSS_Dependency( cCore ); - TSS_REGISTER_PKG_ERRORS( util ) + TSS_Dependency(cCore); + TSS_REGISTER_PKG_ERRORS(util) } //----------------------------------------------------------------------------- @@ -56,19 +56,17 @@ cUtil::cUtil() #include "test/utx.h" -TSS_DeclareTestSuite( cDisplayEncoderTest ); -TSS_DeclareTestSuite( cCharEncoderTest ); +TSS_DeclareTestSuite(cDisplayEncoderTest); +TSS_DeclareTestSuite(cCharEncoderTest); // // Add the test suites to the package test suite // -TSS_BeginTestSuite( cUtil ) +TSS_BeginTestSuite(cUtil) - TSS_AddTestSuite( cDisplayEncoderTest ); - TSS_AddTestSuite( cCharEncoderTest ); + TSS_AddTestSuite(cDisplayEncoderTest); +TSS_AddTestSuite(cCharEncoderTest); -TSS_EndTestSuite( cUtil ) +TSS_EndTestSuite(cUtil) #endif // #ifdef TSS_TEST - -// eof: util.cpp diff --git a/src/util/util.h b/src/util/util.h index 20adbdd..be787d0 100644 --- a/src/util/util.h +++ b/src/util/util.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,16 +39,15 @@ #ifndef __UTIL_H #define __UTIL_H -#include "core/core.h" // for: cCore Strings +#include "core/core.h" // for: cCore Strings -TSS_BeginPackage( cUtil ) +TSS_BeginPackage(cUtil) TSS_DECLARE_STRINGTABLE; - public: - cUtil(); - -TSS_EndPackage( cUtil ) +public: +cUtil(); -#endif//__UTIL_H +TSS_EndPackage(cUtil) +#endif //__UTIL_H diff --git a/src/util/utilerrors.cpp b/src/util/utilerrors.cpp index 0427df2..1cceebc 100644 --- a/src/util/utilerrors.cpp +++ b/src/util/utilerrors.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -40,14 +40,14 @@ #include "fileutil.h" -TSS_BEGIN_ERROR_REGISTRATION( util ) +TSS_BEGIN_ERROR_REGISTRATION(util) // // FileUtil // -TSS_REGISTER_ERROR( eFileUtil(), _T("File Util Error.") ) -TSS_REGISTER_ERROR( eFileUtilBackup(), _T("File Backup Failed.") ) +TSS_REGISTER_ERROR(eFileUtil(), _T("File Util Error.")) +TSS_REGISTER_ERROR(eFileUtilBackup(), _T("File Backup Failed.")) TSS_END_ERROR_REGISTRATION() diff --git a/src/util/utilerrors.h b/src/util/utilerrors.h index 10aa2c6..501e71a 100644 --- a/src/util/utilerrors.h +++ b/src/util/utilerrors.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -41,7 +41,6 @@ #include "core/errortable.h" -TSS_DECLARE_ERROR_REGISTRATION( util ) - -#endif//__UTILERRORS_H +TSS_DECLARE_ERROR_REGISTRATION(util) +#endif //__UTILERRORS_H diff --git a/src/util/utilstrings.cpp b/src/util/utilstrings.cpp index 2c78e15..5baac79 100644 --- a/src/util/utilstrings.cpp +++ b/src/util/utilstrings.cpp @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,14 +39,11 @@ #include "utilstrings.h" -TSS_BeginStringtable( cUtil ) - - TSS_StringEntry( util::STR_ERR_BACKUP_FAILED, _T("File Backup Failed.") ), - TSS_StringEntry( util::STR_ERR2_BACKUP_FAILED1, _T("Error backing up \"") ), - TSS_StringEntry( util::STR_ERR2_BACKUP_FAILED2, _T("\" to \"") ), - TSS_StringEntry( util::STR_ERR2_BACKUP_FAILED3, _T("\".") ) - -TSS_EndStringtable( cUtil ) +TSS_BeginStringtable(cUtil) + TSS_StringEntry(util::STR_ERR_BACKUP_FAILED, _T("File Backup Failed.")), + TSS_StringEntry(util::STR_ERR2_BACKUP_FAILED1, _T("Error backing up \"")), + TSS_StringEntry(util::STR_ERR2_BACKUP_FAILED2, _T("\" to \"")), + TSS_StringEntry(util::STR_ERR2_BACKUP_FAILED3, _T("\".")) -// eof: utilstrings.cpp + TSS_EndStringtable(cUtil) diff --git a/src/util/utilstrings.h b/src/util/utilstrings.h index 0e37e21..46c2b9d 100644 --- a/src/util/utilstrings.h +++ b/src/util/utilstrings.h @@ -1,31 +1,31 @@ // // The developer of the original code and/or files is Tripwire, Inc. -// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire, +// Portions created by Tripwire, Inc. are copyright (C) 2000-2018 Tripwire, // Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights // reserved. -// +// // This program is free software. The contents of this file are subject // to the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. You may redistribute it and/or modify it // only in compliance with the GNU General Public License. -// +// // This program is distributed in the hope that it will be useful. // However, this program is distributed AS-IS WITHOUT ANY // WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS // FOR A PARTICULAR PURPOSE. Please see the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. -// +// // Nothing in the GNU General Public License or any other license to use // the code or files shall permit you to use Tripwire's trademarks, // service marks, or other intellectual property without Tripwire's // prior written consent. -// +// // If you have any questions, please contact Tripwire, Inc. at either // info@tripwire.org or www.tripwire.org. // @@ -39,18 +39,16 @@ #ifndef __UTILSTRINGS_H #define __UTILSTRINGS_H -#include "util.h" // for TSS_BeginStringIds +#include "util.h" // for TSS_BeginStringIds -TSS_BeginStringIds( util ) +TSS_BeginStringIds(util) - STR_ERR_BACKUP_FAILED, - STR_ERR2_BACKUP_FAILED1, - STR_ERR2_BACKUP_FAILED2, + STR_ERR_BACKUP_FAILED, + STR_ERR2_BACKUP_FAILED1, STR_ERR2_BACKUP_FAILED2, STR_ERR2_BACKUP_FAILED3 -TSS_EndStringIds( util ) - + TSS_EndStringIds(util) -#endif//__UTILSTRINGS_H +#endif //__UTILSTRINGS_H diff --git a/touchconfig.sh b/touchconfig.sh index 9e3fbb3..2b6c8db 100755 --- a/touchconfig.sh +++ b/touchconfig.sh @@ -4,5 +4,6 @@ # and insists they need to be regenerated, though they really don't. # This script bumps the timestamps on the right files in the right order, # such that they don't all match, and make can proceed on its way. -touch configure.in acinclude.m4 aclocal.m4 configure Makefile.am Makefile.in +touch configure.ac acinclude.m4 aclocal.m4 configure Makefile.am Makefile.in config.h.in +