.cproject
New file @@ -0,0 +1,82 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage"> <storageModule moduleId="org.eclipse.cdt.core.settings"> <cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1941555127"> <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1941555127" moduleId="org.eclipse.cdt.core.settings" name="Default"> <externalSettings/> <extensions> <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/> <extension id="org.eclipse.cdt.core.GNU_ELF" point="org.eclipse.cdt.core.BinaryParser"/> <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/> </extensions> </storageModule> <storageModule moduleId="cdtBuildSystem" version="4.0.0"> <configuration artifactName="${ProjName}" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1941555127" name="Default" parent="org.eclipse.cdt.build.core.emptycfg"> <folderInfo id="cdt.managedbuild.toolchain.gnu.base.1941555127.38772218" name="/" resourcePath=""> <toolChain id="cdt.managedbuild.toolchain.gnu.base.1610910832" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base"> <targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF;org.eclipse.cdt.core.GNU_ELF" id="cdt.managedbuild.target.gnu.platform.base.333980180" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/> <builder autoBuildTarget="" buildPath="${workspace_loc:/license-manager-cpp}/build/linux" enableAutoBuild="true" id="cdt.managedbuild.target.gnu.builder.base.516265988" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="cdt.managedbuild.target.gnu.builder.base"> <outputEntries> <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="outputPath" name=""/> </outputEntries> </builder> <tool id="cdt.managedbuild.tool.gnu.archiver.base.1063978701" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/> <tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1465609732" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base"> <option id="gnu.cpp.compiler.option.preprocessor.def.1664583179" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" valueType="definedSymbols"> <listOptionValue builtIn="false" value="__GXX_EXPERIMENTAL_CXX0X__"/> </option> <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.18539696" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.compiler.base.589770174" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base"> <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1441923396" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/> </tool> <tool id="cdt.managedbuild.tool.gnu.c.linker.base.1466986479" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/> <tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.233385682" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base"> <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1900932213" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input"> <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/> <additionalInput kind="additionalinput" paths="$(LIBS)"/> </inputType> </tool> <tool id="cdt.managedbuild.tool.gnu.assembler.base.1674253564" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base"> <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1912634158" superClass="cdt.managedbuild.tool.gnu.assembler.input"/> </tool> </toolChain> </folderInfo> <sourceEntries> <entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/> <entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="test"/> </sourceEntries> </configuration> </storageModule> <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/> </cconfiguration> </storageModule> <storageModule moduleId="cdtBuildSystem" version="4.0.0"> <project id="license-manager-cpp.null.937270172" name="license-manager-cpp"/> </storageModule> <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/> <storageModule moduleId="scannerConfiguration"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> <scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1941555127;cdt.managedbuild.toolchain.gnu.base.1941555127.38772218;cdt.managedbuild.tool.gnu.cpp.compiler.base.1465609732;cdt.managedbuild.tool.gnu.cpp.compiler.input.18539696"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> </scannerConfigBuildInfo> <scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1941555127;cdt.managedbuild.toolchain.gnu.base.1941555127.38772218;cdt.managedbuild.tool.gnu.c.compiler.base.589770174;cdt.managedbuild.tool.gnu.c.compiler.input.1441923396"> <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/> </scannerConfigBuildInfo> </storageModule> <storageModule moduleId="refreshScope" versionNumber="2"> <configuration configurationName="Default"> <resource resourceType="FOLDER" workspacePath="/license-manager-cpp/build/linux"/> </configuration> </storageModule> <storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"/> <storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"> <doc-comment-owner id="org.eclipse.cdt.ui.doxygen"> <path value=""/> </doc-comment-owner> </storageModule> </cproject> .gitignore
New file @@ -0,0 +1,14 @@ # Compiled Object files *.slo *.lo *.o # Compiled Dynamic libraries *.so *.dylib # Compiled Static libraries *.lai *.la *.a /Makefile .project
New file @@ -0,0 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>license-manager-cpp</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name> <triggers>full,incremental,</triggers> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.cdt.core.cnature</nature> <nature>org.eclipse.cdt.core.ccnature</nature> <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature> <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature> </natures> </projectDescription> .settings/language.settings.xml
New file @@ -0,0 +1,15 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <project> <configuration id="cdt.managedbuild.toolchain.gnu.base.1941555127" name="Default"> <extension point="org.eclipse.cdt.core.LanguageSettingsProvider"> <provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/> <provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/> <provider copy-of="extension" id="org.eclipse.cdt.managedbuilder.core.GCCBuildCommandParser"/> <provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="true" env-hash="-1162336436791480065" id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD --std=c++11 "${INPUTS}""> <language-scope id="org.eclipse.cdt.core.gcc"/> <language-scope id="org.eclipse.cdt.core.g++"/> </provider> <provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/> </extension> </configuration> </project> .settings/org.eclipse.cdt.codan.core.prefs
New file @@ -0,0 +1,67 @@ eclipse.preferences.version=1 org.eclipse.cdt.codan.checkers.errnoreturn=Warning org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} org.eclipse.cdt.codan.checkers.errreturnvalue=Error org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.checkers.noreturn=Error org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=Error org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=Error org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>false,empty_case_param\=>false} org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=Error org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=Warning org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.InvalidArguments=Error org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=Error org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=Error org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=Error org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.OverloadProblem=Error org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=Error org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=Error org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} CMakeLists.txt
New file @@ -0,0 +1,135 @@ cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR) #version variables, major and minor must be 1 character only SET(LICENSECC_MAJOR_VERSION 1) SET(LICENSECC_MINOR_VERSION 0) SET(LICENSECC_PATCH_VERSION 0 CACHE STRING "License++ patch version string") SET(LICENSECC_INT_VERSION "${LICENSECC_MAJOR_VERSION}${LICENSECC_MINOR_VERSION}${LICENSECC_PATCH_VERSION}") SET(LICENSECC_VERSION "${LICENSECC_MAJOR_VERSION}.${LICENSECC_MINOR_VERSION}.${LICENSECC_PATCH_VERSION}") SET(LICENSECC_SHORT_LICENSE "BSD Software License") # add this options before PROJECT keyword SET(CMAKE_DISABLE_SOURCE_CHANGES OFF) SET(CMAKE_DISABLE_IN_SOURCE_BUILD ON) project (license++ C CXX) SET(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "CMake verbose" FORCE) SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) if(WIN32) SET(PLATFORM_LIBS "") if(CMAKE_CL_64) SET(CMAKE_EXE_LINKER_FLAGS "/machine:X64 /INCREMENTAL:NO" CACHE STRING "Linker flags") endif(CMAKE_CL_64) SET(CMAKE_FIND_LIBRARY_SUFFIXES .lib ) #${CMAKE_FIND_LIBRARY_SUFFIXES} set_property(DIRECTORY PROPERTY COMPILE_DEFINITIONS_DEBUG _CRT_SECURE_NO_WARNINGS) else(WIN32) SET(PLATFORM_LIBS "m") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pipe -fmessage-length=0 -std=c++11 -Wall -Wuninitialized -fPIC") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pipe -fmessage-length=0 -Wall -Wuninitialized -fPIC") SET(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -pipe" CACHE INTERNAL "Linker flags") SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS} -Wl,--strip-all") #SET(CMAKE_FIND_LIBRARY_SUFFIXES .a) #.so for dynamic libraries #you need to "force" the change in cmake_install_prefix after the project keyword IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) SET(CMAKE_INSTALL_PREFIX "/usr/local" CACHE PATH "Install path prefix" FORCE) ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) endif(WIN32) if(CMAKE_SIZEOF_VOID_P EQUAL 8) SET(HAVE_64BIT_SIZE_T 1) else(CMAKE_SIZEOF_VOID_P EQUAL 8) SET(HAVE_64BIT_SIZE_T 0) endif(CMAKE_SIZEOF_VOID_P EQUAL 8) set_property(DIRECTORY PROPERTY COMPILE_DEFINITIONS_DEBUG _DEBUG) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/build/modules/") #find_package(CryptoPP REQUIRED) #include_directories(${CRYPTOPP_INCLUDE_DIRS}) #link_directories ( ${Boost_LIBRARY_DIRS} ) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) list(APPEND EXTERNAL_LIBS ${OPENSSL_CRYPTO_LIBRARY}) #link_directories ( ${OPENSSL_LIBRARIES} ) SET(Boost_USE_STATIC_LIBS ON) # static runtime requires /MT #SET(Boost_USE_MULTITHREADED ON) #SET(Boost_USE_STATIC_RUNTIME OFF) #find_package(Boost COMPONENTS thread date_time program_options filesystem system regex unit_test_framework) find_package(Boost COMPONENTS date_time program_options filesystem system unit_test_framework) #include_directories(${Boost_INCLUDE_DIRS}) #link_directories ( ${Boost_LIBRARY_DIRS} ) FIND_PACKAGE(Doxygen) IF (DOXYGEN_FOUND) SET(DOXYGEN_INPUT ${CMAKE_BINARY_DIR}/doc/Doxyfile) SET(DOXYGEN_OUTPUT ${CMAKE_BINARY_DIR}/doc/doxy_output) configure_file ( "doc/Doxyfile.in" "doc/Doxyfile" ) ADD_CUSTOM_COMMAND( OUTPUT ${DOXYGEN_OUTPUT} COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..." COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT} COMMAND ${CMAKE_COMMAND} -E echo "Done." WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${DOXYGEN_INPUT}) ADD_CUSTOM_TARGET(apidoc ALL DEPENDS ${DOXYGEN_OUTPUT}) ADD_CUSTOM_TARGET(apidoc_forced COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..." COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT} COMMAND ${CMAKE_COMMAND} -E echo "Done." WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) ENDIF (DOXYGEN_FOUND) configure_file ( "src/build_properties.h.in" "${CMAKE_BINARY_DIR}/build_properties.h" ) #include build directory to find build_properties.h include_directories(${CMAKE_BINARY_DIR}) add_subdirectory(src) #test are done with boost_tests:disable them if boost not found. IF(Boost_FOUND) ENABLE_TESTING() INCLUDE(CTest) IF(BUILD_TESTING) SET(BUILDNAME "${BUILDNAME}" CACHE STRING "Name of build on the dashboard") MARK_AS_ADVANCED(BUILDNAME) ENDIF(BUILD_TESTING) add_subdirectory(test) ENDIF(Boost_FOUND) #include(build/modules/CmakeDebugVariables.txt) message("") message( STATUS "C compiler: " ${CMAKE_C_COMPILER}) message( STATUS "C compiler flags: " ${CMAKE_C_FLAGS}) if(CMAKE_BUILD_TYPE) message( STATUS "Build type: " ${CMAKE_BUILD_TYPE}) endif(CMAKE_BUILD_TYPE) message( STATUS "Install prefix: " ${CMAKE_INSTALL_PREFIX}) IF(Boost_FOUND) message( STATUS "Boost found: running a complete build.") ELSE(Boost_FOUND) message( STATUS "Boost not found: tests, pc-identifier will be skipped") ENDIF(Boost_FOUND) if(DOXYGEN_FOUND) message(STATUS "Doxygen: " ${DOXYGEN_EXECUTABLE}) else(DOXYGEN_FOUND) message(STATUS "Doxygen: not found.") endif(DOXYGEN_FOUND) LICENSE
@@ -1,4 +1,4 @@ Copyright (c) 2014, Copyright (c) 2014, rillf All rights reserved. Redistribution and use in source and binary forms, with or without README.md
@@ -1,4 +1,14 @@ open-license-manager ==================== license-manager-cpp =================== An open license manager written in c++ A lincense manager written in C++ Linux =================== apt-get install libcrypto++dev (version 5.6.1) libboost-dev libboost-filesystem-dev libboost-program-options-dev libboost-test-dev libboost-date-time-dev libssl-dev? openssl genrsa -out src/license-generator/privkey.pem 2048 build/linux/.gitignore
New file @@ -0,0 +1,13 @@ /CMakeFiles /src /test /Testing /CMakeCache.txt /DartConfiguration.tcl /lib /cmake_install.cmake /CTestTestfile.cmake /Makefile /doc /nohup.out /build_properties.h build/modules/CmakeDebugVariables.txt
New file @@ -0,0 +1,152 @@ # ------------------------- Begin Generic CMake Variable Logging ------------------ # /* C++ comment style not allowed */ # if you are building in-source, this is the same as CMAKE_SOURCE_DIR, otherwise # this is the top level directory of your build tree MESSAGE( STATUS "CMAKE_BINARY_DIR: " ${CMAKE_BINARY_DIR} ) # if you are building in-source, this is the same as CMAKE_CURRENT_SOURCE_DIR, otherwise this # is the directory where the compiled or generated files from the current CMakeLists.txt will go to MESSAGE( STATUS "CMAKE_CURRENT_BINARY_DIR: " ${CMAKE_CURRENT_BINARY_DIR} ) # this is the directory, from which cmake was started, i.e. the top level source directory MESSAGE( STATUS "CMAKE_SOURCE_DIR: " ${CMAKE_SOURCE_DIR} ) # this is the directory where the currently processed CMakeLists.txt is located in MESSAGE( STATUS "CMAKE_CURRENT_SOURCE_DIR: " ${CMAKE_CURRENT_SOURCE_DIR} ) # contains the full path to the top level directory of your build tree MESSAGE( STATUS "PROJECT_BINARY_DIR: " ${PROJECT_BINARY_DIR} ) # contains the full path to the root of your project source directory, # i.e. to the nearest directory where CMakeLists.txt contains the PROJECT() command MESSAGE( STATUS "PROJECT_SOURCE_DIR: " ${PROJECT_SOURCE_DIR} ) # set this variable to specify a common place where CMake should put all executable files # (instead of CMAKE_CURRENT_BINARY_DIR) MESSAGE( STATUS "EXECUTABLE_OUTPUT_PATH: " ${EXECUTABLE_OUTPUT_PATH} ) # set this variable to specify a common place where CMake should put all libraries # (instead of CMAKE_CURRENT_BINARY_DIR) MESSAGE( STATUS "LIBRARY_OUTPUT_PATH: " ${LIBRARY_OUTPUT_PATH} ) # tell CMake to search first in directories listed in CMAKE_MODULE_PATH # when you use FIND_PACKAGE() or INCLUDE() MESSAGE( STATUS "CMAKE_MODULE_PATH: " ${CMAKE_MODULE_PATH} ) # this is the complete path of the cmake which runs currently (e.g. /usr/local/bin/cmake) MESSAGE( STATUS "CMAKE_COMMAND: " ${CMAKE_COMMAND} ) # this is the CMake installation directory MESSAGE( STATUS "CMAKE_ROOT: " ${CMAKE_ROOT} ) # this is the filename including the complete path of the file where this variable is used. MESSAGE( STATUS "CMAKE_CURRENT_LIST_FILE: " ${CMAKE_CURRENT_LIST_FILE} ) # this is linenumber where the variable is used MESSAGE( STATUS "CMAKE_CURRENT_LIST_LINE: " ${CMAKE_CURRENT_LIST_LINE} ) # this is used when searching for include files e.g. using the FIND_PATH() command. MESSAGE( STATUS "CMAKE_INCLUDE_PATH: " ${CMAKE_INCLUDE_PATH} ) # this is used when searching for libraries e.g. using the FIND_LIBRARY() command. MESSAGE( STATUS "CMAKE_LIBRARY_PATH: " ${CMAKE_LIBRARY_PATH} ) # the complete system name, e.g. "Linux-2.4.22", "FreeBSD-5.4-RELEASE" or "Windows 5.1" MESSAGE( STATUS "CMAKE_SYSTEM: " ${CMAKE_SYSTEM} ) # the short system name, e.g. "Linux", "FreeBSD" or "Windows" MESSAGE( STATUS "CMAKE_SYSTEM_NAME: " ${CMAKE_SYSTEM_NAME} ) # only the version part of CMAKE_SYSTEM MESSAGE( STATUS "CMAKE_SYSTEM_VERSION: " ${CMAKE_SYSTEM_VERSION} ) # the processor name (e.g. "Intel(R) Pentium(R) M processor 2.00GHz") MESSAGE( STATUS "CMAKE_SYSTEM_PROCESSOR: " ${CMAKE_SYSTEM_PROCESSOR} ) # is TRUE on all UNIX-like OS's, including Apple OS X and CygWin MESSAGE( STATUS "UNIX: " ${UNIX} ) # is TRUE on Windows, including CygWin MESSAGE( STATUS "WIN32: " ${WIN32} ) # is TRUE on Apple OS X MESSAGE( STATUS "APPLE: " ${APPLE} ) # is TRUE when using the MinGW compiler in Windows MESSAGE( STATUS "MINGW: " ${MINGW} ) # is TRUE on Windows when using the CygWin version of cmake MESSAGE( STATUS "CYGWIN: " ${CYGWIN} ) # is TRUE on Windows when using a Borland compiler MESSAGE( STATUS "BORLAND: " ${BORLAND} ) # Microsoft compiler MESSAGE( STATUS "MSVC: " ${MSVC} ) MESSAGE( STATUS "MSVC_IDE: " ${MSVC_IDE} ) MESSAGE( STATUS "MSVC60: " ${MSVC60} ) MESSAGE( STATUS "MSVC70: " ${MSVC70} ) MESSAGE( STATUS "MSVC71: " ${MSVC71} ) MESSAGE( STATUS "MSVC80: " ${MSVC80} ) MESSAGE( STATUS "CMAKE_COMPILER_2005: " ${CMAKE_COMPILER_2005} ) # set this to true if you don't want to rebuild the object files if the rules have changed, # but not the actual source files or headers (e.g. if you changed the some compiler switches) MESSAGE( STATUS "CMAKE_SKIP_RULE_DEPENDENCY: " ${CMAKE_SKIP_RULE_DEPENDENCY} ) # since CMake 2.1 the install rule depends on all, i.e. everything will be built before installing. # If you don't like this, set this one to true. MESSAGE( STATUS "CMAKE_SKIP_INSTALL_ALL_DEPENDENCY: " ${CMAKE_SKIP_INSTALL_ALL_DEPENDENCY} ) # If set, runtime paths are not added when using shared libraries. Default it is set to OFF MESSAGE( STATUS "CMAKE_SKIP_RPATH: " ${CMAKE_SKIP_RPATH} ) # set this to true if you are using makefiles and want to see the full compile and link # commands instead of only the shortened ones MESSAGE( STATUS "CMAKE_VERBOSE_MAKEFILE: " ${CMAKE_VERBOSE_MAKEFILE} ) # this will cause CMake to not put in the rules that re-run CMake. This might be useful if # you want to use the generated build files on another machine. MESSAGE( STATUS "CMAKE_SUPPRESS_REGENERATION: " ${CMAKE_SUPPRESS_REGENERATION} ) # A simple way to get switches to the compiler is to use ADD_DEFINITIONS(). # But there are also two variables exactly for this purpose: # the compiler flags for compiling C sources MESSAGE( STATUS "CMAKE_C_FLAGS: " ${CMAKE_C_FLAGS} ) # the compiler flags for compiling C++ sources MESSAGE( STATUS "CMAKE_CXX_FLAGS: " ${CMAKE_CXX_FLAGS} ) # Choose the type of build. Example: SET(CMAKE_BUILD_TYPE Debug) MESSAGE( STATUS "CMAKE_BUILD_TYPE: " ${CMAKE_BUILD_TYPE} ) # if this is set to ON, then all libraries are built as shared libraries by default. MESSAGE( STATUS "BUILD_SHARED_LIBS: " ${BUILD_SHARED_LIBS} ) # the compiler used for C files MESSAGE( STATUS "CMAKE_C_COMPILER: " ${CMAKE_C_COMPILER} ) # the compiler used for C++ files MESSAGE( STATUS "CMAKE_CXX_COMPILER: " ${CMAKE_CXX_COMPILER} ) # if the compiler is a variant of gcc, this should be set to 1 MESSAGE( STATUS "CMAKE_COMPILER_IS_GNUCC: " ${CMAKE_COMPILER_IS_GNUCC} ) # if the compiler is a variant of g++, this should be set to 1 MESSAGE( STATUS "CMAKE_COMPILER_IS_GNUCXX : " ${CMAKE_COMPILER_IS_GNUCXX} ) # the tools for creating libraries MESSAGE( STATUS "CMAKE_AR: " ${CMAKE_AR} ) MESSAGE( STATUS "CMAKE_RANLIB: " ${CMAKE_RANLIB} ) # #MESSAGE( STATUS ": " ${} ) # ------------------------- End of Generic CMake Variable Logging ------------------ build/modules/FindCryptoPP.cmake
New file @@ -0,0 +1,109 @@ # Module for locating the Crypto++ encryption library. # # Customizable variables: # CRYPTOPP_ROOT_DIR # This variable points to the CryptoPP root directory. On Windows the # library location typically will have to be provided explicitly using the # -D command-line option. The directory should include the include/cryptopp, # lib and/or bin sub-directories. # # Read-only variables: # CRYPTOPP_FOUND # Indicates whether the library has been found. # # CRYPTOPP_INCLUDE_DIRS # Points to the CryptoPP include directory. # # CRYPTOPP_LIBRARIES # Points to the CryptoPP libraries that should be passed to # target_link_libararies. # # # Copyright (c) 2012 Sergiu Dotenco # # 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 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. INCLUDE (FindPackageHandleStandardArgs) FIND_PATH (CRYPTOPP_ROOT_DIR NAMES cryptopp/cryptlib.h include/cryptopp/cryptlib.h PATHS ENV CRYPTOPPROOT DOC "CryptoPP root directory") # Re-use the previous path: FIND_PATH (CRYPTOPP_INCLUDE_DIR NAMES cryptopp/cryptlib.h HINTS ${CRYPTOPP_ROOT_DIR} PATH_SUFFIXES include DOC "CryptoPP include directory") FIND_LIBRARY (CRYPTOPP_LIBRARY_DEBUG NAMES cryptlibd cryptoppd HINTS ${CRYPTOPP_ROOT_DIR} PATH_SUFFIXES lib DOC "CryptoPP debug library") FIND_LIBRARY (CRYPTOPP_LIBRARY_RELEASE NAMES cryptlib cryptopp HINTS ${CRYPTOPP_ROOT_DIR} PATH_SUFFIXES lib DOC "CryptoPP release library") IF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) SET (CRYPTOPP_LIBRARY optimized ${CRYPTOPP_LIBRARY_RELEASE} debug ${CRYPTOPP_LIBRARY_DEBUG} CACHE DOC "CryptoPP library") ELSEIF (CRYPTOPP_LIBRARY_RELEASE) SET (CRYPTOPP_LIBRARY ${CRYPTOPP_LIBRARY_RELEASE} CACHE DOC "CryptoPP library") ENDIF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) IF (CRYPTOPP_INCLUDE_DIR) SET (_CRYPTOPP_VERSION_HEADER ${CRYPTOPP_INCLUDE_DIR}/cryptopp/config.h) IF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) FILE (STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION_TMP REGEX "^#define CRYPTOPP_VERSION[ \t]+[0-9]+$") STRING (REGEX REPLACE "^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION_TMP ${_CRYPTOPP_VERSION_TMP}) STRING (REGEX REPLACE "([0-9]+)[0-9][0-9]" "\\1" CRYPTOPP_VERSION_MAJOR ${_CRYPTOPP_VERSION_TMP}) STRING (REGEX REPLACE "[0-9]([0-9])[0-9]" "\\1" CRYPTOPP_VERSION_MINOR ${_CRYPTOPP_VERSION_TMP}) STRING (REGEX REPLACE "[0-9][0-9]([0-9])" "\\1" CRYPTOPP_VERSION_PATCH ${_CRYPTOPP_VERSION_TMP}) SET (CRYPTOPP_VERSION_COUNT 3) SET (CRYPTOPP_VERSION ${CRYPTOPP_VERSION_MAJOR}.${CRYPTOPP_VERSION_MINOR}.${CRYPTOPP_VERSION_PATCH}) ENDIF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) ENDIF (CRYPTOPP_INCLUDE_DIR) SET (CRYPTOPP_INCLUDE_DIRS ${CRYPTOPP_INCLUDE_DIR}) SET (CRYPTOPP_LIBRARIES ${CRYPTOPP_LIBRARY}) MARK_AS_ADVANCED (CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY CRYPTOPP_LIBRARY_DEBUG CRYPTOPP_LIBRARY_RELEASE) FIND_PACKAGE_HANDLE_STANDARD_ARGS (CryptoPP REQUIRED_VARS CRYPTOPP_ROOT_DIR CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY VERSION_VAR CRYPTOPP_VERSION) doc/Doxyfile.in
New file @@ -0,0 +1,1904 @@ # Doxyfile 1.8.4 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed # in front of the TAG it is preceding . # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = license++ # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = ${LICENSE_MAN_VERSION} # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = ${DOXYGEN_OUTPUT} # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Latvian, Lithuanian, Norwegian, Macedonian, # Persian, Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, # Slovak, Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = YES # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. Note that you specify absolute paths here, but also # relative paths, which will be relative from the directory where doxygen is # started. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, # and language is one of the parsers supported by doxygen: IDL, Java, # Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, # C++. For instance to make doxygen treat .inc files as Fortran files (default # is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note # that for custom extensions you also need to set FILE_PATTERNS otherwise the # files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by by putting a % sign in front of the word # or globally by setting AUTOLINK_SUPPORT to NO. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES (the # default) will make doxygen replace the get and set methods by a property in # the documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields or simple typedef fields will be shown # inline in the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO (the default), structs, classes, and unions are shown on a separate # page (for HTML and Man pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can # be an expensive process and often the same symbol appear multiple times in # the code, doxygen keeps a cache of pre-resolved symbols. If the cache is too # small doxygen will become slower. If the cache is too large, memory is wasted. # The cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid # range is 0..9, the default is 0, corresponding to a cache size of 2^16 = 65536 # symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES all members with package or internal # scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = YES # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = NO # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = NO # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if section-label ... \endif # and \cond section-label ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command <command> <input-file>, where <command> is the value of # the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. Do not use # file names with spaces, bibtex cannot handle them. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = /usbpp.cpp \ /usbpp.h # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.h \ *.cpp \ *.cc \ *.hpp \ *.dox \ *.c++ \ *.cxx \ *.h++ \ *.hh # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = YES # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = *.moc.* \ moc* \ *.all_cpp.* \ *unload.* \ */test/* \ */tests/* # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command <filter> <input-file>, where <filter> # is the value of the INPUT_FILTER tag, and <input-file> is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be ignored. # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = # If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C, C++ and Fortran comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = K #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = ./html/ # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = ${CMAKE_SOURCE_DIR}/doc/header.html # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = ${CMAKE_SOURCE_DIR}/doc/footer.html # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If left blank doxygen will # generate a default style sheet. Note that it is recommended to use # HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this # tag will in the future become obsolete. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify an additional # user-defined cascading style sheet that is included after the standard # style sheets created by doxygen. Using this option one can overrule # certain style aspects. This is preferred over using HTML_STYLESHEET # since it does not replace the standard style sheet and is therefor more # robust against future updates. Doxygen will copy the style sheet file to # the output directory. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of # entries shown in the various tree structured indices initially; the user # can expand and collapse entries dynamically later on. Doxygen will expand # the tree to such a level that at most the specified number of entries are # visible (unless a fully collapsed tree already exceeds this amount). # So setting the number of entries 1 will produce a full collapsed tree by # default. 0 is a special value representing an infinite number of entries # and will result in a full expanded tree by default. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely # identify the documentation publisher. This should be a reverse domain-name # style string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters"> # Qt Help Project / Custom Filters</a>. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes"> # Qt Help Project / Filter Attributes</a>. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and # SVG. The default value is HTML-CSS, which is slower, but has the best # compatibility. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript # pieces of code that will be used on startup of the MathJax code. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. # There are two flavours of web server based search depending on the # EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for # searching and an index file used by the script. When EXTERNAL_SEARCH is # enabled the indexing and searching needs to be provided by external tools. # See the manual for details. SERVER_BASED_SEARCH = NO # When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP # script for searching. Instead the search results are written to an XML file # which needs to be processed by an external indexer. Doxygen will invoke an # external search engine pointed to by the SEARCHENGINE_URL option to obtain # the search results. Doxygen ships with an example indexer (doxyindexer) and # search engine (doxysearch.cgi) which are based on the open source search # engine library Xapian. See the manual for configuration details. EXTERNAL_SEARCH = NO # The SEARCHENGINE_URL should point to a search engine hosted by a web server # which will returned the search results when EXTERNAL_SEARCH is enabled. # Doxygen ships with an example search engine (doxysearch) which is based on # the open source search engine library Xapian. See the manual for configuration # details. SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the # SEARCHDATA_FILE tag the name of this file can be specified. SEARCHDATA_FILE = searchdata.xml # When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the # EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is # useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple # projects and redirect the results back to the right project. EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are # all added to the same external search index. Each project needs to have a # unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id # of to a relative location where the documentation can be found. # The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4 will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # The LATEX_EXTRA_FILES tag can be used to specify one or more extra images # or other source files which should be copied to the LaTeX output directory. # Note that the files will be copied as-is; there are no commands or markers # available. LATEX_EXTRA_FILES = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .kde3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = YES #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options related to the DOCBOOK output #--------------------------------------------------------------------------- # If the GENERATE_DOCBOOK tag is set to YES Doxygen will generate DOCBOOK files # that can be used to generate PDF. GENERATE_DOCBOOK = NO # The DOCBOOK_OUTPUT tag is used to specify where the DOCBOOK pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be put in # front of it. If left blank docbook will be used as the default path. DOCBOOK_OUTPUT = docbook #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = __cplusplus # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = NO # If the EXTERNAL_PAGES tag is set to YES all external pages will be listed # in the related pages index. If set to NO, only the current project's # pages will be listed. EXTERNAL_PAGES = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = NO # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = YES # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 0 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # manageable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES doc/footer.html
doc/header.html
src/CMakeLists.txt
New file @@ -0,0 +1,9 @@ add_subdirectory("bootstrap") add_subdirectory("library") IF(Boost_FOUND) add_subdirectory("pc-identifier") add_subdirectory("license-generator") ENDIF(Boost_FOUND) src/bootstrap/CMakeLists.txt
New file @@ -0,0 +1,32 @@ add_executable( bootstrap bootstrap.cpp ) SET_TARGET_PROPERTIES(bootstrap PROPERTIES LINK_SEARCH_START_STATIC ON) SET_TARGET_PROPERTIES(bootstrap PROPERTIES LINK_SEARCH_END_STATIC OFF) target_link_libraries( bootstrap ${EXTERNAL_LIBS} ) # add the command to generate the source code add_custom_command ( OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/../license-generator/private-key.h" "${CMAKE_CURRENT_SOURCE_DIR}/../library/base/public-key.h" COMMAND bootstrap "${CMAKE_CURRENT_SOURCE_DIR}/../license-generator/private-key.h" "${CMAKE_CURRENT_SOURCE_DIR}/../library/base/public-key.h" DEPENDS bootstrap ) add_custom_target(private_key DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/../license-generator/private-key.h") add_custom_target(public_key DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/../library/base/public-key.h") # add the command to generate the source code #add_custom_command ( # OUTPUT "${CMAKE_BINARY_DIR}/public-key.h" # COMMAND bootstrap derive_public "${CMAKE_CURRENT_SOURCE_DIR}/../license-generator/private-key.h" "${CMAKE_BINARY_DIR}/public-key.h" # DEPENDS bootstrap private_key #) #add_custom_target(public_key DEPENDS "${CMAKE_BINARY_DIR}/public-key.h") src/bootstrap/bootstrap.cpp
New file @@ -0,0 +1,110 @@ /* * boostrap.c * * Created on: Apr 5, 2014 * Author: devel */ #include <string> #include <iostream> #include <build_properties.h> #include <openssl/rsa.h> #include <openssl/pem.h> const int kBits = 1024; const int kExp = 65537; using namespace std; std::string replaceAll(std::string subject, const std::string& search, const std::string& replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } /* * TODO: a large security bug here. PEM format included into * the executable can easily replaced thanks to its headers and * footers. Use a binary format instead * http://www.openssl.org/docs/crypto/d2i_X509.html * http://www.openssl.org/docs/crypto/d2i_RSAPublicKey.html * */ void writePublicRSAHeader(const std::string& public_fname, RSA* rsa,int random) { /* To get the C-string PEM form: */ //BIO bio_private* = BIO_new_file(const char *filename, "w") BIO* bio_private = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(bio_private, rsa); int keylen = BIO_pending(bio_private); char* pem_key = (char*) (calloc(keylen + 1, 1)); /* Null-terminate */ BIO_read(bio_private, pem_key, keylen); std::string dest = replaceAll(string(pem_key), string("\n"), string("\" \\\n\"")); FILE* fp = fopen(public_fname.c_str(), "w"); fprintf(fp, "//file generated by bootstrap.c, do not edit.\n\n"); fprintf(fp, "#ifndef PUBLIC_KEY_H_\n#define PUBLIC_KEY_H_\n"); fprintf(fp, "#define PUBLIC_KEY \"%s\";\n", dest.c_str()); fprintf(fp, "#define SHARED_RANDOM %d;\n", abs(random)); fprintf(fp, "#endif\n"); fclose(fp); BIO_free_all(bio_private); free(pem_key); } void writePrivateRSAHeader(const std::string& private_fname, RSA* rsa) { /* To get the C-string PEM form: */ //BIO bio_private* = BIO_new_file(const char *filename, "w") BIO* bio_private = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPrivateKey(bio_private, rsa, NULL, NULL, 0, NULL, NULL); int keylen = BIO_pending(bio_private); char* pem_key = (char*) (calloc(keylen + 1, 1)); /* Null-terminate */ BIO_read(bio_private, pem_key, keylen); std::string dest = replaceAll(string(pem_key), string("\n"), string("\\n\" \\\n\"")); FILE* fp = fopen(private_fname.c_str(), "w"); fprintf(fp, "//file generated by bootstrap.c, do not edit.\n\n"); fprintf(fp, "#ifndef PRIVATE_KEY_H_\n#define PRIVATE_KEY_H_\n"); fprintf(fp, "#define PRIVATE_KEY \"%s\";\n", dest.c_str()); fprintf(fp, "#endif\n"); fclose(fp); BIO_free_all(bio_private); free(pem_key); } void generatePk(std::string private_fname,string public_fname) { RSA *rsa = RSA_generate_key(kBits, kExp, 0, 0); srand(time(NULL)); /* seed random number generator */ int random=rand(); /* To get the C-string PEM form: */ //BIO bio_private* = BIO_new_file(const char *filename, "w") writePrivateRSAHeader(private_fname, rsa); writePublicRSAHeader(public_fname, rsa, random); RSA_free(rsa); } void print_usage() { printf("usage: bootstrap private-fname public-fname\n"); } int main(int argc, char** argv) { if (argc != 3) { print_usage(); exit(2); } else { printf("********************************************\n"); printf("* Bootstrap!!! *\n"); printf("********************************************\n"); } string private_fname = string(argv[1]); string public_fname(argv[2]); generatePk(private_fname,public_fname); return 0; } src/build_properties.h.in
New file @@ -0,0 +1,12 @@ #ifndef BUILD_PROPERTIES_H_ #define BUILD_PROPERTIES_H_ #define PROJECT_INT_VERSION @LICENSECC_INT_VERSION@ #define PROJECT_VERSION "@LICENSECC_VERSION@" #define PROJECT_BINARY_DIR "@CMAKE_BINARY_DIR@" #define PROJECT_SRC_DIR "@CMAKE_CURRENT_LIST_DIR@" #define PROJECT_BASE_DIR "@CMAKE_SOURCE_DIR@" #define PROJECT_TEST_SRC_DIR "@CMAKE_SOURCE_DIR@/test" #define PROJECT_TEST_TEMP_DIR "@CMAKE_BINARY_DIR@/Testing/Temporary" #define BUILD_TYPE "@CMAKE_BUILD_TYPE@" #endif src/library/.gitignore
New file @@ -0,0 +1 @@ /Licensepp.h src/library/CMakeLists.txt
New file @@ -0,0 +1,33 @@ IF(WIN32) add_subdirectory("os/win") ELSE(WIN32) add_subdirectory("os/linux") ENDIF(WIN32) add_subdirectory("base") add_subdirectory("reader") ADD_LIBRARY(license++_static STATIC license++.cpp ) target_link_libraries( license++_static reader os ${EXTERNAL_LIBS} ) ADD_LIBRARY(license++ SHARED license++.cpp ) SET_TARGET_PROPERTIES(license++ PROPERTIES LINK_SEARCH_START_STATIC OFF) SET_TARGET_PROPERTIES(license++ PROPERTIES LINK_SEARCH_END_STATIC OFF) target_link_libraries( license++ reader_dynl #os #${EXTERNAL_LIBS} ) set_target_properties(license++ PROPERTIES PREFIX "lib") src/library/api/Licensepp-features.h
New file @@ -0,0 +1,13 @@ #ifndef LICENSEPP_FEATURES_H_ #define LICENSEPP_FEATURES_H_ #include "license++.h" #ifdef __cplusplus extern "C" { #endif enum FEATURE_NAMES { FEATURE1 }; #endif src/library/api/datatypes.h
New file @@ -0,0 +1,103 @@ #ifndef DATATYPES_H_ #define DATATYPES_H_ /* * This include file is the public api di License++ * You should include this file if your software don't plan to use * the part of the library dealing with features. * Otherwise licensepp-features.h should be included. */ #ifdef __cplusplus extern "C" { #endif #ifdef __unix__ #define DllExport #define MAX_PATH 1024 #else #include <windows.h> #define DllExport __declspec( dllexport ) #endif #define ENVIRONMENT_VAR_NAME_MAX 64 #define PC_IDENTIFIER_SIZE 18 #define PROPRIETARY_DATA_SIZE 16 #define LICENESE_INT_VERSION 100 #define LICENSEPP_VERSION "1.0.0" enum EVENT_TYPE { LICENSE_OK = 0, //OK LICENSE_FILE_NOT_FOUND = 1, //license file not found LICENSE_SERVER_NOT_FOUND = 2, //license server can't be contacted ENVIRONMENT_VARIABLE_NOT_DEFINED = 3, //environment variable not defined FILE_FORMAT_NOT_RECOGNIZED = 4, //license file has invalid format (not .ini file) LICENSE_MALFORMED = 5,//some mandatory field are missing, or data can't be fully read. PRODUCT_NOT_LICENSED = 6, //this product was not licensed PRODUCT_EXPIRED = 7, LICENSE_CORRUPTED = 8, //License serial and calculated one didn't match IDENTIFIERS_MISMATCH = 9, //Calculated identifier and the one provided in license didn't match LICENSE_FILE_FOUND = 100 }; enum LICENSE_TYPE { LOCAL, REMOTE //remote licenses are not supported now. }; enum SEVERITY { INFO, WARN, SEVERITY_ERROR }; struct AuditEvent { SEVERITY severity; EVENT_TYPE event_type; char param1[256]; char param2[256]; }; typedef struct { const char *licenseFileLocation; const char *environmentVariableName; bool openFileNearModule; } LicenseLocation; typedef struct { /** * Detailed reason of success/failure. Reasons for a failure can be * multiple (for instance, license expired and signature not verified). * Only the last 5 are reported. */ AuditEvent status[5]; /** * Eventual expiration date of the software, * can be '\0' if the software don't expire * */ char expiry_date[11]; unsigned int days_left; bool has_expiry; bool linked_to_pc; LICENSE_TYPE license_type; // Local or Remote /* A string of character inserted into the license understood * by the calling application. * '\0' if the application didn't specify one */ char proprietary_data[PROPRIETARY_DATA_SIZE+1]; int license_version; //license file version } LicenseInfo; /** * Enum to select a specific pc identification_strategy. DEFAULT Should be used * in most cases. */ enum IDENTIFICATION_STRATEGY { DEFAULT, ETHERNET, IP_ADDRESS, DISK_NUM, DISK_LABEL }; #ifdef __cplusplus } #endif #endif src/library/api/license++.h
New file @@ -0,0 +1,66 @@ #ifndef LICENSEPP_H_ #define LICENSEPP_H_ /* * This include file is the public api di License++ * You should include this file if your software don't plan to use * the part of the library dealing with features. * Otherwise licensepp-features.h should be included. */ #ifdef __cplusplus extern "C" { #endif #ifdef __unix__ #define DllExport #define MAX_PATH 1024 #else #include <windows.h> #define DllExport __declspec( dllexport ) #endif #include "datatypes.h" /* * Method used to convert the LicenseInfo into a human readable * representation. */ DllExport void print_error(char out_buffer[256], LicenseInfo* licenseInfo); /** * This method calculate the pc identifier. The string has to be shown * to the user in order to calculate the license. */ void identify_pc(IDENTIFICATION_STRATEGY pc_id_method, char chbuffer[PC_IDENTIFIER_SIZE + 1]); /* * The optional parameter License contains the information the program that uses the library * should display: * * @return true if successful. False if there are errors. * @param licenseLocation[in] licenseLocation, either the name of the file * or the name of the environment variable should be !='\0' * @param license[out] optional, can be NULL. */ DllExport EVENT_TYPE acquire_license(char * productName, LicenseLocation licenseLocation, LicenseInfo* license); /** * Do nothing for now, useful for network licenses. * Should be called from time to time to confirm we're still using the * slicense. */ DllExport enum EVENT_TYPE confirm_license(char * productName, LicenseLocation licenseLocation); /** * Do nothing for now, useful for network licenses. */ DllExport enum EVENT_TYPE release_license(char * productName, LicenseLocation licenseLocation); #ifdef __cplusplus } #endif #endif src/library/base/.gitignore
New file @@ -0,0 +1 @@ /public-key.h src/library/base/CMakeLists.txt
New file @@ -0,0 +1,6 @@ ADD_LIBRARY(base STATIC EventRegistry.cpp StringUtils.cpp ) add_dependencies( base public_key ) src/library/base/EventRegistry.cpp
New file @@ -0,0 +1,100 @@ /* * EventRegistry.cpp * * Created on: Mar 30, 2014 * Author: devel */ #include "EventRegistry.h" #include <cstddef> #include <string.h> namespace license { EventRegistry::EventRegistry() { } EventRegistry& operator<<(EventRegistry& eventRegistry, AuditEvent& securityEvent) { eventRegistry.logs.push_back(securityEvent); return eventRegistry; } EventRegistry& operator<<(EventRegistry& eventRegistry1, EventRegistry& otherRegistry) { eventRegistry1.append(otherRegistry); return eventRegistry1; } void EventRegistry::append(const EventRegistry& eventRegistry) { logs.insert(logs.end(), eventRegistry.logs.begin(), eventRegistry.logs.end()); } void EventRegistry::turnLastEventIntoError() { if (logs.size() > 0) { logs.back().severity = SEVERITY_ERROR; } } bool EventRegistry::turnEventIntoError(EVENT_TYPE event) { bool eventFound = false; for (auto it = logs.begin(); it != logs.end(); ++it) { if (it->event_type == event) { it->severity = SEVERITY_ERROR; eventFound = true; } } return eventFound; } AuditEvent const * EventRegistry::getLastFailure() const { const AuditEvent* result = NULL; if(logs.size() == 0){ return result; } auto it = logs.end(); do { --it; if (it->severity == SEVERITY_ERROR) { result = &(*it); break; } } while (it != logs.begin()); return result; } bool EventRegistry::isGood() const { bool isGood = true; for (auto it = logs.begin(); it != logs.end(); ++it) { if (it->severity == SEVERITY_ERROR) { isGood = false; break; } } return isGood; } void EventRegistry::addError(EVENT_TYPE event){ addEvent(event,SEVERITY_ERROR); } void EventRegistry::addEvent(EVENT_TYPE event, SEVERITY severity) { AuditEvent audit; audit.severity = severity; audit.event_type = event; audit.param1[0] = '\0'; audit.param2[0] = '\0'; logs.push_back(audit); } void EventRegistry::addEvent(EVENT_TYPE event, SEVERITY severity, const string& eventParameter) { AuditEvent audit; audit.severity = severity; audit.event_type = event; strncpy(audit.param1,eventParameter.c_str(),255); audit.param2[0] = '\0'; logs.push_back(audit); } } src/library/base/EventRegistry.h
New file @@ -0,0 +1,52 @@ /* * EventRegistry.h * * Created on: Mar 30, 2014 * Author: devel */ #ifndef EVENTREGISTRY_H_ #define EVENTREGISTRY_H_ #include "../api/datatypes.h" #include <vector> #include <string> namespace license { using namespace std; /* AuditEvent error_event_builder(EVENT_TYPE event); AuditEvent audit_event_builder(EVENT_TYPE event, SEVERITY severity); AuditEvent audit_event_builder(EVENT_TYPE event, SEVERITY severity, const string& eventParameter);*/ class EventRegistry { private: friend EventRegistry& operator<<(EventRegistry&, AuditEvent&); friend EventRegistry& operator<<(EventRegistry&, EventRegistry&); //TODO change into map vector<AuditEvent> logs; //Forbid copy //EventRegistry(const EventRegistry& that) = delete; public: EventRegistry(); //operator << void append(const EventRegistry& eventRegistry); void turnLastEventIntoError(); bool turnEventIntoError(EVENT_TYPE event); bool turnErrosIntoWarnings(); /** * @return NULL if no failures are found. */ AuditEvent const * getLastFailure() const; bool isGood() const; void addError(EVENT_TYPE event); void addEvent(EVENT_TYPE event, SEVERITY severity); void addEvent(EVENT_TYPE event, SEVERITY severity, const string& eventParameter); void exportLastEvents(AuditEvent* auditEvents,int nlogs); }; } #endif /* EVENTREGISTRY_H_ */ src/library/base/StringUtils.cpp
New file @@ -0,0 +1,35 @@ /* * StringUtils.cpp * * Created on: Apr 8, 2014 * Author: devel */ #include <cctype> //toupper #include "StringUtils.h" #include <iostream> #include <string> #include <algorithm> namespace license { using namespace std; string trim_copy(const string& string_to_trim) { std::string::const_iterator it = string_to_trim.begin(); while (it != string_to_trim.end() && isspace(*it)) it++; std::string::const_reverse_iterator rit = string_to_trim.rbegin(); while (rit.base() != it && isspace(*rit)) rit++; return std::string(it, rit.base()); } string toupper_copy(const string& lowercase) { string cp(lowercase); std::transform(cp.begin(), cp.end(), cp.begin(), (int(*)(int))toupper); return cp; } } /* namespace license */ src/library/base/StringUtils.h
New file @@ -0,0 +1,27 @@ /* * StringUtils.h * * Created on: Apr 8, 2014 * Author: devel */ #ifndef STRINGUTILS_H_ #define STRINGUTILS_H_ #include <string> namespace license { using namespace std; /** * Eliminate whitespace from both sides of a string and returns a copy * of the string itself. * @param string_to_trim * @return the trimmed string */ string trim_copy(const string& string_to_trim); string toupper_copy(const string& lowercase); } /* namespace license */ #endif /* STRINGUTILS_H_ */ src/library/license++.cpp
New file @@ -0,0 +1,86 @@ //============================================================================ // Name : license-manager-cpp.cpp // Author : // Version : // Copyright : BSD //============================================================================ #include <fstream> #include <stdio.h> #include <stdlib.h> #include <cstring> #include "api/license++.h" #include "reader/LicenseReader.h" using namespace std; DllExport void print_error(char out_buffer[256], LicenseInfo* licenseInfo) { } DllExport void identify_pc(IDENTIFICATION_STRATEGY pc_id_method, char chbuffer[PC_IDENTIFIER_SIZE + 1]) { } static void mergeLicenses(vector<license::FullLicenseInfo> licenses, LicenseInfo* license) { if (license != NULL) { time_t curLicense_exp = 0; for (auto it = licenses.begin(); it != licenses.end(); it++) { //choose the license that expires later... if (!it->has_expiry) { it->toLicenseInfo(license); break; } else if (curLicense_exp < it->to_date) { curLicense_exp = it->to_date; it->toLicenseInfo(license); } } } } EVENT_TYPE acquire_license(char * product, LicenseLocation licenseLocation, LicenseInfo* license) { license::LicenseReader lr = license::LicenseReader(licenseLocation); vector<license::FullLicenseInfo> licenses; license::EventRegistry er = lr.readLicenses(string(product), licenses); EVENT_TYPE result; if (licenses.size() > 0) { vector<license::FullLicenseInfo> licenses_with_errors; vector<license::FullLicenseInfo> licenses_ok; for (auto it = licenses.begin(); it != licenses.end(); it++) { license::EventRegistry validation_er = it->validate(0); if (er.isGood()) { licenses_ok.push_back(*it); } else { licenses_with_errors.push_back(*it); } er.append(validation_er); } if (licenses_ok.size() > 0) { er.turnErrosIntoWarnings(); result = LICENSE_OK; mergeLicenses(licenses_ok, license); } else { result = er.getLastFailure()->event_type; mergeLicenses(licenses_with_errors, license); } } else { result = er.getLastFailure()->event_type; } if (license != NULL) { er.exportLastEvents(license->status, 5); } return result; } DllExport enum EVENT_TYPE confirm_license(char * product, LicenseLocation licenseLocation) { return LICENSE_OK; } DllExport enum EVENT_TYPE release_license(char * product, LicenseLocation licenseLocation) { return LICENSE_OK; } src/library/os/linux/CMakeLists.txt
New file @@ -0,0 +1,10 @@ ADD_LIBRARY(os STATIC os-linux.cpp ) target_link_libraries( os base ${EXTERNAL_LIBS} ) src/library/os/linux/os-linux.cpp
New file @@ -0,0 +1,132 @@ #include <paths.h> #include <stdio.h> #include <stdlib.h> #include <cstring> #include <string> #include <system_error> #include <unistd.h> #include <sstream> #include <sys/ioctl.h> #include <sys/stat.h> #include "../os.hpp" #include "../../base/public-key.h" #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> namespace license { using namespace std; vector<AdapterInfo> OsFunctions::getAdapterInfos() { return vector<AdapterInfo>(); } vector<DiskInfo> OsFunctions::getDiskInfos() { struct stat filename_stat, mount_stat; static char discard[1024]; char device[64], name[64], type[64]; FILE *mounts = fopen(_PATH_MOUNTED, "r"); while (fscanf(mounts, "%64s %64s %64s %1024[^\n]", device, name, type, discard) != EOF) { if (stat(device, &mount_stat) != 0) continue; if (filename_stat.st_dev == mount_stat.st_rdev) fprintf(stderr, "device: %s; name: %s; type: %s\n", device, name, type); } return vector<DiskInfo>(); } string OsFunctions::getModuleName() { char path[2048] = { 0 }; string strPath; string result; pid_t pid = getpid(); const string pidstr = to_string(((long) pid)); strPath = string("/proc/") + pidstr + "/exe"; const char * proc_path = strPath.c_str(); int ch = readlink(proc_path, path, 2048); if (ch != -1) { path[ch] = '\0'; result = string(path); } else { throw runtime_error( string("Can't find: ") + strPath + " proc filesystem mounted?"); } return result; } string OsFunctions::getUserHomePath() { return ""; } bool OsFunctions::verifySignature(const char* stringToVerify, const char* signature) { EVP_MD_CTX *mdctx = NULL; char *pubKey = PUBLIC_KEY ; BIO* bio = BIO_new_mem_buf((void*) (pubKey), sizeof(pubKey)); EVP_PKEY *pktmp = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL); BIO_free(bio); if (pktmp == NULL) { throw new logic_error("Error reading public key"); } /*BIO* bo = BIO_new(BIO_s_mem()); BIO_write(bo, pubKey, strlen(pubKey)); RSA *key = 0; PEM_read_bio_RSAPublicKey(bo, &key, 0, 0); BIO_free(bo);*/ //RSA* rsa = EVP_PKEY_get1_RSA( key ); //RSA * pubKey = d2i_RSA_PUBKEY(NULL, <der encoded byte stream pointer>, <num bytes>); /* Create the Message Digest Context */ if (!(mdctx = EVP_MD_CTX_create())) { throw new logic_error("Error creating context"); } if (1 != EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pktmp)) { throw new logic_error("Error initializing digest"); } if (1 != EVP_DigestVerifyUpdate(mdctx, stringToVerify, strlen(stringToVerify))) { throw new logic_error("Error initializing digest"); } if (1 == EVP_DigestVerifyFinal(mdctx, (unsigned char *) signature, (unsigned long int) strlen(signature))) { return true; } else { return false; } } VIRTUALIZATION OsFunctions::getVirtualization() { //http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html // bool rc = true; /*__asm__ ( "push %edx\n" "push %ecx\n" "push %ebx\n" "mov %eax, 'VMXh'\n" "mov %ebx, 0\n" // any value but not the MAGIC VALUE "mov %ecx, 10\n"// get VMWare version "mov %edx, 'VX'\n"// port number "in %eax, dx\n"// read port on return EAX returns the VERSION "cmp %ebx, 'VMXh'\n"// is it a reply from VMWare? "setz [rc] \n"// set return value "pop %ebx \n" "pop %ecx \n" "pop %edx \n" );*/ return NONE; } } src/library/os/os.hpp
New file @@ -0,0 +1,49 @@ /* * os-dependent.hpp * * Created on: Mar 29, 2014 * Author: devel */ #ifndef OS_DEPENDENT_HPP_ #define OS_DEPENDENT_HPP_ #include <string> #include <vector> namespace license { using namespace std; enum VIRTUALIZATION { NONE,VMWARE }; struct AdapterInfo { int id; string description; unsigned char mac_address[8]; unsigned char ipv4_address[4]; }; struct DiskInfo { int id; string device; unsigned char disk_sn[8]; string label; }; class OsFunctions { public: static vector<AdapterInfo> getAdapterInfos(); static vector<DiskInfo> getDiskInfos(); static string getModuleName(); static string getUserHomePath(); //use system dependent methods to verify signature static bool verifySignature(const char * stringToVerify, const char* signature); static VIRTUALIZATION getVirtualization(); }; } #endif /* OS_DEPENDENT_HPP_ */ src/library/os/win/CMakeLists.txt
src/library/reader/CMakeLists.txt
New file @@ -0,0 +1,26 @@ ADD_LIBRARY(reader STATIC ConvertUTF.c LicenseReader.cpp ) target_link_libraries( reader os base ${EXTERNAL_LIBS} ) ADD_LIBRARY(reader_dynl STATIC ConvertUTF.c LicenseReader.cpp ) SET_TARGET_PROPERTIES(reader_dynl PROPERTIES LINK_SEARCH_START_STATIC OFF) SET_TARGET_PROPERTIES(reader_dynl PROPERTIES LINK_SEARCH_END_STATIC OFF) target_link_libraries( reader_dynl os #base #${EXTERNAL_LIBS} ) src/library/reader/ConvertUTF.c
New file @@ -0,0 +1,539 @@ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Source code file. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Sept 2001: fixed const & error conditions per mods suggested by S. Parent & A. Lillich. June 2002: Tim Dodd added detection and handling of incomplete source sequences, enhanced error detection, added casts to eliminate compiler warnings. July 2003: slight mods to back out aggressive FFFE detection. Jan 2004: updated switches in from-UTF8 conversions. Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions. See the header file "ConvertUTF.h" for complete documentation. ------------------------------------------------------------------------ */ #include "ConvertUTF.h" #ifdef CVTUTF_DEBUG #include <stdio.h> #endif static const int halfShift = 10; /* used for shifting by 10 bits */ static const UTF32 halfBase = 0x0010000UL; static const UTF32 halfMask = 0x3FFUL; #define UNI_SUR_HIGH_START (UTF32)0xD800 #define UNI_SUR_HIGH_END (UTF32)0xDBFF #define UNI_SUR_LOW_START (UTF32)0xDC00 #define UNI_SUR_LOW_END (UTF32)0xDFFF #define false 0 #define true 1 /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF32toUTF16 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF32* source = *sourceStart; UTF16* target = *targetStart; while (source < sourceEnd) { UTF32 ch; if (target >= targetEnd) { result = targetExhausted; break; } ch = *source++; if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = (UTF16)ch; /* normal case */ } } else if (ch > UNI_MAX_LEGAL_UTF32) { if (flags == strictConversion) { result = sourceIllegal; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ if (target + 1 >= targetEnd) { --source; /* Back up source pointer! */ result = targetExhausted; break; } ch -= halfBase; *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF16toUTF32 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF16* source = *sourceStart; UTF32* target = *targetStart; UTF32 ch, ch2; while (source < sourceEnd) { const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ ch = *source++; /* If we have a surrogate pair, convert to UTF32 first. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { /* If the 16 bits following the high surrogate are in the source buffer... */ if (source < sourceEnd) { ch2 = *source; /* If it's a low surrogate, convert to UTF32. */ if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + halfBase; ++source; } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } else { /* We don't have the 16 bits following the high surrogate. */ --source; /* return to the high surrogate */ result = sourceExhausted; break; } } else if (flags == strictConversion) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } if (target >= targetEnd) { source = oldSource; /* Back up source pointer! */ result = targetExhausted; break; } *target++ = ch; } *sourceStart = source; *targetStart = target; #ifdef CVTUTF_DEBUG if (result == sourceIllegal) { fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2); fflush(stderr); } #endif return result; } /* --------------------------------------------------------------------- */ /* * Index into the table below with the first byte of a UTF-8 sequence to * get the number of trailing bytes that are supposed to follow it. * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is * left as-is for anyone who may want to do such conversion, which was * allowed in earlier algorithms. */ static const char trailingBytesForUTF8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; /* * Magic values subtracted from a buffer value during UTF8 conversion. * This table contains as many values as there might be trailing bytes * in a UTF-8 sequence. */ static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed * into the first byte, depending on how many bytes follow. There are * as many entries in this table as there are UTF-8 sequence types. * (I.e., one byte sequence, two byte... etc.). Remember that sequencs * for *legal* UTF-8 will be 4 or fewer bytes total. */ static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; /* --------------------------------------------------------------------- */ /* The interface converts a whole buffer to avoid function-call overhead. * Constants have been gathered. Loops & conditionals have been removed as * much as possible for efficiency, in favor of drop-through switches. * (See "Note A" at the bottom of the file for equivalent code.) * If your compiler supports it, the "isLegalUTF8" call can be turned * into an inline function. */ /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF16toUTF8 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF16* source = *sourceStart; UTF8* target = *targetStart; while (source < sourceEnd) { UTF32 ch; unsigned short bytesToWrite = 0; const UTF32 byteMask = 0xBF; const UTF32 byteMark = 0x80; const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ ch = *source++; /* If we have a surrogate pair, convert to UTF32 first. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { /* If the 16 bits following the high surrogate are in the source buffer... */ if (source < sourceEnd) { UTF32 ch2 = *source; /* If it's a low surrogate, convert to UTF32. */ if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { ch = ((ch - UNI_SUR_HIGH_START) << halfShift) + (ch2 - UNI_SUR_LOW_START) + halfBase; ++source; } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } else { /* We don't have the 16 bits following the high surrogate. */ --source; /* return to the high surrogate */ result = sourceExhausted; break; } } else if (flags == strictConversion) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } /* Figure out how many bytes the result will require */ if (ch < (UTF32)0x80) { bytesToWrite = 1; } else if (ch < (UTF32)0x800) { bytesToWrite = 2; } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; } else if (ch < (UTF32)0x110000) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; } target += bytesToWrite; if (target > targetEnd) { source = oldSource; /* Back up source pointer! */ target -= bytesToWrite; result = targetExhausted; break; } switch (bytesToWrite) { /* note: everything falls through. */ case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ /* * Utility routine to tell whether a sequence of bytes is legal UTF-8. * This must be called with the length pre-determined by the first byte. * If not calling this from ConvertUTF8to*, then the length can be set by: * length = trailingBytesForUTF8[*source]+1; * and the sequence is illegal right away if there aren't that many bytes * available. * If presented with a length > 4, this returns false. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static Boolean isLegalUTF8(const UTF8 *source, int length) { UTF8 a; const UTF8 *srcptr = source+length; switch (length) { default: return false; /* Everything else falls through when "true"... */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; case 2: if ((a = (*--srcptr)) > 0xBF) return false; switch (*source) { /* no fall-through in this inner switch */ case 0xE0: if (a < 0xA0) return false; break; case 0xED: if (a > 0x9F) return false; break; case 0xF0: if (a < 0x90) return false; break; case 0xF4: if (a > 0x8F) return false; break; default: if (a < 0x80) return false; } case 1: if (*source >= 0x80 && *source < 0xC2) return false; } if (*source > 0xF4) return false; return true; } /* --------------------------------------------------------------------- */ /* * Exported function to return whether a UTF-8 sequence is legal or not. * This is not used here; it's just exported. */ Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) { int length = trailingBytesForUTF8[*source]+1; if (source+length > sourceEnd) { return false; } return isLegalUTF8(source, length); } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF16 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF8* source = *sourceStart; UTF16* target = *targetStart; while (source < sourceEnd) { UTF32 ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { result = sourceExhausted; break; } /* Do this check whether lenient or strict */ if (! isLegalUTF8(source, extraBytesToRead+1)) { result = sourceIllegal; break; } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (target >= targetEnd) { source -= (extraBytesToRead+1); /* Back up source pointer! */ result = targetExhausted; break; } if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { source -= (extraBytesToRead+1); /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = (UTF16)ch; /* normal case */ } } else if (ch > UNI_MAX_UTF16) { if (flags == strictConversion) { result = sourceIllegal; source -= (extraBytesToRead+1); /* return to the start */ break; /* Bail out; shouldn't continue */ } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { /* target is a character in range 0xFFFF - 0x10FFFF. */ if (target + 1 >= targetEnd) { source -= (extraBytesToRead+1); /* Back up source pointer! */ result = targetExhausted; break; } ch -= halfBase; *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF32toUTF8 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF32* source = *sourceStart; UTF8* target = *targetStart; while (source < sourceEnd) { UTF32 ch; unsigned short bytesToWrite = 0; const UTF32 byteMask = 0xBF; const UTF32 byteMark = 0x80; ch = *source++; if (flags == strictConversion ) { /* UTF-16 surrogate values are illegal in UTF-32 */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { --source; /* return to the illegal value itself */ result = sourceIllegal; break; } } /* * Figure out how many bytes the result will require. Turn any * illegally large UTF32 things (> Plane 17) into replacement chars. */ if (ch < (UTF32)0x80) { bytesToWrite = 1; } else if (ch < (UTF32)0x800) { bytesToWrite = 2; } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } target += bytesToWrite; if (target > targetEnd) { --source; /* Back up source pointer! */ target -= bytesToWrite; result = targetExhausted; break; } switch (bytesToWrite) { /* note: everything falls through. */ case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- */ ConversionResult ConvertUTF8toUTF32 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { ConversionResult result = conversionOK; const UTF8* source = *sourceStart; UTF32* target = *targetStart; while (source < sourceEnd) { UTF32 ch = 0; unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { result = sourceExhausted; break; } /* Do this check whether lenient or strict */ if (! isLegalUTF8(source, extraBytesToRead+1)) { result = sourceIllegal; break; } /* * The cases all fall through. See "Note A" below. */ switch (extraBytesToRead) { case 5: ch += *source++; ch <<= 6; case 4: ch += *source++; ch <<= 6; case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; if (target >= targetEnd) { source -= (extraBytesToRead+1); /* Back up the source pointer! */ result = targetExhausted; break; } if (ch <= UNI_MAX_LEGAL_UTF32) { /* * UTF-16 surrogate values are illegal in UTF-32, and anything * over Plane 17 (> 0x10FFFF) is illegal. */ if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { if (flags == strictConversion) { source -= (extraBytesToRead+1); /* return to the illegal value itself */ result = sourceIllegal; break; } else { *target++ = UNI_REPLACEMENT_CHAR; } } else { *target++ = ch; } } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */ result = sourceIllegal; *target++ = UNI_REPLACEMENT_CHAR; } } *sourceStart = source; *targetStart = target; return result; } /* --------------------------------------------------------------------- Note A. The fall-through switches in UTF-8 reading code save a temp variable, some decrements & conditionals. The switches are equivalent to the following loop: { int tmpBytesToRead = extraBytesToRead+1; do { ch += *source++; --tmpBytesToRead; if (tmpBytesToRead) ch <<= 6; } while (tmpBytesToRead > 0); } In UTF-8 writing code, the switches on "bytesToWrite" are similarly unrolled loops. --------------------------------------------------------------------- */ src/library/reader/ConvertUTF.h
New file @@ -0,0 +1,149 @@ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Header file. Several funtions are included here, forming a complete set of conversions between the three formats. UTF-7 is not included here, but is handled in a separate source file. Each of these routines takes pointers to input buffers and output buffers. The input buffers are const. Each routine converts the text between *sourceStart and sourceEnd, putting the result into the buffer between *targetStart and targetEnd. Note: the end pointers are *after* the last item: e.g. *(sourceEnd - 1) is the last item. The return result indicates whether the conversion was successful, and if not, whether the problem was in the source or target buffers. (Only the first encountered problem is indicated.) After the conversion, *sourceStart and *targetStart are both updated to point to the end of last text successfully converted in the respective buffers. Input parameters: sourceStart - pointer to a pointer to the source buffer. The contents of this are modified on return so that it points at the next thing to be converted. targetStart - similarly, pointer to pointer to the target buffer. sourceEnd, targetEnd - respectively pointers to the ends of the two buffers, for overflow checking only. These conversion functions take a ConversionFlags argument. When this flag is set to strict, both irregular sequences and isolated surrogates will cause an error. When the flag is set to lenient, both irregular sequences and isolated surrogates are converted. Whether the flag is strict or lenient, all illegal sequences will cause an error return. This includes sequences such as: <F4 90 80 80>, <C0 80>, or <A0> in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code must check for illegal sequences. When the flag is set to lenient, characters over 0x10FFFF are converted to the replacement character; otherwise (when the flag is set to strict) they constitute an error. Output parameters: The value "sourceIllegal" is returned from some routines if the input sequence is malformed. When "sourceIllegal" is returned, the source value will point to the illegal value that caused the problem. E.g., in UTF-8 when a sequence is malformed, it points to the start of the malformed sequence. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Fixes & updates, Sept 2001. ------------------------------------------------------------------------ */ /* --------------------------------------------------------------------- The following 4 definitions are compiler-specific. The C standard does not guarantee that wchar_t has at least 16 bits, so wchar_t is no less portable than unsigned short! All should be unsigned values to avoid sign extension during bit mask & shift operations. ------------------------------------------------------------------------ */ typedef unsigned int UTF32; /* at least 32 bits */ typedef unsigned short UTF16; /* at least 16 bits */ typedef unsigned char UTF8; /* typically 8 bits */ typedef unsigned char Boolean; /* 0 or 1 */ /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD #define UNI_MAX_BMP (UTF32)0x0000FFFF #define UNI_MAX_UTF16 (UTF32)0x0010FFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; typedef enum { strictConversion = 0, lenientConversion } ConversionFlags; /* This is for C++ and does no harm in C */ #ifdef __cplusplus extern "C" { #endif ConversionResult ConvertUTF8toUTF16 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF8 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF8toUTF32 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF8 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF32 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF16 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); #ifdef __cplusplus } #endif /* --------------------------------------------------------------------- */ src/library/reader/LicenseReader.cpp
New file @@ -0,0 +1,311 @@ /* * LicenseReader.cpp * * Created on: Mar 30, 2014 * Author: devel */ #include "LicenseReader.h" #include "../base/StringUtils.h" #include "../base/public-key.h" #include <build_properties.h> #define SI_SUPPORT_IOSTREAMS #include "SimpleIni.h" #include <cstring> #include <ctime> #include <vector> #include <iostream> #include <iterator> #include <fstream> #include <sstream> #include <stdlib.h> #ifdef _WIN32 # pragma warning(disable: 4786) #else # include <unistd.h> #endif #define SI_SUPPORT_IOSTREAMS #include "SimpleIni.h" #include "../os/os.hpp" namespace license { FullLicenseInfo::FullLicenseInfo(const string& source, const string& product, const string& license_signature, int licenseVersion, time_t from_date, time_t to_date, // const string& client_signature, unsigned int from_sw_version, unsigned int to_sw_version, const string& extra_data) : source(source), product(product), // license_signature(license_signature), license_version(licenseVersion), // from_date(from_date), to_date(to_date), // has_expiry(to_date != UNUSED_TIME), // from_sw_version(from_sw_version), to_sw_version(to_sw_version), // has_versions( from_sw_version != UNUSED_SOFTWARE_VERSION || to_sw_version != UNUSED_SOFTWARE_VERSION), // client_signature(client_signature), has_client_sig( client_signature.length() > 0), // extra_data(extra_data) { } void FullLicenseInfo::toLicenseInfo(LicenseInfo* license) const { if (license != NULL) { strncpy(license->proprietary_data, extra_data.c_str(), PROPRIETARY_DATA_SIZE); license->linked_to_pc = has_client_sig; license->has_expiry = has_expiry; if (!has_expiry) { license->expiry_date[0] = '\0'; license->days_left = 999999; } else { tm * timeinfo = localtime(&to_date); strftime(license->expiry_date, 11, "%Y-%m-%d", timeinfo); double secs = difftime(time(NULL), to_date); license->days_left = (int) secs / 60 * 60 * 24; } } } LicenseReader::LicenseReader(const LicenseLocation& licenseLocation) : licenseLocation(licenseLocation) { } EventRegistry LicenseReader::readLicenses(const string &product, vector<FullLicenseInfo>& licenseInfoOut) { vector<string> diskFiles; EventRegistry result = getLicenseDiskFiles(diskFiles); if (!result.isGood()) { return result; } bool loadAtLeastOneFile = false; bool atLeastOneProductLicensed = false; bool atLeastOneLicenseComplete = false; CSimpleIniA ini; for (auto it = diskFiles.begin(); it != diskFiles.end(); it++) { ini.Reset(); SI_Error rc = ini.LoadFile((*it).c_str()); if (rc < 0) { result.addEvent(FILE_FORMAT_NOT_RECOGNIZED, WARN, *it); continue; } else { loadAtLeastOneFile = true; } const char* productNamePtr = product.c_str(); int sectionSize = ini.GetSectionSize(productNamePtr); if (sectionSize <= 0) { result.addEvent(PRODUCT_NOT_LICENSED, WARN, *it); continue; } else { atLeastOneProductLicensed = true; } /* * sw_version_from = (optional int) * sw_version_to = (optional int) * from_date = YYYY-MM-DD (optional) * to_date = YYYY-MM-DD (optional) * client_signature = XXXXXXXX (optional string 16) * license_signature = XXXXXXXXXX (mandatory, 1024) * application_data = xxxxxxxxx (optional string 16) */ const char * license_signature = ini.GetValue(productNamePtr, "license_signature", NULL); long license_version = ini.GetLongValue(productNamePtr, "license_version", -1); if (license_signature != NULL && license_version > 0) { FullLicenseInfo licInfo(*it, product, license_signature, (int) license_version); licenseInfoOut.push_back(licInfo); atLeastOneLicenseComplete = true; } else { result.addEvent(LICENSE_MALFORMED, WARN, *it); } } if (!loadAtLeastOneFile) { result.turnEventIntoError(FILE_FORMAT_NOT_RECOGNIZED); } if (!atLeastOneProductLicensed) { result.turnEventIntoError(PRODUCT_NOT_LICENSED); } if (!atLeastOneLicenseComplete) { result.turnEventIntoError(LICENSE_MALFORMED); } return result; } bool LicenseReader::findLicenseWithExplicitLocation(vector<string>& diskFiles, EventRegistry& eventRegistry) { //bool hasFileLocation = false; bool licenseFoundWithExplicitLocation = false; if (licenseLocation.licenseFileLocation != NULL && licenseLocation.licenseFileLocation[0] != '\0') { //hasFileLocation = true; string varName(licenseLocation.licenseFileLocation); vector<string> declared_positions = splitLicensePositions(varName); vector<string> existing_pos = filterExistingFiles(declared_positions); if (existing_pos.size() > 0) { if (existing_pos.size() > 0) { licenseFoundWithExplicitLocation = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, INFO, *it); } } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, WARN, varName); } } return licenseFoundWithExplicitLocation; } bool LicenseReader::findFileWithEnvironmentVariable(vector<string>& diskFiles, EventRegistry& eventRegistry) { bool licenseFileFoundWithEnvVariable = false; if (licenseLocation.environmentVariableName != NULL && licenseLocation.environmentVariableName[0] != '\0') { string varName(licenseLocation.environmentVariableName); if (varName.length() > 0) { //var name is passed in by the calling application. char* env_var_value = getenv(varName.c_str()); if (env_var_value != NULL && env_var_value[0] != '\0') { vector<string> declared_positions = splitLicensePositions( string(env_var_value)); vector<string> existing_pos = filterExistingFiles( declared_positions); if (existing_pos.size() > 0) { licenseFileFoundWithEnvVariable = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, INFO, *it); } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, WARN, env_var_value); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, WARN); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, WARN); } } return licenseFileFoundWithEnvVariable; } EventRegistry LicenseReader::getLicenseDiskFiles(vector<string>& diskFiles) { EventRegistry eventRegistry; bool licenseFoundWithExplicitLocation = findLicenseWithExplicitLocation( diskFiles, eventRegistry); bool foundNearModule = false; if (licenseLocation.openFileNearModule) { string temptativeLicense = OsFunctions::getModuleName() + ".lic"; ifstream f(temptativeLicense.c_str()); if (f.good()) { foundNearModule = true; diskFiles.push_back(temptativeLicense); eventRegistry.addEvent(LICENSE_FILE_FOUND, INFO, temptativeLicense); } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, WARN, temptativeLicense); } f.close(); } bool licenseFileFoundWithEnvVariable = findFileWithEnvironmentVariable( diskFiles, eventRegistry); if (!foundNearModule && !licenseFoundWithExplicitLocation && !licenseFileFoundWithEnvVariable) { eventRegistry.turnEventIntoError(ENVIRONMENT_VARIABLE_NOT_DEFINED); eventRegistry.turnEventIntoError(LICENSE_FILE_NOT_FOUND); } return eventRegistry; } vector<string> LicenseReader::filterExistingFiles( vector<string> licensePositions) { vector<string> existingFiles; for (auto it = licensePositions.begin(); it != licensePositions.end(); it++) { ifstream f(it->c_str()); if (f.good()) { existingFiles.push_back(*it); } f.close(); } return existingFiles; } vector<string> LicenseReader::splitLicensePositions(string licensePositions) { std::stringstream streamToSplit(licensePositions); std::string segment; std::vector<string> seglist; while (std::getline(streamToSplit, segment, ';')) { seglist.push_back(segment); } return seglist; } LicenseReader::~LicenseReader() { } string FullLicenseInfo::printForSign() const { ostringstream oss; oss << toupper_copy(trim_copy(this->product)); oss << SHARED_RANDOM ; if (has_client_sig) { oss << trim_copy(this->client_signature); } if (has_versions) { oss << "|" << this->from_sw_version << "-" << this->to_sw_version; } if (has_expiry) { oss << "|" << this->from_date << "-" << this->to_date; } if (this->extra_data.length() > 0) { oss << "|" << extra_data; } return oss.str(); } void FullLicenseInfo::printAsIni(ostream & a_ostream) const { CSimpleIniA ini; string result; string product = toupper_copy(trim_copy(this->product)); CSimpleIniA::StreamWriter sw(a_ostream); ini.SetLongValue(product.c_str(), "license_version", PROJECT_INT_VERSION); ini.SetValue(product.c_str(), "license_signature", this->license_signature.c_str()); if (has_client_sig) { ini.SetValue(product.c_str(), "client_signature", this->client_signature.c_str()); } if (has_versions) { ini.SetLongValue(product.c_str(), "from_sw_version", from_sw_version); ini.SetLongValue(product.c_str(), "to_sw_version", to_sw_version); } char buff[20]; if (this->from_date != UNUSED_TIME) { strftime(buff, 20, "%Y-%m-%d", localtime(&this->from_date)); ini.SetValue(product.c_str(), "from_date", buff); } if (this->to_date != UNUSED_TIME) { strftime(buff, 20, "%Y-%m-%d", localtime(&this->to_date)); ini.SetValue(product.c_str(), "to_date", buff); } if (this->extra_data.length() > 0) { ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str()); } ini.Save(sw); } } src/library/reader/LicenseReader.h
New file @@ -0,0 +1,91 @@ /* * LicenseReader.h * * Created on: Mar 30, 2014 * Author: devel */ #ifndef LICENSEREADER_H_ #define LICENSEREADER_H_ #include "../api/datatypes.h" #include "../base/EventRegistry.h" #include "../os/os.hpp" #include <string> #include <ctime> namespace license { using namespace std; class FullLicenseInfo { public: string source; string product; string license_signature; int license_version; time_t from_date; time_t to_date; bool has_expiry; unsigned int from_sw_version; unsigned int to_sw_version; bool has_versions; string client_signature; bool has_client_sig; string extra_data; static const time_t UNUSED_TIME = (time_t) 0; static const unsigned int UNUSED_SOFTWARE_VERSION = 0; FullLicenseInfo(const string& source, const string& product, const string& license_signature, int licenseVersion, time_t from_date = UNUSED_TIME, time_t tp_date = UNUSED_TIME, // const string& client_signature = "", // unsigned int from_sw_version = UNUSED_SOFTWARE_VERSION, unsigned int to_sw_version = UNUSED_SOFTWARE_VERSION, const string& extra_data = ""); string printForSign() const; void printAsIni(ostream & a_ostream) const; inline bool signatureVerified() const { return OsFunctions::verifySignature(printForSign().c_str(), license_signature.c_str()); } void toLicenseInfo(LicenseInfo* license) const; EventRegistry validate(int sw_version); }; /** * This class it is responsible to read the licenses from the disk * (in future from network) examining all the possible LicenseLocation * positions. * * Each section of the ini file represents a product. * <pre> * [product] * sw_version_from = (optional int) * sw_version_to = (optional int) * from_date = YYYY-MM-DD (optional) * to_date = YYYY-MM-DD (optional) * client_signature = XXXXXXXX (optional string 16) * license_signature = XXXXXXXXXX (mandatory, 1024) * application_data = xxxxxxxxx (optional string 16) * license_version = 100 (mandatory int) * </pre> */ class LicenseReader { private: const LicenseLocation licenseLocation; EventRegistry getLicenseDiskFiles(vector<string>& diskFiles); vector<string> filterExistingFiles(vector<string> licensePositions); vector<string> splitLicensePositions(string licensePositions); bool findLicenseWithExplicitLocation(vector<string>& diskFiles, EventRegistry& eventRegistry); bool findFileWithEnvironmentVariable(vector<string>& diskFiles, EventRegistry& eventRegistry); public: LicenseReader(const LicenseLocation& licenseLocation); EventRegistry readLicenses(const string &product, vector<FullLicenseInfo>& licenseInfoOut); virtual ~LicenseReader(); }; } #endif /* LICENSEREADER_H_ */ src/library/reader/SimpleIni.h
New file @@ -0,0 +1,3384 @@ /** @mainpage <table> <tr><th>Library <td>SimpleIni <tr><th>File <td>SimpleIni.h <tr><th>Author <td>Brodie Thiesfield [code at jellycan dot com] <tr><th>Source <td>https://github.com/brofield/simpleini <tr><th>Version <td>4.17 </table> Jump to the @link CSimpleIniTempl CSimpleIni @endlink interface documentation. @section intro INTRODUCTION This component allows an INI-style configuration file to be used on both Windows and Linux/Unix. It is fast, simple and source code using this component will compile unchanged on either OS. @section features FEATURES - MIT Licence allows free use in all software (including GPL and commercial) - multi-platform (Windows 95/98/ME/NT/2K/XP/2003, Windows CE, Linux, Unix) - loading and saving of INI-style configuration files - configuration files can have any newline format on all platforms - liberal acceptance of file format - key/values with no section - removal of whitespace around sections, keys and values - support for multi-line values (values with embedded newline characters) - optional support for multiple keys with the same name - optional case-insensitive sections and keys (for ASCII characters only) - saves files with sections and keys in the same order as they were loaded - preserves comments on the file, section and keys where possible. - supports both char or wchar_t programming interfaces - supports both MBCS (system locale) and UTF-8 file encodings - system locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file - support for non-ASCII characters in section, keys, values and comments - support for non-standard character types or file encodings via user-written converter classes - support for adding/modifying values programmatically - compiles cleanly in the following compilers: - Windows/VC6 (warning level 3) - Windows/VC.NET 2003 (warning level 4) - Windows/VC 2005 (warning level 4) - Linux/gcc (-Wall) @section usage USAGE SUMMARY -# Define the appropriate symbol for the converter you wish to use and include the SimpleIni.h header file. If no specific converter is defined then the default converter is used. The default conversion mode uses SI_CONVERT_WIN32 on Windows and SI_CONVERT_GENERIC on all other platforms. If you are using ICU then SI_CONVERT_ICU is supported on all platforms. -# Declare an instance the appropriate class. Note that the following definitions are just shortcuts for commonly used types. Other types (PRUnichar, unsigned short, unsigned char) are also possible. <table> <tr><th>Interface <th>Case-sensitive <th>Load UTF-8 <th>Load MBCS <th>Typedef <tr><th>SI_CONVERT_GENERIC <tr><td>char <td>No <td>Yes <td>Yes #1 <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW <tr><th>SI_CONVERT_WIN32 <tr><td>char <td>No <td>No #2 <td>Yes <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW <tr><th>SI_CONVERT_ICU <tr><td>char <td>No <td>Yes <td>Yes <td>CSimpleIniA <tr><td>char <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseA <tr><td>UChar <td>No <td>Yes <td>Yes <td>CSimpleIniW <tr><td>UChar <td>Yes <td>Yes <td>Yes <td>CSimpleIniCaseW </table> #1 On Windows you are better to use CSimpleIniA with SI_CONVERT_WIN32.<br> #2 Only affects Windows. On Windows this uses MBCS functions and so may fold case incorrectly leading to uncertain results. -# Call LoadData() or LoadFile() to load and parse the INI configuration file -# Access and modify the data of the file using the following functions <table> <tr><td>GetAllSections <td>Return all section names <tr><td>GetAllKeys <td>Return all key names within a section <tr><td>GetAllValues <td>Return all values within a section & key <tr><td>GetSection <td>Return all key names and values in a section <tr><td>GetSectionSize <td>Return the number of keys in a section <tr><td>GetValue <td>Return a value for a section & key <tr><td>SetValue <td>Add or update a value for a section & key <tr><td>Delete <td>Remove a section, or a key from a section </table> -# Call Save() or SaveFile() to save the INI configuration data @section iostreams IO STREAMS SimpleIni supports reading from and writing to STL IO streams. Enable this by defining SI_SUPPORT_IOSTREAMS before including the SimpleIni.h header file. Ensure that if the streams are backed by a file (e.g. ifstream or ofstream) then the flag ios_base::binary has been used when the file was opened. @section multiline MULTI-LINE VALUES Values that span multiple lines are created using the following format. <pre> key = <<<ENDTAG .... multiline value .... ENDTAG </pre> Note the following: - The text used for ENDTAG can be anything and is used to find where the multi-line text ends. - The newline after ENDTAG in the start tag, and the newline before ENDTAG in the end tag is not included in the data value. - The ending tag must be on it's own line with no whitespace before or after it. - The multi-line value is modified at load so that each line in the value is delimited by a single '\\n' character on all platforms. At save time it will be converted into the newline format used by the current platform. @section comments COMMENTS Comments are preserved in the file within the following restrictions: - Every file may have a single "file comment". It must start with the first character in the file, and will end with the first non-comment line in the file. - Every section may have a single "section comment". It will start with the first comment line following the file comment, or the last data entry. It ends at the beginning of the section. - Every key may have a single "key comment". This comment will start with the first comment line following the section start, or the file comment if there is no section name. - Comments are set at the time that the file, section or key is first created. The only way to modify a comment on a section or a key is to delete that entry and recreate it with the new comment. There is no way to change the file comment. @section save SAVE ORDER The sections and keys are written out in the same order as they were read in from the file. Sections and keys added to the data after the file has been loaded will be added to the end of the file when it is written. There is no way to specify the location of a section or key other than in first-created, first-saved order. @section notes NOTES - To load UTF-8 data on Windows 95, you need to use Microsoft Layer for Unicode, or SI_CONVERT_GENERIC, or SI_CONVERT_ICU. - When using SI_CONVERT_GENERIC, ConvertUTF.c must be compiled and linked. - When using SI_CONVERT_ICU, ICU header files must be on the include path and icuuc.lib must be linked in. - To load a UTF-8 file on Windows AND expose it with SI_CHAR == char, you should use SI_CONVERT_GENERIC. - The collation (sorting) order used for sections and keys returned from iterators is NOT DEFINED. If collation order of the text is important then it should be done yourself by either supplying a replacement SI_STRLESS class, or by sorting the strings external to this library. - Usage of the <mbstring.h> header on Windows can be disabled by defining SI_NO_MBCS. This is defined automatically on Windows CE platforms. @section contrib CONTRIBUTIONS - 2010/05/03: Tobias Gehrig: added GetDoubleValue() @section licence MIT LICENCE The licence text below is the boilerplate "MIT Licence" used from: http://www.opensource.org/licenses/mit-license.php Copyright (c) 2006-2012, Brodie Thiesfield 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 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INCLUDED_SimpleIni_h #define INCLUDED_SimpleIni_h #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // Disable these warnings in MSVC: // 4127 "conditional expression is constant" as the conversion classes trigger // it with the statement if (sizeof(SI_CHAR) == sizeof(char)). This test will // be optimized away in a release build. // 4503 'insert' : decorated name length exceeded, name was truncated // 4702 "unreachable code" as the MS STL header causes it in release mode. // Again, the code causing the warning will be cleaned up by the compiler. // 4786 "identifier truncated to 256 characters" as this is thrown hundreds // of times VC6 as soon as STL is used. #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4127 4503 4702 4786) #endif #include <cstring> #include <string> #include <map> #include <list> #include <algorithm> #include <stdio.h> #ifdef SI_SUPPORT_IOSTREAMS # include <iostream> #endif // SI_SUPPORT_IOSTREAMS #ifdef _DEBUG # ifndef assert # include <cassert> # endif # define SI_ASSERT(x) assert(x) #else # define SI_ASSERT(x) #endif enum SI_Error { SI_OK = 0, //!< No error SI_UPDATED = 1, //!< An existing value was updated SI_INSERTED = 2, //!< A new value was inserted // note: test for any error with (retval < 0) SI_FAIL = -1, //!< Generic failure SI_NOMEM = -2, //!< Out of memory error SI_FILE = -3 //!< File error (see errno for detail error) }; #define SI_UTF8_SIGNATURE "\xEF\xBB\xBF" #ifdef _WIN32 # define SI_NEWLINE_A "\r\n" # define SI_NEWLINE_W L"\r\n" #else // !_WIN32 # define SI_NEWLINE_A "\n" # define SI_NEWLINE_W L"\n" #endif // _WIN32 #if defined(SI_CONVERT_ICU) # include <unicode/ustring.h> #endif #if defined(_WIN32) # define SI_HAS_WIDE_FILE # define SI_WCHAR_T wchar_t #elif defined(SI_CONVERT_ICU) # define SI_HAS_WIDE_FILE # define SI_WCHAR_T UChar #endif // --------------------------------------------------------------------------- // MAIN TEMPLATE CLASS // --------------------------------------------------------------------------- /** Simple INI file reader. This can be instantiated with the choice of unicode or native characterset, and case sensitive or insensitive comparisons of section and key names. The supported combinations are pre-defined with the following typedefs: <table> <tr><th>Interface <th>Case-sensitive <th>Typedef <tr><td>char <td>No <td>CSimpleIniA <tr><td>char <td>Yes <td>CSimpleIniCaseA <tr><td>wchar_t <td>No <td>CSimpleIniW <tr><td>wchar_t <td>Yes <td>CSimpleIniCaseW </table> Note that using other types for the SI_CHAR is supported. For instance, unsigned char, unsigned short, etc. Note that where the alternative type is a different size to char/wchar_t you may need to supply new helper classes for SI_STRLESS and SI_CONVERTER. */ template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> class CSimpleIniTempl { public: typedef SI_CHAR SI_CHAR_T; /** key entry */ struct Entry { const SI_CHAR * pItem; const SI_CHAR * pComment; int nOrder; Entry(const SI_CHAR * a_pszItem = NULL, int a_nOrder = 0) : pItem(a_pszItem) , pComment(NULL) , nOrder(a_nOrder) { } Entry(const SI_CHAR * a_pszItem, const SI_CHAR * a_pszComment, int a_nOrder) : pItem(a_pszItem) , pComment(a_pszComment) , nOrder(a_nOrder) { } Entry(const Entry & rhs) { operator=(rhs); } Entry & operator=(const Entry & rhs) { pItem = rhs.pItem; pComment = rhs.pComment; nOrder = rhs.nOrder; return *this; } #if defined(_MSC_VER) && _MSC_VER <= 1200 /** STL of VC6 doesn't allow me to specify my own comparator for list::sort() */ bool operator<(const Entry & rhs) const { return LoadOrder()(*this, rhs); } bool operator>(const Entry & rhs) const { return LoadOrder()(rhs, *this); } #endif /** Strict less ordering by name of key only */ struct KeyOrder : std::binary_function<Entry, Entry, bool> { bool operator()(const Entry & lhs, const Entry & rhs) const { const static SI_STRLESS isLess = SI_STRLESS(); return isLess(lhs.pItem, rhs.pItem); } }; /** Strict less ordering by order, and then name of key */ struct LoadOrder : std::binary_function<Entry, Entry, bool> { bool operator()(const Entry & lhs, const Entry & rhs) const { if (lhs.nOrder != rhs.nOrder) { return lhs.nOrder < rhs.nOrder; } return KeyOrder()(lhs.pItem, rhs.pItem); } }; }; /** map keys to values */ typedef std::multimap<Entry,const SI_CHAR *,typename Entry::KeyOrder> TKeyVal; /** map sections to key/value map */ typedef std::map<Entry,TKeyVal,typename Entry::KeyOrder> TSection; /** set of dependent string pointers. Note that these pointers are dependent on memory owned by CSimpleIni. */ typedef std::list<Entry> TNamesDepend; /** interface definition for the OutputWriter object to pass to Save() in order to output the INI file data. */ class OutputWriter { public: OutputWriter() { } virtual ~OutputWriter() { } virtual void Write(const char * a_pBuf) = 0; private: OutputWriter(const OutputWriter &); // disable OutputWriter & operator=(const OutputWriter &); // disable }; /** OutputWriter class to write the INI data to a file */ class FileWriter : public OutputWriter { FILE * m_file; public: FileWriter(FILE * a_file) : m_file(a_file) { } void Write(const char * a_pBuf) { fputs(a_pBuf, m_file); } private: FileWriter(const FileWriter &); // disable FileWriter & operator=(const FileWriter &); // disable }; /** OutputWriter class to write the INI data to a string */ class StringWriter : public OutputWriter { std::string & m_string; public: StringWriter(std::string & a_string) : m_string(a_string) { } void Write(const char * a_pBuf) { m_string.append(a_pBuf); } private: StringWriter(const StringWriter &); // disable StringWriter & operator=(const StringWriter &); // disable }; #ifdef SI_SUPPORT_IOSTREAMS /** OutputWriter class to write the INI data to an ostream */ class StreamWriter : public OutputWriter { std::ostream & m_ostream; public: StreamWriter(std::ostream & a_ostream) : m_ostream(a_ostream) { } void Write(const char * a_pBuf) { m_ostream << a_pBuf; } private: StreamWriter(const StreamWriter &); // disable StreamWriter & operator=(const StreamWriter &); // disable }; #endif // SI_SUPPORT_IOSTREAMS /** Characterset conversion utility class to convert strings to the same format as is used for the storage. */ class Converter : private SI_CONVERTER { public: using SI_CONVERTER::SizeToStore; Converter(bool a_bStoreIsUtf8) : SI_CONVERTER(a_bStoreIsUtf8) { m_scratch.resize(1024); } Converter(const Converter & rhs) { operator=(rhs); } Converter & operator=(const Converter & rhs) { m_scratch = rhs.m_scratch; return *this; } bool ConvertToStore(const SI_CHAR * a_pszString) { size_t uLen = SizeToStore(a_pszString); if (uLen == (size_t)(-1)) { return false; } while (uLen > m_scratch.size()) { m_scratch.resize(m_scratch.size() * 2); } return SI_CONVERTER::ConvertToStore( a_pszString, const_cast<char*>(m_scratch.data()), m_scratch.size()); } const char * Data() { return m_scratch.data(); } private: std::string m_scratch; }; public: /*-----------------------------------------------------------------------*/ /** Default constructor. @param a_bIsUtf8 See the method SetUnicode() for details. @param a_bMultiKey See the method SetMultiKey() for details. @param a_bMultiLine See the method SetMultiLine() for details. */ CSimpleIniTempl( bool a_bIsUtf8 = false, bool a_bMultiKey = false, bool a_bMultiLine = false ); /** Destructor */ ~CSimpleIniTempl(); /** Deallocate all memory stored by this object */ void Reset(); /** Has any data been loaded */ bool IsEmpty() const { return m_data.empty(); } /*-----------------------------------------------------------------------*/ /** @{ @name Settings */ /** Set the storage format of the INI data. This affects both the loading and saving of the INI data using all of the Load/Save API functions. This value cannot be changed after any INI data has been loaded. If the file is not set to Unicode (UTF-8), then the data encoding is assumed to be the OS native encoding. This encoding is the system locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP. If the storage format is set to Unicode then the file will be loaded as UTF-8 encoded data regardless of the native file encoding. If SI_CHAR == char then all of the char* parameters take and return UTF-8 encoded data regardless of the system locale. \param a_bIsUtf8 Assume UTF-8 encoding for the source? */ void SetUnicode(bool a_bIsUtf8 = true) { if (!m_pData) m_bStoreIsUtf8 = a_bIsUtf8; } /** Get the storage format of the INI data. */ bool IsUnicode() const { return m_bStoreIsUtf8; } /** Should multiple identical keys be permitted in the file. If set to false then the last value encountered will be used as the value of the key. If set to true, then all values will be available to be queried. For example, with the following input: <pre> [section] test=value1 test=value2 </pre> Then with SetMultiKey(true), both of the values "value1" and "value2" will be returned for the key test. If SetMultiKey(false) is used, then the value for "test" will only be "value2". This value may be changed at any time. \param a_bAllowMultiKey Allow multi-keys in the source? */ void SetMultiKey(bool a_bAllowMultiKey = true) { m_bAllowMultiKey = a_bAllowMultiKey; } /** Get the storage format of the INI data. */ bool IsMultiKey() const { return m_bAllowMultiKey; } /** Should data values be permitted to span multiple lines in the file. If set to false then the multi-line construct <<<TAG as a value will be returned as is instead of loading the data. This value may be changed at any time. \param a_bAllowMultiLine Allow multi-line values in the source? */ void SetMultiLine(bool a_bAllowMultiLine = true) { m_bAllowMultiLine = a_bAllowMultiLine; } /** Query the status of multi-line data */ bool IsMultiLine() const { return m_bAllowMultiLine; } /** Should spaces be added around the equals sign when writing key/value pairs out. When true, the result will be "key = value". When false, the result will be "key=value". This value may be changed at any time. \param a_bSpaces Add spaces around the equals sign? */ void SetSpaces(bool a_bSpaces = true) { m_bSpaces = a_bSpaces; } /** Query the status of spaces output */ bool UsingSpaces() const { return m_bSpaces; } /*-----------------------------------------------------------------------*/ /** @} @{ @name Loading INI Data */ /** Load an INI file from disk into memory @param a_pszFile Path of the file to be loaded. This will be passed to fopen() and so must be a valid path for the current platform. @return SI_Error See error definitions */ SI_Error LoadFile( const char * a_pszFile ); #ifdef SI_HAS_WIDE_FILE /** Load an INI file from disk into memory @param a_pwszFile Path of the file to be loaded in UTF-16. @return SI_Error See error definitions */ SI_Error LoadFile( const SI_WCHAR_T * a_pwszFile ); #endif // SI_HAS_WIDE_FILE /** Load the file from a file pointer. @param a_fpFile Valid file pointer to read the file data from. The file will be read until end of file. @return SI_Error See error definitions */ SI_Error LoadFile( FILE * a_fpFile ); #ifdef SI_SUPPORT_IOSTREAMS /** Load INI file data from an istream. @param a_istream Stream to read from @return SI_Error See error definitions */ SI_Error LoadData( std::istream & a_istream ); #endif // SI_SUPPORT_IOSTREAMS /** Load INI file data direct from a std::string @param a_strData Data to be loaded @return SI_Error See error definitions */ SI_Error LoadData(const std::string & a_strData) { return LoadData(a_strData.c_str(), a_strData.size()); } /** Load INI file data direct from memory @param a_pData Data to be loaded @param a_uDataLen Length of the data in bytes @return SI_Error See error definitions */ SI_Error LoadData( const char * a_pData, size_t a_uDataLen ); /*-----------------------------------------------------------------------*/ /** @} @{ @name Saving INI Data */ /** Save an INI file from memory to disk @param a_pszFile Path of the file to be saved. This will be passed to fopen() and so must be a valid path for the current platform. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this parameter is ignored. @return SI_Error See error definitions */ SI_Error SaveFile( const char * a_pszFile, bool a_bAddSignature = true ) const; #ifdef SI_HAS_WIDE_FILE /** Save an INI file from memory to disk @param a_pwszFile Path of the file to be saved in UTF-16. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this parameter is ignored. @return SI_Error See error definitions */ SI_Error SaveFile( const SI_WCHAR_T * a_pwszFile, bool a_bAddSignature = true ) const; #endif // _WIN32 /** Save the INI data to a file. See Save() for details. @param a_pFile Handle to a file. File should be opened for binary output. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the file. @return SI_Error See error definitions */ SI_Error SaveFile( FILE * a_pFile, bool a_bAddSignature = false ) const; /** Save the INI data. The data will be written to the output device in a format appropriate to the current data, selected by: <table> <tr><th>SI_CHAR <th>FORMAT <tr><td>char <td>same format as when loaded (MBCS or UTF-8) <tr><td>wchar_t <td>UTF-8 <tr><td>other <td>UTF-8 </table> Note that comments from the original data is preserved as per the documentation on comments. The order of the sections and values from the original file will be preserved. Any data prepended or appended to the output device must use the the same format (MBCS or UTF-8). You may use the GetConverter() method to convert text to the correct format regardless of the output format being used by SimpleIni. To add a BOM to UTF-8 data, write it out manually at the very beginning like is done in SaveFile when a_bUseBOM is true. @param a_oOutput Output writer to write the data to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the OutputWriter. @return SI_Error See error definitions */ SI_Error Save( OutputWriter & a_oOutput, bool a_bAddSignature = false ) const; #ifdef SI_SUPPORT_IOSTREAMS /** Save the INI data to an ostream. See Save() for details. @param a_ostream String to have the INI data appended to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the stream. @return SI_Error See error definitions */ SI_Error Save( std::ostream & a_ostream, bool a_bAddSignature = false ) const { StreamWriter writer(a_ostream); return Save(writer, a_bAddSignature); } #endif // SI_SUPPORT_IOSTREAMS /** Append the INI data to a string. See Save() for details. @param a_sBuffer String to have the INI data appended to. @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the string. @return SI_Error See error definitions */ SI_Error Save( std::string & a_sBuffer, bool a_bAddSignature = false ) const { StringWriter writer(a_sBuffer); return Save(writer, a_bAddSignature); } /*-----------------------------------------------------------------------*/ /** @} @{ @name Accessing INI Data */ /** Retrieve all section names. The list is returned as an STL vector of names and can be iterated or searched as necessary. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these pointers are in use! @param a_names Vector that will receive all of the section names. See note above! */ void GetAllSections( TNamesDepend & a_names ) const; /** Retrieve all unique key names in a section. The sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. Only unique key names are returned. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use! @param a_pSection Section to request data for @param a_names List that will receive all of the key names. See note above! @return true Section was found. @return false Matching section was not found. */ bool GetAllKeys( const SI_CHAR * a_pSection, TNamesDepend & a_names ) const; /** Retrieve all values for a specific key. This method can be used when multiple keys are both enabled and disabled. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. NOTE! The returned values are pointers to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer! @param a_pSection Section to search @param a_pKey Key to search for @param a_values List to return if the key is not found @return true Key was found. @return false Matching section/key was not found. */ bool GetAllValues( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, TNamesDepend & a_values ) const; /** Query the number of keys in a specific section. Note that if multiple keys are enabled, then this value may be different to the number of keys returned by GetAllKeys. @param a_pSection Section to request data for @return -1 Section does not exist in the file @return >=0 Number of keys in the section */ int GetSectionSize( const SI_CHAR * a_pSection ) const; /** Retrieve all key and value pairs for a section. The data is returned as a pointer to an STL map and can be iterated or searched as desired. Note that multiple entries for the same key may exist when multiple keys have been enabled. NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use! @param a_pSection Name of the section to return @return boolean Was a section matching the supplied name found. */ const TKeyVal * GetSection( const SI_CHAR * a_pSection ) const; /** Retrieve the value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. NOTE! The returned value is a pointer to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer! @param a_pSection Section to search @param a_pKey Key to search for @param a_pDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_pDefault Key was not found in the section @return other Value of the key */ const SI_CHAR * GetValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, const SI_CHAR * a_pDefault = NULL, bool * a_pHasMultiple = NULL ) const; /** Retrieve a numeric value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. @param a_pSection Section to search @param a_pKey Key to search for @param a_nDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ long GetLongValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, long a_nDefault = 0, bool * a_pHasMultiple = NULL ) const; /** Retrieve a numeric value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. @param a_pSection Section to search @param a_pKey Key to search for @param a_nDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ double GetDoubleValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, double a_nDefault = 0, bool * a_pHasMultiple = NULL ) const; /** Retrieve a boolean value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey. Strings starting with "t", "y", "on" or "1" are returned as logically true. Strings starting with "f", "n", "of" or "0" are returned as logically false. For all other values the default is returned. Character comparisons are case-insensitive. @param a_pSection Section to search @param a_pKey Key to search for @param a_bDefault Value to return if the key is not found @param a_pHasMultiple Optionally receive notification of if there are multiple entries for this key. @return a_nDefault Key was not found in the section @return other Value of the key */ bool GetBoolValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bDefault = false, bool * a_pHasMultiple = NULL ) const; /** Add or update a section or value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. Set to NULL to create an empty section. @param a_pValue Value to set. Set to NULL to create an empty section. @param a_pComment Comment to be associated with the section or the key. If a_pKey is NULL then it will be associated with the section, otherwise the key. Note that a comment may be set ONLY when the section or key is first created (i.e. when this function returns the value SI_INSERTED). If you wish to create a section with a comment then you need to create the section separately to the key. The comment string must be in full comment form already (have a comment character starting every line). @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetValue and SetValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, const SI_CHAR * a_pValue, const SI_CHAR * a_pComment = NULL, bool a_bForceReplace = false ) { return AddEntry(a_pSection, a_pKey, a_pValue, a_pComment, a_bForceReplace, true); } /** Add or update a numeric value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_nValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bUseHex By default the value will be written to the file in decimal format. Set this to true to write it as hexadecimal. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetLongValue and SetLongValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetLongValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, long a_nValue, const SI_CHAR * a_pComment = NULL, bool a_bUseHex = false, bool a_bForceReplace = false ); /** Add or update a double value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_nValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetDoubleValue and SetDoubleValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetDoubleValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, double a_nValue, const SI_CHAR * a_pComment = NULL, bool a_bForceReplace = false ); /** Add or update a boolean value. This will always insert when multiple keys are enabled. @param a_pSection Section to add or update @param a_pKey Key to add or update. @param a_bValue Value to set. @param a_pComment Comment to be associated with the key. See the notes on SetValue() for comments. @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/SetBoolValue and SetBoolValue with a_bForceReplace = true, is that the load order and comment will be preserved this way. @return SI_Error See error definitions @return SI_UPDATED Value was updated @return SI_INSERTED Value was inserted */ SI_Error SetBoolValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bValue, const SI_CHAR * a_pComment = NULL, bool a_bForceReplace = false ); /** Delete an entire section, or a key from a section. Note that the data returned by GetSection is invalid and must not be used after anything has been deleted from that section using this method. Note when multiple keys is enabled, this will delete all keys with that name; there is no way to selectively delete individual key/values in this situation. @param a_pSection Section to delete key from, or if a_pKey is NULL, the section to remove. @param a_pKey Key to remove from the section. Set to NULL to remove the entire section. @param a_bRemoveEmpty If the section is empty after this key has been deleted, should the empty section be removed? @return true Key or section was deleted. @return false Key or section was not found. */ bool Delete( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bRemoveEmpty = false ); /*-----------------------------------------------------------------------*/ /** @} @{ @name Converter */ /** Return a conversion object to convert text to the same encoding as is used by the Save(), SaveFile() and SaveString() functions. Use this to prepare the strings that you wish to append or prepend to the output INI data. */ Converter GetConverter() const { return Converter(m_bStoreIsUtf8); } /*-----------------------------------------------------------------------*/ /** @} */ private: // copying is not permitted CSimpleIniTempl(const CSimpleIniTempl &); // disabled CSimpleIniTempl & operator=(const CSimpleIniTempl &); // disabled /** Parse the data looking for a file comment and store it if found. */ SI_Error FindFileComment( SI_CHAR *& a_pData, bool a_bCopyStrings ); /** Parse the data looking for the next valid entry. The memory pointed to by a_pData is modified by inserting NULL characters. The pointer is updated to the current location in the block of text. */ bool FindEntry( SI_CHAR *& a_pData, const SI_CHAR *& a_pSection, const SI_CHAR *& a_pKey, const SI_CHAR *& a_pVal, const SI_CHAR *& a_pComment ) const; /** Add the section/key/value to our data. @param a_pSection Section name. Sections will be created if they don't already exist. @param a_pKey Key name. May be NULL to create an empty section. Existing entries will be updated. New entries will be created. @param a_pValue Value for the key. @param a_pComment Comment to be associated with the section or the key. If a_pKey is NULL then it will be associated with the section, otherwise the key. This must be a string in full comment form already (have a comment character starting every line). @param a_bForceReplace Should all existing values in a multi-key INI file be replaced with this entry. This option has no effect if not using multi-key files. The difference between Delete/AddEntry and AddEntry with a_bForceReplace = true, is that the load order and comment will be preserved this way. @param a_bCopyStrings Should copies of the strings be made or not. If false then the pointers will be used as is. */ SI_Error AddEntry( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, const SI_CHAR * a_pValue, const SI_CHAR * a_pComment, bool a_bForceReplace, bool a_bCopyStrings ); /** Is the supplied character a whitespace character? */ inline bool IsSpace(SI_CHAR ch) const { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'); } /** Does the supplied character start a comment line? */ inline bool IsComment(SI_CHAR ch) const { return (ch == ';' || ch == '#'); } /** Skip over a newline character (or characters) for either DOS or UNIX */ inline void SkipNewLine(SI_CHAR *& a_pData) const { a_pData += (*a_pData == '\r' && *(a_pData+1) == '\n') ? 2 : 1; } /** Make a copy of the supplied string, replacing the original pointer */ SI_Error CopyString(const SI_CHAR *& a_pString); /** Delete a string from the copied strings buffer if necessary */ void DeleteString(const SI_CHAR * a_pString); /** Internal use of our string comparison function */ bool IsLess(const SI_CHAR * a_pLeft, const SI_CHAR * a_pRight) const { const static SI_STRLESS isLess = SI_STRLESS(); return isLess(a_pLeft, a_pRight); } bool IsMultiLineTag(const SI_CHAR * a_pData) const; bool IsMultiLineData(const SI_CHAR * a_pData) const; bool LoadMultiLineText( SI_CHAR *& a_pData, const SI_CHAR *& a_pVal, const SI_CHAR * a_pTagName, bool a_bAllowBlankLinesInComment = false ) const; bool IsNewLineChar(SI_CHAR a_c) const; bool OutputMultiLineText( OutputWriter & a_oOutput, Converter & a_oConverter, const SI_CHAR * a_pText ) const; private: /** Copy of the INI file data in our character format. This will be modified when parsed to have NULL characters added after all interesting string entries. All of the string pointers to sections, keys and values point into this block of memory. */ SI_CHAR * m_pData; /** Length of the data that we have stored. Used when deleting strings to determine if the string is stored here or in the allocated string buffer. */ size_t m_uDataLen; /** File comment for this data, if one exists. */ const SI_CHAR * m_pFileComment; /** Parsed INI data. Section -> (Key -> Value). */ TSection m_data; /** This vector stores allocated memory for copies of strings that have been supplied after the file load. It will be empty unless SetValue() has been called. */ TNamesDepend m_strings; /** Is the format of our datafile UTF-8 or MBCS? */ bool m_bStoreIsUtf8; /** Are multiple values permitted for the same key? */ bool m_bAllowMultiKey; /** Are data values permitted to span multiple lines? */ bool m_bAllowMultiLine; /** Should spaces be written out surrounding the equals sign? */ bool m_bSpaces; /** Next order value, used to ensure sections and keys are output in the same order that they are loaded/added. */ int m_nOrder; }; // --------------------------------------------------------------------------- // IMPLEMENTATION // --------------------------------------------------------------------------- template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::CSimpleIniTempl( bool a_bIsUtf8, bool a_bAllowMultiKey, bool a_bAllowMultiLine ) : m_pData(0) , m_uDataLen(0) , m_pFileComment(NULL) , m_bStoreIsUtf8(a_bIsUtf8) , m_bAllowMultiKey(a_bAllowMultiKey) , m_bAllowMultiLine(a_bAllowMultiLine) , m_bSpaces(true) , m_nOrder(0) { } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::~CSimpleIniTempl() { Reset(); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::Reset() { // remove all data delete[] m_pData; m_pData = NULL; m_uDataLen = 0; m_pFileComment = NULL; if (!m_data.empty()) { m_data.erase(m_data.begin(), m_data.end()); } // remove all strings if (!m_strings.empty()) { typename TNamesDepend::iterator i = m_strings.begin(); for (; i != m_strings.end(); ++i) { delete[] const_cast<SI_CHAR*>(i->pItem); } m_strings.erase(m_strings.begin(), m_strings.end()); } } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadFile( const char * a_pszFile ) { FILE * fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE fopen_s(&fp, a_pszFile, "rb"); #else // !__STDC_WANT_SECURE_LIB__ fp = fopen(a_pszFile, "rb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) { return SI_FILE; } SI_Error rc = LoadFile(fp); fclose(fp); return rc; } #ifdef SI_HAS_WIDE_FILE template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadFile( const SI_WCHAR_T * a_pwszFile ) { #ifdef _WIN32 FILE * fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE _wfopen_s(&fp, a_pwszFile, L"rb"); #else // !__STDC_WANT_SECURE_LIB__ fp = _wfopen(a_pwszFile, L"rb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = LoadFile(fp); fclose(fp); return rc; #else // !_WIN32 (therefore SI_CONVERT_ICU) char szFile[256]; u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); return LoadFile(szFile); #endif // _WIN32 } #endif // SI_HAS_WIDE_FILE template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadFile( FILE * a_fpFile ) { // load the raw file data int retval = fseek(a_fpFile, 0, SEEK_END); if (retval != 0) { return SI_FILE; } long lSize = ftell(a_fpFile); if (lSize < 0) { return SI_FILE; } if (lSize == 0) { return SI_OK; } // allocate and ensure NULL terminated char * pData = new char[lSize+1]; if (!pData) { return SI_NOMEM; } pData[lSize] = 0; // load data into buffer fseek(a_fpFile, 0, SEEK_SET); size_t uRead = fread(pData, sizeof(char), lSize, a_fpFile); if (uRead != (size_t) lSize) { delete[] pData; return SI_FILE; } // convert the raw data to unicode SI_Error rc = LoadData(pData, uRead); delete[] pData; return rc; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadData( const char * a_pData, size_t a_uDataLen ) { SI_CONVERTER converter(m_bStoreIsUtf8); if (a_uDataLen == 0) { return SI_OK; } // consume the UTF-8 BOM if it exists if (m_bStoreIsUtf8 && a_uDataLen >= 3) { if (memcmp(a_pData, SI_UTF8_SIGNATURE, 3) == 0) { a_pData += 3; a_uDataLen -= 3; } } // determine the length of the converted data size_t uLen = converter.SizeFromStore(a_pData, a_uDataLen); if (uLen == (size_t)(-1)) { return SI_FAIL; } // allocate memory for the data, ensure that there is a NULL // terminator wherever the converted data ends SI_CHAR * pData = new SI_CHAR[uLen+1]; if (!pData) { return SI_NOMEM; } memset(pData, 0, sizeof(SI_CHAR)*(uLen+1)); // convert the data if (!converter.ConvertFromStore(a_pData, a_uDataLen, pData, uLen)) { delete[] pData; return SI_FAIL; } // parse it const static SI_CHAR empty = 0; SI_CHAR * pWork = pData; const SI_CHAR * pSection = ∅ const SI_CHAR * pItem = NULL; const SI_CHAR * pVal = NULL; const SI_CHAR * pComment = NULL; // We copy the strings if we are loading data into this class when we // already have stored some. bool bCopyStrings = (m_pData != NULL); // find a file comment if it exists, this is a comment that starts at the // beginning of the file and continues until the first blank line. SI_Error rc = FindFileComment(pWork, bCopyStrings); if (rc < 0) return rc; // add every entry in the file to the data table while (FindEntry(pWork, pSection, pItem, pVal, pComment)) { rc = AddEntry(pSection, pItem, pVal, pComment, false, bCopyStrings); if (rc < 0) return rc; } // store these strings if we didn't copy them if (bCopyStrings) { delete[] pData; } else { m_pData = pData; m_uDataLen = uLen+1; } return SI_OK; } #ifdef SI_SUPPORT_IOSTREAMS template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadData( std::istream & a_istream ) { std::string strData; char szBuf[512]; do { a_istream.get(szBuf, sizeof(szBuf), '\0'); strData.append(szBuf); } while (a_istream.good()); return LoadData(strData); } #endif // SI_SUPPORT_IOSTREAMS template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::FindFileComment( SI_CHAR *& a_pData, bool a_bCopyStrings ) { // there can only be a single file comment if (m_pFileComment) { return SI_OK; } // Load the file comment as multi-line text, this will modify all of // the newline characters to be single \n chars if (!LoadMultiLineText(a_pData, m_pFileComment, NULL, false)) { return SI_OK; } // copy the string if necessary if (a_bCopyStrings) { SI_Error rc = CopyString(m_pFileComment); if (rc < 0) return rc; } return SI_OK; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::FindEntry( SI_CHAR *& a_pData, const SI_CHAR *& a_pSection, const SI_CHAR *& a_pKey, const SI_CHAR *& a_pVal, const SI_CHAR *& a_pComment ) const { a_pComment = NULL; SI_CHAR * pTrail = NULL; while (*a_pData) { // skip spaces and empty lines while (*a_pData && IsSpace(*a_pData)) { ++a_pData; } if (!*a_pData) { break; } // skip processing of comment lines but keep a pointer to // the start of the comment. if (IsComment(*a_pData)) { LoadMultiLineText(a_pData, a_pComment, NULL, true); continue; } // process section names if (*a_pData == '[') { // skip leading spaces ++a_pData; while (*a_pData && IsSpace(*a_pData)) { ++a_pData; } // find the end of the section name (it may contain spaces) // and convert it to lowercase as necessary a_pSection = a_pData; while (*a_pData && *a_pData != ']' && !IsNewLineChar(*a_pData)) { ++a_pData; } // if it's an invalid line, just skip it if (*a_pData != ']') { continue; } // remove trailing spaces from the section pTrail = a_pData - 1; while (pTrail >= a_pSection && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // skip to the end of the line ++a_pData; // safe as checked that it == ']' above while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } a_pKey = NULL; a_pVal = NULL; return true; } // find the end of the key name (it may contain spaces) // and convert it to lowercase as necessary a_pKey = a_pData; while (*a_pData && *a_pData != '=' && !IsNewLineChar(*a_pData)) { ++a_pData; } // if it's an invalid line, just skip it if (*a_pData != '=') { continue; } // empty keys are invalid if (a_pKey == a_pData) { while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } continue; } // remove trailing spaces from the key pTrail = a_pData - 1; while (pTrail >= a_pKey && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // skip leading whitespace on the value ++a_pData; // safe as checked that it == '=' above while (*a_pData && !IsNewLineChar(*a_pData) && IsSpace(*a_pData)) { ++a_pData; } // find the end of the value which is the end of this line a_pVal = a_pData; while (*a_pData && !IsNewLineChar(*a_pData)) { ++a_pData; } // remove trailing spaces from the value pTrail = a_pData - 1; if (*a_pData) { // prepare for the next round SkipNewLine(a_pData); } while (pTrail >= a_pVal && IsSpace(*pTrail)) { --pTrail; } ++pTrail; *pTrail = 0; // check for multi-line entries if (m_bAllowMultiLine && IsMultiLineTag(a_pVal)) { // skip the "<<<" to get the tag that will end the multiline const SI_CHAR * pTagName = a_pVal + 3; return LoadMultiLineText(a_pData, a_pVal, pTagName); } // return the standard entry return true; } return false; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::IsMultiLineTag( const SI_CHAR * a_pVal ) const { // check for the "<<<" prefix for a multi-line entry if (*a_pVal++ != '<') return false; if (*a_pVal++ != '<') return false; if (*a_pVal++ != '<') return false; return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::IsMultiLineData( const SI_CHAR * a_pData ) const { // data is multi-line if it has any of the following features: // * whitespace prefix // * embedded newlines // * whitespace suffix // empty string if (!*a_pData) { return false; } // check for prefix if (IsSpace(*a_pData)) { return true; } // embedded newlines while (*a_pData) { if (IsNewLineChar(*a_pData)) { return true; } ++a_pData; } // check for suffix if (IsSpace(*--a_pData)) { return true; } return false; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::IsNewLineChar( SI_CHAR a_c ) const { return (a_c == '\n' || a_c == '\r'); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::LoadMultiLineText( SI_CHAR *& a_pData, const SI_CHAR *& a_pVal, const SI_CHAR * a_pTagName, bool a_bAllowBlankLinesInComment ) const { // we modify this data to strip all newlines down to a single '\n' // character. This means that on Windows we need to strip out some // characters which will make the data shorter. // i.e. LINE1-LINE1\r\nLINE2-LINE2\0 will become // LINE1-LINE1\nLINE2-LINE2\0 // The pDataLine entry is the pointer to the location in memory that // the current line needs to start to run following the existing one. // This may be the same as pCurrLine in which case no move is needed. SI_CHAR * pDataLine = a_pData; SI_CHAR * pCurrLine; // value starts at the current line a_pVal = a_pData; // find the end tag. This tag must start in column 1 and be // followed by a newline. No whitespace removal is done while // searching for this tag. SI_CHAR cEndOfLineChar = *a_pData; for(;;) { // if we are loading comments then we need a comment character as // the first character on every line if (!a_pTagName && !IsComment(*a_pData)) { // if we aren't allowing blank lines then we're done if (!a_bAllowBlankLinesInComment) { break; } // if we are allowing blank lines then we only include them // in this comment if another comment follows, so read ahead // to find out. SI_CHAR * pCurr = a_pData; int nNewLines = 0; while (IsSpace(*pCurr)) { if (IsNewLineChar(*pCurr)) { ++nNewLines; SkipNewLine(pCurr); } else { ++pCurr; } } // we have a comment, add the blank lines to the output // and continue processing from here if (IsComment(*pCurr)) { for (; nNewLines > 0; --nNewLines) *pDataLine++ = '\n'; a_pData = pCurr; continue; } // the comment ends here break; } // find the end of this line pCurrLine = a_pData; while (*a_pData && !IsNewLineChar(*a_pData)) ++a_pData; // move this line down to the location that it should be if necessary if (pDataLine < pCurrLine) { size_t nLen = (size_t) (a_pData - pCurrLine); memmove(pDataLine, pCurrLine, nLen * sizeof(SI_CHAR)); pDataLine[nLen] = '\0'; } // end the line with a NULL cEndOfLineChar = *a_pData; *a_pData = 0; // if are looking for a tag then do the check now. This is done before // checking for end of the data, so that if we have the tag at the end // of the data then the tag is removed correctly. if (a_pTagName && (!IsLess(pDataLine, a_pTagName) && !IsLess(a_pTagName, pDataLine))) { break; } // if we are at the end of the data then we just automatically end // this entry and return the current data. if (!cEndOfLineChar) { return true; } // otherwise we need to process this newline to ensure that it consists // of just a single \n character. pDataLine += (a_pData - pCurrLine); *a_pData = cEndOfLineChar; SkipNewLine(a_pData); *pDataLine++ = '\n'; } // if we didn't find a comment at all then return false if (a_pVal == a_pData) { a_pVal = NULL; return false; } // the data (which ends at the end of the last line) needs to be // null-terminated BEFORE before the newline character(s). If the // user wants a new line in the multi-line data then they need to // add an empty line before the tag. *--pDataLine = '\0'; // if looking for a tag and if we aren't at the end of the data, // then move a_pData to the start of the next line. if (a_pTagName && cEndOfLineChar) { SI_ASSERT(IsNewLineChar(cEndOfLineChar)); *a_pData = cEndOfLineChar; SkipNewLine(a_pData); } return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::CopyString( const SI_CHAR *& a_pString ) { size_t uLen = 0; if (sizeof(SI_CHAR) == sizeof(char)) { uLen = strlen((const char *)a_pString); } else if (sizeof(SI_CHAR) == sizeof(wchar_t)) { uLen = wcslen((const wchar_t *)a_pString); } else { for ( ; a_pString[uLen]; ++uLen) /*loop*/ ; } ++uLen; // NULL character SI_CHAR * pCopy = new SI_CHAR[uLen]; if (!pCopy) { return SI_NOMEM; } memcpy(pCopy, a_pString, sizeof(SI_CHAR)*uLen); m_strings.push_back(pCopy); a_pString = pCopy; return SI_OK; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::AddEntry( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, const SI_CHAR * a_pValue, const SI_CHAR * a_pComment, bool a_bForceReplace, bool a_bCopyStrings ) { SI_Error rc; bool bInserted = false; SI_ASSERT(!a_pComment || IsComment(*a_pComment)); // if we are copying strings then make a copy of the comment now // because we will need it when we add the entry. if (a_bCopyStrings && a_pComment) { rc = CopyString(a_pComment); if (rc < 0) return rc; } // create the section entry if necessary typename TSection::iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { // if the section doesn't exist then we need a copy as the // string needs to last beyond the end of this function if (a_bCopyStrings) { rc = CopyString(a_pSection); if (rc < 0) return rc; } // only set the comment if this is a section only entry Entry oSection(a_pSection, ++m_nOrder); if (a_pComment && (!a_pKey || !a_pValue)) { oSection.pComment = a_pComment; } typename TSection::value_type oEntry(oSection, TKeyVal()); typedef typename TSection::iterator SectionIterator; std::pair<SectionIterator,bool> i = m_data.insert(oEntry); iSection = i.first; bInserted = true; } if (!a_pKey || !a_pValue) { // section only entries are specified with pItem and pVal as NULL return bInserted ? SI_INSERTED : SI_UPDATED; } // check for existence of the key TKeyVal & keyval = iSection->second; typename TKeyVal::iterator iKey = keyval.find(a_pKey); // remove all existing entries but save the load order and // comment of the first entry int nLoadOrder = ++m_nOrder; if (iKey != keyval.end() && m_bAllowMultiKey && a_bForceReplace) { const SI_CHAR * pComment = NULL; while (iKey != keyval.end() && !IsLess(a_pKey, iKey->first.pItem)) { if (iKey->first.nOrder < nLoadOrder) { nLoadOrder = iKey->first.nOrder; pComment = iKey->first.pComment; } ++iKey; } if (pComment) { DeleteString(a_pComment); a_pComment = pComment; CopyString(a_pComment); } Delete(a_pSection, a_pKey); iKey = keyval.end(); } // make string copies if necessary bool bForceCreateNewKey = m_bAllowMultiKey && !a_bForceReplace; if (a_bCopyStrings) { if (bForceCreateNewKey || iKey == keyval.end()) { // if the key doesn't exist then we need a copy as the // string needs to last beyond the end of this function // because we will be inserting the key next rc = CopyString(a_pKey); if (rc < 0) return rc; } // we always need a copy of the value rc = CopyString(a_pValue); if (rc < 0) return rc; } // create the key entry if (iKey == keyval.end() || bForceCreateNewKey) { Entry oKey(a_pKey, nLoadOrder); if (a_pComment) { oKey.pComment = a_pComment; } typename TKeyVal::value_type oEntry(oKey, static_cast<const SI_CHAR *>(NULL)); iKey = keyval.insert(oEntry); bInserted = true; } iKey->second = a_pValue; return bInserted ? SI_INSERTED : SI_UPDATED; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> const SI_CHAR * CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, const SI_CHAR * a_pDefault, bool * a_pHasMultiple ) const { if (a_pHasMultiple) { *a_pHasMultiple = false; } if (!a_pSection || !a_pKey) { return a_pDefault; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return a_pDefault; } typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return a_pDefault; } // check for multiple entries with the same key if (m_bAllowMultiKey && a_pHasMultiple) { typename TKeyVal::const_iterator iTemp = iKeyVal; if (++iTemp != iSection->second.end()) { if (!IsLess(a_pKey, iTemp->first.pItem)) { *a_pHasMultiple = true; } } } return iKeyVal->second; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> long CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetLongValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, long a_nDefault, bool * a_pHasMultiple ) const { // return the default if we don't have a value const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_nDefault; // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII char szValue[64] = { 0 }; SI_CONVERTER c(m_bStoreIsUtf8); if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { return a_nDefault; } // handle the value as hex if prefaced with "0x" long nValue = a_nDefault; char * pszSuffix = szValue; if (szValue[0] == '0' && (szValue[1] == 'x' || szValue[1] == 'X')) { if (!szValue[2]) return a_nDefault; nValue = strtol(&szValue[2], &pszSuffix, 16); } else { nValue = strtol(szValue, &pszSuffix, 10); } // any invalid strings will return the default value if (*pszSuffix) { return a_nDefault; } return nValue; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SetLongValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, long a_nValue, const SI_CHAR * a_pComment, bool a_bUseHex, bool a_bForceReplace ) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string char szInput[64]; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE sprintf_s(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); #else // !__STDC_WANT_SECURE_LIB__ sprintf(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); #endif // __STDC_WANT_SECURE_LIB__ // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(szInput, strlen(szInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> double CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetDoubleValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, double a_nDefault, bool * a_pHasMultiple ) const { // return the default if we don't have a value const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_nDefault; // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII char szValue[64] = { 0 }; SI_CONVERTER c(m_bStoreIsUtf8); if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { return a_nDefault; } char * pszSuffix = NULL; double nValue = strtod(szValue, &pszSuffix); // any invalid strings will return the default value if (!pszSuffix || *pszSuffix) { return a_nDefault; } return nValue; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SetDoubleValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, double a_nValue, const SI_CHAR * a_pComment, bool a_bForceReplace ) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string char szInput[64]; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE sprintf_s(szInput, "%f", a_nValue); #else // !__STDC_WANT_SECURE_LIB__ sprintf(szInput, "%f", a_nValue); #endif // __STDC_WANT_SECURE_LIB__ // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(szInput, strlen(szInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetBoolValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bDefault, bool * a_pHasMultiple ) const { // return the default if we don't have a value const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); if (!pszValue || !*pszValue) return a_bDefault; // we only look at the minimum number of characters switch (pszValue[0]) { case 't': case 'T': // true case 'y': case 'Y': // yes case '1': // 1 (one) return true; case 'f': case 'F': // false case 'n': case 'N': // no case '0': // 0 (zero) return false; case 'o': case 'O': if (pszValue[1] == 'n' || pszValue[1] == 'N') return true; // on if (pszValue[1] == 'f' || pszValue[1] == 'F') return false; // off break; } // no recognized value, return the default return a_bDefault; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SetBoolValue( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bValue, const SI_CHAR * a_pComment, bool a_bForceReplace ) { // use SetValue to create sections if (!a_pSection || !a_pKey) return SI_FAIL; // convert to an ASCII string const char * pszInput = a_bValue ? "true" : "false"; // convert to output text SI_CHAR szOutput[64]; SI_CONVERTER c(m_bStoreIsUtf8); c.ConvertFromStore(pszInput, strlen(pszInput) + 1, szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); // actually add it return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetAllValues( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, TNamesDepend & a_values ) const { a_values.clear(); if (!a_pSection || !a_pKey) { return false; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return false; } // insert all values for this key a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); if (m_bAllowMultiKey) { ++iKeyVal; while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)) { a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); ++iKeyVal; } } return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> int CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetSectionSize( const SI_CHAR * a_pSection ) const { if (!a_pSection) { return -1; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return -1; } const TKeyVal & section = iSection->second; // if multi-key isn't permitted then the section size is // the number of keys that we have. if (!m_bAllowMultiKey || section.empty()) { return (int) section.size(); } // otherwise we need to count them int nCount = 0; const SI_CHAR * pLastKey = NULL; typename TKeyVal::const_iterator iKeyVal = section.begin(); for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n) { if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { ++nCount; pLastKey = iKeyVal->first.pItem; } } return nCount; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> const typename CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::TKeyVal * CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetSection( const SI_CHAR * a_pSection ) const { if (a_pSection) { typename TSection::const_iterator i = m_data.find(a_pSection); if (i != m_data.end()) { return &(i->second); } } return 0; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetAllSections( TNamesDepend & a_names ) const { a_names.clear(); typename TSection::const_iterator i = m_data.begin(); for (int n = 0; i != m_data.end(); ++i, ++n ) { a_names.push_back(i->first); } } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::GetAllKeys( const SI_CHAR * a_pSection, TNamesDepend & a_names ) const { a_names.clear(); if (!a_pSection) { return false; } typename TSection::const_iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } const TKeyVal & section = iSection->second; const SI_CHAR * pLastKey = NULL; typename TKeyVal::const_iterator iKeyVal = section.begin(); for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n ) { if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { a_names.push_back(iKeyVal->first); pLastKey = iKeyVal->first.pItem; } } return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SaveFile( const char * a_pszFile, bool a_bAddSignature ) const { FILE * fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE fopen_s(&fp, a_pszFile, "wb"); #else // !__STDC_WANT_SECURE_LIB__ fp = fopen(a_pszFile, "wb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = SaveFile(fp, a_bAddSignature); fclose(fp); return rc; } #ifdef SI_HAS_WIDE_FILE template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SaveFile( const SI_WCHAR_T * a_pwszFile, bool a_bAddSignature ) const { #ifdef _WIN32 FILE * fp = NULL; #if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE _wfopen_s(&fp, a_pwszFile, L"wb"); #else // !__STDC_WANT_SECURE_LIB__ fp = _wfopen(a_pwszFile, L"wb"); #endif // __STDC_WANT_SECURE_LIB__ if (!fp) return SI_FILE; SI_Error rc = SaveFile(fp, a_bAddSignature); fclose(fp); return rc; #else // !_WIN32 (therefore SI_CONVERT_ICU) char szFile[256]; u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); return SaveFile(szFile, a_bAddSignature); #endif // _WIN32 } #endif // SI_HAS_WIDE_FILE template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::SaveFile( FILE * a_pFile, bool a_bAddSignature ) const { FileWriter writer(a_pFile); return Save(writer, a_bAddSignature); } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> SI_Error CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::Save( OutputWriter & a_oOutput, bool a_bAddSignature ) const { Converter convert(m_bStoreIsUtf8); // add the UTF-8 signature if it is desired if (m_bStoreIsUtf8 && a_bAddSignature) { a_oOutput.Write(SI_UTF8_SIGNATURE); } // get all of the sections sorted in load order TNamesDepend oSections; GetAllSections(oSections); #if defined(_MSC_VER) && _MSC_VER <= 1200 oSections.sort(); #elif defined(__BORLANDC__) oSections.sort(Entry::LoadOrder()); #else oSections.sort(typename Entry::LoadOrder()); #endif // write the file comment if we have one bool bNeedNewLine = false; if (m_pFileComment) { if (!OutputMultiLineText(a_oOutput, convert, m_pFileComment)) { return SI_FAIL; } bNeedNewLine = true; } // iterate through our sections and output the data typename TNamesDepend::const_iterator iSection = oSections.begin(); for ( ; iSection != oSections.end(); ++iSection ) { // write out the comment if there is one if (iSection->pComment) { if (bNeedNewLine) { a_oOutput.Write(SI_NEWLINE_A); a_oOutput.Write(SI_NEWLINE_A); } if (!OutputMultiLineText(a_oOutput, convert, iSection->pComment)) { return SI_FAIL; } bNeedNewLine = false; } if (bNeedNewLine) { a_oOutput.Write(SI_NEWLINE_A); a_oOutput.Write(SI_NEWLINE_A); bNeedNewLine = false; } // write the section (unless there is no section name) if (*iSection->pItem) { if (!convert.ConvertToStore(iSection->pItem)) { return SI_FAIL; } a_oOutput.Write("["); a_oOutput.Write(convert.Data()); a_oOutput.Write("]"); a_oOutput.Write(SI_NEWLINE_A); } // get all of the keys sorted in load order TNamesDepend oKeys; GetAllKeys(iSection->pItem, oKeys); #if defined(_MSC_VER) && _MSC_VER <= 1200 oKeys.sort(); #elif defined(__BORLANDC__) oKeys.sort(Entry::LoadOrder()); #else oKeys.sort(typename Entry::LoadOrder()); #endif // write all keys and values typename TNamesDepend::const_iterator iKey = oKeys.begin(); for ( ; iKey != oKeys.end(); ++iKey) { // get all values for this key TNamesDepend oValues; GetAllValues(iSection->pItem, iKey->pItem, oValues); typename TNamesDepend::const_iterator iValue = oValues.begin(); for ( ; iValue != oValues.end(); ++iValue) { // write out the comment if there is one if (iValue->pComment) { a_oOutput.Write(SI_NEWLINE_A); if (!OutputMultiLineText(a_oOutput, convert, iValue->pComment)) { return SI_FAIL; } } // write the key if (!convert.ConvertToStore(iKey->pItem)) { return SI_FAIL; } a_oOutput.Write(convert.Data()); // write the value if (!convert.ConvertToStore(iValue->pItem)) { return SI_FAIL; } a_oOutput.Write(m_bSpaces ? " = " : "="); if (m_bAllowMultiLine && IsMultiLineData(iValue->pItem)) { // multi-line data needs to be processed specially to ensure // that we use the correct newline format for the current system a_oOutput.Write("<<<END_OF_TEXT" SI_NEWLINE_A); if (!OutputMultiLineText(a_oOutput, convert, iValue->pItem)) { return SI_FAIL; } a_oOutput.Write("END_OF_TEXT"); } else { a_oOutput.Write(convert.Data()); } a_oOutput.Write(SI_NEWLINE_A); } } bNeedNewLine = true; } return SI_OK; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::OutputMultiLineText( OutputWriter & a_oOutput, Converter & a_oConverter, const SI_CHAR * a_pText ) const { const SI_CHAR * pEndOfLine; SI_CHAR cEndOfLineChar = *a_pText; while (cEndOfLineChar) { // find the end of this line pEndOfLine = a_pText; for (; *pEndOfLine && *pEndOfLine != '\n'; ++pEndOfLine) /*loop*/ ; cEndOfLineChar = *pEndOfLine; // temporarily null terminate, convert and output the line *const_cast<SI_CHAR*>(pEndOfLine) = 0; if (!a_oConverter.ConvertToStore(a_pText)) { return false; } *const_cast<SI_CHAR*>(pEndOfLine) = cEndOfLineChar; a_pText += (pEndOfLine - a_pText) + 1; a_oOutput.Write(a_oConverter.Data()); a_oOutput.Write(SI_NEWLINE_A); } return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> bool CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::Delete( const SI_CHAR * a_pSection, const SI_CHAR * a_pKey, bool a_bRemoveEmpty ) { if (!a_pSection) { return false; } typename TSection::iterator iSection = m_data.find(a_pSection); if (iSection == m_data.end()) { return false; } // remove a single key if we have a keyname if (a_pKey) { typename TKeyVal::iterator iKeyVal = iSection->second.find(a_pKey); if (iKeyVal == iSection->second.end()) { return false; } // remove any copied strings and then the key typename TKeyVal::iterator iDelete; do { iDelete = iKeyVal++; DeleteString(iDelete->first.pItem); DeleteString(iDelete->second); iSection->second.erase(iDelete); } while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)); // done now if the section is not empty or we are not pruning away // the empty sections. Otherwise let it fall through into the section // deletion code if (!a_bRemoveEmpty || !iSection->second.empty()) { return true; } } else { // delete all copied strings from this section. The actual // entries will be removed when the section is removed. typename TKeyVal::iterator iKeyVal = iSection->second.begin(); for ( ; iKeyVal != iSection->second.end(); ++iKeyVal) { DeleteString(iKeyVal->first.pItem); DeleteString(iKeyVal->second); } } // delete the section itself DeleteString(iSection->first.pItem); m_data.erase(iSection); return true; } template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER> void CSimpleIniTempl<SI_CHAR,SI_STRLESS,SI_CONVERTER>::DeleteString( const SI_CHAR * a_pString ) { // strings may exist either inside the data block, or they will be // individually allocated and stored in m_strings. We only physically // delete those stored in m_strings. if (a_pString < m_pData || a_pString >= m_pData + m_uDataLen) { typename TNamesDepend::iterator i = m_strings.begin(); for (;i != m_strings.end(); ++i) { if (a_pString == i->pItem) { delete[] const_cast<SI_CHAR*>(i->pItem); m_strings.erase(i); break; } } } } // --------------------------------------------------------------------------- // CONVERSION FUNCTIONS // --------------------------------------------------------------------------- // Defines the conversion classes for different libraries. Before including // SimpleIni.h, set the converter that you wish you use by defining one of the // following symbols. // // SI_CONVERT_GENERIC Use the Unicode reference conversion library in // the accompanying files ConvertUTF.h/c // SI_CONVERT_ICU Use the IBM ICU conversion library. Requires // ICU headers on include path and icuuc.lib // SI_CONVERT_WIN32 Use the Win32 API functions for conversion. #if !defined(SI_CONVERT_GENERIC) && !defined(SI_CONVERT_WIN32) && !defined(SI_CONVERT_ICU) # ifdef _WIN32 # define SI_CONVERT_WIN32 # else # define SI_CONVERT_GENERIC # endif #endif /** * Generic case-sensitive less than comparison. This class returns numerically * ordered ASCII case-sensitive text for all possible sizes and types of * SI_CHAR. */ template<class SI_CHAR> struct SI_GenericCase { bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { long cmp; for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { cmp = (long) *pLeft - (long) *pRight; if (cmp != 0) { return cmp < 0; } } return *pRight != 0; } }; /** * Generic ASCII case-insensitive less than comparison. This class returns * numerically ordered ASCII case-insensitive text for all possible sizes * and types of SI_CHAR. It is not safe for MBCS text comparison where * ASCII A-Z characters are used in the encoding of multi-byte characters. */ template<class SI_CHAR> struct SI_GenericNoCase { inline SI_CHAR locase(SI_CHAR ch) const { return (ch < 'A' || ch > 'Z') ? ch : (ch - 'A' + 'a'); } bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { long cmp; for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { cmp = (long) locase(*pLeft) - (long) locase(*pRight); if (cmp != 0) { return cmp < 0; } } return *pRight != 0; } }; /** * Null conversion class for MBCS/UTF-8 to char (or equivalent). */ template<class SI_CHAR> class SI_ConvertA { bool m_bStoreIsUtf8; protected: SI_ConvertA() { } public: SI_ConvertA(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } /* copy and assignment */ SI_ConvertA(const SI_ConvertA & rhs) { operator=(rhs); } SI_ConvertA & operator=(const SI_ConvertA & rhs) { m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore( const char * a_pInputData, size_t a_uInputDataLen) { (void)a_pInputData; SI_ASSERT(a_uInputDataLen != (size_t) -1); // ASCII/MBCS/UTF-8 needs no conversion return a_uInputDataLen; } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore( const char * a_pInputData, size_t a_uInputDataLen, SI_CHAR * a_pOutputData, size_t a_uOutputDataSize) { // ASCII/MBCS/UTF-8 needs no conversion if (a_uInputDataLen > a_uOutputDataSize) { return false; } memcpy(a_pOutputData, a_pInputData, a_uInputDataLen); return true; } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore( const SI_CHAR * a_pInputData) { // ASCII/MBCS/UTF-8 needs no conversion return strlen((const char *)a_pInputData) + 1; } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_uOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore( const SI_CHAR * a_pInputData, char * a_pOutputData, size_t a_uOutputDataSize) { // calc input string length (SI_CHAR type and size independent) size_t uInputLen = strlen((const char *)a_pInputData) + 1; if (uInputLen > a_uOutputDataSize) { return false; } // ascii/UTF-8 needs no conversion memcpy(a_pOutputData, a_pInputData, uInputLen); return true; } }; // --------------------------------------------------------------------------- // SI_CONVERT_GENERIC // --------------------------------------------------------------------------- #ifdef SI_CONVERT_GENERIC #define SI_Case SI_GenericCase #define SI_NoCase SI_GenericNoCase #include <wchar.h> #include "ConvertUTF.h" /** * Converts UTF-8 to a wchar_t (or equivalent) using the Unicode reference * library functions. This can be used on all platforms. */ template<class SI_CHAR> class SI_ConvertW { bool m_bStoreIsUtf8; protected: SI_ConvertW() { } public: SI_ConvertW(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } /* copy and assignment */ SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } SI_ConvertW & operator=(const SI_ConvertW & rhs) { m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore( const char * a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t) -1); if (m_bStoreIsUtf8) { // worst case scenario for UTF-8 to wchar_t is 1 char -> 1 wchar_t // so we just return the same number of characters required as for // the source text. return a_uInputDataLen; } #if defined(SI_NO_MBSTOWCS_NULL) || (!defined(_MSC_VER) && !defined(_linux)) // fall back processing for platforms that don't support a NULL dest to mbstowcs // worst case scenario is 1:1, this will be a sufficient buffer size (void)a_pInputData; return a_uInputDataLen; #else // get the actual required buffer size return mbstowcs(NULL, a_pInputData, a_uInputDataLen); #endif } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore( const char * a_pInputData, size_t a_uInputDataLen, SI_CHAR * a_pOutputData, size_t a_uOutputDataSize) { if (m_bStoreIsUtf8) { // This uses the Unicode reference implementation to do the // conversion from UTF-8 to wchar_t. The required files are // ConvertUTF.h and ConvertUTF.c which should be included in // the distribution but are publically available from unicode.org // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ ConversionResult retval; const UTF8 * pUtf8 = (const UTF8 *) a_pInputData; if (sizeof(wchar_t) == sizeof(UTF32)) { UTF32 * pUtf32 = (UTF32 *) a_pOutputData; retval = ConvertUTF8toUTF32( &pUtf8, pUtf8 + a_uInputDataLen, &pUtf32, pUtf32 + a_uOutputDataSize, lenientConversion); } else if (sizeof(wchar_t) == sizeof(UTF16)) { UTF16 * pUtf16 = (UTF16 *) a_pOutputData; retval = ConvertUTF8toUTF16( &pUtf8, pUtf8 + a_uInputDataLen, &pUtf16, pUtf16 + a_uOutputDataSize, lenientConversion); } return retval == conversionOK; } // convert to wchar_t size_t retval = mbstowcs(a_pOutputData, a_pInputData, a_uOutputDataSize); return retval != (size_t)(-1); } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore( const SI_CHAR * a_pInputData) { if (m_bStoreIsUtf8) { // worst case scenario for wchar_t to UTF-8 is 1 wchar_t -> 6 char size_t uLen = 0; while (a_pInputData[uLen]) { ++uLen; } return (6 * uLen) + 1; } else { size_t uLen = wcstombs(NULL, a_pInputData, 0); if (uLen == (size_t)(-1)) { return uLen; } return uLen + 1; // include NULL terminator } } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_uOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore( const SI_CHAR * a_pInputData, char * a_pOutputData, size_t a_uOutputDataSize ) { if (m_bStoreIsUtf8) { // calc input string length (SI_CHAR type and size independent) size_t uInputLen = 0; while (a_pInputData[uInputLen]) { ++uInputLen; } ++uInputLen; // include the NULL char // This uses the Unicode reference implementation to do the // conversion from wchar_t to UTF-8. The required files are // ConvertUTF.h and ConvertUTF.c which should be included in // the distribution but are publically available from unicode.org // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ ConversionResult retval; UTF8 * pUtf8 = (UTF8 *) a_pOutputData; if (sizeof(wchar_t) == sizeof(UTF32)) { const UTF32 * pUtf32 = (const UTF32 *) a_pInputData; retval = ConvertUTF32toUTF8( &pUtf32, pUtf32 + uInputLen, &pUtf8, pUtf8 + a_uOutputDataSize, lenientConversion); } else if (sizeof(wchar_t) == sizeof(UTF16)) { const UTF16 * pUtf16 = (const UTF16 *) a_pInputData; retval = ConvertUTF16toUTF8( &pUtf16, pUtf16 + uInputLen, &pUtf8, pUtf8 + a_uOutputDataSize, lenientConversion); } return retval == conversionOK; } else { size_t retval = wcstombs(a_pOutputData, a_pInputData, a_uOutputDataSize); return retval != (size_t) -1; } } }; #endif // SI_CONVERT_GENERIC // --------------------------------------------------------------------------- // SI_CONVERT_ICU // --------------------------------------------------------------------------- #ifdef SI_CONVERT_ICU #define SI_Case SI_GenericCase #define SI_NoCase SI_GenericNoCase #include <unicode/ucnv.h> /** * Converts MBCS/UTF-8 to UChar using ICU. This can be used on all platforms. */ template<class SI_CHAR> class SI_ConvertW { const char * m_pEncoding; UConverter * m_pConverter; protected: SI_ConvertW() : m_pEncoding(NULL), m_pConverter(NULL) { } public: SI_ConvertW(bool a_bStoreIsUtf8) : m_pConverter(NULL) { m_pEncoding = a_bStoreIsUtf8 ? "UTF-8" : NULL; } /* copy and assignment */ SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } SI_ConvertW & operator=(const SI_ConvertW & rhs) { m_pEncoding = rhs.m_pEncoding; m_pConverter = NULL; return *this; } ~SI_ConvertW() { if (m_pConverter) ucnv_close(m_pConverter); } /** Calculate the number of UChar required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to UChar. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of UChar required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore( const char * a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t) -1); UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return (size_t) -1; } } nError = U_ZERO_ERROR; int32_t nLen = ucnv_toUChars(m_pConverter, NULL, 0, a_pInputData, (int32_t) a_uInputDataLen, &nError); if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { return (size_t) -1; } return (size_t) nLen; } /** Convert the input string from the storage format to UChar. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to UChar. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in UChar. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore( const char * a_pInputData, size_t a_uInputDataLen, UChar * a_pOutputData, size_t a_uOutputDataSize) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return false; } } nError = U_ZERO_ERROR; ucnv_toUChars(m_pConverter, a_pOutputData, (int32_t) a_uOutputDataSize, a_pInputData, (int32_t) a_uInputDataLen, &nError); if (U_FAILURE(nError)) { return false; } return true; } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore( const UChar * a_pInputData) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return (size_t) -1; } } nError = U_ZERO_ERROR; int32_t nLen = ucnv_fromUChars(m_pConverter, NULL, 0, a_pInputData, -1, &nError); if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { return (size_t) -1; } return (size_t) nLen + 1; } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_pOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore( const UChar * a_pInputData, char * a_pOutputData, size_t a_uOutputDataSize) { UErrorCode nError; if (!m_pConverter) { nError = U_ZERO_ERROR; m_pConverter = ucnv_open(m_pEncoding, &nError); if (U_FAILURE(nError)) { return false; } } nError = U_ZERO_ERROR; ucnv_fromUChars(m_pConverter, a_pOutputData, (int32_t) a_uOutputDataSize, a_pInputData, -1, &nError); if (U_FAILURE(nError)) { return false; } return true; } }; #endif // SI_CONVERT_ICU // --------------------------------------------------------------------------- // SI_CONVERT_WIN32 // --------------------------------------------------------------------------- #ifdef SI_CONVERT_WIN32 #define SI_Case SI_GenericCase // Windows CE doesn't have errno or MBCS libraries #ifdef _WIN32_WCE # ifndef SI_NO_MBCS # define SI_NO_MBCS # endif #endif #include <windows.h> #ifdef SI_NO_MBCS # define SI_NoCase SI_GenericNoCase #else // !SI_NO_MBCS /** * Case-insensitive comparison class using Win32 MBCS functions. This class * returns a case-insensitive semi-collation order for MBCS text. It may not * be safe for UTF-8 text returned in char format as we don't know what * characters will be folded by the function! Therefore, if you are using * SI_CHAR == char and SetUnicode(true), then you need to use the generic * SI_NoCase class instead. */ #include <mbstring.h> template<class SI_CHAR> struct SI_NoCase { bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { if (sizeof(SI_CHAR) == sizeof(char)) { return _mbsicmp((const unsigned char *)pLeft, (const unsigned char *)pRight) < 0; } if (sizeof(SI_CHAR) == sizeof(wchar_t)) { return _wcsicmp((const wchar_t *)pLeft, (const wchar_t *)pRight) < 0; } return SI_GenericNoCase<SI_CHAR>()(pLeft, pRight); } }; #endif // SI_NO_MBCS /** * Converts MBCS and UTF-8 to a wchar_t (or equivalent) on Windows. This uses * only the Win32 functions and doesn't require the external Unicode UTF-8 * conversion library. It will not work on Windows 95 without using Microsoft * Layer for Unicode in your application. */ template<class SI_CHAR> class SI_ConvertW { UINT m_uCodePage; protected: SI_ConvertW() { } public: SI_ConvertW(bool a_bStoreIsUtf8) { m_uCodePage = a_bStoreIsUtf8 ? CP_UTF8 : CP_ACP; } /* copy and assignment */ SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } SI_ConvertW & operator=(const SI_ConvertW & rhs) { m_uCodePage = rhs.m_uCodePage; return *this; } /** Calculate the number of SI_CHAR required for converting the input * from the storage format. The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @return Number of SI_CHAR required by the string when * converted. If there are embedded NULL bytes in the * input data, only the string up and not including * the NULL byte will be converted. * @return -1 cast to size_t on a conversion error. */ size_t SizeFromStore( const char * a_pInputData, size_t a_uInputDataLen) { SI_ASSERT(a_uInputDataLen != (size_t) -1); int retval = MultiByteToWideChar( m_uCodePage, 0, a_pInputData, (int) a_uInputDataLen, 0, 0); return (size_t)(retval > 0 ? retval : -1); } /** Convert the input string from the storage format to SI_CHAR. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData Data in storage format to be converted to SI_CHAR. * @param a_uInputDataLen Length of storage format data in bytes. This * must be the actual length of the data, including * NULL byte if NULL terminated string is required. * @param a_pOutputData Pointer to the output buffer to received the * converted data. * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. * @return true if all of the input data was successfully * converted. */ bool ConvertFromStore( const char * a_pInputData, size_t a_uInputDataLen, SI_CHAR * a_pOutputData, size_t a_uOutputDataSize) { int nSize = MultiByteToWideChar( m_uCodePage, 0, a_pInputData, (int) a_uInputDataLen, (wchar_t *) a_pOutputData, (int) a_uOutputDataSize); return (nSize > 0); } /** Calculate the number of char required by the storage format of this * data. The storage format is always UTF-8. * * @param a_pInputData NULL terminated string to calculate the number of * bytes required to be converted to storage format. * @return Number of bytes required by the string when * converted to storage format. This size always * includes space for the terminating NULL character. * @return -1 cast to size_t on a conversion error. */ size_t SizeToStore( const SI_CHAR * a_pInputData) { int retval = WideCharToMultiByte( m_uCodePage, 0, (const wchar_t *) a_pInputData, -1, 0, 0, 0, 0); return (size_t) (retval > 0 ? retval : -1); } /** Convert the input string to the storage format of this data. * The storage format is always UTF-8 or MBCS. * * @param a_pInputData NULL terminated source string to convert. All of * the data will be converted including the * terminating NULL character. * @param a_pOutputData Pointer to the buffer to receive the converted * string. * @param a_pOutputDataSize Size of the output buffer in char. * @return true if all of the input data, including the * terminating NULL character was successfully * converted. */ bool ConvertToStore( const SI_CHAR * a_pInputData, char * a_pOutputData, size_t a_uOutputDataSize) { int retval = WideCharToMultiByte( m_uCodePage, 0, (const wchar_t *) a_pInputData, -1, a_pOutputData, (int) a_uOutputDataSize, 0, 0); return retval > 0; } }; #endif // SI_CONVERT_WIN32 // --------------------------------------------------------------------------- // TYPE DEFINITIONS // --------------------------------------------------------------------------- typedef CSimpleIniTempl<char, SI_NoCase<char>,SI_ConvertA<char> > CSimpleIniA; typedef CSimpleIniTempl<char, SI_Case<char>,SI_ConvertA<char> > CSimpleIniCaseA; #if defined(SI_CONVERT_ICU) typedef CSimpleIniTempl<UChar, SI_NoCase<UChar>,SI_ConvertW<UChar> > CSimpleIniW; typedef CSimpleIniTempl<UChar, SI_Case<UChar>,SI_ConvertW<UChar> > CSimpleIniCaseW; #else typedef CSimpleIniTempl<wchar_t, SI_NoCase<wchar_t>,SI_ConvertW<wchar_t> > CSimpleIniW; typedef CSimpleIniTempl<wchar_t, SI_Case<wchar_t>,SI_ConvertW<wchar_t> > CSimpleIniCaseW; #endif #ifdef _UNICODE # define CSimpleIni CSimpleIniW # define CSimpleIniCase CSimpleIniCaseW # define SI_NEWLINE SI_NEWLINE_W #else // !_UNICODE # define CSimpleIni CSimpleIniA # define CSimpleIniCase CSimpleIniCaseA # define SI_NEWLINE SI_NEWLINE_A #endif // _UNICODE #ifdef _MSC_VER # pragma warning (pop) #endif #endif // INCLUDED_SimpleIni_h src/license-generator/.gitignore
New file @@ -0,0 +1 @@ /private-key.h src/license-generator/CMakeLists.txt
New file @@ -0,0 +1,30 @@ ADD_LIBRARY(license_generator_lib STATIC license-generator.cpp LicenseSigner.cpp ) link_directories ( ${Boost_LIBRARY_DIRS} ) add_dependencies( license_generator_lib private_key ) target_link_libraries( license_generator_lib license++_static ${Boost_LIBRARIES} ${EXTERNAL_LIBS} ) #SET_TARGET_PROPERTIES(license_generator_lib PROPERTIES LINK_SEARCH_START_STATIC ON) #SET_TARGET_PROPERTIES(license_generator_lib PROPERTIES LINK_SEARCH_END_STATIC ON) add_executable( license_generator license-generator-main.cpp ) target_link_libraries( license_generator license_generator_lib ) SET_TARGET_PROPERTIES(license_generator PROPERTIES LINK_SEARCH_START_STATIC ON) #SET_TARGET_PROPERTIES(license_generator PROPERTIES LINK_SEARCH_END_STATIC ON) src/license-generator/LicenseSigner.cpp
New file @@ -0,0 +1,146 @@ /* * LicenseSigner.cpp * * Created on: Apr 6, 2014 * Author: devel */ #include "LicenseSigner.h" #include "private-key.h" #include <stdexcept> #include <string.h> #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/err.h> #include <iostream> #include <cmath> namespace license { using namespace std; LicenseSigner::LicenseSigner() { } LicenseSigner::LicenseSigner(const std::string& alternatePrimaryKey) { } string LicenseSigner::Opensslb64Encode(size_t slen, unsigned char* signature) { /* FILE* stream = fmemopen(*buffer, encodedSize+1, "w"); */ //bio = BIO_new_fp(stdout, BIO_NOCLOSE); /*int encodedSize = 4 * ceil(slen / 3); char* buffer = (char*) (malloc(encodedSize + 1)); memset(buffer,0,encodedSize+1);*/ BIO* mem_bio = BIO_new(BIO_s_mem()); BIO* b64 = BIO_new(BIO_f_base64()); BIO* bio1 = BIO_push(b64, mem_bio); BIO_set_flags(bio1, BIO_FLAGS_BASE64_NO_NL); BIO_write(bio1, signature, slen); BIO_flush(bio1); char* charBuf; int sz = BIO_get_mem_data(mem_bio, &charBuf); string signatureStr; signatureStr.assign(charBuf, sz); BIO_free_all(bio1); return signatureStr; } string LicenseSigner::signString(const string& license) { ERR_load_ERR_strings(); ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); size_t slen; unsigned char* signature; signature = NULL; /* Create the Message Digest Context */ EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); if (!mdctx) { throw logic_error("Message digest creation context"); } const char *private_key = PRIVATE_KEY; BIO* bio = BIO_new_mem_buf((void*) (private_key), strlen(private_key)); EVP_PKEY *pktmp = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); BIO_free(bio); /*Initialise the DigestSign operation - SHA-256 has been selected * as the message digest function in this example */ if (1 != EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, pktmp)) { EVP_MD_CTX_destroy(mdctx); } /* Call update with the message */ if (EVP_DigestSignUpdate(mdctx, license.c_str(), license.length()) != 1) { EVP_MD_CTX_destroy(mdctx); throw logic_error("Message signing exception"); } /* Finalise the DigestSign operation */ /* First call EVP_DigestSignFinal with a NULL sig parameter to obtain the length of the * signature. Length is returned in slen */ if (EVP_DigestSignFinal(mdctx, NULL, &slen) != 1) { EVP_MD_CTX_destroy(mdctx); throw logic_error("Message signature finalization exception"); } /* Allocate memory for the signature based on size in slen */ if (!(signature = (unsigned char *) OPENSSL_malloc( sizeof(unsigned char) * slen))) { EVP_MD_CTX_destroy(mdctx); throw logic_error("Message signature memory allocation exception"); } /* Obtain the signature */ if (1 != EVP_DigestSignFinal(mdctx, signature, &slen)) { OPENSSL_free(signature); EVP_MD_CTX_destroy(mdctx); throw logic_error("Message signature exception"); } /* FILE* stream = fmemopen(*buffer, encodedSize+1, "w"); */ //bio = BIO_new_fp(stdout, BIO_NOCLOSE); /*int encodedSize = 4 * ceil(slen / 3); char* buffer = (char*) (malloc(encodedSize + 1)); memset(buffer,0,encodedSize+1);*/ string signatureStr = Opensslb64Encode(slen, signature); /* * BIO *bio, *b64; char message[] = "Hello World \n"; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stdout, BIO_NOCLOSE); bio = BIO_push(b64, bio); BIO_write(bio, message, strlen(message)); BIO_flush(bio); BIO_free_all(bio); Read Base64 encoded data from standard input and write the decoded data to standard output: BIO *bio, *b64, *bio_out; char inbuf[512]; int inlen; b64 = BIO_new(BIO_f_base64()); bio = BIO_new_fp(stdin, BIO_NOCLOSE); bio_out = BIO_new_fp(stdout, BIO_NOCLOSE); bio = BIO_push(b64, bio); while((inlen = BIO_read(bio, inbuf, 512)) > 0) BIO_write(bio_out, inbuf, inlen); BIO_free_all(bio); */ /* Clean up */ //free(buffer); if (signature) OPENSSL_free(signature); if (mdctx) EVP_MD_CTX_destroy(mdctx); return signatureStr; } void LicenseSigner::signLicense(FullLicenseInfo& licenseInfo) { string license = licenseInfo.printForSign(); string signature = signString(license); licenseInfo.license_signature = signature; } LicenseSigner::~LicenseSigner() { } } /* namespace license */ src/license-generator/LicenseSigner.h
New file @@ -0,0 +1,29 @@ /* * LicenseSigner.h * * Created on: Apr 6, 2014 * Author: devel */ #ifndef LICENSESIGNER_H_ #define LICENSESIGNER_H_ #include "../library/reader/LicenseReader.h" namespace license { class LicenseSigner { const string privateKey; string signString(const string& license); string Opensslb64Encode(size_t slen, unsigned char* signature); public: LicenseSigner(); LicenseSigner(const string& alternatePrimaryKey); void signLicense(FullLicenseInfo& licenseInfo); virtual ~LicenseSigner(); }; } /* namespace license */ #endif /* LICENSESIGNER_H_ */ src/license-generator/license-generator-main.cpp
New file @@ -0,0 +1,9 @@ #include <stdlib.h> #include "license-generator.h" int main(int argc, const char *argv[]) { //license::LicenseGenerator lic; return license::LicenseGenerator::generateLicense(argc, argv); } src/license-generator/license-generator.cpp
New file @@ -0,0 +1,210 @@ #include <build_properties.h> #include "LicenseSigner.h" #include "license-generator.h" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> #include <iostream> #include <boost/date_time.hpp> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/unordered_map.hpp> #include <boost/assign.hpp> #include <fstream> #include <regex> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace bt = boost::posix_time; namespace po = boost::program_options; using namespace std; namespace license { void LicenseGenerator::printHelp(const char* prog_name, const po::options_description& options) { cout << endl; cout << prog_name << " Version " << PROJECT_VERSION << endl << ". Usage:" << endl; cout << prog_name << " [options] product_name1 product_name2 ... " << endl << endl; cout << " product_name1 ... = Product name. This string must match the one passed by the software." << endl; cout << options << endl; } po::options_description LicenseGenerator::configureProgramOptions() { po::options_description common("General options"); common.add_options()("help,h", "print help message and exit.") // ("verbose,v", "print more information.") // ("output,o", po::value<string>(), "Output file name. If not specified the " "license will be printed in standard output"); // po::options_description licenseGeneration("License Generation"); licenseGeneration.add_options()("private_key,p", po::value<string>(), "Specify an alternate file for the primary key to be used. " "If not specified the internal primary key will be used.") // ("begin_date,b", po::value<string>(), "Specify the start of the validity for this license. " " Format YYYYMMDD. If not specified defaults to today") // ("end_date,e", po::value<string>(), "Specify the expire date for this license. " " Format YYYYMMDD. If not specified the license won't expire") // ("client_signature,s", po::value<string>(), "The signature of the pc that requires the license. " "It should be in the format XXX-XXXX-XXXX." " If not specified the license " "won't be linked to a specific pc.") // ("start_version,t", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the first version of the software this license apply to.") // ("end_version,n", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the last version of the software this license apply to."); // po::options_description visibleOptions; visibleOptions.add(common).add(licenseGeneration); return visibleOptions; } vector<FullLicenseInfo> LicenseGenerator::parseLicenseInfo( po::variables_map vm) { time_t begin_date = FullLicenseInfo::UNUSED_TIME; time_t end_date = FullLicenseInfo::UNUSED_TIME; if (vm.count("end_date")) { const std::string dt_end = vm["end_date"].as<string>(); try { end_date = seconds_from_epoch(dt_end); begin_date = time(NULL); } catch (invalid_argument &e) { cerr << endl << "End date not recognized: " << dt_end << " Please enter a valid date in format YYYYMMDD" << endl; exit(2); } } if (vm.count("begin_date")) { const std::string begin_date_str = vm["begin_date"].as<string>(); try { begin_date = seconds_from_epoch(begin_date_str); } catch (invalid_argument &e) { cerr << endl << "Begin date not recognized: " << begin_date_str << " Please enter a valid date in format YYYYMMDD" << endl; //print_usage(vm); exit(2); } } string client_signature = ""; if (vm.count("client_signature")) { client_signature = vm["client_signature"].as<string>(); regex e("\\d{3}-[:alnum:]{4}-[:alnum:]{4}"); if (!regex_match(client_signature, e)) { cerr << endl << "Client signature not recognized: " << client_signature << " Please enter a valid signature in format XXX-XXXX-XXX" << endl; exit(2); } } string extra_data = ""; if (vm.count("extra_data")) { extra_data = vm["extra_data"].as<string>(); } unsigned int from_sw_version = end_date = vm["start_version"].as< unsigned int>(); unsigned int to_sw_version = end_date = vm["end_version"].as<unsigned int>(); if (vm.count("product") == 0) { cerr << endl << "Parameter [product] not found. " << endl; exit(2); } vector<string> products = vm["product"].as<vector<string>>(); vector<FullLicenseInfo> licInfo; licInfo.reserve(products.size()); for (auto it = products.begin(); it != products.end(); it++) { if (boost::algorithm::trim_copy(*it).length() > 0) { licInfo.push_back( FullLicenseInfo("", *it, "", PROJECT_INT_VERSION, begin_date, end_date, client_signature, from_sw_version, to_sw_version, extra_data)); } } return licInfo; } void LicenseGenerator::generateAndOutptuLicenses(const po::variables_map& vm, ostream& outputFile) { vector<FullLicenseInfo> licenseInfo = parseLicenseInfo(vm); license::LicenseSigner licSigner = vm.count("private_key") == 0 ? license::LicenseSigner() : license::LicenseSigner(vm["private_key"].as<string>()); for (auto it = licenseInfo.begin(); it != licenseInfo.end(); ++it) { licSigner.signLicense(*it); it->printAsIni(outputFile); } } int LicenseGenerator::generateLicense(int argc, const char **argv) { po::options_description visibleOptions = configureProgramOptions(); //positional options must be addedd to standard options po::options_description allOptions; allOptions.add(visibleOptions).add_options()("product", po::value<vector<string>>(), "product names"); po::positional_options_description p; p.add("product", -1); po::variables_map vm; po::store( po::command_line_parser(argc, argv).options(allOptions).positional( p).run(), vm); po::notify(vm); if (vm.count("help") || argc == 1) { printHelp(argv[0], visibleOptions); return 0; } if (vm.count("output")) { const std::string fname = vm["output"].as<string>(); fstream ofstream(fname, std::ios::out | std::ios::trunc); if (!ofstream.is_open()) { cerr << "can't open file [" << fname << "] for output." << endl << " error: " << strerror( errno); exit(3); } generateAndOutptuLicenses(vm, ofstream); ofstream.close(); } else { generateAndOutptuLicenses(vm, cout); } return 0; } const std::locale formats[] = { std::locale(std::locale::classic(), new bt::time_input_facet("%Y-%m-%d")), // std::locale(std::locale::classic(), new bt::time_input_facet("%Y/%m/%d")), // std::locale(std::locale::classic(), new bt::time_input_facet("%Y%m%d")) }; const size_t formats_n = sizeof(formats) / sizeof(formats[0]); time_t LicenseGenerator::seconds_from_epoch(const std::string& s) { bt::ptime pt; for (size_t i = 0; i < formats_n; ++i) { std::istringstream is(s); is.imbue(formats[i]); is >> pt; if (pt != bt::ptime()) { break; } } if (pt == bt::ptime()) { throw invalid_argument(string("Date not regognized") + s); } bt::ptime timet_start(boost::gregorian::date(1970, 1, 1)); bt::time_duration diff = pt - timet_start; return diff.ticks() / bt::time_duration::rep_type::ticks_per_second; } } src/license-generator/license-generator.h
New file @@ -0,0 +1,37 @@ /* * LicenseSigner.h * * Created on: Apr 6, 2014 * Author: devel */ #ifndef LICENSE_GENERATOR_H_ #define LICENSE_GENERATOR_H_ #include <boost/program_options.hpp> #include "../library/reader/LicenseReader.h" namespace license { namespace po = boost::program_options; /** * This class is used to generate a new license. * It has no metnod main, for testing reasons. */ class LicenseGenerator { private: LicenseGenerator(); static void printHelp(const char* prog_name, const po::options_description& options); static po::options_description configureProgramOptions(); static time_t seconds_from_epoch(const std::string& s); static vector<FullLicenseInfo> parseLicenseInfo(po::variables_map vm); static void generateAndOutptuLicenses(const po::variables_map& vm, ostream& outputFile); public: static int generateLicense(int argc, const char** argv); }; } /* namespace license */ #endif /* LICENSE_GENERATOR_H_ */ src/pc-identifier/CMakeLists.txt
New file @@ -0,0 +1,2 @@ #set_target_properties(ui PROPERTIES LINK_FLAGS "-static") test/CMakeLists.txt
New file @@ -0,0 +1,7 @@ #if we're here boost has been found include_directories(${Boost_INCLUDE_DIRS}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) link_directories ( ${Boost_LIBRARY_DIRS} ) add_subdirectory(library) add_subdirectory(license-generator) test/functional/CMakeLists.txt
New file @@ -0,0 +1,14 @@ add_executable( standard_license_test standard-license_test.cpp ) target_link_libraries( standard_license_test license_generator_lib license++_static ) SET_TARGET_PROPERTIES(standard_license_test PROPERTIES LINK_SEARCH_START_STATIC ON) ADD_TEST(standard_license_test ${EXECUTABLE_OUTPUT_PATH}/standard_license_test) test/functional/standard-license_test.cpp
New file @@ -0,0 +1,48 @@ #define BOOST_TEST_MODULE standard_license_test //#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "../../../src/license-generator/license-generator.h" #include "../../../src/library/api/license++.h" #include <build_properties.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; using namespace license; using namespace std; void generate_license(const string& prod_name, const string& fname) { int argc = 4; const char** argv = new const char*[argc + 1]; argv[0] = "lic-generator"; argv[1] = "-o"; argv[2] = fname.c_str(); argv[3] = "test"; int retCode = LicenseGenerator::generateLicense(argc, argv); delete (argv); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(fname)); CSimpleIniA ini; SI_Error rc = ini.LoadFile(fname.c_str()); BOOST_CHECK_GE(rc,0); int sectionSize = ini.GetSectionSize(prod_name.c_str()); BOOST_CHECK_GT(sectionSize,0); } BOOST_AUTO_TEST_CASE( standard_lic_file ) { const string licLocation(PROJECT_TEST_TEMP_DIR "/standard_license.lic"); generate_license(string("TEST"), licLocation); /* */ LicenseInfo license; LicenseLocation licenseLocation; licenseLocation.openFileNearModule=false; licenseLocation.licenseFileLocation = licLocation.c_str(); licenseLocation.environmentVariableName = ""; EVENT_TYPE result = acquire_license("TEST", licenseLocation, & license); BOOST_CHECK_EQUAL(result, LICENSE_OK); BOOST_CHECK_EQUAL(license.has_expiry, false); BOOST_CHECK_EQUAL(license.linked_to_pc, false); } test/library/CMakeLists.txt
New file @@ -0,0 +1 @@ add_subdirectory(reader) test/library/reader/CMakeLists.txt
New file @@ -0,0 +1,18 @@ link_directories ( ${Boost_LIBRARY_DIRS} ) add_executable( license_reader_test LicenseReader_test.cpp ) target_link_libraries( license_reader_test ${Boost_LIBRARIES} reader os base ${PLATFORM_LIBS} ) SET_TARGET_PROPERTIES(license_reader_test PROPERTIES LINK_SEARCH_START_STATIC ON) ADD_TEST(license_reader_test ${EXECUTABLE_OUTPUT_PATH}/LicenseReader_test) test/library/reader/LicenseReader_test.cpp
New file @@ -0,0 +1,68 @@ #define BOOST_TEST_MODULE license_reader_test //#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "../../../src/library/reader/LicenseReader.h" #include <build_properties.h> using namespace license; BOOST_AUTO_TEST_CASE( read_single_file ) { const char * licLocation = PROJECT_TEST_SRC_DIR "/library/reader/test_reader.ini"; const LicenseLocation location = { licLocation, NULL, false }; LicenseReader licenseReader(location); vector<FullLicenseInfo> licenseInfos; EventRegistry registry = licenseReader.readLicenses("PrODUCT", licenseInfos); BOOST_CHECK(registry.isGood()); BOOST_CHECK_EQUAL(1, licenseInfos.size()); } BOOST_AUTO_TEST_CASE( product_not_licensed ) { const char * licLocation = PROJECT_TEST_SRC_DIR "/library/reader/test_reader.ini"; const LicenseLocation location = { licLocation, NULL, false }; LicenseReader licenseReader(location); vector<FullLicenseInfo> licenseInfos; EventRegistry registry = licenseReader.readLicenses("PRODUCT-NOT", licenseInfos); BOOST_CHECK(!registry.isGood()); BOOST_CHECK_EQUAL(0, licenseInfos.size()); BOOST_ASSERT(registry.getLastFailure()!=NULL); BOOST_CHECK_EQUAL(PRODUCT_NOT_LICENSED, registry.getLastFailure()->event_type); } BOOST_AUTO_TEST_CASE( file_not_found ) { const char * licLocation = PROJECT_TEST_SRC_DIR "/library/reader/not_found.ini"; //const char * envName = "MYVAR"; const LicenseLocation location = { licLocation, NULL, false }; LicenseReader licenseReader(location); vector<FullLicenseInfo> licenseInfos; EventRegistry registry = licenseReader.readLicenses("PRODUCT", licenseInfos); BOOST_CHECK(!registry.isGood()); BOOST_CHECK_EQUAL(0, licenseInfos.size()); BOOST_ASSERT(registry.getLastFailure()!=NULL); BOOST_CHECK_EQUAL(LICENSE_FILE_NOT_FOUND, registry.getLastFailure()->event_type); } BOOST_AUTO_TEST_CASE( env_var_not_defined ) { const char * envName = "MYVAR"; const LicenseLocation location = { NULL, envName, false }; LicenseReader licenseReader(location); vector<FullLicenseInfo> licenseInfos; EventRegistry registry = licenseReader.readLicenses("PRODUCT", licenseInfos); BOOST_CHECK(!registry.isGood()); BOOST_CHECK_EQUAL(0, licenseInfos.size()); BOOST_ASSERT(registry.getLastFailure()!=NULL); BOOST_CHECK_EQUAL(ENVIRONMENT_VARIABLE_NOT_DEFINED, registry.getLastFailure()->event_type); } test/library/reader/test_reader.ini
New file @@ -0,0 +1,3 @@ [PRODUCT] license_version = 100 license_signature = qAz test/license-generator/CMakeLists.txt
New file @@ -0,0 +1,13 @@ add_executable( license_generator_test license-generator_test.cpp ) target_link_libraries( license_generator_test license_generator_lib ) SET_TARGET_PROPERTIES(license_generator_test PROPERTIES LINK_SEARCH_START_STATIC ON) ADD_TEST(license_generator_test ${EXECUTABLE_OUTPUT_PATH}/license-generator_test) test/license-generator/license-generator_test.cpp
New file @@ -0,0 +1,36 @@ #define BOOST_TEST_MODULE license_generator_test //#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "../../../src/license-generator/license-generator.h" #include <build_properties.h> #include <boost/filesystem.hpp> #include "../../src/library/reader/SimpleIni.h" namespace fs = boost::filesystem; using namespace license; using namespace std; void generate_license(const string& prod_name, const string& fname) { int argc = 4; const char** argv = new const char*[argc + 1]; argv[0] = "lic-generator"; argv[1] = "-o"; argv[2] = fname.c_str(); argv[3] = "test"; int retCode = LicenseGenerator::generateLicense(argc, argv); delete (argv); BOOST_CHECK_EQUAL(retCode, 0); BOOST_ASSERT(fs::exists(fname)); CSimpleIniA ini; SI_Error rc = ini.LoadFile(fname.c_str()); BOOST_CHECK_GE(rc,0); int sectionSize = ini.GetSectionSize(prod_name.c_str()); BOOST_CHECK_GT(sectionSize,0); } BOOST_AUTO_TEST_CASE( generate_lic_file ) { const string licLocation(PROJECT_TEST_TEMP_DIR "/test1.lic"); generate_license(string("TEST"), licLocation); }