diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml
index 11213c83..e4d8739a 100644
--- a/.azure-pipelines.yml
+++ b/.azure-pipelines.yml
@@ -1,4 +1,4 @@
jobs:
- - template: .ci/azure-pipelines-linux.yml
- - template: .ci/azure-pipelines-win.yml
- - template: .ci/azure-pipelines-macos.yml
+ - template: .ci/azure-pipelines/linux.yml
+ - template: .ci/azure-pipelines/windows.yml
+ - template: .ci/azure-pipelines/macos.yml
diff --git a/.ci/azure-pipelines-macos.yml b/.ci/azure-pipelines-macos.yml
deleted file mode 100644
index ead77931..00000000
--- a/.ci/azure-pipelines-macos.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-jobs:
-- job: macOS
- displayName: 'macOS'
- pool:
- vmImage: macOS-latest
- steps:
- - script: brew install cmake ninja ncurses readline openssl zlib
- displayName: 'Install packages'
- - script: |
- cd $BUILD_BINARIESDIRECTORY
- cmake -G "Ninja" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl $BUILD_SOURCESDIRECTORY
- cmake --build .
- displayName: 'Build'
diff --git a/.ci/azure-pipelines-linux.yml b/.ci/azure-pipelines/linux.yml
similarity index 61%
rename from .ci/azure-pipelines-linux.yml
rename to .ci/azure-pipelines/linux.yml
index f9b37ba6..d8f1512c 100644
--- a/.ci/azure-pipelines-linux.yml
+++ b/.ci/azure-pipelines/linux.yml
@@ -4,12 +4,11 @@ jobs:
pool:
vmImage: ubuntu-16.04
steps:
- - script: |
- cd $BUILD_BINARIESDIRECTORY
- sudo apt -y install cmake gcc g++ ninja-build libncurses5-dev libreadline-dev libssl-dev make zlib1g-dev
- cmake -G "Ninja" -DCMAKE_BUILD_TYPE=RelWithDebInfo $BUILD_SOURCESDIRECTORY
- cmake --build .
- cpack -C Release -G DEB
+ - script: sudo apt-get -y install cmake gcc g++ ninja-build libncurses5-dev libreadline-dev libssl-dev make zlib1g-dev
+ displayName: 'Prepare environment'
+ - script: "$(Build.SourcesDirectory)/.ci/azure-pipelines/linux_build.sh"
+ env:
+ SE_BUILD_NUMBER_TOKEN: $(BUILD_NUMBER_TOKEN)
displayName: 'Build'
- script: |
.ci/appveyor-deb-install-test.sh
diff --git a/.ci/azure-pipelines/linux_build.sh b/.ci/azure-pipelines/linux_build.sh
new file mode 100755
index 00000000..87537491
--- /dev/null
+++ b/.ci/azure-pipelines/linux_build.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+if [[ "${#SE_BUILD_NUMBER_TOKEN}" -eq 64 ]]; then
+ VERSION=$(python3 "version.py")
+ BUILD_NUMBER=$(curl "https://softether.network/get-build-number?commit=${BUILD_SOURCEVERSION}&version=${VERSION}&token=${SE_BUILD_NUMBER_TOKEN}")
+else
+ BUILD_NUMBER=0
+fi
+
+cd ${BUILD_BINARIESDIRECTORY}
+
+cmake -G "Ninja" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_NUMBER=${BUILD_NUMBER} ${BUILD_SOURCESDIRECTORY}
+cmake --build .
+
+cpack -C Release -G DEB
diff --git a/.ci/azure-pipelines/macos.yml b/.ci/azure-pipelines/macos.yml
new file mode 100644
index 00000000..acbd76e1
--- /dev/null
+++ b/.ci/azure-pipelines/macos.yml
@@ -0,0 +1,11 @@
+jobs:
+- job: macOS
+ pool:
+ vmImage: macOS-latest
+ steps:
+ - script: brew install cmake ninja ncurses readline openssl zlib
+ displayName: 'Prepare environment'
+ - script: '$(Build.SourcesDirectory)/.ci/azure-pipelines/macos_build.sh'
+ env:
+ SE_BUILD_NUMBER_TOKEN: $(BUILD_NUMBER_TOKEN)
+ displayName: 'Build'
diff --git a/.ci/azure-pipelines/macos_build.sh b/.ci/azure-pipelines/macos_build.sh
new file mode 100755
index 00000000..5befaebc
--- /dev/null
+++ b/.ci/azure-pipelines/macos_build.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+if [[ "${#SE_BUILD_NUMBER_TOKEN}" -eq 64 ]]; then
+ VERSION=$(python "version.py")
+ BUILD_NUMBER=$(curl "https://softether.network/get-build-number?commit=${BUILD_SOURCEVERSION}&version=${VERSION}&token=${SE_BUILD_NUMBER_TOKEN}")
+else
+ BUILD_NUMBER=0
+fi
+
+cd ${BUILD_BINARIESDIRECTORY}
+
+cmake -G "Ninja" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_NUMBER=${BUILD_NUMBER} -DOPENSSL_ROOT_DIR="/usr/local/opt/openssl" ${BUILD_SOURCESDIRECTORY}
+cmake --build .
diff --git a/.ci/azure-pipelines-win-steps.yml b/.ci/azure-pipelines/windows-steps.yml
similarity index 53%
rename from .ci/azure-pipelines-win-steps.yml
rename to .ci/azure-pipelines/windows-steps.yml
index 30521896..9d053434 100644
--- a/.ci/azure-pipelines-win-steps.yml
+++ b/.ci/azure-pipelines/windows-steps.yml
@@ -18,18 +18,14 @@ steps:
vcpkg install openssl zlib --triplet ${{parameters.vcpkgTriplet}}
workingDirectory: C:/vcpkg
displayName: 'Prepare environment'
-- script: |
- call "${{parameters.vcvarsPath}}"
- cmake -G "Ninja" -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=${{parameters.vcpkgTriplet}} -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_C_COMPILER="${{parameters.compilerPath}}" -DCMAKE_CXX_COMPILER="${{parameters.compilerPath}}" $(Build.SourcesDirectory)
- cmake --build .
- workingDirectory: $(Build.BinariesDirectory)
+- script: '$(Build.SourcesDirectory)/.ci/azure-pipelines/windows_build.bat'
+ env:
+ ARCHITECTURE: ${{parameters.architecture}}
+ COMPILER_PATH: ${{parameters.compilerPath}}
+ VCPKG_TRIPLET: ${{parameters.vcpkgTriplet}}
+ VCVARS_PATH: ${{parameters.vcvarsPath}}
+ SE_BUILD_NUMBER_TOKEN: $(BUILD_NUMBER_TOKEN)
displayName: 'Build'
-- script: |
- mkdir "$(Build.StagingDirectory)/installers"
- vpnsetup /SFXMODE:vpnclient /SFXOUT:"$(Build.StagingDirectory)/installers/softether-vpnclient-$(Build.SourceVersion)-${{parameters.architecture}}.exe"
- vpnsetup /SFXMODE:vpnserver_vpnbridge /SFXOUT:"$(Build.StagingDirectory)/installers/softether-vpnserver_vpnbridge-$(Build.SourceVersion)-${{parameters.architecture}}.exe"
- workingDirectory: $(Build.BinariesDirectory)
- displayName: 'Build installers'
- powershell: |
. .ci/appveyor-vpntest.ps1
displayName: 'Test'
diff --git a/.ci/azure-pipelines-win.yml b/.ci/azure-pipelines/windows.yml
similarity index 90%
rename from .ci/azure-pipelines-win.yml
rename to .ci/azure-pipelines/windows.yml
index 5a63ab08..f8cff95f 100644
--- a/.ci/azure-pipelines-win.yml
+++ b/.ci/azure-pipelines/windows.yml
@@ -4,7 +4,7 @@ jobs:
pool:
vmImage: windows-latest
steps:
- - template: "azure-pipelines-win-steps.yml"
+ - template: "windows-steps.yml"
parameters:
architecture: "x86_64"
compilerPath: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Tools/Llvm/x64/bin/clang-cl.exe"
@@ -15,7 +15,7 @@ jobs:
pool:
vmImage: windows-latest
steps:
- - template: "azure-pipelines-win-steps.yml"
+ - template: "windows-steps.yml"
parameters:
architecture: "x86"
compilerPath: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Tools/Llvm/bin/clang-cl.exe"
diff --git a/.ci/azure-pipelines/windows_build.bat b/.ci/azure-pipelines/windows_build.bat
new file mode 100644
index 00000000..6f533c72
--- /dev/null
+++ b/.ci/azure-pipelines/windows_build.bat
@@ -0,0 +1,26 @@
+@echo on
+
+:: The method we use to store a command's output into a variable:
+:: https://stackoverflow.com/a/6362922
+for /f "tokens=* USEBACKQ" %%g in (`python "version.py"`) do (set "VERSION=%%g")
+
+:: https://stackoverflow.com/a/8566001
+echo %SE_BUILD_NUMBER_TOKEN%> "%tmp%\length.txt"
+for %%? in ("%tmp%\length.txt") do ( set /A SE_BUILD_NUMBER_TOKEN_LENGTH=%%~z? - 2 )
+
+if %SE_BUILD_NUMBER_TOKEN_LENGTH% equ 64 (
+ for /f "tokens=* USEBACKQ" %%g in (`curl "https://softether.network/get-build-number?commit=%BUILD_SOURCEVERSION%&version=%VERSION%&token=%SE_BUILD_NUMBER_TOKEN%"`) do (set "BUILD_NUMBER=%%g")
+) else (
+ set BUILD_NUMBER=0
+)
+
+cd %BUILD_BINARIESDIRECTORY%
+
+call "%VCVARS_PATH%"
+
+cmake -G "Ninja" -DCMAKE_TOOLCHAIN_FILE="C:\vcpkg\scripts\buildsystems\vcpkg.cmake" -DVCPKG_TARGET_TRIPLET=%VCPKG_TRIPLET% -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_C_COMPILER="%COMPILER_PATH%" -DCMAKE_CXX_COMPILER="%COMPILER_PATH%" -DBUILD_NUMBER=%BUILD_NUMBER% "%BUILD_SOURCESDIRECTORY%"
+cmake --build .
+
+mkdir "%BUILD_STAGINGDIRECTORY%\installers"
+vpnsetup /SFXMODE:vpnclient /SFXOUT:"%BUILD_STAGINGDIRECTORY%\installers\softether-vpnclient-%VERSION%.%BUILD_NUMBER%.%ARCHITECTURE%.exe"
+vpnsetup /SFXMODE:vpnserver_vpnbridge /SFXOUT:"%BUILD_STAGINGDIRECTORY%\installers\softether-vpnserver_vpnbridge-%VERSION%.%BUILD_NUMBER%.%ARCHITECTURE%.exe"
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 88cbd1ae..2b5656e2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,7 +1,13 @@
cmake_minimum_required(VERSION 3.7)
+set(BUILD_NUMBER CACHE STRING "The number of the current build.")
+
+if ("${BUILD_NUMBER}" STREQUAL "")
+ set(BUILD_NUMBER "0")
+endif()
+
project("SoftEther VPN"
- VERSION 5.01.9674
+ VERSION "5.01.${BUILD_NUMBER}"
LANGUAGES C
)
@@ -21,20 +27,6 @@ if(EXISTS "${TOP_DIRECTORY}/.git" AND NOT EXISTS "${TOP_DIRECTORY}/src/Mayaqua/3
message (FATAL_ERROR "Submodules are not initialized. Run\n\tgit submodule update --init --recursive")
endif()
-# Compare ${PROJECT_VERSION} and src/CurrentBuild.txt
-file(READ ${TOP_DIRECTORY}/src/CurrentBuild.txt CurrentBuild)
-
-string(REGEX MATCH "VERSION_MAJOR ([0-9]+)" temp ${CurrentBuild})
-string(REGEX REPLACE "VERSION_MAJOR ([0-9]+)" "\\1" CurrentBuild_MAJOR ${temp})
-string(REGEX MATCH "VERSION_MINOR ([0-9]+)" temp ${CurrentBuild})
-string(REGEX REPLACE "VERSION_MINOR ([0-9]+)" "\\1" CurrentBuild_MINOR ${temp})
-string(REGEX MATCH "VERSION_BUILD ([0-9]+)" temp ${CurrentBuild})
-string(REGEX REPLACE "VERSION_BUILD ([0-9]+)" "\\1" CurrentBuild_BUILD ${temp})
-
-if(NOT ${PROJECT_VERSION} VERSION_EQUAL "${CurrentBuild_MAJOR}.${CurrentBuild_MINOR}.${CurrentBuild_BUILD}")
- message (FATAL_ERROR "PROJECT_VERSION does not match to src/CurrentBuild.txt")
-endif()
-
if(UNIX)
include(GNUInstallDirs)
diff --git a/src/BUILD_WINDOWS.md b/src/BUILD_WINDOWS.md
index ad0b13df..318bfde5 100644
--- a/src/BUILD_WINDOWS.md
+++ b/src/BUILD_WINDOWS.md
@@ -1,59 +1,18 @@
How to build SoftEther VPN for Windows
======================================
-
-Requirements
-------------
-
-You need to install the following software to run a full release build of SoftEther VPN for Windows.
-
-- Microsoft Windows XP, Vista, 7, 8 or later.
-- Microsoft Visual Studio 2008 with the latest SP (SP1 9.0.30729.4462 QFE).
- Make sure that you installed the x64 compiler and build tools.
-- Microsoft Windows Driver Kit 7.1.0.
-
-
Full Build Instructions
-----------------------
-The following steps will build all SoftEther VPN program files, and also build
-the installer packages of SoftEther VPN. It is very easy.
-
-1. Run the "BuildAll.cmd" batch file in the "src" directory.
-2. Wait until the building process will complete.
-3. The built files are stored on the "output" directory.
-
-
-Partly Build, Debug, or Development Instructions on Visual Studio 2008
----------------------------------------------------------------------
-
-If you are a programmer, you can open the SoftEther VPN solution file
-with Visual Studio 2008 to customize. Open "src\SEVPN.sln" and enjoy it.
-
-Visual Studio 2008 is required as to maintain compatibility with Windows 9x, due to Visual C++ 2008 being the last version compatibile with Windows 9x and Windows NT 4.x binary linking.
-
-- Visual Studio 2008's installer ISO can be found on Microsoft's site here: https://download.microsoft.com/download/E/8/E/E8EEB394-7F42-4963-A2D8-29559B738298/VS2008ExpressWithSP1ENUX1504728.iso
-
-- The Microsoft Windows Driver Kit 7.1.0 can be found here: https://download.microsoft.com/download/4/A/2/4A25C7D5-EFBE-4182-B6A9-AE6850409A78/GRMWDK_EN_7600_1.ISO
-
-If using anything else other than Visual Studio 2008 for development, your code **MUST** support Microsoft Visual C++ 2008 due to aforementioned reasons.
-
-It is OK to add newer Visual Studio (2015, 2017) solution files to the project, but there then must be dual solution files for both Visual C++ 2008 and the latest Visual Studio.
-
-Build and Development Instructions with Visual Studio 2017 & CMake
----------------------------------------------------------------------
-
-An alternative method for development of the SoftEtherVPN project on Windows is through CMake.
-
-There are several methods for using CMake but the easiest by far is through Visual Studio 2017 by importing the CMake project directly
+There are several methods for using CMake but the easiest by far is through Visual Studio 2019 by importing the CMake project directly
into it. So that is what will be described below.
Requirements:
-1. Download Visual Studio 2017 (Community Edition is fine).
+1. Download Visual Studio 2019 (Community Edition is fine).
2. During install, make sure to check "Desktop development with C++" under "Workloads".
3. Click on individual components and scroll until you see "Visual C++ tools for CMake" under the compilers section. Make sure this is checked.
-4. Proceed with and finish Visual Studio 2017 install.
+4. Proceed with and finish Visual Studio 2019 installation.
5. Install the needed submodules to build the project, avoiding CMake telling you to do so with: `git submodule update --init --recursive`
Building:
@@ -69,9 +28,4 @@ of all the SoftEtherVPN components.
Congrats, you now have a complete CMake development environment for SoftEtherVPN on Windows, enjoy and happy contributing!
Download Links:
-- Visual Studio 2017 from Microsoft: https://visualstudio.microsoft.com/downloads
-
-************************************
-Thank You Using SoftEther VPN !
-By SoftEther VPN Open-Source Project
-https://www.softether.org/
+- Visual Studio 2019 from Microsoft: https://visualstudio.microsoft.com/downloads
diff --git a/src/BuildAll.cmd b/src/BuildAll.cmd
deleted file mode 100644
index f3e2a148..00000000
--- a/src/BuildAll.cmd
+++ /dev/null
@@ -1,38 +0,0 @@
-SETLOCAL
-SET BATCH_FILE_NAME=%0
-SET BATCH_DIR_PATH=%~dp0
-SET NOW_TMP=%time:~0,2%
-SET NOW=%date:~0,4%%date:~5,2%%date:~8,2%_%NOW_TMP: =0%%time:~3,2%%time:~6,2%
-
-if exist "C:\Program Files\Microsoft Visual Studio 9.0" (
- call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"
-) else if exist "C:\Program Files (x86)\Microsoft Visual Studio 9.0" (
- call "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"
-) else (
- echo "Visual Studio 2008 not found!"
- exit /b 1
-)
-
-if not exist "C:\windows\Microsoft.NET\Framework\v3.5" (
- echo ".NET Framework 3.5 not found!"
- exit /b 1
-)
-
-echo on
-
-copy "%BATCH_DIR_PATH%..\AUTHORS.TXT" "%BATCH_DIR_PATH%bin\hamcore\authors.txt"
-
-echo f | xcopy "%BATCH_DIR_PATH%BuildFiles\Library\vs2008\Win32_Release\ossl_static.pdb" "%BATCH_DIR_PATH%DebugFiles\pdb\Win32_Release\ossl_static.pdb"
-echo f | xcopy "%BATCH_DIR_PATH%BuildFiles\Library\vs2008\x64_Release\ossl_static.pdb" "%BATCH_DIR_PATH%DebugFiles\pdb\x64_Release\ossl_static.pdb"
-
-if exist "%BATCH_DIR_PATH%bin\BuildUtil.exe" (
- del "%BATCH_DIR_PATH%bin\BuildUtil.exe"
-)
-
-C:\windows\Microsoft.NET\Framework\v3.5\MSBuild.exe /toolsversion:3.5 /target:Clean;Rebuild /property:Configuration=Debug "%BATCH_DIR_PATH%BuildUtil\BuildUtil.csproj"
-
-cd "%BATCH_DIR_PATH%bin"
-
-BuildUtil.exe /CMD:All
-
-if errorlevel 1 exit /b %errorlevel%
diff --git a/src/BuildUtil/BuildUtil.csproj b/src/BuildUtil/BuildUtil.csproj
deleted file mode 100644
index 8710d63b..00000000
--- a/src/BuildUtil/BuildUtil.csproj
+++ /dev/null
@@ -1,214 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 9.0.30729
- 2.0
- {384815C3-333C-4CEC-9DCD-B6AB2602EBB9}
- Exe
- Properties
- BuildUtil
- BuildUtilTmp
- v2.0
- 512
- BuildUtilIcon.ico
- false
- BuildUtil.BuildUtilMain
- true
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
-
- true
- full
- false
- ..\bin\
- TRACE;DEBUG;BU_SOFTETHER;BU_OSS
- prompt
- 4
- AnyCPU
-
-
- false
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- True
- True
- Resources.resx
-
-
- True
- True
- Settings.settings
-
-
-
-
-
-
-
- True
- True
- Reference.map
-
-
- True
- True
- Reference.map
-
-
-
-
-
-
-
-
-
- Dynamic
- Web References\SignService\
- http://dv/Sign/Sign.asmx
-
-
-
-
- Settings
- BuildUtil_SignService_Sign
-
-
- Dynamic
- Web References\HvSignService\
- http://hvsigncode/Sign.asmx
-
-
-
-
- Settings
- BuildUtilTmp_HvSignService_Sign
-
-
-
-
-
- SettingsSingleFileGenerator
- Settings.Designer.cs
-
-
-
- MSDiscoCodeGenerator
- Reference.cs
-
-
-
-
-
-
-
- MSDiscoCodeGenerator
- Reference.cs
-
-
-
-
-
- False
- .NET Framework Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
-
-
-
- ResXFileCodeGenerator
- Resources.Designer.cs
-
-
-
-
-
- $(ProjectDir)CopyBuildUtil.cmd
-
-
\ No newline at end of file
diff --git a/src/BuildUtil/BuildUtilCommands.cs b/src/BuildUtil/BuildUtilCommands.cs
deleted file mode 100644
index 79dddd00..00000000
--- a/src/BuildUtil/BuildUtilCommands.cs
+++ /dev/null
@@ -1,1244 +0,0 @@
-// SoftEther VPN Source Code - Developer Edition Master Branch
-// Build Utility
-
-
-using System;
-using System.Threading;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Net;
-using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
-using CoreUtil;
-
-namespace BuildUtil
-{
- public static class BuildUtilCommands
- {
- // Perform all
- [ConsoleCommandMethod(
- "Builds all sources and releases all packages.",
- "All [yes|no] [/NORMALIZESRC:yes|no] [/IGNOREERROR:yes|no] [/DEBUG:yes|no] [/SERIAL:yes|no]",
- "Builds all sources and releases all packages.",
- "[yes|no]:Specify 'yes' if you'd like to increment the build number.",
- "NORMALIZESRC:Specity 'yes' if you'd like to normalize the build informations in the source codes and resource scripts.",
- "IGNOREERROR:Specify yes if you'd like to ignore the child process to show the error message.",
- "SERIAL:Specify yes not to use parallel mode.",
- "DEBUG:Specity yes to enable debug mode. (UNIX only)"
-#if !BU_SOFTETHER
- , "SEVPN:Build SoftEther VPN Automatically After PacketiX VPN Build"
-#endif
- )]
- static int All(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
-#if !BU_SOFTETHER
- new ConsoleParam("[yes|no]", ConsoleService.Prompt, "Increments build number (y/n) ? ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("SEVPN", ConsoleService.Prompt, "Build SoftEther VPN automatically after PacketiX VPN Build (y/n) ? ", ConsoleService.EvalNotEmpty, null),
-#else
- new ConsoleParam("[yes|no]"),
-#endif
- new ConsoleParam("IGNOREERROR"),
- new ConsoleParam("DEBUG"),
- new ConsoleParam("SERIAL"),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- DateTime start = Time.NowDateTime;
-
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:BuildWin32 {0} /NORMALIZESRC:{1}",
- vl["[yes|no]"].BoolValue ? "yes" : "no",
- "yes"));
-
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:ReleaseWin32 all /IGNOREERROR:{0} /SERIAL:{1}",
- vl["IGNOREERROR"].BoolValue ? "yes" : "no",
- vl["SERIAL"].BoolValue ? "yes" : "no"));
-
-#if !BU_OSS
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:ReleaseUnix all /IGNOREERROR:{0} /DEBUG:{1} /SERIAL:{2}",
- vl["IGNOREERROR"].BoolValue ? "yes" : "no",
- vl["DEBUG"].BoolValue ? "yes" : "no",
- vl["SERIAL"].BoolValue ? "yes" : "no"));
-#endif
-
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:CopyRelease"));
-
-#if !BU_SOFTETHER
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:MakeSoftEtherDir"));
-
- if (vl["SEVPN"].BoolValue)
- {
- // Build SEVPN
- Win32BuildUtil.ExecCommand(Paths.CmdFileName, string.Format("/C \"{0}\"", Path.Combine(Paths.SoftEtherBuildDir, @"Main\BuildAll.cmd")));
- }
-
- Win32BuildUtil.ExecCommand(Env.ExeFileName, string.Format("/CMD:MakeOpenSource"));
-#endif
-
- DateTime end = Time.NowDateTime;
-
- Con.WriteLine("Taken time: {0}.", (end - start));
-
- return 0;
- }
-
-#if !BU_SOFTETHER
- // Create SoftEther Edition source
- [ConsoleCommandMethod(
- "Make MakeSoftEtherDir Source Dir.",
- "MakeSoftEtherDir",
- "Make MakeSoftEtherDir Source Dir."
- )]
- static int MakeSoftEtherDir(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- OpenSourceUtil.MakeSoftEtherDir();
-
- return 0;
- }
-
- // Create an open source version of source
- [ConsoleCommandMethod(
- "Make MakeOpenSource Source Dir.",
- "MakeOpenSource",
- "Make MakeOpenSource Source Dir."
- )]
- static int MakeOpenSource(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- OpenSourceUtil.MakeOpenSource();
-
- return 0;
- }
-#endif
-
- // Copy the released files
- [ConsoleCommandMethod(
- "Copies all release files.",
- "CopyRelease",
- "Copies all release files."
- )]
- static int CopyRelease(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- int versionMajor, versionMinor, versionBuild;
- string name;
- DateTime date;
- Win32BuildUtil.ReadBuildInfoFromTextFile(out versionMajor, out versionMinor, out versionBuild, out name, out date);
-
- string baseName = string.Format("v{0}-{1}-{2}-{3:D4}.{4:D2}.{5:D2}",
- BuildHelper.VersionIntToString(versionMajor, versionMinor),
- versionBuild,
- name,
- date.Year, date.Month, date.Day);
-
-#if !BU_OSS
- string destDirName = Path.Combine(Paths.ReleaseDestDir,
- string.Format(@"{0}-{1}-{2}-{3}",
- Str.DateToStrShort(BuildSoftwareList.ListCreatedDateTime),
- baseName,
- Env.MachineName, Env.UserName));
-#else // !BU_OSS
- string destDirName = Path.Combine(Paths.ReleaseDestDir,
- string.Format(@"{1}",
- Str.DateToStrShort(BuildSoftwareList.ListCreatedDateTime),
- baseName,
- Env.MachineName, Env.UserName));
-#endif
-
-#if !BU_OSS
- string publicDir = Path.Combine(destDirName, "Public");
-#else // !BU_OSS
- string publicDir = destDirName;
-#endif
-
-#if !BU_OSS
- string filesReleaseDir = Path.Combine(publicDir, baseName);
-#else // !BU_OSS
- string filesReleaseDir = publicDir;
-#endif
-
- string autorunReleaseSrcDir = Path.Combine(publicDir, "autorun");
-
- IO.CopyDir(Paths.ReleaseDir, filesReleaseDir, null, false, true);
-
-#if !BU_OSS
- IO.CopyDir(Paths.ReleaseSrckitDir, Path.Combine(destDirName, "Private"), null, false, true);
- IO.CopyDir(Path.Combine(Paths.BaseDirName, @"tmp\lib"), Path.Combine(destDirName, @"Private\lib"), null, false, true);
-#endif
-
- //IO.MakeDir(autorunReleaseSrcDir);
-
- /*
- File.Copy(Path.Combine(Paths.AutorunSrcDir, "Project1.exe"),
- Path.Combine(autorunReleaseSrcDir, "autorun.exe"), true);
-
- File.Copy(Path.Combine(Paths.AutorunSrcDir, "autorun.inf"),
- Path.Combine(autorunReleaseSrcDir, "autorun.inf"), true);
-
- File.Copy(Path.Combine(Paths.AutorunSrcDir, "packetix.ico"),
- Path.Combine(autorunReleaseSrcDir, "autorun.ico"), true);*/
-
- // Create a batch file
- string batchFileName = Path.Combine(publicDir, "MakeCD.cmd");
-#if !BU_OSS
- StreamWriter w = new StreamWriter(batchFileName);
-#else // !BU_OSS
- StringWriter w = new StringWriter();
-#endif
- w.WriteLine(@"SETLOCAL");
- w.WriteLine(@"SET BATCH_FILE_NAME=%0");
- w.WriteLine(@"SET BATCH_DIR_NAME=%0\..");
- w.WriteLine(@"SET NOW_TMP=%time:~0,2%");
- w.WriteLine(@"SET NOW=%date:~0,4%%date:~5,2%%date:~8,2%_%NOW_TMP: =0%%time:~3,2%%time:~6,2%");
- w.WriteLine();
- w.WriteLine();
-
- string[] files = Directory.GetFiles(filesReleaseDir, "*", SearchOption.AllDirectories);
-
- string cddir = "CD";
- /*string.Format("CD-v{0}.{1}-{2}-{3}-{4:D4}.{5:D2}.{6:D2}",
- version / 100, version % 100, build, name,
- date.Year, date.Month, date.Day);*/
-
- StringWriter txt = new StringWriter();
-
- foreach (string filename in files)
- {
- string file = filename;
-
- BuildSoftware s = new BuildSoftware(file);
-
- // Software\Windows\PacketiX VPN Server 4.0\32bit (Intel x86)\filename.exe
- string cpustr = string.Format("{0} - {1}", CPUBitsUtil.CPUBitsToString(s.Cpu.Bits), s.Cpu.Title).Replace("/", "or");
- string cpustr2 = cpustr;
-
- if (s.Cpu == CpuList.intel)
- {
- cpustr2 = "";
- cpustr = "Intel";
- }
-
- string tmp = string.Format(@"{1}\{2}\{3}\{5}{4}",
- 0,
- s.Os.Title,
- BuildHelper.GetSoftwareTitle(s.Software),
- cpustr2,
- Path.GetFileName(file),
- ""
- );
-
- tmp = Str.ReplaceStr(tmp, "\\\\", "\\");
-
- tmp = Str.ReplaceStr(tmp, " ", "_");
-
- w.WriteLine("mkdir \"{1}\\{0}\"", Path.GetDirectoryName(tmp), cddir);
- w.WriteLine("copy /b /y \"{2}\\{0}\" \"{3}\\{1}\"", IO.GetRelativeFileName(file, filesReleaseDir), tmp, baseName, cddir);
- w.WriteLine();
-
- string txt_filename = tmp;
- txt_filename = Str.ReplaceStr(txt_filename, "\\", "/");
-
- string txt_description = BuildHelper.GetSoftwareTitle(s.Software);
-
- string txt_products = BuildHelper.GetSoftwareProductList(s.Software);
-
- string txt_os = s.Os.Title;
-
- string txt_cpu = s.Cpu.Title;
- if (s.Cpu.Bits != CPUBits.Both)
- {
- txt_cpu += " (" + CPUBitsUtil.CPUBitsToString(s.Cpu.Bits) + ")";
- }
- else
- {
- txt_cpu += " (x86 and x64)";
- }
-
- string txt_version = BuildHelper.VersionIntToString(versionMajor, versionMinor);
-
- string txt_build = versionBuild.ToString();
-
- string txt_verstr = name;
-
- string txt_date = Str.DateTimeToStrShortWithMilliSecs(date);
-
- string txt_lang = "English, Japanese, Simplified Chinese";
-
- string txt_category = "PacketiX VPN (Commercial)";
-
-#if BU_SOFTETHER
- txt_category = "SoftEther VPN (Freeware)";
-#endif
-
- txt.WriteLine("FILENAME\t" + txt_filename);
- txt.WriteLine("DESCRIPTION\t" + txt_description);
- txt.WriteLine("CATEGORY\t" + txt_category);
- txt.WriteLine("PRODUCT\t" + txt_products);
- txt.WriteLine("OS\t" + txt_os);
- txt.WriteLine("OSLIST\t" + s.Os.OSSimpleList);
- txt.WriteLine("CPU\t" + txt_cpu);
- txt.WriteLine("VERSION\t" + txt_version);
- txt.WriteLine("BUILD\t" + txt_build);
- txt.WriteLine("VERSTR\t" + txt_verstr);
- txt.WriteLine("DATE\t" + txt_date);
- txt.WriteLine("LANGUAGE\t" + txt_lang);
- txt.WriteLine("*");
- txt.WriteLine();
- }
-
-#if BU_OSS
- Con.WriteLine("Installer packages are built on '{0}'. Enjoy it !!", publicDir);
-
- return 0;
-#endif // BU_OSS
-
- /*
- w.WriteLine("mkdir \"{0}\\autorun\"", cddir);
- w.WriteLine("copy /b /y autorun\\autorun.ico \"{0}\\autorun\"", cddir);
- w.WriteLine("copy /b /y autorun\\autorun.exe \"{0}\\autorun\"", cddir);
- w.WriteLine("copy /b /y autorun\\autorun.inf \"{0}\\autorun.inf\"", cddir);
- * */
-
- string zipFileName = string.Format("VPN-CD-v{0}.{1:D2}-{2}-{3}-{4:D4}.{5:D2}.{6:D2}.zip",
- versionMajor, versionMinor, versionBuild, name,
- date.Year, date.Month, date.Day);
- w.WriteLine("del {0}", zipFileName);
- w.WriteLine("CD {0}", cddir);
- w.WriteLine("zip -r -0 ../{0} *", zipFileName);
- w.WriteLine("cd ..");
- w.WriteLine("move {0} CD\\", zipFileName);
- w.WriteLine("rename CD {0}-tree", baseName);
- w.WriteLine();
-
- w.Close();
-
- // Copy of fastcopy
- string fastcopy_dest = Path.Combine(destDirName, @"Private\fastcopy_bin");
- IO.MakeDirIfNotExists(fastcopy_dest);
- File.Copy(Path.Combine(Paths.UtilityDirName, "FastCopy.exe"), Path.Combine(fastcopy_dest, "FastCopy.exe"), true);
- File.Copy(Path.Combine(Paths.UtilityDirName, "FastEx64.dll"), Path.Combine(fastcopy_dest, "FastEx64.dll"), true);
- File.Copy(Path.Combine(Paths.UtilityDirName, "FastExt1.dll"), Path.Combine(fastcopy_dest, "FastExt1.dll"), true);
-
- string fastcopy_exe = @"..\Private\fastcopy_bin\FastCopy.exe";
-
- // Create a upload batch
- string uploadBatchFileName = Path.Combine(publicDir, "UploadNow.cmd");
-#if !BU_OSS
- w = new StreamWriter(uploadBatchFileName);
-#endif // !BU_OSS
-
- string folder_name = "packetix";
-#if BU_SOFTETHER
- folder_name = "softether";
-#endif
- w.WriteLine(@"mkdir \\download\FILES\{1}\{0}-tree", baseName, folder_name);
- w.WriteLine(@"{0} /cmd=force_copy /exclude={3} /auto_close /force_start /estimate /open_window /error_stop=TRUE /bufsize=128 /disk_mode=diff /speed=full /verify {1}-tree /to=\\download\FILES\{2}\{1}-tree", fastcopy_exe, baseName, folder_name,
- "\"*files.txt*\"");
-
- w.WriteLine();
- /*
- w.WriteLine(@"mkdir \\downloadjp\FILES\{1}\{0}-tree", baseName, folder_name);
- w.WriteLine(@"{0} /cmd=force_copy /exclude={3} /auto_close /force_start /estimate /open_window /error_stop=TRUE /bufsize=128 /disk_mode=diff /speed=full /verify {1}-tree /to=\\downloadjp\FILES\{2}\{1}-tree", fastcopy_exe, baseName, folder_name,
- "\"*files.txt*\"");
-
- w.WriteLine();*/
-
- w.WriteLine(@"copy /y /b {0}-tree\files.txt \\download\FILES\{1}\{0}-tree\files.txt", baseName, folder_name);
- //w.WriteLine(@"copy /y /b {0}-tree\files.txt \\downloadjp\FILES\{1}\{0}-tree\files.txt", baseName, folder_name);
-
-
- w.WriteLine();
- w.WriteLine(@"pause");
- w.WriteLine();
-
- w.Close();
-
-
- txt.WriteLine("FILENAME\t" + zipFileName);
-#if BU_SOFTETHER
- txt.WriteLine("DESCRIPTION\t" + "ZIP CD-ROM Image Package of SoftEther VPN (for Admins)");
- txt.WriteLine("CATEGORY\t" + "SoftEther VPN (Freeware)");
- txt.WriteLine("PRODUCT\t" + "ZIP CD-ROM Image Package of SoftEther VPN");
-#else // BU_SOFTETHER
- txt.WriteLine("DESCRIPTION\t" + "ZIP CD-ROM Image Package of PacketiX VPN (for Admins)");
- txt.WriteLine("CATEGORY\t" + "PacketiX VPN (Commercial)");
- txt.WriteLine("PRODUCT\t" + "ZIP CD-ROM Image Package of PacketiX VPN");
-#endif // BU_SOFTETHER
- txt.WriteLine("OS\t" + "Any");
- txt.WriteLine("OSLIST\t" + "Any");
- txt.WriteLine("CPU\t" + "CD-ROM");
- txt.WriteLine("VERSION\t" + BuildHelper.VersionIntToString(versionMajor, versionMinor));
- txt.WriteLine("BUILD\t" + versionBuild.ToString());
- txt.WriteLine("VERSTR\t" + name);
- txt.WriteLine("DATE\t" + Str.DateTimeToStrShortWithMilliSecs(date));
- txt.WriteLine("LANGUAGE\t" + "English, Japanese, Simplified Chinese");
- txt.WriteLine("*");
- txt.WriteLine();
-
- string src_bindir = Path.Combine(Paths.BaseDirName, "bin");
- string vpnsmgr_zip_filename_relative = @"Windows\Admin_Tools\VPN_Server_Manager_and_Command-line_Utility_Package\";
- vpnsmgr_zip_filename_relative +=
-#if BU_SOFTETHER
- "softether-" +
-#endif // BU_SOFTETHER
- string.Format("vpn_admin_tools-v{0}.{1:D2}-{2}-{3}-{4:D4}.{5:D2}.{6:D2}-win32.zip",
- versionMajor, versionMinor, versionBuild, name,
- date.Year, date.Month, date.Day);
-
- string vpnsmgr_zip_filename_full = Path.Combine(Path.Combine(publicDir, cddir), vpnsmgr_zip_filename_relative);
-
- ZipPacker zip = new ZipPacker();
- zip.AddFileSimple("vpnsmgr.exe", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, "vpnsmgr.exe")), true);
- zip.AddFileSimple("vpncmd.exe", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, "vpncmd.exe")), true);
- zip.AddFileSimple("hamcore.se2", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"BuiltHamcoreFiles\hamcore_win32\hamcore.se2")), true);
- zip.AddFileSimple("ReadMeFirst_License.txt", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"hamcore\eula.txt")), true);
- zip.AddFileSimple("ReadMeFirst_Important_Notices_ja.txt", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"hamcore\warning_ja.txt")), true);
- zip.AddFileSimple("ReadMeFirst_Important_Notices_en.txt", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"hamcore\warning_en.txt")), true);
- zip.AddFileSimple("ReadMeFirst_Important_Notices_ru.txt", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"hamcore\warning_ru.txt")), true);
- zip.AddFileSimple("ReadMeFirst_Important_Notices_cn.txt", DateTime.Now, FileAttributes.Normal,
- IO.ReadFile(Path.Combine(src_bindir, @"hamcore\warning_cn.txt")), true);
- zip.Finish();
- byte[] zip_data = zip.GeneratedData.Read();
- IO.MakeDirIfNotExists(Path.GetDirectoryName(vpnsmgr_zip_filename_full));
- IO.SaveFile(vpnsmgr_zip_filename_full, zip_data);
-
- // ZIP package for VPN Server Manager GUI
- txt.WriteLine("FILENAME\t" + Str.ReplaceStr(vpnsmgr_zip_filename_relative, @"\", "/"));
-#if BU_SOFTETHER
- txt.WriteLine("DESCRIPTION\t" + "ZIP Package of vpnsmgr.exe and vpncmd.exe (without installers)");
- txt.WriteLine("CATEGORY\t" + "SoftEther VPN (Freeware)");
- txt.WriteLine("PRODUCT\t" + "SoftEther VPN Server Manager for Windows, SoftEther VPN Command-Line Admin Utility (vpncmd)");
-#else // BU_SOFTETHER
- txt.WriteLine("DESCRIPTION\t" + "ZIP Package of vpnsmgr.exe and vpncmd.exe (without installers)");
- txt.WriteLine("CATEGORY\t" + "PacketiX VPN (Commercial)");
- txt.WriteLine("PRODUCT\t" + "PacketiX VPN Server Manager for Windows, PacketiX VPN Command-Line Admin Utility (vpncmd)");
-#endif // BU_SOFTETHER
- txt.WriteLine("OS\t" + "Windows (.zip package without installers)");
- txt.WriteLine("OSLIST\t" + OSList.Windows.OSSimpleList);
- txt.WriteLine("CPU\t" + "Intel (x86 and x64)");
- txt.WriteLine("VERSION\t" + BuildHelper.VersionIntToString(versionMajor, versionMinor));
- txt.WriteLine("BUILD\t" + versionBuild.ToString());
- txt.WriteLine("VERSTR\t" + name);
- txt.WriteLine("DATE\t" + Str.DateTimeToStrShortWithMilliSecs(date));
- txt.WriteLine("LANGUAGE\t" + "English, Japanese, Simplified Chinese");
- txt.WriteLine("*");
- txt.WriteLine();
-
- IO.MakeDirIfNotExists(Path.Combine(publicDir, cddir));
- File.WriteAllText(Path.Combine(Path.Combine(publicDir, cddir), "files.txt"), txt.ToString(), Str.Utf8Encoding);
-
-
- // Execution of batch file
- string old_cd = Environment.CurrentDirectory;
-
- try
- {
- Environment.CurrentDirectory = Path.GetDirectoryName(batchFileName);
- }
- catch
- {
- }
-
- Win32BuildUtil.ExecCommand(Paths.CmdFileName, string.Format("/C \"{0}\"", batchFileName));
-
- try
- {
- Environment.CurrentDirectory = old_cd;
- }
- catch
- {
- }
-
- Con.WriteLine();
- Con.WriteLine("'{0}' に出力されました。", destDirName);
-
- return 0;
- }
-
- // UNIX release
- [ConsoleCommandMethod(
- "Builds UNIX installer package files.",
- "ReleaseUnix [id] [/IGNOREERROR:yes|no] [/DEBUG:yes|no] [/SERIAL:yes|no]",
- "Builds Unix installer package files.",
- "[id]:Specify target package ID which you'd like to build. If you'd like to erase and rebuild all packages, specify 'all'. Specify 'clean' to delete all release files.",
- "IGNOREERROR:Specify yes if you'd like to ignore the child process to show the error message.",
- "SERIAL:Specify yes not to use parallel mode.",
- "DEBUG:Specity yes to enable debug mode."
- )]
- static int ReleaseUnix(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[id]"),
- new ConsoleParam("IGNOREERROR"),
- new ConsoleParam("DEBUG"),
- new ConsoleParam("SERIAL"),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- int versionMajor, versionMinor, versionBuild;
- string name;
- DateTime date;
- Win32BuildUtil.ReadBuildInfoFromTextFile(out versionMajor, out versionMinor, out versionBuild, out name, out date);
- BuildSoftware[] softs = BuildSoftwareList.List;
- bool serial = vl["SERIAL"].BoolValue;
-
- if (Str.IsEmptyStr(vl.DefaultParam.StrValue))
- {
- Con.WriteLine("IDs:");
- foreach (BuildSoftware soft in softs)
- {
- if (soft.Os.IsWindows == false)
- {
- soft.SetBuildNumberVersionName(versionMajor, versionMinor, versionBuild, name, date);
- Con.WriteLine(" {0}", soft.IDString);
- Con.WriteLine(" - \"{0}\"", soft.OutputFileName);
- }
- }
- }
- else
- {
- string key = vl.DefaultParam.StrValue;
- bool all = false;
-
- if ("all".StartsWith(key, StringComparison.InvariantCultureIgnoreCase))
- {
- all = true;
- }
-
- if ("clean".StartsWith(key, StringComparison.InvariantCultureIgnoreCase))
- {
- // Delete the release directory
- Paths.DeleteAllReleaseTarGz();
- Con.WriteLine("Clean completed.");
- return 0;
- }
-
- List o = new List();
-
- foreach (BuildSoftware soft in softs)
- {
- soft.SetBuildNumberVersionName(versionMajor, versionMinor, versionBuild, name, date);
-
- if (soft.Os.IsWindows == false)
- {
- if (all || soft.IDString.IndexOf(key, StringComparison.InvariantCultureIgnoreCase) != -1)
- {
- o.Add(soft);
- }
- }
- }
-
- if (o.Count == 0)
- {
- throw new ApplicationException(string.Format("Software ID '{0}' not found.", key));
- }
- else
- {
- if (all)
- {
- // Delete the release directory
- Paths.DeleteAllReleaseTarGz();
- }
- else
- {
- IO.MakeDir(Paths.ReleaseDir);
- }
-
- if (serial)
- {
- // Build in series
- int i;
- for (i = 0; i < o.Count; i++)
- {
- Con.WriteLine("{0} / {1}: Executing for '{2}'...",
- i + 1, o.Count, o[i].IDString);
-
- BuildHelper.BuildMain(o[i], vl["DEBUG"].BoolValue);
- }
- }
- else if (o.Count == 1)
- {
- // To build
- BuildHelper.BuildMain(o[0], vl["DEBUG"].BoolValue);
- }
- else
- {
- // Make a child process build
- Process[] procs = new Process[o.Count];
-
- int i;
-
- for (i = 0; i < o.Count; i++)
- {
- Con.WriteLine("{0} / {1}: Executing for '{2}'...",
- i + 1, o.Count, o[i].IDString);
-
- procs[i] = Kernel.Run(Env.ExeFileName,
- string.Format("/PAUSEIFERROR:{1} /DT:{2} /CMD:ReleaseUnix /DEBUG:{3} {0}",
- o[i].IDString, vl["IGNOREERROR"].BoolValue ? "no" : "yes", Str.DateTimeToStrShort(BuildSoftwareList.ListCreatedDateTime), vl["DEBUG"].BoolValue ? "yes" : "no")
- );
- }
-
- Con.WriteLine("Waiting child processes...");
-
- int numError = 0;
-
- for (i = 0; i < o.Count; i++)
- {
- procs[i].WaitForExit();
-
- bool ok = procs[i].ExitCode == 0;
-
- if (ok == false)
- {
- numError++;
- }
-
- Con.WriteLine("{0} / {1} ({2}):", i + 1, o.Count, o[i].IDString);
- Con.WriteLine(" {0}", ok ? "Success" : "* Error *");
- }
-
- Con.WriteLine();
- if (numError != 0)
- {
- throw new ApplicationException(string.Format("{0} Errors.", numError));
- }
- Con.WriteLine("No Errors.");
- }
- }
- }
-
- return 0;
- }
-
- // Win32 Release
- [ConsoleCommandMethod(
- "Builds Win32 installer package files.",
- "ReleaseWin32 [id] [/IGNOREERROR:yes|no] [/SERIAL:yes|no]",
- "Builds Win32 installer package files.",
- "[id]:Specify target package ID which you'd like to build. If you'd like to erase and rebuild all packages, specify 'all'. Specify 'clean' to delete all release files.",
- "SERIAL:Specify yes not to use parallel mode.",
- "IGNOREERROR:Specify yes if you'd like to ignore the child process to show the error message."
- )]
- static int ReleaseWin32(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[id]"),
- new ConsoleParam("IGNOREERROR"),
- new ConsoleParam("SERIAL"),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- bool serial = vl["SERIAL"].BoolValue;
- int versionMajor, versionMinor, versionBuild;
- string name;
- DateTime date;
- Win32BuildUtil.ReadBuildInfoFromTextFile(out versionMajor, out versionMinor, out versionBuild, out name, out date);
- BuildSoftware[] softs = BuildSoftwareList.List;
-
- if (Str.IsEmptyStr(vl.DefaultParam.StrValue))
- {
- Con.WriteLine("IDs:");
- foreach (BuildSoftware soft in softs)
- {
- if (soft.Os.IsWindows)
- {
- soft.SetBuildNumberVersionName(versionMajor, versionMinor, versionBuild, name, date);
- Con.WriteLine(" {0}", soft.IDString);
- Con.WriteLine(" - \"{0}\"", soft.OutputFileName);
- }
- }
- }
- else
- {
- string key = vl.DefaultParam.StrValue;
- bool all = false;
-
- if ("all".StartsWith(key, StringComparison.InvariantCultureIgnoreCase))
- {
- all = true;
- }
-
- if ("clean".StartsWith(key, StringComparison.InvariantCultureIgnoreCase))
- {
- // Delete the release directory
- Paths.DeleteAllReleaseExe();
- Con.WriteLine("Clean completed.");
- return 0;
- }
-
- List o = new List();
-
- foreach (BuildSoftware soft in softs)
- {
- soft.SetBuildNumberVersionName(versionMajor, versionMinor, versionBuild, name, date);
-
- if (soft.Os.IsWindows)
- {
- if (all || soft.IDString.IndexOf(key, StringComparison.InvariantCultureIgnoreCase) != -1)
- {
- o.Add(soft);
- }
- }
- }
-
- if (o.Count == 0)
- {
- throw new ApplicationException(string.Format("Software ID '{0}' not found.", key));
- }
- else
- {
- if (all)
- {
- // Delete the release directory
- Paths.DeleteAllReleaseExe();
- }
- else
- {
- IO.MakeDir(Paths.ReleaseDir);
- }
-
- if (serial)
- {
- // Build in series
- int i;
- for (i = 0; i < o.Count; i++)
- {
- Con.WriteLine("{0} / {1}: Executing for '{2}'...",
- i + 1, o.Count, o[i].IDString);
-
- BuildHelper.BuildMain(o[i], false);
- }
- }
- else if (o.Count == 1)
- {
- // To build
- BuildHelper.BuildMain(o[0], false);
- }
- else
- {
- // Make a child process build
- Process[] procs = new Process[o.Count];
-
- int i;
-
- for (i = 0; i < o.Count; i++)
- {
- Con.WriteLine("{0} / {1}: Executing for '{2}'...",
- i + 1, o.Count, o[i].IDString);
-
- procs[i] = Kernel.Run(Env.ExeFileName,
- string.Format("/PAUSEIFERROR:{1} /CMD:ReleaseWin32 {0}",
- o[i].IDString, vl["IGNOREERROR"].BoolValue ? "no" : "yes"));
- }
-
- Con.WriteLine("Waiting child processes...");
-
- int numError = 0;
-
- for (i = 0; i < o.Count; i++)
- {
- procs[i].WaitForExit();
-
- bool ok = procs[i].ExitCode == 0;
-
- if (ok == false)
- {
- numError++;
- }
-
- Con.WriteLine("{0} / {1} ({2}):", i + 1, o.Count, o[i].IDString);
- Con.WriteLine(" {0}", ok ? "Success" : "* Error *");
- }
-
- Con.WriteLine();
- if (numError != 0)
- {
- throw new ApplicationException(string.Format("{0} Errors.", numError));
- }
- Con.WriteLine("No Errors.");
- }
- }
- }
-
- return 0;
- }
-
- // Copy the Unix source
- [ConsoleCommandMethod(
- "Copies source codes for Unix.",
- "CopyUnixSrc [destdir]",
- "Copies source codes for Unix.",
- "[destdir]:Specify the destination directory."
- )]
- static int CopyUnixSrc(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[destdir]", ConsoleService.Prompt, "Destination directory : ", ConsoleService.EvalNotEmpty, null),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- ((BuildSoftwareUnix)BuildSoftwareList.vpnbridge_linux_x86_ja).CopyUnixSrc(vl.DefaultParam.StrValue);
-
- return 0;
- }
-
- // Driver package build
- // Win32 build
- [ConsoleCommandMethod(
- "Builds the driver package.",
- "BuildDriverPackage",
- "Builds the driver package.")]
- static int BuildDriverPackage(ConsoleService c, string cmdName, string str)
- {
- Win32BuildUtil.MakeDriverPackage();
-
- return 0;
- }
-
- // Win32 build
- [ConsoleCommandMethod(
- "Builds all executable files for win32 and HamCore for all OS.",
- "BuildWin32 [yes|no] [/NORMALIZESRC:yes|no]",
- "Builds all executable files for win32 and HamCore for all OS.",
- "[yes|no]:Specify 'yes' if you'd like to increment the build number.",
- "NORMALIZESRC:Specity 'yes' if you'd like to normalize the build informations in the source codes and resource scripts."
- )]
- static int BuildWin32(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[yes|no]", ConsoleService.Prompt, "Increments build number (y/n) ? ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("NORMALIZESRC", ConsoleService.Prompt, "Normalizes source codes (y/n) ? ", ConsoleService.EvalNotEmpty, null)
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- if (vl.DefaultParam.BoolValue)
- {
- Win32BuildUtil.IncrementBuildNumber();
- }
- if (vl.DefaultParam.BoolValue || vl["NORMALIZESRC"].BoolValue)
- {
- Win32BuildUtil.NormalizeBuildInfo();
- }
-
- Paths.DeleteAllReleaseTarGz();
- Paths.DeleteAllReleaseExe();
- Paths.DeleteAllReleaseManuals();
- Paths.DeleteAllReleaseAdminKits();
-
- Win32BuildUtil.BuildMain();
- Win32BuildUtil.SignAllBinaryFiles();
- HamCoreBuildUtil.BuildHamcore();
- Win32BuildUtil.CopyDebugSnapshot();
-
- return 0;
- }
-
- // Process of post-build
- [ConsoleCommandMethod(
- "Process necessary tasks after building.",
- "PostBuild",
- "Process necessary tasks after building."
- )]
- static int PostBuild(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- Win32BuildUtil.SignAllBinaryFiles();
- HamCoreBuildUtil.BuildHamcore();
-
- return 0;
- }
-
- // Increment the build number
- [ConsoleCommandMethod(
- "Increments the build number.",
- "IncrementBuildNumber",
- "Increments the build number written in 'CurrentBuild.txt' text file."
- )]
- static int IncrementBuildNumber(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- Win32BuildUtil.IncrementBuildNumber();
-
- return 0;
- }
-
-
- // Test processing
- [ConsoleCommandMethod(
- "Run Test Procedure.",
- "Test",
- "Run Test Procedure."
- )]
- static int Test(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- TestClass.Test();
-
- return 0;
- }
-
- // Build a HamCore
- [ConsoleCommandMethod(
- "Builds a HamCore file.",
- "BuildHamCore",
- "Builds a HamCore file."
- )]
- static int BuildHamCore(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- HamCoreBuildUtil.BuildHamcore();
-
- return 0;
- }
-
- // Sign a binary file
- [ConsoleCommandMethod(
- "Sign all binary files.",
- "SignAll",
- "Sign all binary files."
- )]
- static int SignAll(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- Win32BuildUtil.SignAllBinaryFiles();
-
- return 0;
- }
-
- // Create and sign a Inf file of SeLow for Windows 8
- [ConsoleCommandMethod(
- "Generate INF files for SeLow.",
- "SignSeLowInfFiles",
- "Generate INF files for SeLow."
- )]
- static int SignSeLowInfFiles(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[cpu]", ConsoleService.Prompt, "x86 / x64: ", ConsoleService.EvalNotEmpty, null)
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
-#if !BU_OSS
-
- Win32BuildUtil.SignSeLowInfFiles(vl.DefaultParam.StrValue);
-
-#endif
-
- return 0;
- }
-
- // Create Inf file for Windows 8
- [ConsoleCommandMethod(
- "Generate INF files for Windows 8.",
- "GenerateWin8InfFiles",
- "Generate INF files for Windows 8."
- )]
- static int GenerateWin8InfFiles(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[cpu]", ConsoleService.Prompt, "x86 / x64: ", ConsoleService.EvalNotEmpty, null)
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
-#if !BU_OSS
-
- Win32BuildUtil.GenerateINFFilesForWindows8(vl.DefaultParam.StrValue);
-
-#endif
-
- return 0;
- }
-
- // Set the version of the PE to 4
- [ConsoleCommandMethod(
- "Set the version of the PE file to 4.",
- "SetPE4 [filename]",
- "Set the version of the PE file to 4.",
- "[filename]:Specify the target filename."
- )]
- static int SetPE4(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[filename]", ConsoleService.Prompt, "Filename: ", ConsoleService.EvalNotEmpty, null)
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- PEUtil.SetPEVersionTo4(vl.DefaultParam.StrValue);
-
- return 0;
- }
-
- // Set the Manifest
- [ConsoleCommandMethod(
- "Set the manifest to the executable file.",
- "SetManifest [filename] [/MANIFEST:manifest_file_name]",
- "Set the manifest to the executable file.",
- "[filename]:Specify the target executable filename.",
- "MANIFEST:Specify the manifest XML file."
- )]
- static int SetManifest(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[filename]", ConsoleService.Prompt, "Target Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("MANIFEST", ConsoleService.Prompt, "Manifest Filename: ", ConsoleService.EvalNotEmpty, null),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- PEUtil.SetManifest(vl.DefaultParam.StrValue, vl["MANIFEST"].StrValue);
-
- return 0;
- }
-
- // Generate a version information resource
- [ConsoleCommandMethod(
- "Generate a Version Information Resource File.",
- "GenerateVersionResource [targetFileName] [/OUT:destFileName]",
- "Generate a Version Information Resource File.",
- "[targetFileName]:Specify the target exe/dll file name.",
- "OUT:Specify the output .res file.",
- "RC:Specify a template RC file name.")]
- static int GenerateVersionResource(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[targetFileName]", ConsoleService.Prompt, "Target Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("OUT", ConsoleService.Prompt, "Dst Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("PRODUCT"),
- new ConsoleParam("RC"),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- string targetFilename = vl.DefaultParam.StrValue;
- string outFilename = vl["OUT"].StrValue;
- string product_name = vl["PRODUCT"].StrValue;
-
- Win32BuildUtil.GenerateVersionInfoResource(targetFilename, outFilename, vl["RC"].StrValue, product_name);
-
- return 0;
- }
-
- // Measure the number of lines of code
- [ConsoleCommandMethod(
- "Count the number of lines of the sources.",
- "Count [DIR]",
- "Count the number of lines of the sources.",
- "[DIR]:dir name.")]
- static int Count(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[DIR]", null, null, null, null),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- string dir = vl.DefaultParam.StrValue;
- if (Str.IsEmptyStr(dir))
- {
- dir = Paths.BaseDirName;
- }
-
- string[] files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
-
- int numLines = 0;
- int numBytes = 0;
- int numComments = 0;
- int totalLetters = 0;
-
- Dictionary commentsDict = new Dictionary();
-
- foreach (string file in files)
- {
- string ext = Path.GetExtension(file);
-
- if (Str.StrCmpi(ext, ".c") || Str.StrCmpi(ext, ".cpp") || Str.StrCmpi(ext, ".h") ||
- Str.StrCmpi(ext, ".rc") || Str.StrCmpi(ext, ".stb") || Str.StrCmpi(ext, ".cs")
- || Str.StrCmpi(ext, ".fx") || Str.StrCmpi(ext, ".hlsl"))
- {
- if (Str.InStr(file, "\\.svn\\") == false && Str.InStr(file, "\\seedll\\") == false && Str.InStr(file, "\\see\\") == false && Str.InStr(file, "\\openssl\\") == false)
- {
- string[] lines = File.ReadAllLines(file);
-
- numLines += lines.Length;
- numBytes += (int)new FileInfo(file).Length;
-
- foreach (string line in lines)
- {
- if (Str.InStr(line, "//") && Str.InStr(line, "// Validate arguments") == false)
- {
- if (commentsDict.ContainsKey(line) == false)
- {
- commentsDict.Add(line, 1);
- }
- numComments++;
-
- totalLetters += line.Trim().Length - 3;
- }
- }
- }
- }
- }
-
- Con.WriteLine("{0} Lines, {1} Bytes. {2} Comments ({3} distinct, aver: {4})", Str.ToStr3(numLines), Str.ToStr3(numBytes),
- Str.ToStr3(numComments), commentsDict.Count, totalLetters / numComments);
-
- return 0;
- }
-
- // Add to Cab by compressing OCX
- [ConsoleCommandMethod(
- "Compress a OCX and Generate a Cab file.",
- "GenerateVpnWebOcxCab [src] [/DEST:dest]",
- "Compress a OCX and Generate a Cab file.",
- "[src]:Specify the ocx file.",
- "DEST:Specify the destination cab file.")]
- static int GenerateVpnWebOcxCab(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[src]", ConsoleService.Prompt, "Src Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("DEST", ConsoleService.Prompt, "Dst Filename: ", ConsoleService.EvalNotEmpty, null),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
-#if !BU_OSS
- string destFileName = vl["DEST"].StrValue;
- string srcFileName = vl.DefaultParam.StrValue;
-
- Win32BuildUtil.GenerateVpnWebOcxCab(destFileName, srcFileName);
-#endif
-
- return 0;
- }
-
-
- // Copy the file
- [ConsoleCommandMethod(
- "Copy a File.",
- "FileCopy [src] [/DEST:dest]",
- "Copy a File.",
- "[src]:Specify the source file.",
- "DEST:Specify the destination file.")]
- static int FileCopy(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[src]", ConsoleService.Prompt, "Src Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("DEST", ConsoleService.Prompt, "Dst Filename: ", ConsoleService.EvalNotEmpty, null),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- string destFileName = vl["DEST"].StrValue;
- string srcFileName = vl.DefaultParam.StrValue;
-
- IO.FileCopy(srcFileName, destFileName, true, false);
-
- return 0;
- }
-
- // Sign the file
- [ConsoleCommandMethod(
- "Sign files using Authenticode certificates.",
- "SignCode [filename] [/DEST:destfilename] [/COMMENT:comment] [/KERNEL:yes|no]",
- "Sign files using Authenticode certificates.",
- "[filename]:Specify the target filename.",
- "DEST:Specify the destination filename. If this parameter is not specified, the target file will be overwritten.",
- "COMMENT:Provide a description of the signed content.",
- "KERNEL:Specify \"yes\" if Windows Vista / 7 Kernel Mode Driver Signing is needed."
- )]
- static int SignCode(ConsoleService c, string cmdName, string str)
- {
- ConsoleParam[] args =
- {
- new ConsoleParam("[filename]", ConsoleService.Prompt, "Filename: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("DEST"),
- new ConsoleParam("COMMENT", ConsoleService.Prompt, "Comment: ", ConsoleService.EvalNotEmpty, null),
- new ConsoleParam("KERNEL"),
- new ConsoleParam("CERTID"),
- new ConsoleParam("SHAMODE"),
- };
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- string destFileName = vl["DEST"].StrValue;
- string srcFileName = vl.DefaultParam.StrValue;
- if (Str.IsEmptyStr(destFileName))
- {
- destFileName = srcFileName;
- }
- string comment = vl["COMMENT"].StrValue;
- bool kernel = vl["KERNEL"].BoolValue;
-
- int certid = vl["CERTID"].IntValue;
- int shamode = vl["SHAMODE"].IntValue;
-
- CodeSign.SignFile(destFileName, srcFileName, comment, kernel, certid, shamode);
-
- return 0;
- }
- }
-}
-
diff --git a/src/BuildUtil/BuildUtilIcon.ico b/src/BuildUtil/BuildUtilIcon.ico
deleted file mode 100644
index 75d3c4aa..00000000
Binary files a/src/BuildUtil/BuildUtilIcon.ico and /dev/null differ
diff --git a/src/BuildUtil/BuildUtilMain.cs b/src/BuildUtil/BuildUtilMain.cs
deleted file mode 100644
index b3b3e7a4..00000000
--- a/src/BuildUtil/BuildUtilMain.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-// SoftEther VPN Source Code - Developer Edition Master Branch
-// Build Utility
-
-
-using System;
-using System.Threading;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Net;
-using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
-using CoreUtil;
-
-namespace BuildUtil
-{
- public class BuildUtilMain
- {
- public static bool pause = false;
-
- // Main function
- public static int Main(string[] args)
- {
- string errMsg = "";
-
- int ret = 0;
-
- ret = ConsoleService.EntryPoint("BuildUtil " + Env.CommandLine, "BuildUtil", typeof(BuildUtilMain), out errMsg);
-
- if (ret != 0)
- {
- Con.WriteLine("{0}: fatal error C0001: {1}", Path.GetFileNameWithoutExtension(Env.ExeFileName), errMsg);
-
- if (pause)
- {
- Console.Write("Press any key to exit...");
- Console.ReadKey();
- }
-
- Environment.Exit(1);
- }
-
- return ret;
- }
-
- // Command execution
- [ConsoleCommandMethod(
- "VPN Build Utility",
- "[/IN:infile] [/OUT:outfile] [/CSV] [/PAUSEIFERROR:yes|no] [/CMD command_line...]",
- "VPN Build Utility",
- "IN:This will specify the text file 'infile' that contains the list of commands that are automatically executed after the connection is completed. If the /IN parameter is specified, the vpncmd program will terminate automatically after the execution of all commands in the file are finished. If the file contains multiple-byte characters, the encoding must be Unicode (UTF-8). This cannot be specified together with /CMD (if /CMD is specified, /IN will be ignored).",
- "OUT:You can specify the text file 'outfile' to write all strings such as onscreen prompts, message, error and execution results. Note that if the specified file already exists, the contents of the existing file will be overwritten. Output strings will be recorded using Unicode (UTF-8) encoding.",
- "CMD:If the optional command 'command_line...' is included after /CMD, that command will be executed after the connection is complete and the vpncmd program will terminate after that. This cannot be specified together with /IN (if specified together with /IN, /IN will be ignored). Specify the /CMD parameter after all other vpncmd parameters.",
- "CSV:Enable CSV Mode.",
- "PAUSEIFERROR:Specify yes if you'd like to pause before exiting the process if there are any errors."
- )]
- public static int BuildUtil(ConsoleService c, string cmdName, string str)
- {
- Con.WriteLine("");
- Con.WriteLine("Copyright (c) SoftEther VPN Project. All Rights Reserved.");
- Con.WriteLine("");
-
- ConsoleParam[] args =
- {
- new ConsoleParam("IN", null, null, null, null),
- new ConsoleParam("OUT", null, null, null, null),
- new ConsoleParam("CMD", null, null, null, null),
- new ConsoleParam("CSV", null, null, null, null),
- new ConsoleParam("PAUSEIFERROR", null, null, null, null),
- new ConsoleParam("DT", null, null, null, null),
- };
-
- ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);
-
- pause = vl["PAUSEIFERROR"].BoolValue;
-
- string cmdline = vl["CMD"].StrValue;
-
- if (vl["DT"].IsEmpty == false)
- {
- BuildSoftwareList.ListCreatedDateTime = Str.StrToDateTime(vl["DT"].StrValue);
- }
-
- ConsoleService cs = c;
-
- while (cs.DispatchCommand(cmdline, "BuildUtil>", typeof(BuildUtilCommands), null))
- {
- if (Str.IsEmptyStr(cmdline) == false)
- {
- break;
- }
- }
-
- return cs.RetCode;
- }
- }
-}
-
-
diff --git a/src/BuildUtil/CodeSign.cs b/src/BuildUtil/CodeSign.cs
deleted file mode 100644
index 9da51394..00000000
--- a/src/BuildUtil/CodeSign.cs
+++ /dev/null
@@ -1,195 +0,0 @@
-// SoftEther VPN Source Code - Developer Edition Master Branch
-// Build Utility
-
-
-using System;
-using System.Threading;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Net;
-using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
-using CoreUtil;
-using BuildUtil.HvSignService;
-
-namespace BuildUtil
-{
- public static class CodeSign
- {
- public const int NumRetries = 1;
- public const int RetryIntervals = 200;
-
- public const int NumRetriesForCopy = 50;
- public const int RetryIntervalsForCopy = 10;
-
- const string in_dir = @"\\hvsigncode\SIGN\IN";
- const string out_dir = @"\\hvsigncode\SIGN\OUT";
-
-#if !BU_SOFTETHER
- public static int UsingCertId = 1;
-#else
- public static int UsingCertId = 2;
-#endif
-
- static object lockObj = new object();
-
- // Digital-sign the data on the memory
- public static byte[] SignMemory(byte[] srcData, string comment, bool kernelModeDriver, int cert_id, int sha_mode)
- {
-#if !BU_OSS
- int i;
- string out_filename = null;
- byte[] ret = null;
-
- string in_tmp_filename = Path.Combine(in_dir,
- Str.DateTimeToStrShortWithMilliSecs(DateTime.Now) + "_" +
- Env.MachineName + "_" +
- Secure.Rand63i().ToString() + ".dat");
-
- IO.SaveFile(in_tmp_filename, srcData);
-
- for (i = 0; i < NumRetries; i++)
- {
- Sign sign = new Sign();
- sign.Proxy = new WebProxy();
-
- try
- {
- out_filename = sign.ExecSignEx(Path.GetFileName(in_tmp_filename),
- kernelModeDriver,
- comment,
- cert_id,
- sha_mode);
- break;
- }
- catch (Exception ex)
- {
- if (i != (NumRetries - 1))
- {
- Kernel.SleepThread(RetryIntervals);
- }
- else
- {
- throw ex;
- }
- }
- }
-
- for (i = 0; i < NumRetriesForCopy; i++)
- {
- try
- {
- ret = IO.ReadFile(Path.Combine(out_dir, out_filename));
- }
- catch (Exception ex)
- {
- if (i != (NumRetriesForCopy - 1))
- {
- Kernel.SleepThread(RetryIntervalsForCopy);
- }
- else
- {
- throw ex;
- }
- }
- }
-
- string tmpFileName = IO.CreateTempFileNameByExt(".exe");
- try
- {
- File.Delete(tmpFileName);
- }
- catch
- {
- }
- File.WriteAllBytes(tmpFileName, ret);
-
- lock (lockObj)
- {
- if (ExeSignChecker.CheckFileDigitalSignature(tmpFileName) == false)
- {
- throw new ApplicationException("CheckFileDigitalSignature failed.");
- }
-
- if (kernelModeDriver)
- {
- if (ExeSignChecker.IsKernelModeSignedFile(tmpFileName) == false)
- {
- throw new ApplicationException("IsKernelModeSignedFile failed.");
- }
- }
- }
-
- try
- {
- }
- catch
- {
- File.Delete(tmpFileName);
- }
-
- return ret;
-#else // BU_OSS
- return srcData;
-#endif // BU_OSS
- }
-
- // Digital-sign the data on the file
- public static void SignFile(string destFileName, string srcFileName, string comment, bool kernelModeDriver)
- {
- int cert_id = UsingCertId;
-
- SignFile(destFileName, srcFileName, comment, kernelModeDriver, cert_id, 0);
- }
- public static void SignFile(string destFileName, string srcFileName, string comment, bool kernelModeDriver, int cert_id, int sha_mode)
- {
-#if !BU_OSS
- if (cert_id == 0)
- {
- cert_id = UsingCertId;
- }
-
- Con.WriteLine("Signing for '{0}'...", Path.GetFileName(destFileName));
- byte[] srcData = File.ReadAllBytes(srcFileName);
-
- if (srcFileName.EndsWith(".msi", StringComparison.InvariantCultureIgnoreCase))
- {
- sha_mode = 1;
- // todo: Set 2 in future !!!
- }
-
- byte[] destData = SignMemory(srcData, comment, kernelModeDriver, cert_id, sha_mode);
-
- try
- {
- File.Delete(destFileName);
- }
- catch
- {
- }
-
- File.WriteAllBytes(destFileName, destData);
-
- Con.WriteLine("Done.");
-#else // BU_OSS
- Con.WriteLine("Skipping the code signing for '{0}' in the build process. You can insert your own authenticode sign process here.", srcFileName);
-#endif // BU_OSS
- }
- }
-}
-
diff --git a/src/BuildUtil/CopyBuildUtil.cmd b/src/BuildUtil/CopyBuildUtil.cmd
deleted file mode 100644
index 808aa1e9..00000000
--- a/src/BuildUtil/CopyBuildUtil.cmd
+++ /dev/null
@@ -1,2 +0,0 @@
-copy "%0\..\..\bin\BuildUtilTmp.exe" "%0\..\..\bin\BuildUtil.exe"
-exit /b 0
diff --git a/src/BuildUtil/CoreUtil/Bmp.cs b/src/BuildUtil/CoreUtil/Bmp.cs
deleted file mode 100644
index e63b8dbc..00000000
--- a/src/BuildUtil/CoreUtil/Bmp.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- public static class Bmp
- {
- public static Bitmap Load(string filename)
- {
- return Load(IO.ReadFile(filename));
- }
- public static Bitmap Load(byte[] data)
- {
- MemoryStream ms = new MemoryStream();
- ms.Write(data, 0, data.Length);
- ms.Seek(0, SeekOrigin.Begin);
-
- return new Bitmap(ms);
- }
-
- public static void SaveAsBitmap(Bitmap bmp, string filename)
- {
- IO.SaveFile(filename, SaveAsBitmap(bmp));
- }
- public static byte[] SaveAsBitmap(Bitmap bmp)
- {
- MemoryStream ms = new MemoryStream();
-
- bmp.Save(ms, ImageFormat.Bmp);
-
- return ms.ToArray();
- }
-
- public static void SaveAsJpeg(Bitmap bmp, string filename)
- {
- IO.SaveFile(filename, SaveAsJpeg(bmp));
- }
- public static byte[] SaveAsJpeg(Bitmap bmp)
- {
- return SaveAsJpeg(bmp, 100);
- }
- public static void SaveAsJpeg(Bitmap bmp, string filename, int quality)
- {
- IO.SaveFile(filename, SaveAsJpeg(bmp, quality));
- }
- public static byte[] SaveAsJpeg(Bitmap bmp, int quality)
- {
- EncoderParameters eps = new EncoderParameters(1);
- EncoderParameter ep = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
- eps.Param[0] = ep;
-
- ImageCodecInfo info = getEncoderInfo("image/jpeg");
-
- MemoryStream ms = new MemoryStream();
- bmp.Save(ms, info, eps);
-
- return ms.ToArray();
- }
-
- static ImageCodecInfo getEncoderInfo(string type)
- {
- ImageCodecInfo[] encs = ImageCodecInfo.GetImageEncoders();
-
- foreach (ImageCodecInfo enc in encs)
- {
- if (Str.StrCmpi(enc.MimeType, type))
- {
- return enc;
- }
- }
-
- return null;
- }
-
- public static Bitmap ResizeBitmap(Bitmap bmp, int width, int height)
- {
- Bitmap dst = new Bitmap(width, height, PixelFormat.Format24bppRgb);
- Graphics g = Graphics.FromImage(dst);
- g.SmoothingMode = SmoothingMode.HighQuality;
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
-
- Rectangle r = new Rectangle(0, 0, width, height);
-
- g.DrawImage(bmp, r);
-
- return dst;
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Buf.cs b/src/BuildUtil/CoreUtil/Buf.cs
deleted file mode 100644
index 25e76c70..00000000
--- a/src/BuildUtil/CoreUtil/Buf.cs
+++ /dev/null
@@ -1,602 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-
-namespace CoreUtil
-{
- // FIFO
- public class Fifo
- {
- byte[] p;
- int pos, size;
- public int Size
- {
- get { return size; }
- }
- public byte[] Data
- {
- get
- {
- return this.p;
- }
- }
- public int DataOffset
- {
- get
- {
- return this.pos;
- }
- }
- public int PhysicalSize
- {
- get
- {
- return p.Length;
- }
- }
-
- int reallocMemSize;
- public const int FifoInitMemSize = 4096;
- public const int FifoReallocMemSize = 65536;
- public const int FifoReallocMemSizeSmall = 65536;
-
- long totalWriteSize = 0, totalReadSize = 0;
-
- public long TotalReadSize
- {
- get { return totalReadSize; }
- }
- public long TotalWriteSize
- {
- get { return totalWriteSize; }
- }
-
- public Fifo()
- {
- init(0);
- }
- public Fifo(int reallocMemSize)
- {
- init(reallocMemSize);
- }
-
- void init(int reallocMemSize)
- {
- if (reallocMemSize == 0)
- {
- reallocMemSize = FifoReallocMemSize;
- }
-
- this.size = this.pos = 0;
- this.reallocMemSize = reallocMemSize;
-
- this.p = new byte[FifoInitMemSize];
- }
-
- public void Write(Buf buf)
- {
- Write(buf.ByteData);
- }
- public void Write(byte[] src)
- {
- Write(src, src.Length);
- }
- public void SkipWrite(int size)
- {
- Write(null, size);
- }
- public void Write(byte[] src, int size)
- {
- Write(src, 0, size);
- }
- public void Write(byte[] src, int offset, int size)
- {
- int i, need_size;
- bool realloc_flag;
-
- i = this.size;
- this.size += size;
- need_size = this.pos + this.size;
- realloc_flag = false;
-
- int memsize = p.Length;
- while (need_size > memsize)
- {
- memsize = Math.Max(memsize, FifoInitMemSize) * 3;
- realloc_flag = true;
- }
-
- if (realloc_flag)
- {
- byte[] new_p = new byte[memsize];
- Util.CopyByte(new_p, 0, this.p, 0, this.p.Length);
- this.p = new_p;
- }
-
- if (src != null)
- {
- Util.CopyByte(this.p, this.pos + i, src, offset, size);
- }
-
- totalWriteSize += size;
- }
-
- public byte[] Read()
- {
- return Read(this.Size);
- }
- public void ReadToBuf(Buf buf, int size)
- {
- byte[] data = Read(size);
-
- buf.Write(data);
- }
- public Buf ReadToBuf(int size)
- {
- byte[] data = Read(size);
-
- return new Buf(data);
- }
- public byte[] Read(int size)
- {
- byte[] ret = new byte[size];
- int read_size = Read(ret);
- Array.Resize(ref ret, read_size);
-
- return ret;
- }
- public int Read(byte[] dst)
- {
- return Read(dst, dst.Length);
- }
- public int SkipRead(int size)
- {
- return Read(null, size);
- }
- public int Read(byte[] dst, int size)
- {
- return Read(dst, 0, size);
- }
- public int Read(byte[] dst, int offset, int size)
- {
- int read_size;
-
- read_size = Math.Min(size, this.size);
- if (read_size == 0)
- {
- return 0;
- }
- if (dst != null)
- {
- Util.CopyByte(dst, offset, this.p, this.pos, size);
- }
- this.pos += read_size;
- this.size -= read_size;
-
- if (this.size == 0)
- {
- this.pos = 0;
- }
-
- if (this.pos >= FifoInitMemSize &&
- this.p.Length >= this.reallocMemSize &&
- (this.p.Length / 2) > this.size)
- {
- byte[] new_p;
- int new_size;
-
- new_size = Math.Max(this.p.Length / 2, FifoInitMemSize);
- new_p = new byte[new_size];
- Util.CopyByte(new_p, 0, this.p, this.pos, this.size);
-
- this.p = new_p;
-
- this.pos = 0;
- }
-
- totalReadSize += read_size;
-
- return read_size;
- }
- }
-
- public class Buf
- {
- MemoryStream buf;
-
- public Buf()
- {
- init(new byte[0]);
- }
- public Buf(byte[] data)
- {
- init(data);
- }
- void init(byte[] data)
- {
- buf = new MemoryStream();
- Write(data);
- SeekToBegin();
- }
-
- public void Clear()
- {
- buf.SetLength(0);
- }
-
- public void WriteByte(byte data)
- {
- byte[] a = new byte[1] { data };
-
- Write(a);
- }
- public void Write(byte[] data)
- {
- buf.Write(data, 0, data.Length);
- }
- public void Write(byte[] data, int pos, int len)
- {
- buf.Write(data, pos, len);
- }
-
- public uint Size
- {
- get
- {
- return (uint)buf.Length;
- }
- }
-
- public uint Pos
- {
- get
- {
- return (uint)buf.Position;
- }
- }
-
- public byte[] ByteData
- {
- get
- {
- return buf.ToArray();
- }
- }
-
- public byte this[uint i]
- {
- get
- {
- return buf.GetBuffer()[i];
- }
-
- set
- {
- buf.GetBuffer()[i] = value;
- }
- }
-
- public byte[] Read()
- {
- return Read(this.Size);
- }
- public byte[] Read(uint size)
- {
- byte[] tmp = new byte[size];
- int i = buf.Read(tmp, 0, (int)size);
-
- byte[] ret = new byte[i];
- Array.Copy(tmp, 0, ret, 0, i);
-
- return ret;
- }
- public byte ReadByte()
- {
- byte[] a = Read(1);
-
- return a[0];
- }
-
- public void SeekToBegin()
- {
- Seek(0);
- }
- public void SeekToEnd()
- {
- Seek(0, SeekOrigin.End);
- }
- public void Seek(uint offset)
- {
- Seek(offset, SeekOrigin.Begin);
- }
- public void Seek(uint offset, SeekOrigin mode)
- {
- buf.Seek(offset, mode);
- }
-
- public ushort ReadShort()
- {
- byte[] data = Read(2);
- if (data.Length != 2)
- {
- return 0;
- }
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- return BitConverter.ToUInt16(data, 0);
- }
- public ushort RawReadShort()
- {
- byte[] data = Read(2);
- if (data.Length != 2)
- {
- return 0;
- }
- return BitConverter.ToUInt16(data, 0);
- }
-
- public uint ReadInt()
- {
- byte[] data = Read(4);
- if (data.Length != 4)
- {
- return 0;
- }
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- return BitConverter.ToUInt32(data, 0);
- }
- public uint RawReadInt()
- {
- byte[] data = Read(4);
- if (data.Length != 4)
- {
- return 0;
- }
- return BitConverter.ToUInt32(data, 0);
- }
-
- public ulong ReadInt64()
- {
- byte[] data = Read(8);
- if (data.Length != 8)
- {
- return 0;
- }
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- return BitConverter.ToUInt64(data, 0);
- }
- public ulong RawReadInt64()
- {
- byte[] data = Read(8);
- if (data.Length != 8)
- {
- return 0;
- }
- return BitConverter.ToUInt64(data, 0);
- }
-
- public string ReadStr()
- {
- return ReadStr(false);
- }
- public string ReadStr(bool include_null)
- {
- uint len = ReadInt();
- byte[] data = Read(len - (uint)(include_null ? 1 : 0));
- return Str.ShiftJisEncoding.GetString(data);
- }
-
- public string ReadUniStr()
- {
- return ReadUniStr(false);
- }
- public string ReadUniStr(bool include_null)
- {
- uint len = ReadInt();
- if (len == 0)
- {
- return null;
- }
- byte[] data = Read(len - (uint)(include_null ? 2 : 0));
- return Str.Utf8Encoding.GetString(data);
- }
- public void WriteShort(ushort shortValue)
- {
- byte[] data = BitConverter.GetBytes(shortValue);
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- Write(data);
- }
- public void RawWriteShort(ushort shortValue)
- {
- byte[] data = BitConverter.GetBytes(shortValue);
- Write(data);
- }
-
- public void WriteInt(uint intValue)
- {
- byte[] data = BitConverter.GetBytes(intValue);
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- Write(data);
- }
- public void RawWriteInt(uint intValue)
- {
- byte[] data = BitConverter.GetBytes(intValue);
- Write(data);
- }
-
- public void WriteInt64(ulong int64Value)
- {
- byte[] data = BitConverter.GetBytes(int64Value);
- if (Env.IsLittleEndian)
- {
- Array.Reverse(data);
- }
- Write(data);
- }
- public void RawWriteInt64(ulong int64Value)
- {
- byte[] data = BitConverter.GetBytes(int64Value);
- Write(data);
- }
-
- public string ReadNextLineAsString()
- {
- return ReadNextLineAsString(Str.Utf8Encoding);
- }
- public string ReadNextLineAsString(Encoding encoding)
- {
- byte[] ret = ReadNextLineAsData();
- if (ret == null)
- {
- return null;
- }
-
- return encoding.GetString(ret);
- }
-
- public byte[] ReadNextLineAsData()
- {
- if (this.Size <= this.Pos)
- {
- return null;
- }
-
- long pos = buf.Position;
-
- long i;
- byte[] tmp = new byte[1];
- for (i = pos; i < buf.Length; i++)
- {
- buf.Read(tmp, 0, 1);
-
- if (tmp[0] == 13 || tmp[0] == 10)
- {
- if (tmp[0] == 13)
- {
- if ((i + 2) < buf.Length)
- {
- i++;
- }
- }
-
- break;
- }
- }
-
- long len = i - pos;
-
- buf.Position = pos;
-
- byte[] ret = Read((uint)((int)len));
-
- try
- {
- Seek(1, SeekOrigin.Current);
- }
- catch
- {
- }
-
- if (ret.Length >= 1 && ret[ret.Length - 1] == 13)
- {
- Array.Resize(ref ret, ret.Length - 1);
- }
-
- return ret;
- }
-
- public void WriteStr(string strValue)
- {
- WriteStr(strValue, false);
- }
- public void WriteStr(string strValue, bool include_null)
- {
- byte[] data = Str.ShiftJisEncoding.GetBytes(strValue);
- WriteInt((uint)data.Length + (uint)(include_null ? 1 : 0));
- Write(data);
- }
-
- public void WriteUniStr(string strValue)
- {
- WriteUniStr(strValue, false);
- }
- public void WriteUniStr(string strValue, bool include_null)
- {
- byte[] data = Str.Utf8Encoding.GetBytes(strValue);
- WriteInt((uint)data.Length + (uint)(include_null ? 2 : 0));
- Write(data);
- }
-
- public static Buf ReadFromFile(string filename)
- {
- return new Buf(IO.ReadFile(filename));
- }
-
- public void WriteToFile(string filename)
- {
- IO.SaveFile(filename, this.ByteData);
- }
-
- public static Buf ReadFromStream(Stream st)
- {
- Buf ret = new Buf();
- int size = 32767;
-
- while (true)
- {
- byte[] tmp = new byte[size];
- int i = st.Read(tmp, 0, tmp.Length);
-
- if (i <= 0)
- {
- break;
- }
-
- Array.Resize(ref tmp, i);
-
- ret.Write(tmp);
- }
-
- ret.SeekToBegin();
-
- return ret;
- }
- }
-}
-
diff --git a/src/BuildUtil/CoreUtil/Cache.cs b/src/BuildUtil/CoreUtil/Cache.cs
deleted file mode 100644
index 637c1b03..00000000
--- a/src/BuildUtil/CoreUtil/Cache.cs
+++ /dev/null
@@ -1,249 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-
-namespace CoreUtil
-{
- public enum CacheType
- {
- UpdateExpiresWhenAccess = 0,
- DoNotUpdateExpiresWhenAccess = 1,
- }
-
- public class Cache
- {
- class Entry
- {
- DateTime createdDateTime;
- public DateTime CreatedDateTime
- {
- get { return createdDateTime; }
- }
- DateTime updatedDateTime;
- public DateTime UpdatedDateTime
- {
- get { return updatedDateTime; }
- }
- DateTime lastAccessedDateTime;
- public DateTime LastAccessedDateTime
- {
- get { return lastAccessedDateTime; }
- }
-
- TKey key;
- public TKey Key
- {
- get
- {
- return key;
- }
- }
-
- TValue value;
- public TValue Value
- {
- get
- {
- lastAccessedDateTime = Time.NowDateTime;
- return this.value;
- }
- set
- {
- this.value = value;
- updatedDateTime = Time.NowDateTime;
- lastAccessedDateTime = Time.NowDateTime;
- }
- }
-
- public Entry(TKey key, TValue value)
- {
- this.key = key;
- this.value = value;
- lastAccessedDateTime = updatedDateTime = createdDateTime = Time.NowDateTime;
- }
-
- public override int GetHashCode()
- {
- return key.GetHashCode();
- }
-
- public override string ToString()
- {
- return key.ToString() + "," + value.ToString();
- }
- }
-
- public static readonly TimeSpan DefaultExpireSpan = new TimeSpan(0, 5, 0);
- public const CacheType DefaultCacheType = CacheType.UpdateExpiresWhenAccess;
-
- TimeSpan expireSpan;
- public TimeSpan ExpireSpan
- {
- get { return expireSpan; }
- }
- CacheType type;
- public CacheType Type
- {
- get { return type; }
- }
- Dictionary list;
- object lockObj;
-
- public Cache()
- {
- init(DefaultExpireSpan, DefaultCacheType);
- }
- public Cache(CacheType type)
- {
- init(DefaultExpireSpan, type);
- }
- public Cache(TimeSpan expireSpan)
- {
- init(expireSpan, DefaultCacheType);
- }
- public Cache(TimeSpan expireSpan, CacheType type)
- {
- init(expireSpan, type);
- }
- void init(TimeSpan expireSpan, CacheType type)
- {
- this.expireSpan = expireSpan;
- this.type = type;
-
- list = new Dictionary();
- lockObj = new object();
- }
-
- public void Add(TKey key, TValue value)
- {
- lock (lockObj)
- {
- Entry e;
-
- deleteExpired();
-
- if (list.ContainsKey(key) == false)
- {
- e = new Entry(key, value);
-
- list.Add(e.Key, e);
-
- deleteExpired();
- }
- else
- {
- e = list[key];
- e.Value = value;
- }
- }
- }
-
- public void Delete(TKey key)
- {
- lock (lockObj)
- {
- if (list.ContainsKey(key))
- {
- list.Remove(key);
- }
- }
- }
-
- public TValue this[TKey key]
- {
- get
- {
- lock (lockObj)
- {
- deleteExpired();
-
- if (list.ContainsKey(key) == false)
- {
- return default(TValue);
- }
-
- return list[key].Value;
- }
- }
- }
-
- static long last_deleted = 0;
-
- void deleteExpired()
- {
- bool do_delete = false;
- long now = Tick64.Value;
- long delete_interval = expireSpan.Milliseconds / 10;
-
- lock (lockObj)
- {
- if (last_deleted == 0 || now > (last_deleted + delete_interval))
- {
- last_deleted = now;
- do_delete = true;
- }
- }
-
- if (do_delete == false)
- {
- return;
- }
-
- lock (lockObj)
- {
- List o = new List();
- DateTime expire = Time.NowDateTime - this.expireSpan;
-
- foreach (Entry e in list.Values)
- {
- if (this.type == CacheType.UpdateExpiresWhenAccess)
- {
- if (e.LastAccessedDateTime < expire)
- {
- o.Add(e);
- }
- }
- else
- {
- if (e.UpdatedDateTime < expire)
- {
- o.Add(e);
- }
- }
- }
-
- foreach (Entry e in o)
- {
- list.Remove(e.Key);
- }
- }
- }
- }
-}
-
diff --git a/src/BuildUtil/CoreUtil/Compress.cs b/src/BuildUtil/CoreUtil/Compress.cs
deleted file mode 100644
index 64947527..00000000
--- a/src/BuildUtil/CoreUtil/Compress.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-using CoreUtil.Internal;
-
-namespace CoreUtil
-{
- public static class ZLib
- {
- public static byte[] Compress(byte[] src)
- {
- return Compress(src, zlibConst.Z_DEFAULT_COMPRESSION);
- }
- public static byte[] Compress(byte[] src, int level)
- {
- return Compress(src, level, false);
- }
- public static byte[] Compress(byte[] src, int level, bool noHeader)
- {
- int dstSize = src.Length * 2 + 100;
- byte[] dst = new byte[dstSize];
-
- compress2(ref dst, src, level, noHeader);
-
- return dst;
- }
-
- public static byte[] Uncompress(byte[] src, int originalSize)
- {
- byte[] dst = new byte[originalSize];
-
- uncompress(ref dst, src);
-
- return dst;
- }
-
- static void compress2(ref byte[] dest, byte[] src, int level, bool noHeader)
- {
- ZStream stream = new ZStream();
-
- stream.next_in = src;
- stream.avail_in = src.Length;
-
- stream.next_out = dest;
- stream.avail_out = dest.Length;
-
- if (noHeader == false)
- {
- stream.deflateInit(level);
- }
- else
- {
- stream.deflateInit(level, -15);
- }
-
- stream.deflate(zlibConst.Z_FINISH);
-
- Array.Resize(ref dest, (int)stream.total_out);
- }
-
- static void uncompress(ref byte[] dest, byte[] src)
- {
- ZStream stream = new ZStream();
-
- stream.next_in = src;
- stream.avail_in = src.Length;
-
- stream.next_out = dest;
- stream.avail_out = dest.Length;
-
- stream.inflateInit();
-
- int err = stream.inflate(zlibConst.Z_FINISH);
- if (err != zlibConst.Z_STREAM_END)
- {
- stream.inflateEnd();
- throw new ApplicationException();
- }
-
- Array.Resize(ref dest, (int)stream.total_out);
-
- err = stream.inflateEnd();
- if (err != zlibConst.Z_OK)
- {
- throw new ApplicationException();
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Console.cs b/src/BuildUtil/CoreUtil/Console.cs
deleted file mode 100644
index 4ad9865d..00000000
--- a/src/BuildUtil/CoreUtil/Console.cs
+++ /dev/null
@@ -1,2109 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-#if ASPNET
-using Resources.BuildUtil.Properties;
-#else
-using BuildUtil.Properties;
-#endif
-
-namespace CoreUtil
-{
- public static class Con
- {
- static ConsoleService cs = null;
-
- public static ConsoleService ConsoleService
- {
- get { return Con.cs; }
- }
-
- public static void SetConsoleService(ConsoleService svc)
- {
- cs = svc;
- }
-
- public static void UnsetConsoleService()
- {
- cs = null;
- }
-
- public static string ReadLine()
- {
- return ReadLine("");
- }
- public static string ReadLine(string prompt)
- {
- return ReadLine(prompt, false);
- }
- public static string ReadLine(string prompt, bool noFile)
- {
- if (cs != null)
- {
- return cs.ReadLine(prompt, noFile);
- }
- else
- {
- Console.Write(prompt);
- return Console.ReadLine();
- }
- }
-
- public static void WriteLine()
- {
- WriteLine("");
- }
-
- public static void WriteLine(object arg)
- {
- if (cs != null)
- {
- cs.WriteLine(arg);
- }
- else
- {
- Console.WriteLine(arg);
- }
- }
-
- public static void WriteLine(string str)
- {
- if (cs != null)
- {
- cs.WriteLine(str);
- }
- else
- {
- Console.WriteLine(str);
- }
- }
-
- public static void WriteLine(string str, object arg)
- {
- if (cs != null)
- {
- cs.WriteLine(str, arg);
- }
- else
- {
- Console.WriteLine(str, arg);
- }
- }
-
- public static void WriteLine(string str, params object[] args)
- {
- if (cs != null)
- {
- cs.WriteLine(str, args);
- }
- else
- {
- Console.WriteLine(str, args);
- }
- }
- }
-
- public class ConsoleUserCancelException : Exception
- {
- public ConsoleUserCancelException(string msg)
- : base(msg)
- {
- }
- }
-
- public class ConsoleEvalMinMaxParam
- {
- public readonly string ErrorMessageString;
- public readonly int MinValue, MaxValue;
-
- public ConsoleEvalMinMaxParam(string errorMessageString, int minValue, int maxValue)
- {
- this.ErrorMessageString = errorMessageString;
- this.MinValue = minValue;
- this.MaxValue = maxValue;
- }
- }
-
- public enum ConsoleType
- {
- Local,
- Csv,
- }
-
- public class ConsoleParam
- {
- public readonly string Name;
- public readonly ConsolePromptProcDelegate PromptProc;
- public readonly object PromptProcParam;
- public readonly ConsoleEvalProcDelegate EvalProc;
- public readonly object EvalProcParam;
- internal string Tmp = null;
- public ConsoleParam(string name)
- : this(name, null, null)
- {
- }
- public ConsoleParam(string name,
- ConsolePromptProcDelegate promptProc,
- object promptProcParam)
- : this(name, promptProc, promptProcParam, null, null)
- {
- }
- public ConsoleParam(string name,
- ConsolePromptProcDelegate promptProc,
- object promptProcParam,
- ConsoleEvalProcDelegate evalProc,
- object evalProcParam)
- {
- this.Name = name;
- this.PromptProc = promptProc;
- this.PromptProcParam = promptProcParam;
- this.EvalProc = evalProc;
- this.EvalProcParam = evalProcParam;
- }
- }
-
- public delegate string ConsolePromptProcDelegate(ConsoleService c, object param);
- public delegate bool ConsoleEvalProcDelegate(ConsoleService c, string str, object param);
-
- delegate void ConsoleFreeDelegate();
- delegate string ConsoleReadLineDelegate(string prompt, bool nofile);
- delegate string ConsoleReadPasswordDelegate(string prompt);
- delegate bool ConsoleWriteDelegate(string str);
- delegate int ConsoleGetWidthDelegate();
-
- public class ConsoleParamValueList
- {
- List o;
-
- public ConsoleParamValueList()
- {
- o = new List();
- }
-
- public IEnumerable Values
- {
- get
- {
- int i;
- for (i = 0; i < o.Count; i++)
- {
- yield return o[i];
- }
- }
- }
-
- public void Add(ConsoleParamValue v)
- {
- if (o.Contains(v) == false)
- {
- o.Add(v);
- }
- }
-
- public ConsoleParamValue this[string name]
- {
- get
- {
- ConsoleParamValue v = new ConsoleParamValue(name, "", 0);
-
- int i = o.IndexOf(v);
- if (i == -1)
- {
- return new ConsoleParamValue(name, "", 0);
- }
-
- return o[i];
- }
- }
-
- public ConsoleParamValue DefaultParam
- {
- get
- {
- foreach (ConsoleParamValue c in o)
- {
- if (c.IsDefaultParam)
- {
- return c;
- }
- }
-
- return new ConsoleParamValue("", "", 0, true);
- }
- }
-
- public string GetStr(string name)
- {
- ConsoleParamValue v = this[name];
- if (v == null)
- {
- return null;
- }
-
- return v.StrValue;
- }
-
- public int GetInt(string name)
- {
- ConsoleParamValue v = this[name];
- if (v == null)
- {
- return 0;
- }
-
- return v.IntValue;
- }
-
- public bool GetYes(string name)
- {
- return Str.StrToBool(name);
- }
- }
-
- public class ConsoleParamValue : IComparable, IEquatable
- {
- public readonly string Name;
- public readonly string StrValue;
- public readonly int IntValue;
- public readonly bool BoolValue;
- public readonly bool IsEmpty;
- public readonly bool IsDefaultParam;
-
- public ConsoleParamValue(string name, string strValue, int intValue)
- : this(name, strValue, intValue, false)
- {
- }
- public ConsoleParamValue(string name, string strValue, int intValue, bool isDefaultParam)
- {
- this.Name = name;
- this.IntValue = intValue;
- this.StrValue = strValue;
- this.BoolValue = Str.StrToBool(strValue);
- this.IsDefaultParam = isDefaultParam;
-
- this.IsEmpty = Str.IsEmptyStr(strValue);
- }
-
- public int CompareTo(ConsoleParamValue other)
- {
- return Str.StrCmpiRetInt(this.Name, other.Name);
- }
-
- public bool Equals(ConsoleParamValue other)
- {
- return Str.StrCmpi(this.Name, other.Name);
- }
- }
-
- public class ConsoleCommandParam : Attribute
- {
- }
-
- public class ConsoleCommandMethod : Attribute
- {
- public readonly string Description;
- public readonly string ArgsHelp;
- public readonly string BodyHelp;
- public readonly SortedList ParamHelp;
-
- internal BindingFlags bindingFlag;
- internal MemberInfo memberInfo;
- internal MethodInfo methodInfo;
- internal string name;
-
- public ConsoleCommandMethod(string description, string argsHelp, string bodyHelp, params string[] paramHelp)
- {
- this.Description = description;
- this.ArgsHelp = argsHelp;
- this.BodyHelp = bodyHelp;
- this.ParamHelp = new SortedList(new StrComparer(false));
-
- foreach (string s in paramHelp)
- {
- int i = s.IndexOf(":");
- if (i == -1)
- {
- throw new ArgumentException(s);
- }
-
- this.ParamHelp.Add(s.Substring(0, i), s.Substring(i + 1));
- }
- }
- }
-
- public static class ConsoleErrorCode
- {
- public const int ERR_BAD_COMMAND_OR_PARAM = -100001;
- public const int ERR_INNER_EXCEPTION = -100002;
- public const int ERR_USER_CANCELED = -100003;
-
- public static string ErrorCodeToString(int code)
- {
- bool b;
-
- return ErrorCodeToString(code, out b);
- }
- public static string ErrorCodeToString(int code, out bool unknownError)
- {
- unknownError = false;
-
- switch (code)
- {
- case ERR_BAD_COMMAND_OR_PARAM:
- return "Bad command or parameters.";
-
- case ERR_USER_CANCELED:
- return "User canceled.";
-
- case ERR_INNER_EXCEPTION:
- default:
- unknownError = true;
- return string.Format("Unknown Error {0}", code);
- }
- }
- }
-
- public class ConsoleService
- {
- IO inFile;
- Buf inBuf;
- IO outFile;
- int win32_OldConsoleWidth;
-
- public const int MaxPromptStrSize = 65536;
- public const int Win32DefaultConsoleWidth = 100;
-
- ConsoleType consoleType;
- public ConsoleType ConsoleType
- {
- get { return consoleType; }
- }
-
- int retCode;
- public int RetCode
- {
- get { return retCode; }
- }
-
- string retErrorMessage;
- public string RetErrorMessage
- {
- get
- {
- bool b;
- string s = ConsoleErrorCode.ErrorCodeToString(this.RetCode, out b);
-
- if (b)
- {
- s = this.retErrorMessage;
- }
-
- Str.NormalizeString(ref s);
-
- return s;
- }
- }
-
- ConsoleFreeDelegate free;
-
- ConsoleReadLineDelegate readLine;
-
- ConsoleReadPasswordDelegate readPassword;
-
- ConsoleWriteDelegate write;
-
- ConsoleGetWidthDelegate getWidth;
-
- SortedList currentCmdList = null;
-
-
- private ConsoleService()
- {
- }
-
- public static int EntryPoint(string cmdLine, string programName, Type commandClass)
- {
- string s;
- return EntryPoint(cmdLine, programName, commandClass, out s);
- }
- public static int EntryPoint(string cmdLine, string programName, Type commandClass, out string lastErrorMessage)
- {
- int ret = 0;
- string infile, outfile;
- string csvmode;
- ConsoleService c;
-
- lastErrorMessage = "";
-
- infile = ParseCommand(cmdLine, "in");
- outfile = ParseCommand(cmdLine, "out");
- if (Str.IsEmptyStr(infile))
- {
- infile = null;
- }
- if (Str.IsEmptyStr(outfile))
- {
- outfile = null;
- }
- c = ConsoleService.NewLocalConsoleService(infile, outfile);
-
- csvmode = ParseCommand(cmdLine, "csv");
- if (csvmode != null)
- {
- c.consoleType = ConsoleType.Csv;
- }
-
- if (c.DispatchCommand(cmdLine, ">", commandClass) == false)
- {
- ret = ConsoleErrorCode.ERR_BAD_COMMAND_OR_PARAM;
- }
- else
- {
- ret = c.retCode;
- }
-
- lastErrorMessage = c.RetErrorMessage;
-
- return ret;
- }
-
- public bool WriteLine(object value)
- {
- return WriteLine(value.ToString());
- }
- public bool WriteLine(string str)
- {
- return localWrite(str);
- }
- public bool WriteLine(string format, object arg0)
- {
- return WriteLine(string.Format(format, arg0));
- }
- public bool WriteLine(string format, params object[] arg)
- {
- return WriteLine(string.Format(format, arg));
- }
-
- public string ReadLine(string prompt)
- {
- return ReadLine(prompt, false);
- }
- public string ReadLine(string prompt, bool noFile)
- {
- return localReadLine(prompt, noFile);
- }
-
- public string ReadPassword(string prompt)
- {
- return localReadPassword(prompt);
- }
-
- public static ConsolePromptProcDelegate Prompt
- {
- get { return new ConsolePromptProcDelegate(prompt); }
- }
- static string prompt(ConsoleService c, object param)
- {
- string p = (param == null) ? Resources.CMD_PROMPT : (string)param;
-
- return c.readLine(p, true);
- }
-
- public static ConsoleEvalProcDelegate EvalIsFile
- {
- get { return new ConsoleEvalProcDelegate(evalIsFile); }
- }
- static bool evalIsFile(ConsoleService c, string str, object param)
- {
- string tmp;
- if (c == null || str == null)
- {
- return false;
- }
-
- tmp = str;
-
- if (Str.IsEmptyStr(tmp))
- {
- c.write(Resources.CMD_FILE_NAME_EMPTY);
- return false;
- }
-
- if (IO.IsFileExists(tmp) == false)
- {
- c.write(Str.FormatC(Resources.CMD_FILE_NOT_FOUND, tmp));
-
- return false;
- }
-
- return true;
- }
-
- public static ConsoleEvalProcDelegate EvalInt1
- {
- get { return new ConsoleEvalProcDelegate(evalInt1); }
- }
- static bool evalInt1(ConsoleService c, string str, object param)
- {
- string p = (param == null) ? Resources.CMD_EVAL_INT : (string)param;
-
- if (Str.StrToInt(str) == 0)
- {
- c.write(p);
-
- return false;
- }
-
- return true;
- }
-
- public static ConsoleEvalProcDelegate EvalNotEmpty
- {
- get { return new ConsoleEvalProcDelegate(evalNotEmpty); }
- }
- static bool evalNotEmpty(ConsoleService c, string str, object param)
- {
- string p = (param == null) ? Resources.CMD_EVAL_NOT_EMPTY : (string)param;
-
- if (Str.IsEmptyStr(str) == false)
- {
- return true;
- }
-
- c.write(p);
-
- return false;
- }
-
- public static ConsoleEvalProcDelegate EvalMinMax
- {
- get { return new ConsoleEvalProcDelegate(evalMinMax); }
- }
- static bool evalMinMax(ConsoleService c, string str, object param)
- {
- string tag;
- int v;
- if (param == null)
- {
- return false;
- }
-
- ConsoleEvalMinMaxParam e = (ConsoleEvalMinMaxParam)param;
-
- if (Str.IsEmptyStr(e.ErrorMessageString))
- {
- tag = Resources.CMD_EVAL_MIN_MAX;
- }
- else
- {
- tag = e.ErrorMessageString;
- }
-
- v = Str.StrToInt(str);
-
- if (v >= e.MinValue && v <= e.MaxValue)
- {
- return true;
- }
- else
- {
- c.write(Str.FormatC(tag, e.MinValue, e.MaxValue));
-
- return false;
- }
- }
-
- public void PrintCmdHelp(string cmdName, List paramList)
- {
- string tmp;
- string buf;
- string description, args, help;
- List t;
- int width;
- int i;
- string space;
- if (cmdName == null || paramList == null)
- {
- return;
- }
-
- width = GetConsoleWidth() - 2;
-
- description = this.currentCmdList[cmdName].Description;
- args = this.currentCmdList[cmdName].ArgsHelp;
- help = this.currentCmdList[cmdName].BodyHelp;
-
- space = Str.MakeCharArray(' ', 2);
-
- tmp = Str.FormatC(Resources.CMD_HELP_TITLE, cmdName);
- this.write(tmp);
- this.write("");
-
- this.write(Resources.CMD_HELP_DESCRIPTION);
- t = Str.StrArrayToList(SeparateStringByWidth(description, width - 2));
- for (i = 0; i < t.Count; i++)
- {
- buf = Str.FormatC("%S%s", space, t[i]);
- this.write(buf);
- }
- this.write("");
-
- this.write(Resources.CMD_HELP_HELP);
- t = Str.StrArrayToList(SeparateStringByWidth(help, width - 2));
- for (i = 0; i < t.Count; i++)
- {
- buf = Str.FormatC("%S%s", space, t[i]);
- this.write(buf);
- }
- this.write("");
-
- this.write(Resources.CMD_HELP_USAGE);
- t = Str.StrArrayToList(SeparateStringByWidth(args, width - 2));
- for (i = 0; i < t.Count; i++)
- {
- buf = Str.FormatC("%S%s", space, t[i]);
- this.write(buf);
- }
-
- if (paramList.Count >= 1)
- {
- this.write("");
- this.write(Resources.CMD_HELP_ARGS);
- PrintCandidateHelp(cmdName, paramList.ToArray(), 2, this.currentCmdList);
- }
- }
-
- public void PrintCandidateHelp(string cmdName, string[] candidateList, int leftSpace, SortedList ccList)
- {
- int console_width;
- int max_keyword_width;
- List o;
- int i;
- string tmpbuf;
- string left_space_array;
- string max_space_array;
- if (candidateList == null)
- {
- return;
- }
-
- console_width = GetConsoleWidth() - 1;
-
- left_space_array = Str.MakeCharArray(' ', leftSpace);
-
- o = new List();
-
- max_keyword_width = 0;
-
- for (i = 0; i < candidateList.Length; i++)
- {
- int keyword_width;
-
- o.Add(candidateList[i]);
-
- keyword_width = Str.GetStrWidth(candidateList[i]);
- if (cmdName != null)
- {
- if (candidateList[i].StartsWith("[", StringComparison.InvariantCultureIgnoreCase) == false)
- {
- keyword_width += 1;
- }
- else
- {
- keyword_width -= 2;
- }
- }
-
- max_keyword_width = Math.Max(max_keyword_width, keyword_width);
- }
-
- max_space_array = Str.MakeCharArray(' ', max_keyword_width);
-
- for (i = 0; i < o.Count; i++)
- {
- string tmp;
- string name = o[i];
- List t;
- string help;
- int j;
- int keyword_start_width = leftSpace;
- int descript_start_width = leftSpace + max_keyword_width + 1;
- int descript_width;
- string space;
-
- if (console_width >= (descript_start_width + 5))
- {
- descript_width = console_width - descript_start_width - 3;
- }
- else
- {
- descript_width = 2;
- }
-
- if (cmdName != null && name.StartsWith("[", StringComparison.InvariantCultureIgnoreCase) == false)
- {
- tmp = Str.FormatC("/%s", name);
- }
- else
- {
- if (cmdName == null)
- {
- tmp = name;
- }
- else
- {
- if (name.Length >= 1)
- {
- tmp = name.Substring(1);
- }
- else
- {
- tmp = "";
- }
-
- if (tmp.Length >= 1)
- {
- tmp = tmp.Substring(0, tmp.Length - 1);
- }
- }
- }
-
- if (cmdName == null)
- {
- help = ccList[name].Description;
- }
- else
- {
- if (ccList[cmdName].ParamHelp.ContainsKey(name))
- {
- help = ccList[cmdName].ParamHelp[name];
- }
- else
- {
- help = Resources.CMD_UNKNOWN_PARAM;
- }
- }
-
- space = Str.MakeCharArray(' ', max_keyword_width - Str.GetStrWidth(name) -
- (cmdName == null ? 0 : (name.StartsWith("[", StringComparison.InvariantCultureIgnoreCase) == false ? 1 : -2)));
-
- t = Str.StrArrayToList(SeparateStringByWidth(help, descript_width));
-
- for (j = 0; j < t.Count; j++)
- {
- if (j == 0)
- {
- tmpbuf = Str.FormatC("%S%S%S - %s",
- left_space_array, tmp, space, t[j]);
- }
- else
- {
- tmpbuf = Str.FormatC("%S%S %s",
- left_space_array, max_space_array, t[j]);
- }
-
- this.write(tmpbuf);
- }
- }
- }
-
- public static string[] SeparateStringByWidth(string str, int width)
- {
- if (str == null)
- {
- return new string[0];
- }
- if (width <= 0)
- {
- width = 1;
- }
-
- StringBuilder tmp = new StringBuilder();
- int len, i;
- List o = new List();
-
- str += (char)0;
- len = str.Length;
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
-
- switch (c)
- {
- case (char)0:
- case '\r':
- case '\n':
- if (c == '\r')
- {
- if (str[i + 1] == '\n')
- {
- i++;
- }
- }
-
- o.Add(tmp.ToString());
- tmp = new StringBuilder();
- break;
-
- default:
- tmp.Append(c);
- if (Str.GetStrWidth(tmp.ToString()) >= width)
- {
- o.Add(tmp.ToString());
- tmp = new StringBuilder();
- }
- break;
- }
- }
-
- if (o.Count == 0)
- {
- o.Add("");
- }
-
- return o.ToArray();
- }
-
- public static bool IsHelpStr(string str)
- {
- if (str == null)
- {
- return false;
- }
-
- if (Str.IsStrInList(str, true,
- "help", "?", "man", "/man", "-man", "--man",
- "/help", "/?", "-help", "-?",
- "/h", "--help", "--?"))
- {
- return true;
- }
-
- return false;
- }
-
- public bool DispatchCommand(string execCommandOrNull, string prompt, Type commandClass)
- {
- return DispatchCommand(execCommandOrNull, prompt, commandClass, null);
- }
- public bool DispatchCommand(string execCommandOrNull, string prompt, Type commandClass, object invokerInstance)
- {
- SortedList cmdList = GetCommandList(commandClass);
-
- currentCmdList = cmdList;
- try
- {
- string str, tmp, cmd_name;
- bool b_exit = false;
- string cmd_param;
- int ret = 0;
- List t, candidate;
- int i;
-
- if (Str.IsEmptyStr(execCommandOrNull))
- {
- RETRY:
- tmp = prompt;
- str = this.readLine(tmp, false);
-
- if (str != null && Str.IsEmptyStr(str))
- {
- goto RETRY;
- }
- }
- else
- {
- if (prompt != null)
- {
- if (this.consoleType != ConsoleType.Csv)
- {
- }
- }
- str = execCommandOrNull;
- }
-
- if (str == null)
- {
- return false;
- }
-
- str = Str.TrimCrlf(str).Trim();
-
- if (Str.IsEmptyStr(str))
- {
- return true;
- }
-
- if (SeparateCommandAndParam(str, out cmd_name, out cmd_param) == false)
- {
- return true;
- }
-
- if (cmd_name.Length >= 2 && cmd_name[0] == '?' && cmd_name[1] != '?')
- {
- cmd_name = cmd_name.Substring(1);
- cmd_param = "/?";
- }
-
- if (cmd_name.Length >= 2 && cmd_name.EndsWith("?") && cmd_name[cmd_name.Length - 2] != '?')
- {
- cmd_name = cmd_name.Substring(0, cmd_name.Length - 1);
- cmd_param = "/?";
- }
-
- t = new List();
- for (i = 0; i < cmdList.Count; i++)
- {
- t.Add(cmdList.Keys[i]);
- }
-
- if (IsHelpStr(cmd_name))
- {
- if (Str.IsEmptyStr(cmd_param))
- {
- this.write(Str.FormatC(Resources.CMD_HELP_1, t.Count));
-
- string[] candidateList = t.ToArray();
-
- PrintCandidateHelp(null, candidateList, 1, cmdList);
-
- this.write("");
- this.write(Resources.CMD_HELP_2);
- }
- else
- {
- string tmp2, tmp3;
- if (SeparateCommandAndParam(cmd_param, out tmp2, out tmp3))
- {
- bool b = true;
-
- if (IsHelpStr(tmp2))
- {
- b = false;
- }
-
- if (b)
- {
- DispatchCommand(Str.FormatC("%S /help", tmp2), null, commandClass, invokerInstance);
- }
- }
- }
- }
- else if (Str.StrCmpi(cmd_name, "exit") ||
- Str.StrCmpi(cmd_name, "quit"))
- {
- b_exit = true;
- }
- else
- {
- candidate = Str.StrArrayToList(GetRealnameCandidate(cmd_name, t.ToArray()));
-
- if (candidate == null || candidate.Count == 0)
- {
- this.write(Str.FormatC(Resources.CON_UNKNOWN_CMD, cmd_name));
-
- this.retCode = ConsoleErrorCode.ERR_BAD_COMMAND_OR_PARAM;
- }
- else if (candidate.Count >= 2)
- {
- this.write(Str.FormatC(Resources.CON_AMBIGUOUS_CMD, cmd_name));
- this.write(Resources.CON_AMBIGUOUS_CMD_1);
- string[] candidateArray = candidate.ToArray();
-
- PrintCandidateHelp(null, candidateArray, 1, cmdList);
- this.write(Resources.CON_AMBIGUOUS_CMD_2);
-
- this.retCode = ConsoleErrorCode.ERR_BAD_COMMAND_OR_PARAM;
- }
- else
- {
- string real_cmd_name;
- int j;
-
- real_cmd_name = candidate[0];
-
- for (j = 0; j < cmdList.Count; j++)
- {
- if (Str.Equals(cmdList.Values[j].name, real_cmd_name))
- {
- if (this.consoleType != ConsoleType.Csv)
- {
- this.write(Str.FormatC(Resources.CMD_EXEC_MSG_NAME,
- cmdList.Values[j].name,
- cmdList.Values[j].Description));
- }
-
- object srcObject = null;
- if (cmdList.Values[j].methodInfo.IsStatic == false)
- {
- srcObject = invokerInstance;
- }
- object[] paramList =
- {
- this,
- real_cmd_name,
- cmd_param,
- };
-
- try
- {
- ret = (int)cmdList.Values[j].methodInfo.Invoke(srcObject, paramList);
- }
- catch (TargetInvocationException ex)
- {
- Exception ex2 = ex.GetBaseException();
-
- if (ex2 is ConsoleUserCancelException)
- {
- this.write(Resources.CON_USER_CANCELED);
- this.write("");
- this.retCode = ConsoleErrorCode.ERR_USER_CANCELED;
- }
- else
- {
- this.write(ex2.ToString());
- this.write("");
-
- this.retCode = ConsoleErrorCode.ERR_INNER_EXCEPTION;
- this.retErrorMessage = ex2.Message;
- }
-
- return true;
- }
-
- if (ret == -1)
- {
- b_exit = true;
- }
- else
- {
- this.retCode = ret;
- }
- }
- }
- }
- }
-
- if (b_exit)
- {
- return false;
- }
-
- return true;
- }
- finally
- {
- currentCmdList = null;
- }
- }
-
- public static SortedList GetCommandList(Type commandClass)
- {
- SortedList cmdList = new SortedList(new StrComparer(false));
-
- BindingFlags[] searchFlags =
- {
- BindingFlags.Static | BindingFlags.NonPublic,
- BindingFlags.Static | BindingFlags.Public,
- BindingFlags.Instance | BindingFlags.NonPublic,
- BindingFlags.Instance | BindingFlags.Public,
- };
-
- foreach (BindingFlags bFlag in searchFlags)
- {
- MemberInfo[] members = commandClass.GetMembers(bFlag);
-
- foreach (MemberInfo info in members)
- {
- if ((info.MemberType & MemberTypes.Method) != 0)
- {
- MethodInfo mInfo = commandClass.GetMethod(info.Name, bFlag);
-
- object[] customAtts = mInfo.GetCustomAttributes(true);
-
- foreach (object att in customAtts)
- {
- if (att is ConsoleCommandMethod)
- {
- ConsoleCommandMethod cc = (ConsoleCommandMethod)att;
- cc.bindingFlag = bFlag;
- cc.memberInfo = info;
- cc.methodInfo = mInfo;
- cc.name = info.Name;
-
- cmdList.Add(info.Name, cc);
-
- break;
- }
- }
- }
- }
- }
-
- return cmdList;
- }
-
- public int GetConsoleWidth()
- {
- int size = this.getWidth();
-
- if (size == 0)
- {
- size = 80;
- }
-
- if (size < 32)
- {
- size = 32;
- }
-
- if (size > 65535)
- {
- size = 65535;
- }
-
- return size;
- }
-
- public static bool SeparateCommandAndParam(string src, out string cmd, out string param)
- {
- int i, len;
- StringBuilder tmp;
- string src_tmp;
- cmd = param = null;
- if (src == null)
- {
- return false;
- }
-
- src_tmp = Str.TrimCrlf(src).Trim();
-
- len = src_tmp.Length;
- tmp = new StringBuilder();
-
- for (i = 0; i < (len + 1); i++)
- {
- char c;
-
- if (i != len)
- {
- c = src_tmp[i];
- }
- else
- {
- c = (char)0;
- }
-
- switch (c)
- {
- case (char)0:
- case ' ':
- case '\t':
- if (Str.IsEmptyStr(tmp.ToString()))
- {
- return false;
- }
- cmd = tmp.ToString().Trim();
- goto ESCAPE;
-
- default:
- tmp.Append(c);
- break;
- }
- }
-
- ESCAPE:
- param = src_tmp.Substring(tmp.Length).Trim();
-
- return true;
- }
-
- public static string[] GetRealnameCandidate(string inputName, string[] realNameList)
- {
- List o = new List();
- if (inputName == null || realNameList == null)
- {
- return new string[0];
- }
-
- int i;
- bool ok = false;
- for (i = 0; i < realNameList.Length; i++)
- {
- string name = realNameList[i];
-
- if (Str.StrCmpi(name, inputName))
- {
- o.Add(name);
- ok = true;
- break;
- }
- }
-
- if (ok == false)
- {
- for (i = 0; i < realNameList.Length; i++)
- {
- string name = realNameList[i];
-
- if (IsOmissionName(inputName, name) ||
- IsNameInRealName(inputName, name))
- {
- o.Add(name);
- ok = true;
- }
- }
- }
-
- if (ok)
- {
- return o.ToArray();
- }
- else
- {
- return new string[0];
- }
- }
-
- public static bool IsOmissionName(string inputName, string realName)
- {
- string oname;
- if (inputName == null || realName == null)
- {
- return false;
- }
-
- if (Str.IsAllUpperStr(realName))
- {
- return false;
- }
-
- oname = GetOmissionName(realName);
-
- if (Str.IsEmptyStr(oname))
- {
- return false;
- }
-
- if (oname.StartsWith(inputName, StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
-
- if (inputName.StartsWith(oname, StringComparison.InvariantCultureIgnoreCase))
- {
- if (realName.EndsWith(inputName.Substring(oname.Length), StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static string GetOmissionName(string src)
- {
- int i, len;
- if (src == null)
- {
- return null;
- }
-
- string dst = "";
- len = src.Length;
-
- for (i = 0; i < len; i++)
- {
- char c = src[i];
-
- if ((c >= '0' && c <= '9') ||
- (c >= 'A' && c <= 'Z'))
- {
- dst += c;
- }
- }
-
- return dst;
- }
-
- public static bool IsNameInRealName(string inputName, string realName)
- {
- if (inputName == null || realName == null)
- {
- return false;
- }
-
- if (realName.StartsWith(inputName, StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
-
- return false;
- }
-
- public ConsoleParamValueList ParseCommandList(string cmdName, string command, ConsoleParam[] param)
- {
- ConsoleParamValueList ret = parseCommandLineMain(cmdName, command, param);
-
- if (ret == null)
- {
- throw new ConsoleUserCancelException("");
- }
-
- return ret;
- }
- private ConsoleParamValueList parseCommandLineMain(string cmdName, string command, ConsoleParam[] param)
- {
- int i;
- ConsoleParamValueList o;
- List param_list;
- List real_name_list;
- bool help_mode = false;
- string tmp;
- bool ok = true;
- if (command == null || cmdName == null)
- {
- return null;
- }
-
- for (i = 0; i < param.Length; i++)
- {
- if (Str.IsEmptyStr(param[i].Name) == false)
- {
- if (param[i].Name.StartsWith("["))
- {
- param[i].Tmp = "";
- }
- else
- {
- param[i].Tmp = null;
- }
- }
- else
- {
- param[i].Tmp = "";
- }
- }
-
- param_list = Str.StrArrayToList(GetCommandNameList(command));
-
- real_name_list = new List();
-
- for (i = 0; i < param.Length; i++)
- {
- real_name_list.Add(param[i].Name);
- }
-
- for (i = 0; i < param_list.Count; i++)
- {
- string s = param_list[i];
-
- if (Str.StrCmpi(s, "help") ||
- Str.StrCmpi(s, "?"))
- {
- help_mode = true;
- break;
- }
- }
-
- tmp = ParseCommand(command, "");
- if (tmp != null)
- {
- if (Str.StrCmpi(tmp, "?"))
- {
- help_mode = true;
- }
- }
-
- if (help_mode)
- {
- PrintCmdHelp(cmdName, real_name_list);
- return null;
- }
-
- for (i = 0; i < param_list.Count; i++)
- {
- string[] candidate = GetRealnameCandidate(param_list[i], real_name_list.ToArray());
-
- if (candidate != null && candidate.Length >= 1)
- {
- if (candidate.Length >= 2)
- {
- this.write(Str.FormatC(Resources.CON_AMBIGUOUS_PARAM,
- param_list[i]));
-
- this.write(Str.FormatC(Resources.CON_AMBIGUOUS_PARAM_1,
- cmdName));
-
- PrintCandidateHelp(cmdName, candidate, 1, this.currentCmdList);
- this.write(Resources.CON_AMBIGUOUS_PARAM_2);
-
- ok = false;
- }
- else
- {
- int j;
- string real_name = candidate[0];
-
- for (j = 0; j < param.Length; j++)
- {
- if (Str.StrCmpi(param[j].Name, real_name))
- {
- param[j].Tmp = param_list[i];
- }
- }
- }
- }
- else
- {
- this.write(Str.FormatC(Resources.CON_INVALID_PARAM,
- param_list[i],
- cmdName,
- cmdName));
-
- ok = false;
- }
- }
-
- if (ok == false)
- {
- return null;
- }
-
- o = new ConsoleParamValueList();
-
- for (i = 0; i < param.Length; i++)
- {
- ConsoleParam p = param[i];
- bool is_default_value = false;
-
- if (p.Tmp == "")
- {
- is_default_value = true;
- }
-
- if (p.Tmp != null || p.PromptProc != null)
- {
- string name = p.Name;
- string tmp2, str;
-
- if (p.Tmp != null)
- {
- tmp2 = p.Tmp;
- }
- else
- {
- tmp2 = p.Name;
- }
-
- str = ParseCommand(command, tmp2);
-
- if (str != null)
- {
- string unistr;
- bool ret;
- EVAL_VALUE:
- unistr = str;
-
- if (p.EvalProc != null)
- {
- ret = p.EvalProc(this, unistr, p.EvalProcParam);
- }
- else
- {
- ret = true;
- }
-
- if (ret == false)
- {
- string tmp3;
- if (p.PromptProc == null)
- {
- ok = false;
- break;
- }
- else
- {
- str = null;
- tmp3 = p.PromptProc(this, p.PromptProcParam);
- if (tmp3 == null)
- {
- ok = false;
- break;
- }
- else
- {
- this.write("");
- str = tmp3;
- goto EVAL_VALUE;
- }
- }
- }
- else
- {
- o.Add(new ConsoleParamValue(p.Name, str, Str.StrToInt(str), is_default_value));
- }
- }
- else
- {
- if (p.PromptProc != null)
- {
- string tmp4;
- tmp4 = p.PromptProc(this, p.PromptProcParam);
- if (tmp4 == null)
- {
- ok = false;
- break;
- }
- else
- {
- this.write("");
- str = tmp4;
- if (true)
- {
- string unistr;
- bool ret;
- EVAL_VALUE:
- unistr = str;
-
- if (p.EvalProc != null)
- {
- ret = p.EvalProc(this, unistr, p.EvalProcParam);
- }
- else
- {
- ret = true;
- }
-
- if (ret == false)
- {
- if (p.PromptProc == null)
- {
- ok = false;
- break;
- }
- else
- {
- str = null;
- tmp4 = p.PromptProc(this, p.PromptProcParam);
- if (tmp4 == null)
- {
- ok = false;
- break;
- }
- else
- {
- this.write("");
- str = tmp4;
- goto EVAL_VALUE;
- }
- }
- }
- else
- {
- o.Add(new ConsoleParamValue(p.Name, str, Str.StrToInt(str), is_default_value));
- }
- }
- }
- }
- }
- }
- }
-
- if (ok)
- {
- return o;
- }
- else
- {
- return null;
- }
- }
-
- public static string[] GetCommandNameList(string str)
- {
- if (str == null)
- {
- return new string[0];
- }
-
- string[] pl;
- ParseCommand(str, "dummy_str", out pl);
-
- return pl;
- }
-
- public static string ParseCommand(string str, string name)
- {
- string[] pl;
- return ParseCommand(str, name, out pl);
- }
- public static string ParseCommand(string str, string name, out string[] paramList)
- {
- int i;
- string tmp, ret = null;
- SortedList o;
- paramList = null;
- if (str == null)
- {
- return null;
- }
- if (Str.IsEmptyStr(name))
- {
- name = null;
- }
-
- o = new SortedList(new StrComparer(false));
-
- tmp = str.Trim();
-
- i = Str.SearchStr(tmp, "/CMD", 0, false);
-
- if (i >= 1 && tmp[i - 1] == '/')
- {
- i = -1;
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "/CMD\t", 0, false);
- if (i >= 1 && tmp[i - 1] == '/')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "/CMD:", 0, false);
- if (i >= 1 && tmp[i - 1] == '/')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "/CMD=", 0, false);
- if (i >= 1 && tmp[i - 1] == '/')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "-CMD ", 0, false);
- if (i >= 1 && tmp[i - 1] == '-')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "-CMD\t", 0, false);
- if (i >= 1 && tmp[i - 1] == '-')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "-CMD:", 0, false);
- if (i >= 1 && tmp[i - 1] == '-')
- {
- i = -1;
- }
- }
- if (i == -1)
- {
- i = Str.SearchStr(tmp, "-CMD=", 0, false);
- if (i >= 1 && tmp[i - 1] == '-')
- {
- i = -1;
- }
- }
-
- if (i != -1)
- {
- string s = "CMD";
- if (o != null)
- {
- if (o.ContainsKey(s) == false)
- {
- o.Add(s, 0);
- }
- }
- if (Str.StrCmpi(name, "CMD"))
- {
- ret = str.Substring(i + 5).Trim();
- }
- else
- {
- tmp = tmp.Substring(0, i);
- }
- }
-
- if (ret == null)
- {
- string[] t = Str.ParseCmdLine(tmp);
-
- if (t != null)
- {
- for (i = 0; i < t.Length; i++)
- {
- string token = t[i];
-
- if ((token[0] == '-' && token[1] != '-') ||
- (Str.StrCmpi(token, "--help")) ||
- (token[0] == '/' && token[1] != '/'))
- {
- int j;
- if (Str.StrCmpi(token, "--help"))
- {
- token = token.Substring(1);
- }
-
- j = Str.SearchStr(token, ":", 0, false);
- if (j == -1)
- {
- j = Str.SearchStr(token, "=", 0, false);
- }
- if (j != -1)
- {
- string tmp2;
- string a;
-
- tmp2 = token;
- if (tmp2.Length >= j)
- {
- tmp2 = tmp2.Substring(0, j);
- }
-
- a = tmp2.Substring(1);
- if (o != null)
- {
- if (o.ContainsKey(a) == false)
- {
- o.Add(a, 0);
- }
- }
-
- if (tmp2.Length >= 1 && Str.StrCmpi(name, tmp2.Substring(1)))
- {
- if (ret == null)
- {
- ret = token.Substring(j + 1);
- }
- }
- }
- else
- {
- string a = token.Substring(1);
-
- if (o != null)
- {
- if (o.ContainsKey(a) == false)
- {
- o.Add(a, 0);
- }
-
- if (Str.StrCmpi(name, token.Substring(1)))
- {
- if (ret == null)
- {
- ret = "";
- }
- }
- }
- }
- }
- else
- {
- if (name == null)
- {
- if (ret == null)
- {
- if (token.StartsWith("--"))
- {
- ret = token.Substring(1);
- }
- else if (token.StartsWith("//"))
- {
- ret = token.Substring(1);
- }
- else
- {
- ret = token;
- }
- }
- }
- }
- }
- }
- }
-
- if (o != null)
- {
- List t = new List();
-
- int j;
- for (j = 0; j < o.Count; j++)
- {
- t.Add(o.Keys[j]);
- }
-
- paramList = t.ToArray();
- }
-
- if (ret != null)
- {
- if (Str.StrCmpi(ret, "none") || Str.StrCmpi(ret, "null"))
- {
- ret = "";
- }
- }
-
- return ret;
- }
-
- public static ConsoleService NewLocalConsoleService()
- {
- return NewLocalConsoleService(null, null);
- }
- public static ConsoleService NewLocalConsoleService(string outFileName)
- {
- return NewLocalConsoleService(null, outFileName);
- }
- public static ConsoleService NewLocalConsoleService(string inFileName, string outFileName)
- {
- IO in_io = null, out_io = null;
-
- ConsoleService c = new ConsoleService();
- int old_size = 0;
-
- c.consoleType = ConsoleType.Local;
- c.free = new ConsoleFreeDelegate(c.localFree);
- c.readLine = new ConsoleReadLineDelegate(c.localReadLine);
- c.readPassword = new ConsoleReadPasswordDelegate(c.localReadPassword);
- c.write = new ConsoleWriteDelegate(c.localWrite);
- c.getWidth = new ConsoleGetWidthDelegate(c.localGetWidth);
-
- if (Str.IsEmptyStr(inFileName) == false)
- {
- try
- {
- in_io = IO.FileOpen(inFileName, false);
- }
- catch
- {
- c.write(Str.FormatC(Resources.CON_INFILE_ERROR, inFileName));
- return null;
- }
- c.write(Str.FormatC(Resources.CON_INFILE_START, inFileName));
- }
-
- if (Str.IsEmptyStr(outFileName) == false)
- {
- try
- {
- out_io = IO.FileCreate(outFileName);
- }
- catch
- {
- c.write(Str.FormatC(Resources.CON_OUTFILE_ERROR, outFileName));
- if (in_io != null)
- {
- in_io.Close();
- }
-
- return null;
- }
- c.write(Str.FormatC(Resources.CON_OUTFILE_START, outFileName));
- }
-
- c.inFile = in_io;
- c.outFile = out_io;
- c.win32_OldConsoleWidth = old_size;
-
- if (in_io != null)
- {
- byte[] data = in_io.ReadAll();
-
- c.inBuf = new Buf(data);
- }
-
- Con.SetConsoleService(c);
-
- return c;
- }
-
- void localFree()
- {
- if (inFile != null)
- {
- inFile.Close();
- inFile = null;
- }
-
- if (outFile != null)
- {
- outFile.Close();
- outFile = null;
- }
- }
-
- int localGetWidth()
- {
- int ret = Console.WindowWidth;
-
- if (ret <= 0)
- {
- ret = 1;
- }
-
- return ret;
- }
-
- string localReadLine(string prompt, bool noFile)
- {
- string ret;
- if (prompt == null)
- {
- prompt = ">";
- }
-
- writeOutFile(prompt, false);
-
- if (noFile == false && inBuf != null)
- {
- ret = readNextFromInFile();
-
- if (ret != null)
- {
- Console.Write(prompt);
-
- Console.WriteLine(ret);
- }
- }
- else
- {
- Console.Write(prompt);
- ret = Console.ReadLine();
-
- if (ret != null)
- {
- if (ret.IndexOf((char)0x04) != -1 || ret.IndexOf((char)0x1a) != -1)
- {
- ret = null;
- }
- }
- }
-
- if (ret != null)
- {
- writeOutFile(ret, true);
- }
- else
- {
- writeOutFile("[EOF]", true);
- }
-
- return ret;
- }
-
- string localReadPassword(string prompt)
- {
- if (prompt == null)
- {
- prompt = "Password>";
- }
-
- Console.Write(prompt);
- writeOutFile(prompt, false);
-
- string tmp = Str.PasswordPrompt();
- if (tmp != null)
- {
- writeOutFile("********", true);
- return tmp;
- }
-
- return null;
- }
-
- bool localWrite(string str)
- {
- Console.Write("{0}{1}",
- str,
- (str.EndsWith("\n") ? "" : "\n"));
-
- writeOutFile(str, true);
-
- return true;
- }
-
- string readNextFromInFile()
- {
- if (inBuf == null)
- {
- return null;
- }
-
- while (true)
- {
- string str = inBuf.ReadNextLineAsString();
- if (str == null)
- {
- return null;
- }
-
- str = str.Trim();
-
- if (Str.IsEmptyStr(str) == false)
- {
- return str;
- }
- }
- }
-
- void writeOutFile(string str, bool addLastCrlf)
- {
- if (outFile != null)
- {
- string tmp = Str.NormalizeCrlf(str);
-
- outFile.Write(Str.Utf8Encoding.GetBytes(str));
-
- if (str.EndsWith("\n") == false && addLastCrlf)
- {
- outFile.Write(Str.Utf8Encoding.GetBytes(Env.NewLine));
- }
-
- outFile.Flush();
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Csv.cs b/src/BuildUtil/CoreUtil/Csv.cs
deleted file mode 100644
index bbc65f42..00000000
--- a/src/BuildUtil/CoreUtil/Csv.cs
+++ /dev/null
@@ -1,426 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-
-
-namespace CoreUtil
-{
- class CsvTimeSpan
- {
- public DateTime StartDateTime;
- public DateTime EndDateTime;
- public int StartIndex;
- public int NumIndex;
-
- public CsvTimeSpan(DateTime startDateTime, DateTime endDateTime, int startIndex, int numIndex)
- {
- StartDateTime = startDateTime;
- EndDateTime = endDateTime;
- StartIndex = startIndex;
- NumIndex = numIndex;
- }
- }
-
- public class Csv
- {
- List entryList;
- Encoding encoding;
- static Encoding defaultEncoding = Str.ShiftJisEncoding;
-
- public Encoding Encoding
- {
- get
- {
- return encoding;
- }
- set
- {
- this.encoding = value;
- }
- }
-
- public CsvEntry First
- {
- get
- {
- return entryList[0];
- }
- }
-
- public CsvEntry Last
- {
- get
- {
- return entryList[entryList.Count - 1];
- }
- }
-
- public Csv()
- : this(defaultEncoding)
- {
- }
- public Csv(Encoding encoding)
- {
- init(null, encoding);
- }
-
- public Csv(string filename)
- : this(filename, defaultEncoding)
- {
- }
- public Csv(string filename, Encoding encoding)
- {
- init(Buf.ReadFromFile(filename), encoding);
- }
-
- public Csv(Buf data)
- {
- byte[] src = data.ByteData;
- int bomSize;
-
- Encoding enc = Str.CheckBOM(src, out bomSize);
-
- if (bomSize >= 1)
- {
- src = Util.RemoveStartByteArray(src, bomSize);
- }
-
- init(new Buf(src), enc);
- }
- public Csv(Buf data, Encoding encoding)
- {
- init(data, encoding);
- }
-
- void init(Buf data, Encoding encoding)
- {
- if (encoding == null)
- {
- encoding = defaultEncoding;
- }
-
- int bomSize = 0;
- Encoding enc2 = null;
- if (data != null)
- {
- enc2 = Str.CheckBOM(data.ByteData, out bomSize);
- }
- if (bomSize >= 1)
- {
- data = new Buf(Util.RemoveStartByteArray(data.ByteData, bomSize));
- }
- if (enc2 != null)
- {
- encoding = enc2;
- }
- this.encoding = encoding;
-
- entryList = new List();
-
- if (data != null)
- {
- MemoryStream ms = new MemoryStream(data.ByteData);
- StreamReader sr = new StreamReader(ms, this.encoding);
-
- while (true)
- {
- string s = sr.ReadLine();
-
- if (s == null)
- {
- break;
- }
-
- char[] sep = { ',' };
- string[] strings = s.Trim().Split(sep, StringSplitOptions.None);
-
- CsvEntry e = new CsvEntry(strings);
- Add(e);
- }
- }
- }
-
- public override string ToString()
- {
- StringBuilder b = new StringBuilder();
-
- foreach (CsvEntry e in entryList)
- {
- b.AppendLine(e.ToString());
- }
-
- return b.ToString();
- }
-
- public Buf ToBuf()
- {
- string s = ToString();
-
- Buf b = new Buf();
-
- byte[] bom = Str.GetBOM(this.Encoding);
-
- if (bom != null)
- {
- b.Write(bom);
- }
-
- b.Write(encoding.GetBytes(s));
-
- b.SeekToBegin();
-
- return b;
- }
-
- public void SaveToFile(string filename)
- {
- File.WriteAllBytes(filename, ToBuf().ByteData);
- }
-
- public void Add(CsvEntry e)
- {
- entryList.Add(e);
- }
-
- public int Count
- {
- get
- {
- return entryList.Count;
- }
- }
-
- public CsvEntry this[int index]
- {
- get
- {
- return entryList[index];
- }
- }
-
- public IEnumerable Items
- {
- get
- {
- int i;
- for (i = 0; i < entryList.Count; i++)
- {
- yield return entryList[i];
- }
- }
- }
-
- CsvCompare csvCompareMethod;
- int csvCompareIndex;
- Type csvCompareType;
- bool csvCompareReverse;
-
- int sortInternal(CsvEntry e1, CsvEntry e2)
- {
- if (csvCompareMethod != null)
- {
- object o1 = e1.Convert(csvCompareType, csvCompareIndex);
- object o2 = e2.Convert(csvCompareType, csvCompareIndex);
-
- return csvCompareMethod(o1, o2) * (csvCompareReverse ? -1 : 1);
- }
- else
- {
- IComparable o1 = (IComparable)e1.Convert(csvCompareType, csvCompareIndex);
- IComparable o2 = (IComparable)e2.Convert(csvCompareType, csvCompareIndex);
-
- return o1.CompareTo(o2) * (csvCompareReverse ? -1 : 1);
- }
- }
-
- public void Sort(Type type)
- {
- Sort(null, type);
- }
- public void Sort(CsvCompare cmp, Type type)
- {
- Sort(cmp, type, false);
- }
- public void Sort(Type type, bool reverse)
- {
- Sort(null, type, reverse);
- }
- public void Sort(CsvCompare cmp, Type type, bool reverse)
- {
- Sort(cmp, 0, type, reverse);
- }
- public void Sort(int index, Type type)
- {
- Sort(null, index, type);
- }
- public void Sort(CsvCompare cmp, int index, Type type)
- {
- Sort(cmp, 0, type, false);
- }
- public void Sort(int index, Type type, bool reverse)
- {
- Sort(null, index, type, reverse);
- }
- public void Sort(CsvCompare cmp, int index, Type type, bool reverse)
- {
- csvCompareMethod = cmp;
- csvCompareIndex = index;
- csvCompareType = type;
- csvCompareReverse = reverse;
-
- entryList.Sort(new Comparison(sortInternal));
- }
-
- public static int CompareString(object o1, object o2)
- {
- string s1 = (string)o1;
- string s2 = (string)o2;
- return s1.CompareTo(s2);
- }
-
- public static int CompareDatetime(object o1, object o2)
- {
- DateTime d1 = (DateTime)o1;
- DateTime d2 = (DateTime)o2;
-
- return d1.CompareTo(d2);
- }
-
- public void SetEncoding(Encoding e)
- {
- this.encoding = e;
- }
-
- public Csv Clone()
- {
- Csv csv = new Csv(this.encoding);
-
- foreach (CsvEntry e in entryList)
- {
- csv.Add(e.Clone());
- }
-
- return csv;
- }
- }
-
- public delegate int CsvCompare(object o1, object o2);
-
- public class CsvEntry
- {
- List strings;
-
- public CsvEntry Clone()
- {
- string[] array = (string[])strings.ToArray().Clone();
-
- CsvEntry e = new CsvEntry(array);
-
- return e;
- }
-
- public CsvEntry(params string[] elements)
- {
- strings = new List();
- foreach (string s in elements)
- {
- string str = s;
-
- if (str.StartsWith("\"") && str.EndsWith("\"") && str.Length >= 2)
- {
- str = str.Substring(1, str.Length - 2);
- }
-
- strings.Add(str);
- }
- }
-
- public string this[int index]
- {
- get
- {
- return strings[index];
- }
- }
-
- public int Count
- {
- get
- {
- return strings.Count;
- }
- }
-
- public override string ToString()
- {
- int i, num;
- string ret = "";
-
- num = strings.Count;
- for (i = 0; i < num; i++)
- {
- string s = strings[i];
-
- s = Str.ReplaceStr(s, ",", ".", false);
- s = Str.ReplaceStr(s, "\r\n", " ", false);
- s = Str.ReplaceStr(s, "\r", " ", false);
- s = Str.ReplaceStr(s, "\n", " ", false);
-
- ret += s;
-
- if ((i + 1) < num)
- {
- ret += ",";
- }
- }
-
- return ret;
- }
-
- Type lastType = null;
- object lastObject = null;
- int lastIndex = -1;
-
- public object Convert(Type type, int index)
- {
- if (lastType == type && lastIndex == index)
- {
- return lastObject;
- }
-
- lastType = type;
- lastIndex = index;
- lastObject = System.Convert.ChangeType(strings[index], type);
-
- return lastObject;
- }
-
- public DateTime ToDateTime(int index)
- {
- return (DateTime)Convert(typeof(DateTime), index);
- }
- }
-}
-
diff --git a/src/BuildUtil/CoreUtil/Env.cs b/src/BuildUtil/CoreUtil/Env.cs
deleted file mode 100644
index be10c79e..00000000
--- a/src/BuildUtil/CoreUtil/Env.cs
+++ /dev/null
@@ -1,501 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using System.Net.Mail;
-using System.Net.Mime;
-using System.Reflection;
-using CoreUtil;
-
-namespace CoreUtil
-{
- public static class Env
- {
- static object lockObj = new object();
- static bool inited = false;
-
- static Env()
- {
- initCache();
- }
-
- static void initCache()
- {
- lock (lockObj)
- {
- if (inited == false)
- {
- initValues();
- inited = true;
- }
- }
- }
-
- static string homeDir;
- static public string HomeDir
- {
- get { return homeDir; }
- }
- static string exeFileName;
- static public string ExeFileName
- {
- get { return exeFileName; }
- }
- static string exeFileDir;
- static public string ExeFileDir
- {
- get { return exeFileDir; }
- }
- static string windowsDir;
- static public string WindowsDir
- {
- get { return windowsDir; }
- }
- static string systemDir;
- static public string SystemDir
- {
- get { return systemDir; }
- }
- static string tempDir;
- static public string TempDir
- {
- get { return tempDir; }
- }
- static string winTempDir;
- static public string WinTempDir
- {
- get { return winTempDir; }
- }
- static string windowsDrive;
- static public string WindowsDrive
- {
- get { return windowsDrive; }
- }
- static string programFilesDir;
- static public string ProgramFilesDir
- {
- get { return programFilesDir; }
- }
- static string personalStartMenuDir;
- static public string PersonalStartMenuDir
- {
- get { return personalStartMenuDir; }
- }
- static string personalProgramsDir;
- static public string PersonalProgramsDir
- {
- get { return personalProgramsDir; }
- }
- static string personalStartupDir;
- static public string PersonalStartupDir
- {
- get { return personalStartupDir; }
- }
- static string personalAppDataDir;
- static public string PersonalAppDataDir
- {
- get { return personalAppDataDir; }
- }
- static string personalDesktopDir;
- static public string PersonalDesktopDir
- {
- get { return personalDesktopDir; }
- }
- static string myDocumentsDir;
- static public string MyDocumentsDir
- {
- get { return myDocumentsDir; }
- }
- static string localAppDataDir;
- static public string LocalAppDataDir
- {
- get { return localAppDataDir; }
- }
- static string userName;
- static public string UserName
- {
- get { return userName; }
- }
- static string userNameEx;
- static public string UserNameEx
- {
- get { return userNameEx; }
- }
- static string machineName;
- static public string MachineName
- {
- get { return machineName; }
- }
- static string commandLine;
- public static string CommandLine
- {
- get { return commandLine; }
- }
- public static StrToken CommandLineList
- {
- get
- {
- return new StrToken(CommandLine);
- }
- }
- static OperatingSystem osInfo;
- public static OperatingSystem OsInfo
- {
- get { return osInfo; }
- }
- static bool isNt;
- public static bool IsNt
- {
- get { return isNt; }
- }
- static bool is9x;
- public static bool Is9x
- {
- get { return is9x; }
- }
- static bool isCe;
- public static bool IsCe
- {
- get { return isCe; }
- }
- static bool isLittleEndian;
- public static bool IsLittleEndian
- {
- get { return Env.isLittleEndian; }
- }
- public static bool IsBigEndian
- {
- get { return !IsLittleEndian; }
- }
- static bool isAdmin;
- public static bool IsAdmin
- {
- get { return Env.isAdmin; }
- }
- static int processId;
- public static int ProcessId
- {
- get { return Env.processId; }
- }
- static string myTempDir;
- public static string MyTempDir
- {
- get { return myTempDir; }
- }
- static IO lockFile;
-
- public static bool Is64BitProcess
- {
- get
- {
- return (IntPtr.Size == 8);
- }
- }
-
- public static bool Is64BitWindows
- {
- get
- {
- return Is64BitProcess || Kernel.InternalCheckIsWow64();
- }
- }
-
- public static bool IsWow64
- {
- get
- {
- return Kernel.InternalCheckIsWow64();
- }
- }
-
- static void initValues()
- {
- exeFileName = IO.RemoteLastEnMark(getMyExeFileName());
- if (Str.IsEmptyStr(exeFileName) == false)
- {
- exeFileDir = IO.RemoteLastEnMark(Path.GetDirectoryName(exeFileName));
- }
- else
- {
- exeFileDir = "";
- }
- homeDir = IO.RemoteLastEnMark(Kernel.GetEnvStr("HOME"));
- if (Str.IsEmptyStr(homeDir))
- {
- homeDir = IO.RemoteLastEnMark(Kernel.GetEnvStr("HOMEDRIVE") + Kernel.GetEnvStr("HOMEPATH"));
- }
- if (Str.IsEmptyStr(homeDir))
- {
- homeDir = CurrentDir;
- }
- systemDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.System));
- windowsDir = IO.RemoteLastEnMark(Path.GetDirectoryName(systemDir));
- tempDir = IO.RemoteLastEnMark(Path.GetTempPath());
- winTempDir = IO.RemoteLastEnMark(Path.Combine(windowsDir, "Temp"));
- IO.MakeDir(winTempDir);
- if (windowsDir.Length >= 2 && windowsDir[1] == ':')
- {
- windowsDrive = windowsDir.Substring(0, 2).ToUpper();
- }
- else
- {
- windowsDrive = "C:";
- }
- programFilesDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
- personalStartMenuDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu));
- personalProgramsDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Programs));
- personalStartupDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Startup));
- personalAppDataDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
- personalDesktopDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
- myDocumentsDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
- localAppDataDir = IO.RemoteLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
- userName = Environment.UserName;
- try
- {
- userNameEx = Environment.UserDomainName + "\\" + userName;
- }
- catch
- {
- userNameEx = userName;
- }
- machineName = Environment.MachineName;
- commandLine = initCommandLine(Environment.CommandLine);
- osInfo = Environment.OSVersion;
- isNt = (osInfo.Platform == PlatformID.Win32NT);
- isCe = (osInfo.Platform == PlatformID.WinCE);
- is9x = !(isNt || isCe);
- isLittleEndian = BitConverter.IsLittleEndian;
- processId = System.Diagnostics.Process.GetCurrentProcess().Id;
- isAdmin = checkIsAdmin();
- initMyTempDir();
- }
-
- static void deleteUnusedTempDir()
- {
- DirEntry[] files;
-
- files = IO.EnumDir(Env.tempDir);
-
- foreach (DirEntry e in files)
- {
- if (e.IsFolder)
- {
- if (e.FileName.StartsWith("NET_", StringComparison.CurrentCultureIgnoreCase) && e.FileName.Length == 8)
- {
- string dirFullName = Path.Combine(Env.tempDir, e.fileName);
- string lockFileName = Path.Combine(dirFullName, "LockFile.dat");
- bool deleteNow = false;
-
- try
- {
- IO io = IO.FileOpen(lockFileName);
- io.Close();
-
- try
- {
- io = IO.FileOpen(lockFileName, true);
- deleteNow = true;
- io.Close();
- }
- catch
- {
- }
- }
- catch
- {
- DirEntry[] files2;
-
- deleteNow = true;
-
- try
- {
- files2 = IO.EnumDir(dirFullName);
-
- foreach (DirEntry e2 in files2)
- {
- if (e2.IsFolder == false)
- {
- string fullPath = Path.Combine(dirFullName, e2.fileName);
-
- try
- {
- IO io2 = IO.FileOpen(fullPath, true);
- io2.Close();
- }
- catch
- {
- deleteNow = false;
- }
- }
- }
- }
- catch
- {
- deleteNow = false;
- }
- }
-
- if (deleteNow)
- {
- IO.DeleteDir(dirFullName, true);
- }
- }
- }
- }
- }
-
- static void initMyTempDir()
- {
- try
- {
- deleteUnusedTempDir();
- }
- catch
- {
- }
-
- int num = 0;
-
- while (true)
- {
- byte[] rand = Secure.Rand(2);
- string tmp2 = Str.ByteToStr(rand);
-
- string tmp = Path.Combine(Env.tempDir, "NET_" + tmp2);
-
- if (IO.IsDirExists(tmp) == false && IO.MakeDir(tmp))
- {
- Env.myTempDir = tmp;
-
- break;
- }
-
- if ((num++) >= 100)
- {
- throw new SystemException();
- }
- }
-
- string lockFileName = Path.Combine(Env.myTempDir, "LockFile.dat");
- lockFile = IO.FileCreate(lockFileName);
- }
-
- static bool checkIsAdmin()
- {
- try
- {
- string name = "Vpn_Check_Admin_Key_NET_" + processId.ToString();
- string teststr = Str.GenRandStr();
-
- if (Reg.WriteStr(RegRoot.LocalMachine, "", name, teststr) == false)
- {
- return false;
- }
-
- try
- {
-
- string ret = Reg.ReadStr(RegRoot.LocalMachine, "", name);
-
- if (ret == teststr)
- {
- return true;
- }
-
- return false;
- }
- finally
- {
- Reg.DeleteValue(RegRoot.LocalMachine, "", name);
- }
- }
- catch
- {
- return false;
- }
- }
-
- static string initCommandLine(string src)
- {
- try
- {
- int i;
- if (src.Length >= 1 && src[0] == '\"')
- {
- i = src.IndexOf('\"', 1);
- }
- else
- {
- i = src.IndexOf(' ');
- }
-
- if (i == -1)
- {
- return "";
- }
- else
- {
- return src.Substring(i + 1).TrimStart(' ');
- }
- }
- catch
- {
- return "";
- }
- }
-
- static string getMyExeFileName()
- {
- try
- {
- Assembly mainAssembly = Assembly.GetEntryAssembly();
- Module[] modules = mainAssembly.GetModules();
- return modules[0].FullyQualifiedName;
- }
- catch
- {
- return "";
- }
- }
-
- static public string CurrentDir
- {
- get
- {
- return IO.RemoteLastEnMark(Environment.CurrentDirectory);
- }
- }
- static public string NewLine
- {
- get
- {
- return Environment.NewLine;
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/FileIO.cs b/src/BuildUtil/CoreUtil/FileIO.cs
deleted file mode 100644
index 1417014a..00000000
--- a/src/BuildUtil/CoreUtil/FileIO.cs
+++ /dev/null
@@ -1,1631 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-
-namespace CoreUtil
-{
- internal class HamCoreEntry : IComparable
- {
- public string FileName = "";
- public uint Size = 0;
- public uint SizeCompressed = 0;
- public uint Offset = 0;
- public byte[] Buffer = null;
- public long LastAccess = 0;
-
- public int CompareTo(object obj)
- {
- HamCoreEntry hc1, hc2;
- hc1 = this;
- hc2 = (HamCoreEntry)obj;
-
- return Str.StrCmpiRetInt(hc1.FileName, hc2.FileName);
- }
- }
-
- public class HamCoreBuilderFileEntry : IComparable
- {
- public string Name;
- public Buf RawData;
- public Buf CompressedData;
- public int Offset = 0;
-
- int IComparable.CompareTo(HamCoreBuilderFileEntry other)
- {
- return this.Name.CompareTo(other.Name);
- }
- }
-
- public class HamCoreBuilder
- {
- List fileList;
- public List FileList
- {
- get { return fileList; }
- }
-
- public bool IsFile(string name)
- {
- foreach (HamCoreBuilderFileEntry f in fileList)
- {
- if (f.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public bool DeleteFile(string name)
- {
- foreach (HamCoreBuilderFileEntry f in fileList)
- {
- if (f.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
- {
- fileList.Remove(f);
- return true;
- }
- }
-
- return false;
- }
-
- public HamCoreBuilder()
- {
- fileList = new List();
- }
-
- public void AddDir(string dirName)
- {
- dirName = IO.RemoteLastEnMark(dirName);
-
- DirEntry[] ee = IO.EnumDirEx(dirName);
-
- foreach (DirEntry e in ee)
- {
- if (e.IsFolder == false)
- {
- AddFile(e.FullPath, dirName);
- }
- }
- }
-
- public void AddFile(string fileName, string baseDirFileName)
- {
- string name = IO.GetRelativeFileName(fileName, baseDirFileName);
-
- AddFile(name, File.ReadAllBytes(fileName));
- }
-
- public void AddFile(string name, byte[] data)
- {
- if (IsFile(name))
- {
- throw new InvalidOperationException("fileName");
- }
-
- HamCoreBuilderFileEntry f = new HamCoreBuilderFileEntry();
-
- Console.Write("{0}: ", name);
-
- f.Name = name;
- f.RawData = new Buf(Util.CloneByteArray(data));
- Console.Write("{0} -> ", f.RawData.Size);
- f.CompressedData = new Buf(ZLib.Compress(f.RawData.ByteData));
- Console.WriteLine("{0}", f.CompressedData.Size);
-
- this.fileList.Add(f);
- }
-
- public void Build(string dstFileName)
- {
- Buf b = Build();
-
- IO.SaveFile(dstFileName, b.ByteData);
- }
-
- public Buf Build()
- {
- int z;
- Buf b;
-
- this.fileList.Sort();
-
- z = 0;
-
- z += HamCore.HamcoreHeaderSize;
-
- z += sizeof(int);
-
- foreach (HamCoreBuilderFileEntry f in this.fileList)
- {
- z += Str.ShiftJisEncoding.GetByteCount(f.Name) + sizeof(int);
- z += sizeof(int);
- z += sizeof(int);
- z += sizeof(int);
- }
- foreach (HamCoreBuilderFileEntry f in this.fileList)
- {
- f.Offset = z;
- z += (int)f.CompressedData.Size;
- }
-
- b = new Buf();
- b.Write(Str.ShiftJisEncoding.GetBytes(HamCore.HamcoreHeaderData));
- b.WriteInt((uint)this.fileList.Count);
- foreach (HamCoreBuilderFileEntry f in this.fileList)
- {
- b.WriteStr(f.Name, true);
- b.WriteInt(f.RawData.Size);
- b.WriteInt(f.CompressedData.Size);
- b.WriteInt((uint)f.Offset);
- }
- foreach (HamCoreBuilderFileEntry f in this.fileList)
- {
- b.Write(f.CompressedData.ByteData);
- }
-
- b.SeekToBegin();
-
- return b;
- }
- }
-
- public class HamCore
- {
- public const string HamcoreDirName = "@hamcore";
- public const string HamcoreHeaderData = "HamCore";
- public const int HamcoreHeaderSize = 7;
- public const long HamcoreCacheExpires = 5 * 60 * 1000;
- bool disableReadRawFile = false;
- public bool DisableReadRawFile
- {
- get { return disableReadRawFile; }
- set { disableReadRawFile = value; }
- }
-
- Dictionary list;
-
- IO hamcore_io;
-
- public HamCore(string filename)
- {
- init(filename);
- }
-
- public string[] GetFileNames()
- {
- List ret = new List();
-
- foreach (HamCoreEntry e in list.Values)
- {
- ret.Add(e.FileName);
- }
-
- return ret.ToArray();
- }
-
- void init(string filename)
- {
- filename = IO.InnerFilePath(filename);
- string filenameOnly = Path.GetFileName(filename);
- string filenameAlt = Path.Combine(Path.GetDirectoryName(filename), "_" + filenameOnly);
-
- try
- {
- IO.FileReplaceRename(filenameAlt, filename);
- }
- catch
- {
- }
-
- list = new Dictionary();
-
- try
- {
- hamcore_io = IO.FileOpen(filename);
- }
- catch
- {
- return;
- }
-
- try
- {
- byte[] header = hamcore_io.Read(HamcoreHeaderSize);
- byte[] header2 = Str.AsciiEncoding.GetBytes(HamcoreHeaderData);
- if (header == null || Util.CompareByte(header, header2) == false)
- {
- throw new SystemException();
- }
-
- uint num = 0;
- byte[] buf = hamcore_io.Read(Util.SizeOfInt32);
- num = Util.ByteToUInt(buf);
- uint i;
- for (i = 0; i < num; i++)
- {
- uint str_size;
-
- buf = hamcore_io.Read(Util.SizeOfInt32);
- str_size = Util.ByteToUInt(buf);
- if (str_size >= 1)
- {
- str_size--;
- }
-
- byte[] str_data = hamcore_io.Read((int)str_size);
- string tmp = Str.ShiftJisEncoding.GetString(str_data);
-
- HamCoreEntry c = new HamCoreEntry();
- c.FileName = tmp;
-
- buf = hamcore_io.Read(Util.SizeOfInt32);
- c.Size = Util.ByteToUInt(buf);
-
- buf = hamcore_io.Read(Util.SizeOfInt32);
- c.SizeCompressed = Util.ByteToUInt(buf);
-
- buf = hamcore_io.Read(Util.SizeOfInt32);
- c.Offset = Util.ByteToUInt(buf);
-
- list.Add(c.FileName.ToUpper(), c);
- }
- }
- catch
- {
- hamcore_io.Close();
- }
- }
-
- public Buf ReadHamcore(string name)
- {
- if (name[0] == '|')
- {
- name = name.Substring(1);
- }
- if (name[0] == '/' || name[0] == '\\')
- {
- name = name.Substring(1);
- }
-
- string filename = name;
-
- filename = filename.Replace("/", "\\");
-
- Buf b;
-
- if (this.disableReadRawFile == false)
- {
- try
- {
- b = Buf.ReadFromFile(HamcoreDirName + "\\" + filename);
-
- return b;
- }
- catch
- {
- }
- }
-
- lock (list)
- {
- HamCoreEntry c;
- string key = filename.ToUpper();
-
- b = null;
-
- if (list.ContainsKey(key))
- {
- c = list[key];
-
- if (c.Buffer != null)
- {
- b = new Buf(c.Buffer);
- b.SeekToBegin();
- c.LastAccess = Time.Tick64;
- }
- else
- {
- if (hamcore_io.Seek(SeekOrigin.Begin, (int)c.Offset))
- {
- byte[] data = hamcore_io.Read((int)c.SizeCompressed);
-
- int dstSize = (int)c.Size;
- byte[] buffer = ZLib.Uncompress(data, dstSize);
-
- c.Buffer = buffer;
- b = new Buf(buffer);
- b.SeekToBegin();
- c.LastAccess = Time.Tick64;
- }
- }
- }
-
- long now = Time.Tick64;
- foreach (HamCoreEntry cc in list.Values)
- {
- if (cc.Buffer != null)
- {
- if (((cc.LastAccess + HamcoreCacheExpires) < now) ||
- cc.FileName.StartsWith("Li", StringComparison.CurrentCultureIgnoreCase))
- {
- cc.Buffer = null;
- }
- }
- }
- }
-
- return b;
- }
- }
-
- public class DirEntry : IComparable
- {
- internal bool folder;
- public bool IsFolder
- {
- get { return folder; }
- }
- internal string fileName;
- public string FileName
- {
- get { return fileName; }
- }
- internal string fullPath;
- public string FullPath
- {
- get { return fullPath; }
- }
- internal string relativePath;
- public string RelativePath
- {
- get { return relativePath; }
- }
- internal long fileSize;
- public long FileSize
- {
- get { return fileSize; }
- }
- internal DateTime createDate;
- public DateTime CreateDate
- {
- get { return createDate; }
- }
- internal DateTime updateDate;
- public DateTime UpdateDate
- {
- get { return updateDate; }
- }
-
- public int CompareTo(DirEntry other)
- {
- int i;
- i = Str.StrCmpiRetInt(this.fileName, other.fileName);
- if (i == 0)
- {
- i = Str.StrCmpRetInt(this.fileName, other.fileName);
- }
-
- return i;
- }
-
- public override string ToString()
- {
- return FileName;
- }
- };
-
- public class IO
- {
- public delegate bool CopyDirPreCopyDelegate(FileInfo srcFileInfo);
- public static void CopyDir(string srcDirName, string destDirName, CopyDirPreCopyDelegate preCopy, bool ignoreError, bool printStatus)
- {
- CopyDir(srcDirName, destDirName, preCopy, ignoreError, printStatus, false, false, false);
- }
- public static void CopyDir(string srcDirName, string destDirName, CopyDirPreCopyDelegate preCopy, bool ignoreError, bool printStatus,
- bool skipIfNoChange, bool deleteBom)
- {
- CopyDir(srcDirName, destDirName, preCopy, ignoreError, printStatus, skipIfNoChange, deleteBom, false);
- }
- public static void CopyDir(string srcDirName, string destDirName, CopyDirPreCopyDelegate preCopy, bool ignoreError, bool printStatus,
- bool skipIfNoChange, bool deleteBom, bool useTimeStampToCheckNoChange)
- {
- string[] files = Directory.GetFiles(srcDirName, "*", SearchOption.AllDirectories);
-
- foreach (string srcFile in files)
- {
- FileInfo info = new FileInfo(srcFile);
-
- string relativeFileName = IO.GetRelativeFileName(srcFile, srcDirName);
- string destFileName = Path.Combine(destDirName, relativeFileName);
- string destFileDirName = Path.GetDirectoryName(destFileName);
-
- if (preCopy != null)
- {
- if (preCopy(info) == false)
- {
- continue;
- }
- }
-
- try
- {
- if (Directory.Exists(destFileDirName) == false)
- {
- Directory.CreateDirectory(destFileDirName);
- }
-
- FileCopy(srcFile, destFileName, skipIfNoChange, deleteBom, useTimeStampToCheckNoChange);
- }
- catch
- {
- if (ignoreError == false)
- {
- throw;
- }
- }
-
- if (printStatus)
- {
- Con.WriteLine(relativeFileName);
- }
- }
- }
-
- public const string DefaultHamcoreFileName = "@hamcore.se2";
-
- static string hamcoreFileName = DefaultHamcoreFileName;
- public static string HamcoreFileName
- {
- get { return IO.hamcoreFileName; }
- set
- {
- lock (hamLockObj)
- {
- if (hamCore != null)
- {
- throw new ApplicationException();
- }
-
- IO.hamcoreFileName = value;
- tryToUseHamcore = false;
- }
- }
- }
-
- static bool tryToUseHamcore = true;
- static HamCore hamCore = null;
- static object hamLockObj = new object();
- public static HamCore HamCore
- {
- get
- {
- HamCore ret = null;
-
- lock (hamLockObj)
- {
- if (hamCore == null)
- {
- if (tryToUseHamcore)
- {
- if (hamCore == null)
- {
- try
- {
- ret = hamCore = new HamCore(hamcoreFileName);
- }
- catch
- {
- tryToUseHamcore = false;
- }
- }
- }
- }
- }
-
- return ret;
- }
- }
-
- string name;
- public string Name
- {
- get { return name; }
- }
- FileStream p;
- public FileStream InnerFileStream
- {
- get { return p; }
- }
- bool writeMode;
- public bool WriteMode
- {
- get { return writeMode; }
- }
- bool hamMode;
- public bool HamMode
- {
- get { return hamMode; }
- }
- Buf hamBuf;
-
- object lockObj;
-
- private IO()
- {
- name = "";
- p = null;
- writeMode = hamMode = false;
- lockObj = new object();
- hamBuf = null;
- }
-
- ~IO()
- {
- Close();
- }
-
- public static void WriteAllTextWithEncoding(string fileName, string str, Encoding encoding)
- {
- WriteAllTextWithEncoding(fileName, str, encoding, false);
- }
- public static void WriteAllTextWithEncoding(string fileName, string str, Encoding encoding, bool appendBom)
- {
- fileName = InnerFilePath(fileName);
-
- byte[] data = encoding.GetBytes(str);
- byte[] bom = null;
- if (appendBom)
- {
- bom = Str.GetBOM(encoding);
- }
-
- data = Util.CombineByteArray(bom, data);
-
- File.WriteAllBytes(fileName, data);
- }
-
- public static string ReadAllTextWithAutoGetEncoding(string fileName)
- {
- fileName = InnerFilePath(fileName);
-
- byte[] data = File.ReadAllBytes(fileName);
-
- int bomSize;
- Encoding enc = Str.GetEncoding(data, out bomSize);
- if (enc == null)
- {
- enc = Encoding.Default;
- }
-
- data = Util.RemoveStartByteArray(data, bomSize);
-
- return enc.GetString(data);
- }
-
- public static IO CreateTempFileByExt(string ext)
- {
- return IO.FileCreate(CreateTempFileNameByExt(ext));
- }
-
- public static string CreateTempFileNameByExt(string ext)
- {
- if (Str.IsEmptyStr(ext))
- {
- ext = "tmp";
- }
- if (ext[0] == '.')
- {
- ext = ext.Substring(1);
- }
-
- while (true)
- {
- string newFilename;
- string fullPath;
- string randStr;
-
- randStr = Str.GenRandStr();
- newFilename = "__" + randStr + "." + ext;
-
- fullPath = CreateTempFileName(newFilename);
-
- if (IO.IsFileExists(fullPath) == false)
- {
- return fullPath;
- }
- }
- }
-
- public static IO CreateTempFile(string name)
- {
- return IO.FileCreate(CreateTempFileName(name));
- }
-
- public static string CreateTempFileName(string name)
- {
- return Path.Combine(Env.MyTempDir, name);
- }
-
- public static DirEntry[] EnumDirEx(string dirName)
- {
- List list = new List();
-
- enumDirEx(dirName, dirName, list);
-
- return list.ToArray();
- }
- static void enumDirEx(string dirName, string baseDirName, List list)
- {
- string tmp = IO.InnerFilePath(dirName);
-
- string[] dirs = Directory.GetDirectories(tmp);
- foreach (string name in dirs)
- {
- string fullPath = name;
- DirectoryInfo info = new DirectoryInfo(fullPath);
-
- DirEntry e = new DirEntry();
-
- e.fileName = Path.GetFileName(name);
- e.fileSize = 0;
- e.createDate = info.CreationTimeUtc;
- e.folder = true;
- e.updateDate = info.LastWriteTimeUtc;
- e.fullPath = fullPath;
- e.relativePath = GetRelativeFileName(fullPath, baseDirName);
-
- list.Add(e);
-
- enumDirEx(fullPath, baseDirName, list);
- }
-
- string[] files = Directory.GetFiles(tmp);
- foreach (string name in files)
- {
- string fullPath = name;
- FileInfo info = new FileInfo(fullPath);
-
- DirEntry e = new DirEntry();
-
- e.fileName = Path.GetFileName(name);
- e.fileSize = info.Length;
- e.createDate = info.CreationTimeUtc;
- e.folder = false;
- e.updateDate = info.LastWriteTimeUtc;
- e.fullPath = fullPath;
- e.relativePath = GetRelativeFileName(fullPath, baseDirName);
-
- list.Add(e);
- }
- }
-
- public static DirEntry[] EnumDir(string dirName)
- {
- List list = new List();
- string tmp = IO.InnerFilePath(dirName);
-
- string[] dirs = Directory.GetDirectories(tmp);
- foreach (string name in dirs)
- {
- string fullPath = name;
- DirectoryInfo info = new DirectoryInfo(fullPath);
-
- DirEntry e = new DirEntry();
-
- e.fileName = Path.GetFileName(name);
- e.fileSize = 0;
- e.createDate = info.CreationTimeUtc;
- e.folder = true;
- e.updateDate = info.LastWriteTimeUtc;
- e.fullPath = fullPath;
- e.relativePath = GetRelativeFileName(fullPath, dirName);
-
- list.Add(e);
- }
-
- string[] files = Directory.GetFiles(tmp);
- foreach (string name in files)
- {
- string fullPath = name;
- FileInfo info = new FileInfo(fullPath);
-
- DirEntry e = new DirEntry();
-
- e.fileName = Path.GetFileName(name);
- e.fileSize = info.Length;
- e.createDate = info.CreationTimeUtc;
- e.folder = false;
- e.updateDate = info.LastWriteTimeUtc;
- e.fullPath = fullPath;
- e.relativePath = GetRelativeFileName(fullPath, dirName);
-
- list.Add(e);
- }
-
- list.Sort();
-
- return list.ToArray();
- }
-
- public static void FileReplaceRename(string oldName, string newName)
- {
- try
- {
- FileCopy(oldName, newName);
- FileDelete(oldName);
- }
- catch (Exception e)
- {
- throw e;
- }
- }
-
- public static void FileCopy(string oldName, string newName)
- {
- FileCopy(oldName, newName, false, false);
- }
- public static void FileCopy(string oldName, string newName, bool skipIfNoChange, bool deleteBom)
- {
- FileCopy(oldName, newName, skipIfNoChange, deleteBom, false);
- }
- public static void FileCopy(string oldName, string newName, bool skipIfNoChange, bool deleteBom, bool useTimeStampToCheckNoChange)
- {
- string tmp1 = InnerFilePath(oldName);
- string tmp2 = InnerFilePath(newName);
-
- if (useTimeStampToCheckNoChange && skipIfNoChange)
- {
- DateTime dt1, dt2;
-
- try
- {
- dt1 = Directory.GetLastWriteTimeUtc(tmp1);
- dt2 = Directory.GetLastWriteTimeUtc(tmp2);
-
- TimeSpan ts = dt2 - dt1;
- if (ts.TotalSeconds >= -5.0)
- {
- return;
- }
- }
- catch
- {
- }
- }
-
- if (skipIfNoChange || deleteBom)
- {
- byte[] srcData = File.ReadAllBytes(tmp1);
- byte[] destData = new byte[0];
- bool changed = true;
- int bomSize;
-
- Str.GetEncoding(srcData, out bomSize);
- if (bomSize >= 1)
- {
- srcData = Util.ExtractByteArray(srcData, bomSize, srcData.Length - bomSize);
- }
-
- if (skipIfNoChange)
- {
- try
- {
- FileStream fs = File.OpenRead(tmp2);
- long size = 0xffffffff;
- try
- {
- size = fs.Length;
- }
- finally
- {
- fs.Close();
- }
-
- if (size == srcData.Length || srcData.Length == 0)
- {
- destData = File.ReadAllBytes(tmp2);
- }
- }
- catch
- {
- }
-
- if (Util.CompareByte(srcData, destData))
- {
- changed = false;
- }
- }
-
- if (changed)
- {
- File.WriteAllBytes(tmp2, srcData);
- CopyFileTimestamp(tmp2, tmp1);
- }
- }
- else
- {
- File.Copy(tmp1, tmp2, true);
- }
- }
-
- public static void CopyFileTimestamp(string dstFileName, string srcFileName)
- {
- DateTime dt1 = File.GetCreationTimeUtc(srcFileName);
- DateTime dt2 = File.GetLastAccessTimeUtc(srcFileName);
- DateTime dt3 = File.GetLastWriteTimeUtc(srcFileName);
-
- File.SetCreationTimeUtc(dstFileName, dt1);
- File.SetLastAccessTimeUtc(dstFileName, dt2);
- File.SetLastWriteTimeUtc(dstFileName, dt3);
- }
-
- public static void SetFileTimestamp(string dstFileName, FileInfo fi)
- {
- File.SetCreationTimeUtc(dstFileName, fi.CreationTimeUtc);
- File.SetLastAccessTimeUtc(dstFileName, fi.LastAccessTimeUtc);
- File.SetLastWriteTimeUtc(dstFileName, fi.LastWriteTimeUtc);
- }
-
- static public byte[] ReadFile(string name)
- {
- IO io = FileOpen(name);
- try
- {
- int size = io.FileSize;
- byte[] ret = io.Read(size);
- return ret;
- }
- finally
- {
- io.Close();
- }
- }
-
- static public void SaveFile(string name, byte[] data)
- {
- SaveFile(name, data, 0, data.Length);
- }
- static public void SaveFile(string name, byte[] data, int offset, int size)
- {
- IO io = FileCreate(name);
- try
- {
- io.Write(data, offset, size);
- }
- finally
- {
- io.Close();
- }
- }
-
- static public string MakeSafeFileName(string src)
- {
- return src
- .Replace("..", "__")
- .Replace("/", "_")
- .Replace("\\", "_")
- .Replace("@", "_")
- .Replace("|", "_");
- }
-
- public static bool IsDirExists(string name)
- {
- string tmp = InnerFilePath(name);
-
- return Directory.Exists(tmp);
- }
-
- public static bool IsFileExists(string name)
- {
- string tmp = InnerFilePath(name);
-
- return File.Exists(tmp);
- }
-
- static void fileDeleteInner(string name)
- {
- string name2 = ConvertPath(name);
-
- File.Delete(name2);
- }
- public static void FileDelete(string name)
- {
- string tmp = InnerFilePath(name);
-
- fileDeleteInner(tmp);
- }
-
- public bool Seek(SeekOrigin mode, int offset)
- {
- lock (lockObj)
- {
- if (p != null)
- {
- try
- {
- p.Seek(offset, mode);
-
- return true;
- }
- catch
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- }
-
- public long FileSize64
- {
- get
- {
- lock (lockObj)
- {
- if (p != null)
- {
- return p.Length;
- }
- else
- {
- if (hamMode)
- {
- return (long)hamBuf.Size;
- }
- }
-
- return 0;
- }
- }
- }
- public int FileSize
- {
- get
- {
- long size64 = this.FileSize64;
-
- if (size64 >= 2147483647)
- {
- size64 = 2147483647;
- }
-
- return (int)size64;
- }
- }
- public static int GetFileSize(string name)
- {
- IO io = IO.FileOpen(name, false);
- try
- {
- return io.FileSize;
- }
- finally
- {
- io.Close();
- }
- }
-
- public byte[] ReadAll()
- {
- this.Seek(SeekOrigin.Begin, 0);
- int size = this.FileSize;
-
- byte[] data = new byte[size];
- this.Read(data, 0, size);
-
- this.Seek(SeekOrigin.Begin, 0);
-
- return data;
- }
-
- public byte[] Read(int size)
- {
- byte[] buf = new byte[size];
- bool ret = Read(buf, size);
- if (ret == false)
- {
- return null;
- }
- return buf;
- }
- public bool Read(byte[] buf, int size)
- {
- return Read(buf, 0, size);
- }
- public bool Read(byte[] buf, int offset, int size)
- {
- if (size == 0)
- {
- return true;
- }
-
- lock (lockObj)
- {
- if (this.HamMode)
- {
- byte[] ret = hamBuf.Read((uint)size);
-
- if (ret.Length != size)
- {
- return false;
- }
-
- Util.CopyByte(buf, offset, ret, 0, size);
-
- return true;
- }
-
- if (p != null)
- {
- try
- {
- int ret = p.Read(buf, offset, size);
- if (ret == size)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- catch
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- }
-
- public bool Write(byte[] buf)
- {
- return Write(buf, 0, buf.Length);
- }
- public bool Write(byte[] buf, int size)
- {
- return Write(buf, 0, size);
- }
- public bool Write(byte[] buf, int offset, int size)
- {
- if (writeMode == false)
- {
- return false;
- }
- if (size == 0)
- {
- return true;
- }
-
- lock (lockObj)
- {
- if (p != null)
- {
- try
- {
- p.Write(buf, offset, size);
-
- return true;
- }
- catch
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- }
-
- public bool CloseAndDelete()
- {
- string name = this.Name;
-
- Close();
-
- try
- {
- FileDelete(name);
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public void Close()
- {
- Close(false);
- }
- public void Close(bool noFlush)
- {
- lock (this.lockObj)
- {
- if (this.hamMode == false)
- {
- if (this.p != null)
- {
- if (this.writeMode && noFlush == false)
- {
- Flush();
- }
-
- this.p.Close();
- }
-
- this.p = null;
- }
- }
- }
-
- public void Flush()
- {
- try
- {
- lock (this.lockObj)
- {
- if (this.p != null)
- {
- this.p.Flush();
- }
- }
- }
- catch
- {
- }
- }
-
- static IO fileCreateInner(string name)
- {
- IO o = new IO();
-
- string name2 = ConvertPath(name);
-
- lock (o.lockObj)
- {
- o.p = File.Open(name2, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
- o.name = name2;
- o.writeMode = true;
- }
-
- return o;
- }
-
- public static IO FileCreate(string name)
- {
- name = InnerFilePath(name);
-
- return fileCreateInner(name);
- }
-
- static IO fileOpenInner(string name, bool writeMode, bool readLock)
- {
- IO o = new IO();
-
- string name2 = ConvertPath(name);
-
- lock (o.lockObj)
- {
- o.p = File.Open(name2, FileMode.Open, (writeMode ? FileAccess.ReadWrite : FileAccess.Read),
- (readLock ? FileShare.None : FileShare.Read));
-
- o.name = name2;
- o.writeMode = writeMode;
- }
-
- return o;
- }
-
- public static IO FileOpen(string name)
- {
- return FileOpen(name, false);
- }
- public static IO FileOpen(string name, bool writeMode)
- {
- return FileOpen(name, writeMode, false);
- }
- public static IO FileOpen(string name, bool writeMode, bool readLock)
- {
- name = InnerFilePath(name);
-
- if (name[0] == '|')
- {
- HamCore hc = IO.HamCore;
-
- Buf b = hc.ReadHamcore(name);
- if (b == null)
- {
- throw new FileNotFoundException();
- }
-
- IO o = new IO();
- o.name = name.Substring(1);
- o.hamMode = true;
- o.hamBuf = b;
-
- return o;
- }
- else
- {
- return fileOpenInner(name, writeMode, readLock);
- }
- }
-
- public static IO FileCreateOrAppendOpen(string name)
- {
- if (IsFileExists(name))
- {
- IO io = FileOpen(name, true);
- io.Seek(SeekOrigin.End, 0);
- return io;
- }
- else
- {
- return FileCreate(name);
- }
- }
-
- public static string GetRelativeFileName(string fileName, string baseDirName)
- {
- baseDirName = RemoteLastEnMark(baseDirName).Trim() + "\\";
- fileName = fileName.Trim();
-
- if (fileName.Length <= baseDirName.Length)
- {
- throw new ArgumentException("fileName, baseDirName");
- }
-
- if (fileName.StartsWith(baseDirName, StringComparison.InvariantCultureIgnoreCase) == false)
- {
- throw new ArgumentException("fileName, baseDirName");
- }
-
- return fileName.Substring(baseDirName.Length);
- }
-
- public static string RemoteLastEnMark(string path)
- {
- if (path == null)
- {
- path = "";
- }
- if (path.EndsWith("\\"))
- {
- path = path.Substring(0, path.Length - 1);
- }
- return path;
- }
-
- public static void FileRename(string oldName, string newName)
- {
- string tmp1 = InnerFilePath(oldName);
- string tmp2 = InnerFilePath(newName);
-
- File.Move(tmp1, tmp2);
- }
-
- public static void DeleteFilesAndSubDirsInDir(string dirName)
- {
- dirName = InnerFilePath(dirName);
-
- if (Directory.Exists(dirName) == false)
- {
- Directory.CreateDirectory(dirName);
- return;
- }
-
- string[] files = Directory.GetFiles(dirName);
- string[] dirs = Directory.GetDirectories(dirName);
-
- foreach (string file in files)
- {
- File.SetAttributes(file, FileAttributes.Normal);
- File.Delete(file);
- }
-
- foreach (string dir in dirs)
- {
- Directory.Delete(dir, true);
- }
- }
-
- public static bool DeleteDir(string dirName)
- {
- return DeleteDir(dirName, false);
- }
- public static bool DeleteDir(string dirName, bool deleteSubDirs)
- {
- try
- {
- Directory.Delete(InnerFilePath(dirName), deleteSubDirs);
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public static bool MakeDir(string dirName)
- {
- try
- {
- Directory.CreateDirectory(InnerFilePath(dirName));
- return true;
- }
- catch
- {
- return false;
- }
- }
- public static bool MakeDirIfNotExists(string dirName)
- {
- string path = InnerFilePath(dirName);
-
- if (Directory.Exists(path) == false)
- {
- Directory.CreateDirectory(path);
-
- return true;
- }
-
- return false;
- }
-
- public static string NormalizePath(string src)
- {
- bool first_double_slash = false;
- bool first_single_slash = false;
- string win32_drive_char = "";
- int i;
- string tmp;
-
- tmp = ConvertPath(src).Trim();
-
- if (tmp.StartsWith(".\\") || tmp.StartsWith("..\\") || tmp.StartsWith(".") || tmp.StartsWith(".."))
- {
- if (tmp.StartsWith(".."))
- {
- tmp = Env.CurrentDir + "/../" + tmp.Substring(2);
- }
- else
- {
- tmp = Env.CurrentDir + "/" + tmp;
- }
- }
-
- if (tmp.StartsWith("~/") || tmp.StartsWith("~\\"))
- {
- tmp = Env.HomeDir + "/" + tmp.Substring(2);
- }
-
- if (tmp.StartsWith("//") || tmp.StartsWith("\\\\"))
- {
- first_double_slash = true;
- }
- else
- {
- if (tmp.StartsWith("/") || tmp.StartsWith("\\"))
- {
- first_single_slash = true;
- }
- }
-
- if (tmp.Length >= 2)
- {
- if (tmp[1] == ':')
- {
- win32_drive_char = "" + tmp[0];
- tmp = tmp.Substring(2);
- }
- }
-
- if (tmp == "/" || tmp == "\\")
- {
- tmp = "";
- }
-
- char[] splitChars = { '/', '\\' };
- string[] t = tmp.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
-
- Stack sk = new Stack();
-
- for (i = 0; i < t.Length; i++)
- {
- string s = t[i];
-
- if (Str.StrCmpi(s, "."))
- {
- continue;
- }
- else if (Str.StrCmpi(s, ".."))
- {
- if (sk.Count >= 1 && (first_double_slash == false || sk.Count >= 2))
- {
- sk.Pop();
- }
- }
- else
- {
- sk.Push(s);
- }
- }
-
- tmp = "";
-
- if (first_double_slash)
- {
- tmp += "//";
- }
- else if (first_single_slash)
- {
- tmp += "/";
- }
-
- if (Str.IsEmptyStr(win32_drive_char) == false)
- {
- tmp = win32_drive_char + ":/" + tmp;
- }
-
- string[] sks = sk.ToArray();
- Array.Reverse(sks);
- for (i = 0; i < sks.Length; i++)
- {
- tmp += sks[i];
- if (i != (sks.Length - 1))
- {
- tmp += "/";
- }
- }
-
- tmp = ConvertPath(tmp);
-
- return tmp;
- }
-
- public static string ConvertPath(string path)
- {
- return path.Replace('/', '\\');
- }
-
- public static string ConbinePath(string dirname, string filename)
- {
- return CombinePath(dirname, filename);
- }
- public static string CombinePath(string dirname, string filename)
- {
- bool is_full_path;
- string filename_ident = NormalizePath(filename);
-
- is_full_path = false;
-
- if (filename_ident.StartsWith("\\") || filename_ident.StartsWith("/"))
- {
- is_full_path = true;
- }
-
- filename = filename_ident;
-
- if (filename.Length >= 2)
- {
- char c = filename[0];
- if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
- {
- if (filename[1] == ':')
- {
- is_full_path = true;
- }
- }
- }
-
- string tmp;
-
- if (is_full_path == false)
- {
- tmp = dirname;
- if (tmp.EndsWith("/") == false && tmp.EndsWith("\\") == false)
- {
- tmp += "/";
- }
-
- tmp += filename;
- }
- else
- {
- tmp = filename;
- }
-
- return NormalizePath(tmp);
- }
-
- public static string InnerFilePath(string src)
- {
- if (src[0] != '@')
- {
- return NormalizePath(src);
- }
- else
- {
- return CombinePath(Env.ExeFileDir, src.Substring(1));
- }
- }
-
- public static DateTime GetCreationTimeUtc(string filename)
- {
- return File.GetCreationTimeUtc(InnerFilePath(filename));
- }
- public static DateTime GetCreationTimeLocal(string filename)
- {
- return File.GetCreationTime(InnerFilePath(filename));
- }
-
- public static DateTime GetLastWriteTimeUtc(string filename)
- {
- return File.GetLastWriteTimeUtc(InnerFilePath(filename));
- }
- public static DateTime GetLastWriteTimeLocal(string filename)
- {
- return File.GetLastWriteTime(InnerFilePath(filename));
- }
-
- public static DateTime GetLastAccessTimeUtc(string filename)
- {
- return File.GetLastAccessTimeUtc(InnerFilePath(filename));
- }
- public static DateTime GetLastAccessTimeLocal(string filename)
- {
- return File.GetLastAccessTime(InnerFilePath(filename));
- }
-
- public static byte[] ReadFileData(string filename)
- {
- FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- try
- {
- long size = fs.Length;
- int size2 = (int)Math.Min(size, int.MaxValue);
- byte[] ret = new byte[size2];
- fs.Read(ret, 0, size2);
- return ret;
- }
- finally
- {
- fs.Close();
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/GZip.cs b/src/BuildUtil/CoreUtil/GZip.cs
deleted file mode 100644
index 1869d427..00000000
--- a/src/BuildUtil/CoreUtil/GZip.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.IO.Compression;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Runtime.InteropServices;
-using CoreUtil.Internal;
-
-namespace CoreUtil
-{
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- public struct GZipHeader
- {
- public byte ID1, ID2, CM, FLG;
- public uint MTIME;
- public byte XFL, OS;
- }
-
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- public struct GZipFooter
- {
- public uint CRC32;
- public uint ISIZE;
- }
-
- public static class GZipUtil
- {
- public static byte[] Decompress(byte[] gzip)
- {
- using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
- {
- const int size = 4096;
- byte[] buffer = new byte[size];
- using (MemoryStream memory = new MemoryStream())
- {
- int count = 0;
- do
- {
- count = stream.Read(buffer, 0, size);
- if (count > 0)
- {
- memory.Write(buffer, 0, count);
- }
- }
- while (count > 0);
- return memory.ToArray();
- }
- }
- }
- }
-
- public class GZipPacker
- {
- Fifo fifo;
- ZStream zs;
- long currentSize;
- uint crc32;
- bool finished;
-
- public bool Finished
- {
- get { return finished; }
- }
-
- public Fifo GeneratedData
- {
- get
- {
- return this.fifo;
- }
- }
-
- public GZipPacker()
- {
- fifo = new Fifo();
-
- zs = new ZStream();
- zs.deflateInit(-1, -15);
-
- this.currentSize = 0;
- this.crc32 = 0xffffffff;
- this.finished = false;
-
- GZipHeader h = new GZipHeader();
- h.ID1 = 0x1f;
- h.ID2 = 0x8b;
- h.FLG = 0;
- h.MTIME = Util.DateTimeToUnixTime(DateTime.Now.ToUniversalTime());
- h.XFL = 0;
- h.OS = 3;
- h.CM = 8;
-
- fifo.Write(Util.StructToByte(h));
- }
-
- public void Write(byte[] data, int pos, int len, bool finish)
- {
- byte[] srcData = Util.ExtractByteArray(data, pos, len);
- byte[] dstData = new byte[srcData.Length * 2 + 100];
-
- if (this.finished)
- {
- throw new ApplicationException("already finished");
- }
-
- zs.next_in = srcData;
- zs.avail_in = srcData.Length;
- zs.next_in_index = 0;
-
- zs.next_out = dstData;
- zs.avail_out = dstData.Length;
- zs.next_out_index = 0;
-
- if (finish)
- {
- zs.deflate(zlibConst.Z_FINISH);
- }
- else
- {
- zs.deflate(zlibConst.Z_SYNC_FLUSH);
- }
-
- fifo.Write(dstData, 0, dstData.Length - zs.avail_out);
-
- currentSize += len;
-
- this.crc32 = ZipUtil.Crc32Next(data, pos, len, this.crc32);
-
- if (finish)
- {
- this.finished = true;
- this.crc32 = ~this.crc32;
-
- GZipFooter f = new GZipFooter();
- f.CRC32 = this.crc32;
- f.ISIZE = (uint)(this.currentSize % 0x100000000);
-
- fifo.Write(Util.StructToByte(f));
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Kernel.cs b/src/BuildUtil/CoreUtil/Kernel.cs
deleted file mode 100644
index 45e666e5..00000000
--- a/src/BuildUtil/CoreUtil/Kernel.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using System.Net.Mail;
-using System.Net.Mime;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- public static class Kernel
- {
- [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool IsWow64Process(
- [In] IntPtr hProcess,
- [Out] out bool wow64Process
- );
-
- public static bool InternalCheckIsWow64()
- {
- if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
- Environment.OSVersion.Version.Major >= 6)
- {
- using (Process p = Process.GetCurrentProcess())
- {
- bool retVal;
- if (!IsWow64Process(p.Handle, out retVal))
- {
- return false;
- }
- return retVal;
- }
- }
- else
- {
- return false;
- }
- }
-
- public static void SleepThread(int millisec)
- {
- ThreadObj.Sleep(millisec);
- }
-
- public static string GetEnvStr(string name)
- {
- string ret = Environment.GetEnvironmentVariable(name);
-
- if (ret == null)
- {
- ret = "";
- }
-
- return ret;
- }
-
- static public void SelfKill()
- {
- System.Diagnostics.Process.GetCurrentProcess().Kill();
- }
-
- public static Process Run(string exeName, string args)
- {
- Process p = new Process();
- p.StartInfo.FileName = IO.InnerFilePath(exeName);
- p.StartInfo.Arguments = args;
-
- p.Start();
-
- return p;
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/MultiLang.cs b/src/BuildUtil/CoreUtil/MultiLang.cs
deleted file mode 100644
index 99c4482b..00000000
--- a/src/BuildUtil/CoreUtil/MultiLang.cs
+++ /dev/null
@@ -1,868 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-using System.Threading;
-using System.Xml;
-using System.Xml.Schema;
-using System.Xml.Serialization;
-using CoreUtil;
-
-public static class AspUtil
-{
- public static void Redirect(Page page, string url)
- {
- Redirect(page, url, true);
- }
- public static void Redirect(Page page, string url, bool endSession)
- {
- MultiLang ml = new MultiLang(page, true);
-
- ml.Redirect(url, true);
- }
-
- public static string GetCurrentRequestUrl(Page page)
- {
- string s = (string)page.Request.Headers["SEISAPI_PHYSICAL_URL"];
- if (Str.IsEmptyStr(s) == false)
- {
- string[] tokens = s.Split('?');
- return tokens[0];
- }
- return page.Request.Path;
- }
-
- public static string GetCurrentPhysicalFilePathForUser(Page page)
- {
- string s = (string)page.Request.Headers["SEISAPI_ORIGINAL_FILEPATH"];
- if (Str.IsEmptyStr(s) == false)
- {
- return s;
- }
- return page.Request.PhysicalPath;
- }
-
- public static string RemoveDefaultHtml(string url)
- {
- string tmp = url.ToLower();
- if (tmp.EndsWith("/default.asp") || tmp.EndsWith("/default.aspx") || tmp.EndsWith("/default.htm") || tmp.EndsWith("/default.html"))
- {
- return GetUrlDirNameFromPath(url);
- }
- else
- {
- return url;
- }
- }
-
- public static string GetUrlDirNameFromPath(string url)
- {
- string ret = "";
- string[] strs = url.Split('/');
- int i;
- if (strs.Length >= 1)
- {
- for (i = 0; i < strs.Length - 1; i++)
- {
- ret += strs[i] + "/";
- }
- }
- return ret;
- }
-
- public static string WebPathToFilePath(System.Web.UI.Page page, string path)
- {
- string appRootFilePath = page.Request.PhysicalApplicationPath;
- string appRootVirtualPath = page.Request.ApplicationPath;
- string ret;
-
- path = RemoveDefaultHtml(path);
- if (path.ToUpper().StartsWith(appRootVirtualPath.ToUpper()) == false)
- {
- return null;
- }
-
- path = path.Substring(appRootVirtualPath.Length).Replace("/", "\\");
-
- if (path.StartsWith("\\"))
- {
- path = path.Substring(1);
- }
-
- ret = appRootFilePath + path;
-
- if (ret.IndexOf("..") != -1)
- {
- return null;
- }
-
- if (ret.EndsWith("\\"))
- {
- ret = GetDefaultDocumentIfExists(ret);
- }
-
- return ret;
- }
-
- public static string GetDefaultDocumentIfExists(string dir)
- {
- string[] targets =
- {
- "default.aspx",
- "default.asp",
- "default.html",
- "default.htm",
- "index.html",
- "index.htm",
- };
-
- foreach (string s in targets)
- {
- string name = dir + s;
-
- if (IsFileExists(name))
- {
- return name;
- }
- }
-
- return null;
- }
-
- public static bool IsFileExists(string name)
- {
- return File.Exists(name);
- }
-}
-
-public class MultiLang
-{
- public readonly Page Page;
- public readonly HttpRequest Request;
- public readonly HttpResponse Response;
- public readonly bool IsUrlModified;
- public readonly string OriginalUrl;
- public readonly string PhysicalUrl;
- public readonly bool IsFilenameModified;
- public readonly string OriginalFileName;
- public readonly string OriginalFilePath;
- public readonly string Args;
- public readonly CoreLanguageClass CurrentLanguage;
- public readonly CoreLanguageClass ContentsPrintLanguage;
- public readonly string CurrentLanguageCode;
- public readonly bool IsCurrentLanguageSupported;
- public readonly string GoogleTranslateUrl;
- public readonly string OriginalFullUrl;
- public readonly bool IsSSL;
- public readonly string Host;
- public readonly string BasicHostName;
- MultiLanguageFilterStream mfs;
- public readonly List> ReplaceList;
-
- public bool DisableFilter
- {
- get
- {
- return mfs.DisableFilter;
- }
- set
- {
- mfs.DisableFilter = value;
- }
- }
-
- public readonly string HtmlBody = "";
- public readonly string HtmlFileName = "";
-
- static MultiLang()
- {
- CoreLanguageList.RegardsJapanAsJP = true;
- }
-
- public bool IsJapanese
- {
- get
- {
- if (this.CurrentLanguage == CoreLanguageList.Japanese)
- {
- return true;
- }
- return false;
- }
- }
-
- public bool IsJapanesePrinting
- {
- get
- {
- if (this.ContentsPrintLanguage == CoreLanguageList.Japanese)
- {
- return true;
- }
- return false;
- }
- }
-
- public void Redirect(string url, bool endSession)
- {
- url = ConvertPath(url);
- if (url.StartsWith("http://") || url.StartsWith("https://") || url.StartsWith("ftp://") ||
- url.StartsWith("/"))
- {
- }
- else
- {
- string originalUrl = OriginalUrl;
- if (originalUrl.EndsWith("/"))
- {
- }
- else
- {
- int i;
- for (i = originalUrl.Length - 1; i >= 0; i--)
- {
- if (originalUrl[i] == '/' || originalUrl[i] == '\\')
- {
- originalUrl = originalUrl.Substring(0, i + 1);
- break;
- }
- }
- }
- url = originalUrl + url;
- }
- Response.Redirect(url, endSession);
- }
-
- public MultiLang(Page currentPage)
- : this(currentPage, false)
- {
- }
- public MultiLang(Page currentPage, bool fast) : this(currentPage, fast, null)
- {
- }
- public MultiLang(Page currentPage, bool fast, string basicHostName)
- : this(currentPage, fast, basicHostName, new List>())
- {
- }
- public MultiLang(Page currentPage, bool fast, string basicHostName, List> replaceList)
- {
- this.Page = currentPage;
-
- this.Request = Page.Request;
- this.Response = Page.Response;
- this.BasicHostName = basicHostName;
- string tmp = Page.Request.ServerVariables["HTTPS"];
- string hostRaw = Page.Request.Headers["Host"];
- this.ReplaceList = replaceList;
- bool isSsl = false;
- string[] tokens;
- string host = "";
-
- tokens = hostRaw.Split(':');
- if (tokens.Length >= 1)
- {
- host = tokens[0];
- }
-
- host = host.ToLower();
-
- if (tmp != null)
- {
- if (tmp.Equals("on", StringComparison.InvariantCultureIgnoreCase))
- {
- isSsl = true;
- }
- }
-
- this.IsSSL = isSsl;
- this.Host = host;
-
- this.IsUrlModified = Str.StrToBool((string)Request.Headers["SEISAPI_MODIFIED_URL"]);
- this.OriginalUrl = (string)Request.Headers["SEISAPI_ORIGINAL_URL"];
-
- int i;
- i = this.OriginalUrl.IndexOf("?");
- if (i != -1)
- {
- this.OriginalUrl = this.OriginalUrl.Substring(0, i);
- }
-
- if (Str.IsEmptyStr(this.OriginalUrl) || this.IsUrlModified == false)
- {
- this.OriginalUrl = AspUtil.RemoveDefaultHtml(AspUtil.GetCurrentRequestUrl(Page));
- }
-
- string s = (string)Request.Headers["SEISAPI_ORIGINAL_FILENAME"];
- if (Str.IsEmptyStr(s) == false)
- {
- this.IsFilenameModified = true;
- this.OriginalFileName = s;
- this.OriginalFilePath = (string)Request.Headers["SEISAPI_ORIGINAL_FILEPATH"];
- }
-
- string langCode = GetCurrentLangCodeFromPath(this.OriginalUrl);
-
- this.CurrentLanguage = CoreLanguageList.GetLanguageClassByName(langCode);
- this.CurrentLanguageCode = CurrentLanguage.Name;
-
- try
- {
- HtmlFileName = AspUtil.WebPathToFilePath(currentPage, AspUtil.GetCurrentRequestUrl(currentPage));
- }
- catch
- {
- }
-
- if (this.IsFilenameModified)
- {
- HtmlFileName = Path.Combine(Path.GetDirectoryName(HtmlFileName), Path.GetFileName(OriginalFilePath));
- }
-
- try
- {
- if (fast == false)
- {
- HtmlBody = File.ReadAllText(HtmlFileName, Str.Utf8Encoding);
- }
- }
- catch
- {
- }
-
- PhysicalUrl = AspUtil.RemoveDefaultHtml(AspUtil.GetCurrentRequestUrl((currentPage)));
-
- Args = currentPage.Request.ServerVariables["QUERY_STRING"];
-
- if (CurrentLanguage == CoreLanguageList.Japanese)
- {
- IsCurrentLanguageSupported = true;
- }
- else
- {
- IsCurrentLanguageSupported = Str.SearchStr(HtmlBody, string.Format("", CurrentLanguage.Name), 0, false) != -1;
- }
-
- GoogleTranslateUrl = string.Format("http://translate.google.com/translate?js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&sl=ja&tl={1}&u={0}",
- HttpUtility.UrlEncode((isSsl ? "https://" : "http://") + host + this.OriginalUrl, Str.Utf8Encoding),
- this.CurrentLanguageCode);
-
- OriginalFullUrl = (isSsl ? "https://" : "http://") + host + this.OriginalUrl;
-
- ContentsPrintLanguage = this.CurrentLanguage;
- if (IsCurrentLanguageSupported == false)
- {
- ContentsPrintLanguage = CoreLanguageList.Japanese;
- }
-
- if (fast == false)
- {
- mfs = new MultiLanguageFilterStream(Response.Filter, ContentsPrintLanguage, this.CurrentLanguage, this.BasicHostName, this.ReplaceList);
- mfs.Page = Page;
- Response.Filter = mfs;
- }
- }
-
- public string ConvertPath(string url)
- {
- return ConvertPath(url, this.CurrentLanguage);
- }
- public string ConvertPath(string url, CoreLanguageClass lang)
- {
- string ja = CoreLanguageList.Japanese.Name;
-
- if (url.StartsWith("/" + ja, StringComparison.InvariantCultureIgnoreCase))
- {
- url = "/" + lang.Name + url.Substring(ja.Length + 1);
- }
-
- return url;
- }
-
- public string GetPathForLanguage(CoreLanguageClass lang)
- {
- string url = PhysicalUrl;
-
- return ConvertPath(url, lang);
- }
-
- public string GetFullUrlForLanguage(CoreLanguageClass lang)
- {
- string url = (IsSSL ? "https://" : "http://") + Host + GetPathForLanguage(lang);
-
- if (Str.IsEmptyStr(Args) == false)
- {
- url += "?" + Args;
- }
-
- return url;
- }
-
- public string ProcStr(string str)
- {
- return ProcStr(str, ContentsPrintLanguage);
- }
-
- public static string ProcStrDefault(string str)
- {
- return ProcStr(str, CoreLanguageClass.CurrentThreadLanguageClass);
- }
-
- public static string ProcStr(string str, CoreLanguageClass lang)
- {
- return ProcStr(str, lang, lang);
- }
-
- public static string ProcStr(string str, CoreLanguageClass lang, CoreLanguageClass langPure)
- {
- MultiLanguageFilterStream st = new MultiLanguageFilterStream(null, lang, langPure, null, null);
-
- return st.FilterString(str);
- }
-
- public static string GetCurrentLangCodeFromPath(string str)
- {
- char[] sps =
- {
- '/', '?',
- };
- string[] tokens = str.Split(sps, StringSplitOptions.RemoveEmptyEntries);
-
- if (tokens.Length >= 1)
- {
- return tokens[0].ToLower();
- }
-
- return CoreLanguageList.Japanese.Name;
- }
-}
-
-public static class MultiString
-{
- public const string ChangeLanguage = "[j]Select Language[e]Select Language[/]";
- public const string LanguageNotSupported = "[j]申し訳ございませんが、以下のコンテンツは現在日本語で公開されていません。[e]Unfortunately, following contents are not published in English yet. [/]";
- public const string ThisIsTranslatedByMachine = "Following contents are translated automatically by Google Translate.";
- public const string GoogleTranslate = "[j]Google で翻訳[e]Click here to translate the contents into English by Google Now[/]";
- public const string ShowSrc = "Show the original page";
-
- public static string GetStr(string srcStr, CoreLanguageClass lang)
- {
- return MultiLang.ProcStr(srcStr, lang);
- }
-}
-
-public class MultiLanguageFilterStream : Stream
-{
- public static readonly List> langKeys = new List>();
- public readonly List> ReplaceList = null;
- public const string TagPure = "";
- public const string TagEndPure = "";
- public bool DisableFilter = false;
- public Page Page;
-
- static MultiLanguageFilterStream()
- {
- langKeys.Add(new KeyValuePair("[j]", CoreLanguageList.Japanese));
- langKeys.Add(new KeyValuePair("[e]", CoreLanguageList.English));
- langKeys.Add(new KeyValuePair("[/]", null));
- }
-
- Stack stack = new Stack();
- CoreLanguageClass currentBodyLanguage
- {
- get
- {
- if (stack.Count == 0)
- {
- return null;
- }
- else
- {
- return stack.ToArray()[0];
- }
- }
- }
- bool isLang(CoreLanguageClass lang)
- {
- CoreLanguageClass[] langList = stack.ToArray();
-
- foreach (CoreLanguageClass c in langList)
- {
- if (c != lang)
- {
- return false;
- }
- }
-
- return true;
- }
- CoreLanguageClass lastBodyLanguage
- {
- get
- {
- if (stack.Count == 0)
- {
- return null;
- }
- else
- {
- return stack.Peek();
- }
- }
- }
-
- public string FilterString(string src)
- {
- string[] strList = Str.DivideStringMulti(src, true,
- TagPure, TagEndPure);
-
- bool b = false;
-
- StringBuilder ret = new StringBuilder();
-
- foreach (string str in strList)
- {
- if (str == TagPure)
- {
- b = true;
- }
- else if (str == TagEndPure)
- {
- b = false;
- }
-
- ret.Append(filterStringInner(str, b ? this.currentLanguagePure : this.currentLanguage, this.currentLanguagePure));
- }
-
- return ret.ToString();
- }
-
- string filterStringInner(string src, CoreLanguageClass useLang, CoreLanguageClass useLangPure)
- {
- int i;
- string ret = src;
-
- if (Str.IsEmptyStr(basicHostName) == false)
- {
- ret = Str.ReplaceStr(ret, "=\"/\"", "=\"http://" + basicHostName + "/\"", false);
- ret = Str.ReplaceStr(ret, "=\'/\'", "=\'http://" + basicHostName + "/\'", false);
-
- ret = Str.ReplaceStr(ret, "=\"/" + CoreLanguageList.Japanese.Name + "/\"", "=\"http://" + basicHostName + "/" + useLangPure.Name + "/\"", false);
- ret = Str.ReplaceStr(ret, "=\'/" + CoreLanguageList.Japanese.Name + "/\'", "=\'http://" + basicHostName + "/" + useLangPure.Name + "/\'", false);
- }
-
- ret = Str.ReplaceStr(ret, "=\"/" + CoreLanguageList.Japanese.Name + "/", "=\"/" + useLangPure.Name + "/", false);
- ret = Str.ReplaceStr(ret, "=\'/" + CoreLanguageList.Japanese.Name + "/", "=\'/" + useLangPure.Name + "/", false);
-
- ret = Str.ReplaceStr(ret, "_lm_" + CoreLanguageList.Japanese.Name, "_lm_" + useLang.Name, false);
-
- if (this.ReplaceList != null)
- {
- foreach (KeyValuePair p in this.ReplaceList)
- {
- ret = Str.ReplaceStr(ret, p.Key, p.Value, false);
- }
- }
-
- StringBuilder ret2 = new StringBuilder();
-
- int next = 0;
- while (true)
- {
- int min = int.MaxValue;
- int j = -1;
- for (i = 0; i < langKeys.Count; i++)
- {
- int r = Str.SearchStr(ret, langKeys[i].Key, next, false);
- if (r != -1)
- {
- if (r < min)
- {
- j = i;
- min = r;
- }
- }
- }
-
- if (j != -1)
- {
- KeyValuePair v = langKeys[j];
-
- if (currentBodyLanguage == null || isLang(useLang))
- {
- ret2.Append(ret.Substring(next, min - next));
- }
-
- if (v.Value != null)
- {
- if (lastBodyLanguage == null || v.Value.Id <= lastBodyLanguage.Id)
- {
- stack.Push(v.Value);
- }
- else
- {
- stack.Pop();
- stack.Push(v.Value);
- }
- }
- else
- {
- stack.Pop();
- }
-
- next = min + v.Key.Length;
- }
- else
- {
- if (currentBodyLanguage == null || isLang(useLang))
- {
- ret2.Append(ret.Substring(next, ret.Length - next));
- }
- break;
- }
- }
-
- ret = ret2.ToString();
-
- string lang = useLangPure != CoreLanguageList.Japanese ? useLangPure.Name : "ja";
-
- if (useLangPure != CoreLanguageList.Japanese)
- {
- ret = Str.ReplaceStr(ret, "",
- string.Format("", lang), false);
- }
-
- ret = Str.ReplaceStr(ret, "", string.Format("", lang), false);
-
- next = 0;
- while (true)
- {
- i = Str.SearchStr(ret, "", next, false);
- if (j == -1)
- {
- break;
- }
- string linkStr = ret.Substring(i, j - i + 2 - 1);
- int k = Str.SearchStr(linkStr, "href=\"", 0, false);
- if (k != -1)
- {
- int m = Str.SearchStr(linkStr, "\"", k + 6, false);
- if (m != -1)
- {
- string fileName = linkStr.Substring(k + 6, m - k - 6);
- fileName = Str.ReplaceStr(fileName, ".css", "_" + lang + ".css", false);
- string linkStr2 = string.Format("", fileName);
-
- ret = ret.Substring(0, j + 2) + linkStr2 + ret.Substring(j + 2);
- next = j + 2 + linkStr2.Length;
- }
- }
- }
-
- return ret;
- }
-
- Stream baseStream;
- long position;
- CoreLanguageClass currentLanguage;
- CoreLanguageClass currentLanguagePure;
- string basicHostName;
-
- public override bool CanRead
- {
- get { return true; }
- }
-
- public override bool CanSeek
- {
- get { return true; }
- }
-
- public override bool CanWrite
- {
- get { return true; }
- }
-
- public override void Flush()
- {
- baseStream.Flush();
- }
-
- public override long Length
- {
- get { return 0; }
- }
-
- public override long Position
- {
- get
- {
- return position;
- }
- set
- {
- position = value;
- }
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- return baseStream.Seek(offset, origin);
- }
-
- public override void SetLength(long value)
- {
- baseStream.SetLength(value);
- }
-
- public MultiLanguageFilterStream(Stream baseStream, CoreLanguageClass currentLanguage, CoreLanguageClass currentLanguagePure, string basicHostName, List> replaceList)
- {
- this.baseStream = baseStream;
- this.currentLanguage = currentLanguage;
- this.currentLanguagePure = currentLanguagePure;
- this.basicHostName = basicHostName;
- this.ReplaceList = replaceList;
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- return baseStream.Read(buffer, offset, count);
- }
-
- string savedString = "";
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- if (DisableFilter)
- {
- baseStream.Write(buffer, offset, count);
- return;
- }
- byte[] data = new byte[count];
- Buffer.BlockCopy(buffer, offset, data, 0, count);
-
- string inSrc = savedString + ByteDataToString(data);// Str.Utf8Encoding.GetString(data);
-
- savedString = "";
-
- if (inSrc.Length >= 2)
- {
- int len = inSrc.Length;
- string last2 = inSrc.Substring(len - 2, 2);
- string last1 = inSrc.Substring(len - 1, 1);
-
- if (last1 == "[")
- {
- inSrc = inSrc.Substring(0, len - 1);
-
- savedString = last1;
- }
- else if (Str.InStr(last2, "["))
- {
- inSrc = inSrc.Substring(0, len - 2);
-
- savedString = last2;
- }
- }
-
- string inStr = FilterString(inSrc);
-
- data = StringToByteData(inStr);// Str.Utf8Encoding.GetBytes(inStr);
-
- if (data.Length >= 1)
- {
- baseStream.Write(data, 0, data.Length);
- //byte[] t = Str.Utf8Encoding.GetBytes("" + count.ToString() + "");
- //baseStream.Write(t, 0, t.Length);
- }
- }
-
- public static string ByteDataToString(byte[] data)
- {
- StringBuilder sb = new StringBuilder();
-
- foreach (byte b in data)
- {
- if (b <= 0x7f && b != (byte)('\\'))
- {
- sb.Append((char)b);
- }
- else
- {
- sb.Append("\\" + ((uint)b).ToString("X2"));
- }
- }
-
- return sb.ToString();
- }
-
- public byte[] StringToByteData(string str)
- {
- int i, len;
-
- len = str.Length;
- Buf b = new Buf();
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
- if (c == '\\')
- {
- string tmp = "";
-
- //try
- {
- tmp = "" + str[i + 1] + str[i + 2];
- }
- /*catch (Exception ex)
- {
- tmp += "|err=" + ex.Message + ",len=" + len + ",i=" + i + "|src=" + str + "|";
- byte[] aa = Str.Utf8Encoding.GetBytes(tmp);
- b.Write(aa);
- }*/
-
- i += 2;
-
- //try
- {
- b.WriteByte(byte.Parse(tmp, System.Globalization.NumberStyles.HexNumber));
- }
- //catch
- {
- }
- }
- else
- {
- b.WriteByte((byte)c);
- }
- }
-
- return b.ByteData;
- }
-}
-
diff --git a/src/BuildUtil/CoreUtil/Packer.cs b/src/BuildUtil/CoreUtil/Packer.cs
deleted file mode 100644
index 1b4f36b0..00000000
--- a/src/BuildUtil/CoreUtil/Packer.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- public enum PackerFileFormat
- {
- ZipRaw,
- ZipCompressed,
- Tar,
- TarGZip,
- }
-
- public delegate bool ProgressDelegate(string fileNameFullPath, string fileNameRelative, int currentFileNum, int totalFileNum);
-
- public static class Packer
- {
- public static byte[] PackDir(PackerFileFormat format, string rootDirPath, string appendPrefixDirName)
- {
- return PackDir(format, rootDirPath, appendPrefixDirName, null);
- }
- public static byte[] PackDir(PackerFileFormat format, string topDirPath, string appendPrefixDirName, ProgressDelegate proc)
- {
- string[] fileList = Directory.GetFiles(topDirPath, "*", SearchOption.AllDirectories);
- List relativeFileList = new List();
-
- foreach (string fileName in fileList)
- {
- string relativePath = IO.GetRelativeFileName(fileName, topDirPath);
-
- if (Str.IsEmptyStr(appendPrefixDirName) == false)
- {
- relativePath = IO.RemoteLastEnMark(appendPrefixDirName) + "\\" + relativePath;
- }
-
- relativeFileList.Add(relativePath);
- }
-
- return PackFiles(format, fileList, relativeFileList.ToArray(), proc);
- }
-
- public static byte[] PackFiles(PackerFileFormat format, string[] srcFileNameList, string[] relativeNameList)
- {
- return PackFiles(format, srcFileNameList, relativeNameList, null);
- }
- public static byte[] PackFiles(PackerFileFormat format, string[] srcFileNameList, string[] relativeNameList, ProgressDelegate proc)
- {
- if (srcFileNameList.Length != relativeNameList.Length)
- {
- throw new ApplicationException("srcFileNameList.Length != relativeNameList.Length");
- }
-
- int num = srcFileNameList.Length;
- int i;
-
- ZipPacker zip = new ZipPacker();
- TarPacker tar = new TarPacker();
-
- for (i = 0; i < num; i++)
- {
- if (proc != null)
- {
- bool ret = proc(srcFileNameList[i], relativeNameList[i], i, num);
-
- if (ret == false)
- {
- continue;
- }
- }
-
- byte[] srcData = File.ReadAllBytes(srcFileNameList[i]);
- DateTime date = File.GetLastWriteTime(srcFileNameList[i]);
-
- switch (format)
- {
- case PackerFileFormat.Tar:
- case PackerFileFormat.TarGZip:
- tar.AddFileSimple(relativeNameList[i], srcData, 0, srcData.Length, date);
- break;
-
- case PackerFileFormat.ZipRaw:
- case PackerFileFormat.ZipCompressed:
- zip.AddFileSimple(relativeNameList[i], date, FileAttributes.Normal, srcData, (format == PackerFileFormat.ZipCompressed));
- break;
- }
- }
-
- switch (format)
- {
- case PackerFileFormat.Tar:
- tar.Finish();
- return tar.GeneratedData.Read();
-
- case PackerFileFormat.TarGZip:
- tar.Finish();
- return tar.CompressToGZip();
-
- case PackerFileFormat.ZipCompressed:
- case PackerFileFormat.ZipRaw:
- zip.Finish();
- return zip.GeneratedData.Read();
-
- default:
- throw new ApplicationException("format");
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/RC4.cs b/src/BuildUtil/CoreUtil/RC4.cs
deleted file mode 100644
index c633109f..00000000
--- a/src/BuildUtil/CoreUtil/RC4.cs
+++ /dev/null
@@ -1,154 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-
-namespace CoreUtil
-{
- public class RC4 : ICloneable
- {
- uint x, y;
- uint[] state;
-
- public RC4(byte[] key)
- {
- state = new uint[256];
-
- uint i, t, u, ki, si;
-
- x = 0;
- y = 0;
-
- for (i = 0; i < 256; i++)
- {
- state[i] = i;
- }
-
- ki = si = 0;
- for (i = 0; i < 256; i++)
- {
- t = state[i];
-
- si = (si + key[ki] + t) & 0xff;
- u = state[si];
- state[si] = t;
- state[i] = u;
- if (++ki >= key.Length)
- {
- ki = 0;
- }
- }
- }
-
- private RC4()
- {
- }
-
- public object Clone()
- {
- RC4 rc4 = new RC4();
-
- rc4.x = this.x;
- rc4.y = this.y;
- rc4.state = (uint[])this.state.Clone();
-
- return rc4;
- }
-
- public byte[] Encrypt(byte[] src)
- {
- return Encrypt(src, src.Length);
- }
- public byte[] Encrypt(byte[] src, int len)
- {
- return Encrypt(src, 0, len);
- }
- public byte[] Encrypt(byte[] src, int offset, int len)
- {
- byte[] dst = new byte[len];
-
- uint x, y, sx, sy;
- x = this.x;
- y = this.y;
-
- int src_i = 0, dst_i = 0, end_src_i;
-
- for (end_src_i = src_i + len; src_i != end_src_i; src_i++, dst_i++)
- {
- x = (x + 1) & 0xff;
- sx = state[x];
- y = (sx + y) & 0xff;
- state[x] = sy = state[y];
- state[y] = sx;
- dst[dst_i] = (byte)(src[src_i + offset] ^ state[(sx + sy) & 0xff]);
- }
-
- this.x = x;
- this.y = y;
-
- return dst;
- }
- public void SkipDecrypt(int len)
- {
- SkipEncrypt(len);
- }
- public void SkipEncrypt(int len)
- {
- uint x, y, sx, sy;
- x = this.x;
- y = this.y;
-
- int src_i = 0, dst_i = 0, end_src_i;
-
- for (end_src_i = src_i + len; src_i != end_src_i; src_i++, dst_i++)
- {
- x = (x + 1) & 0xff;
- sx = state[x];
- y = (sx + y) & 0xff;
- state[x] = sy = state[y];
- state[y] = sx;
- }
-
- this.x = x;
- this.y = y;
- }
-
- public byte[] Decrypt(byte[] src)
- {
- return Decrypt(src, src.Length);
- }
- public byte[] Decrypt(byte[] src, int len)
- {
- return Decrypt(src, 0, len);
- }
- public byte[] Decrypt(byte[] src, int offset, int len)
- {
- return Encrypt(src, offset, len);
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/ReadIni.cs b/src/BuildUtil/CoreUtil/ReadIni.cs
deleted file mode 100644
index f71b651d..00000000
--- a/src/BuildUtil/CoreUtil/ReadIni.cs
+++ /dev/null
@@ -1,235 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-
-namespace CoreUtil
-{
- class IniCache
- {
- static Dictionary caches = new Dictionary();
-
- class IniCacheEntry
- {
- DateTime lastUpdate;
- public DateTime LastUpdate
- {
- get { return lastUpdate; }
- }
-
- Dictionary datas;
- public Dictionary Datas
- {
- get { return datas; }
- }
-
- public IniCacheEntry(DateTime lastUpdate, Dictionary datas)
- {
- this.lastUpdate = lastUpdate;
- this.datas = datas;
- }
- }
-
- public static Dictionary GetCache(string filename, DateTime lastUpdate)
- {
- lock (caches)
- {
- try
- {
- IniCacheEntry e = caches[filename];
- if (e.LastUpdate == lastUpdate || lastUpdate.Ticks == 0)
- {
- return e.Datas;
- }
- else
- {
- return null;
- }
- }
- catch
- {
- return null;
- }
- }
- }
-
- public static void AddCache(string filename, DateTime lastUpdate, Dictionary datas)
- {
- lock (caches)
- {
- if (caches.ContainsKey(filename))
- {
- caches.Remove(filename);
- }
-
- caches.Add(filename, new IniCacheEntry(lastUpdate, datas));
- }
- }
- }
-
- public class ReadIni
- {
- Dictionary datas;
- bool updated;
-
- public bool Updated
- {
- get
- {
- return updated;
- }
- }
-
- public StrData this[string key]
- {
- get
- {
- string s;
- try
- {
- s = datas[key.ToUpper()];
- }
- catch
- {
- s = null;
- }
-
- return new StrData(s);
- }
- }
-
- public string[] GetKeys()
- {
- List ret = new List();
-
- foreach (string s in datas.Keys)
- {
- ret.Add(s);
- }
-
- return ret.ToArray();
- }
-
- public ReadIni(string filename)
- {
- init(null, filename);
- }
-
- void init(byte[] data)
- {
- init(data, null);
- }
- void init(byte[] data, string filename)
- {
- updated = false;
-
- lock (typeof(ReadIni))
- {
- string[] lines;
- string srcstr;
- DateTime lastUpdate = new DateTime(0);
-
- if (filename != null)
- {
- lastUpdate = IO.GetLastWriteTimeUtc(filename);
-
- datas = IniCache.GetCache(filename, lastUpdate);
- }
-
- if (datas == null)
- {
- if (data == null)
- {
- try
- {
- data = Buf.ReadFromFile(filename).ByteData;
- }
- catch
- {
- data = new byte[0];
- datas = IniCache.GetCache(filename, new DateTime());
- }
- }
-
- if (datas == null)
- {
- datas = new Dictionary();
- Encoding currentEncoding = Str.Utf8Encoding;
- srcstr = currentEncoding.GetString(data);
-
- lines = Str.GetLines(srcstr);
-
- foreach (string s in lines)
- {
- string line = s.Trim();
-
- if (Str.IsEmptyStr(line) == false)
- {
- if (line.StartsWith("#") == false &&
- line.StartsWith("//") == false &&
- line.StartsWith(";") == false)
- {
- string key, value;
-
- if (Str.GetKeyAndValue(line, out key, out value))
- {
- key = key.ToUpper();
-
- if (datas.ContainsKey(key) == false)
- {
- datas.Add(key, value);
- }
- else
- {
- int i;
- for (i = 1; ; i++)
- {
- string key2 = string.Format("{0}({1})", key, i).ToUpper();
-
- if (datas.ContainsKey(key2) == false)
- {
- datas.Add(key2, value);
- break;
- }
- }
- }
- }
- }
- }
- }
-
- if (filename != null)
- {
- IniCache.AddCache(filename, lastUpdate, datas);
- }
-
- updated = true;
- }
- }
- }
- }
- }
-}
-
diff --git a/src/BuildUtil/CoreUtil/Reg.cs b/src/BuildUtil/CoreUtil/Reg.cs
deleted file mode 100644
index b3c1b669..00000000
--- a/src/BuildUtil/CoreUtil/Reg.cs
+++ /dev/null
@@ -1,466 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using Microsoft.Win32;
-
-namespace CoreUtil
-{
- public class AppReg
- {
- string appSubKey;
- public string AppSubKey
- {
- get { return appSubKey; }
- }
- RegRoot rootKey;
- public RegRoot RootKey
- {
- get { return rootKey; }
- }
-
- public AppReg(RegRoot root, string subkey)
- {
- subkey = subkey.TrimEnd('\\');
- this.rootKey = root;
- this.appSubKey = subkey;
- }
-
- public AppReg GetSubReg(string subKeyName)
- {
- return new AppReg(rootKey, appSubKey + "\\" + subKeyName);
- }
-
- public bool WriteStr(string name, string value)
- {
- return Reg.WriteStr(rootKey, appSubKey, name, value);
- }
-
- public bool WriteInt(string name, int value)
- {
- return Reg.WriteInt(rootKey, appSubKey, name, value);
- }
-
- public bool WriteStrList(string name, string[] values)
- {
- return Reg.WriteStrList(rootKey, appSubKey, name, values);
- }
-
- public bool WriteByte(string name, byte[] data)
- {
- return Reg.WriteByte(rootKey, appSubKey, name, data);
- }
-
- public bool DeleteValue(string name)
- {
- return Reg.DeleteValue(rootKey, appSubKey, name);
- }
-
- public string ReadStr(string name)
- {
- return Reg.ReadStr(rootKey, appSubKey, name);
- }
-
- public int ReadInt(string name)
- {
- return Reg.ReadInt(rootKey, appSubKey, name);
- }
-
- public string[] ReadStrList(string name)
- {
- return Reg.ReadStrList(rootKey, appSubKey, name);
- }
-
- public byte[] ReadByte(string name)
- {
- return Reg.ReadByte(rootKey, appSubKey, name);
- }
- }
-
- public enum RegRoot
- {
- LocalMachine = 0,
- CurrentUser = 1,
- Users = 2,
- }
-
- public static class Reg
- {
- static RegistryKey rootKey(RegRoot r)
- {
- switch (r)
- {
- case RegRoot.LocalMachine:
- return Registry.LocalMachine;
-
- case RegRoot.CurrentUser:
- return Registry.CurrentUser;
-
- case RegRoot.Users:
- return Registry.Users;
- }
-
- throw new ArgumentException();
- }
-
- public static string[] EnumValue(RegRoot root, string keyname)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname);
-
- if (key == null)
- {
- return new string[0];
- }
-
- try
- {
- return key.GetValueNames();
- }
- finally
- {
- key.Close();
- }
- }
- catch
- {
- return new string[0];
- }
- }
-
- public static string[] EnumKey(RegRoot root, string keyname)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname);
-
- if (key == null)
- {
- return new string[0];
- }
-
- try
- {
- return key.GetSubKeyNames();
- }
- finally
- {
- key.Close();
- }
- }
- catch
- {
- return new string[0];
- }
- }
-
- public static bool WriteByte(RegRoot root, string keyname, string valuename, byte[] data)
- {
- return WriteValue(root, keyname, valuename, data);
- }
-
- public static byte[] ReadByte(RegRoot root, string keyname, string valuename)
- {
- object o = ReadValue(root, keyname, valuename);
- if (o == null)
- {
- return new byte[0];
- }
-
- try
- {
- return (byte[])o;
- }
- catch
- {
- return new byte[0];
- }
- }
-
- public static bool WriteInt(RegRoot root, string keyname, string valuename, int value)
- {
- return WriteValue(root, keyname, valuename, value);
- }
-
- public static int ReadInt(RegRoot root, string keyname, string valuename)
- {
- object o = ReadValue(root, keyname, valuename);
- if (o == null)
- {
- return 0;
- }
-
- try
- {
- return (int)o;
- }
- catch
- {
- return 0;
- }
- }
-
- public static bool WriteStrList(RegRoot root, string keyname, string valuename, string[] value)
- {
- return WriteValue(root, keyname, valuename, value);
- }
-
- public static string[] ReadStrList(RegRoot root, string keyname, string valuename)
- {
- object o = ReadValue(root, keyname, valuename);
- if (o == null)
- {
- return new string[0];
- }
-
- try
- {
- return (string[])o;
- }
- catch
- {
- return new string[0];
- }
- }
-
- public static bool WriteStr(RegRoot root, string keyname, string valuename, string value)
- {
- return WriteValue(root, keyname, valuename, value);
- }
-
- public static string ReadStr(RegRoot root, string keyname, string valuename)
- {
- object o = ReadValue(root, keyname, valuename);
- if (o == null)
- {
- return "";
- }
-
- try
- {
- return (string)o;
- }
- catch
- {
- return "";
- }
- }
-
- public static bool WriteValue(RegRoot root, string keyname, string valuename, object o)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname, true);
-
- if (key == null)
- {
- key = rootKey(root).CreateSubKey(keyname);
-
- if (key == null)
- {
- return false;
- }
- }
-
- try
- {
- key.SetValue(valuename, o);
-
- return true;
- }
- catch
- {
- return false;
- }
- finally
- {
- key.Close();
- }
- }
- catch
- {
- return false;
- }
- }
-
- public static object ReadValue(RegRoot root, string keyname, string valuename)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname);
-
- if (key == null)
- {
- return null;
- }
-
- try
- {
- return key.GetValue(valuename);
- }
- finally
- {
- key.Close();
- }
- }
- catch
- {
- return null;
- }
- }
-
- public static bool IsValue(RegRoot root, string keyname, string valuename)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname);
-
- try
- {
- object o = key.GetValue(valuename);
-
- if (o == null)
- {
- return false;
- }
- }
- finally
- {
- key.Close();
- }
-
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public static bool DeleteValue(RegRoot root, string keyname, string valuename)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(keyname, true);
-
- if (key == null)
- {
- return false;
- }
-
- try
- {
- key.DeleteValue(valuename);
-
- return true;
- }
- finally
- {
- key.Close();
- }
- }
- catch
- {
- return false;
- }
- }
-
- public static bool DeleteKey(RegRoot root, string keyname)
- {
- return DeleteKey(root, keyname, false);
- }
- public static bool DeleteKey(RegRoot root, string keyname, bool deleteAll)
- {
- try
- {
- if (deleteAll == false)
- {
- rootKey(root).DeleteSubKey(keyname);
- }
- else
- {
- rootKey(root).DeleteSubKeyTree(keyname);
- }
-
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public static bool NewKey(RegRoot root, string keyname)
- {
- if (IsKey(root, keyname))
- {
- return true;
- }
-
- try
- {
- RegistryKey key = rootKey(root).CreateSubKey(keyname);
-
- if (key == null)
- {
- return false;
- }
-
- key.Close();
-
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public static bool IsKey(RegRoot root, string name)
- {
- try
- {
- RegistryKey key = rootKey(root).OpenSubKey(name);
-
- if (key == null)
- {
- return false;
- }
-
- key.Close();
-
- return true;
- }
- catch
- {
- return false;
- }
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Secure.cs b/src/BuildUtil/CoreUtil/Secure.cs
deleted file mode 100644
index 8d6ca942..00000000
--- a/src/BuildUtil/CoreUtil/Secure.cs
+++ /dev/null
@@ -1,958 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Web.Mail;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- public class CommonSign
- {
- byte[] keyData;
- static uint init_dummy = CryptoConfigHelper.Init();
-
- public CommonSign(byte[] key)
- {
- init(key);
- }
- public CommonSign(Buf buf)
- {
- init(buf.ByteData);
- }
- public CommonSign(string filename)
- {
- init(Buf.ReadFromFile(filename).ByteData);
- }
- void init(byte[] key)
- {
- keyData = (byte[])key.Clone();
- }
-
- public byte[] Sign(byte[] data)
- {
- Buf b = new Buf(data);
- b.SeekToEnd();
- b.Write(keyData);
-
- return Secure.HashSHA1(b.ByteData);
- }
- public bool Verify(byte[] data, byte[] sign)
- {
- byte[] sign2 = Sign(data);
-
- return Util.CompareByte(sign, sign2);
- }
- }
-
- public class Rsa
- {
- byte[] data;
- Cert cert;
- static uint init_dummy = CryptoConfigHelper.Init();
- static object lockObj = new object();
-
- public Rsa(byte[] data)
- {
- init(data);
- }
- public Rsa(string filename)
- {
- Buf b = Buf.ReadFromFile(filename);
- init(b.ByteData);
- }
- public Rsa(Buf b)
- {
- init(b.ByteData);
- }
- void init(byte[] data)
- {
- this.data = (byte[])data.Clone();
- this.cert = null;
-
- Cert.deleteOldTempFiles();
- }
-
- public Rsa(Cert cert)
- {
- init(cert);
- }
- void init(Cert cert)
- {
- this.cert = (Cert)cert.Clone();
- this.data = null;
-
- Cert.deleteOldTempFiles();
- }
-
- public byte[] SignData(byte[] data)
- {
- lock (lockObj)
- {
- byte[] ret;
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- ret = rsa.SignData(data);
- }
- return ret;
- }
- }
-
- public byte[] SignHash(byte[] hash)
- {
- lock (lockObj)
- {
- byte[] ret;
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- ret = rsa.SignHash(hash);
- }
- return ret;
- }
- }
-
- public bool VerifyData(byte[] data, byte[] sign)
- {
- lock (lockObj)
- {
- bool ret;
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- ret = rsa.VerifyData(data, sign);
- }
- return ret;
- }
- }
-
- public bool VerifyHash(byte[] hash, byte[] sign)
- {
- lock (lockObj)
- {
- bool ret;
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- ret = rsa.VerifyHash(hash, sign);
- }
- return ret;
- }
- }
-
- public byte[] Encrypt(byte[] data)
- {
- lock (lockObj)
- {
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- return rsa.Encrypt(data);
- }
- }
- }
-
- public byte[] Decrypt(byte[] data)
- {
- lock (lockObj)
- {
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- return rsa.Decrypt(data);
- }
- }
- }
-
- public int KeySizeBit
- {
- get
- {
- lock (lockObj)
- {
- using (RsaInner rsa = new RsaInner(this.data, this.cert))
- {
- return rsa.KeySizeBit;
- }
- }
- }
- }
- }
-
- class RsaInner : IDisposable
- {
- static string sha1rsa = CryptoConfig.MapNameToOID("SHA1");
- RSACryptoServiceProvider rsa;
- static object lockObj = new Object();
- static LocalDataStoreSlot slot = Thread.AllocateDataSlot();
- static LocalDataStoreSlot slot2 = Thread.AllocateDataSlot();
- static uint init_dummy = CryptoConfigHelper.Init();
-
- public static void Lock()
- {
- }
-
- public static void Unlock()
- {
- }
-
- public RsaInner(byte[] data, Cert cert)
- {
- if (data != null)
- {
- init(data);
- }
- else
- {
- init(cert);
- }
- }
- public RsaInner(byte[] data)
- {
- init(data);
- }
- public RsaInner(string filename)
- {
- Buf b = Buf.ReadFromFile(filename);
- init(b.ByteData);
- }
- public RsaInner(Buf b)
- {
- init(b.ByteData);
- }
- void init(byte[] data)
- {
- Lock();
- rsa = readRsaPrivate(data);
- }
-
- public RsaInner(Cert cert)
- {
- init(cert);
- }
- void init(Cert cert)
- {
- Lock();
- string text1 = cert.X509Cert.GetKeyAlgorithm();
- byte[] buffer1 = cert.X509Cert.GetKeyAlgorithmParameters();
- byte[] buffer2 = cert.X509Cert.GetPublicKey();
- Oid oid1 = new Oid("1.2.840.113549.1.1.1", "RSA");
-
- rsa = (RSACryptoServiceProvider)(new PublicKey(oid1, new AsnEncodedData(oid1, buffer1), new AsnEncodedData(oid1, buffer2))).Key;
- }
-
- public byte[] SignData(byte[] data)
- {
- byte[] hash = Secure.HashSHA1(data);
- return SignHash(hash);
- }
-
- public byte[] SignHash(byte[] hash)
- {
- byte[] ret = null;
- ret = rsa.SignHash(hash, sha1rsa);
-
- return ret;
- }
-
- public bool VerifyData(byte[] data, byte[] sign)
- {
- byte[] hash = Secure.HashSHA1(data);
- return VerifyHash(hash, sign);
- }
-
- public bool VerifyHash(byte[] hash, byte[] sign)
- {
- return rsa.VerifyHash(hash, sha1rsa, sign);
- }
-
- public byte[] Encrypt(byte[] data)
- {
- return rsa.Encrypt(data, false);
- }
-
- public byte[] Decrypt(byte[] data)
- {
- return rsa.Decrypt(data, false);
- }
-
- static RSACryptoServiceProvider readRsaPrivate(byte[] data)
- {
- // From http://forums.l-space-design.com/blogs/day_of_the_developer/archive/2006/06/08/216.aspx
- string t = Str.AsciiEncoding.GetString(data);
- if (!t.StartsWith("-----BEGIN RSA PRIVATE KEY-----"))
- {
- throw new ArgumentException("Not an RSA Private Key");
- }
- t = t.Substring("-----BEGIN RSA PRIVATE KEY-----".Length);
- t = t.Substring(0, t.IndexOf("----"));
- t = t.Replace("\r", "").Replace("\n", "");
- byte[] byteArray = System.Convert.FromBase64String(t);
- System.IO.MemoryStream s = new MemoryStream(byteArray);
- BinaryReader binr = new BinaryReader(s, Str.AsciiEncoding);
- byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
- // --------- Set up stream to decode the asn.1 encoded RSA private key ------
- byte bt = 0;
- ushort twobytes = 0;
- int elems = 0;
- RSAParameters result = new RSAParameters();
- try
- {
- twobytes = binr.ReadUInt16();
- if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
- binr.ReadByte(); //advance 1 byte
- else if (twobytes == 0x8230)
- binr.ReadInt16(); //advance 2 bytes
- else
- return null;
- twobytes = binr.ReadUInt16();
- if (twobytes != 0x0102) //version number
- return null;
- bt = binr.ReadByte();
- if (bt != 0x00)
- return null;
- //------ all private key components are Integer sequences ----
- elems = getIntegerSize(binr);
- MODULUS = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- E = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- D = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- P = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- Q = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- DP = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- DQ = binr.ReadBytes(elems);
- elems = getIntegerSize(binr);
- IQ = binr.ReadBytes(elems);
- result.Modulus = MODULUS;
- result.Exponent = E;
- result.D = D;
- result.P = P;
- result.Q = Q;
- result.DP = DP;
- result.DQ = DQ;
- result.InverseQ = IQ;
- }
- catch (Exception)
- {
- return null;
- }
- finally
- {
- binr.Close();
- }
- CspParameters cp = new CspParameters();
- cp.Flags = CspProviderFlags.UseMachineKeyStore;
- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cp);
- RSA.PersistKeyInCsp = false;
- RSA.ImportParameters(result);
- return RSA;
- }
-
- static int getIntegerSize(BinaryReader binr)
- {
- byte bt = 0;
- byte lowbyte = 0x00;
- byte highbyte = 0x00;
- int count = 0;
- bt = binr.ReadByte();
- if (bt != 0x02) //expect integer
- return 0;
- bt = binr.ReadByte();
- if (bt == 0x81)
- count = binr.ReadByte(); // data size in next byte
- else
- if (bt == 0x82)
- {
- highbyte = binr.ReadByte(); // data size in next 2 bytes
- lowbyte = binr.ReadByte();
- byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
- count = BitConverter.ToInt32(modint, 0);
- }
- else
- {
- count = bt; // we already have the data size
- }
- while (binr.PeekChar() == 0x00)
- { //remove high order zeros in data
- binr.ReadByte();
- count -= 1;
- }
- return count;
- }
-
- public void Dispose()
- {
- rsa.Clear();
- rsa = null;
- Unlock();
- }
-
- public int KeySizeBit
- {
- get
- {
- return rsa.KeySize;
- }
- }
- }
-
- public class Cert
- {
- X509Certificate2 x509;
- static TimeSpan deleteOldCertSpan = new TimeSpan(0, 0, 30);
- static object lockObj = new Object();
- static RSACryptoServiceProvider rsaDummy = null;
- static uint init_dummy = CryptoConfigHelper.Init();
-
- public int KeySizeBit
- {
- get
- {
- Rsa r = new Rsa(this);
-
- return r.KeySizeBit;
- }
- }
-
- public X509Certificate2 X509Cert
- {
- get { return x509; }
- }
-
- public Rsa RsaPublicKey
- {
- get
- {
- return new Rsa(this);
- }
- }
-
- public Cert(byte[] data)
- {
- init(data);
- }
- public Cert(string filename)
- {
- init(IO.ReadFile(filename));
- }
- public Cert(Buf buf)
- {
- init(buf.ByteData);
- }
- void init(byte[] data)
- {
- deleteOldTempFiles();
- x509 = new X509Certificate2(data);
-
- if (rsaDummy == null)
- {
- rsaDummy = (RSACryptoServiceProvider)(new X509Certificate2(data).PublicKey.Key);
- }
- }
-
- public byte[] Hash
- {
- get
- {
- return x509.GetCertHash();
- }
- }
-
- public byte[] PublicKey
- {
- get
- {
- return x509.GetPublicKey();
- }
- }
-
- public byte[] ByteData
- {
- get
- {
- return x509.Export(X509ContentType.Cert);
- }
- }
- public Buf ToBuf()
- {
- return new Buf(ByteData);
- }
- public void ToFile(string filename)
- {
- ToBuf().WriteToFile(filename);
- }
-
- public Cert Clone()
- {
- return new Cert(this.ByteData);
- }
-
- static DateTime lastDeletedDateTime = new DateTime();
- static readonly TimeSpan deleteTimeSpan = new TimeSpan(0, 1, 0);
- internal static void deleteOldTempFiles()
- {
- lock (lockObj)
- {
- DateTime now = Time.NowDateTime;
-
- if (lastDeletedDateTime.Ticks == 0 ||
- now >= (lastDeletedDateTime + deleteTimeSpan))
- {
- lastDeletedDateTime = now;
-
- string tempDir = Path.GetTempPath();
- string[] files = Directory.GetFiles(tempDir);
-
- if (files != null)
- {
- foreach (string name in files)
- {
- try
- {
- if (Str.StrCmpi(Path.GetExtension(name), ".tmp") && Path.GetFileName(name).StartsWith("tmp", StringComparison.CurrentCultureIgnoreCase))
- {
- DateTime dt = File.GetLastWriteTimeUtc(name);
- if ((DateTime.UtcNow - dt) >= deleteOldCertSpan)
- {
- FileInfo info = new FileInfo(name);
-
- if (info.Length == 0)
- {
- try
- {
- File.Delete(name);
- }
- catch
- {
- }
- }
- }
- }
- }
- catch
- {
- }
- }
- }
- }
- }
- }
- }
-
- public class Secure
- {
- static RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
- static MD5 md5 = new MD5CryptoServiceProvider();
- static uint init_dummy = CryptoConfigHelper.Init();
- public const uint SHA1Size = 20;
- public const uint MD5Size = 16;
- static object rand_lock = new object();
-
- public static byte[] Rand(uint size)
- {
- lock (rand_lock)
- {
- byte[] ret = new byte[size];
- rng.GetBytes(ret);
- return ret;
- }
- }
- public static uint Rand32()
- {
- return BitConverter.ToUInt32(Rand(4), 0);
- }
- public static ulong Rand64()
- {
- return BitConverter.ToUInt64(Rand(8), 0);
- }
- public static ushort Rand16()
- {
- return BitConverter.ToUInt16(Rand(2), 0);
- }
- public static int Rand32i()
- {
- return BitConverter.ToInt32(Rand(4), 0);
- }
- public static long Rand64i()
- {
- return BitConverter.ToInt64(Rand(8), 0);
- }
- public static short Rand16i()
- {
- return BitConverter.ToInt16(Rand(2), 0);
- }
- public static int Rand31i()
- {
- while (true)
- {
- int i = Rand32i();
- if (i >= 0)
- {
- return i;
- }
- }
- }
- public static long Rand63i()
- {
- while (true)
- {
- long i = Rand64i();
- if (i >= 0)
- {
- return i;
- }
- }
- }
- public static short Rand15i()
- {
- while (true)
- {
- short i = Rand16i();
- if (i >= 0)
- {
- return i;
- }
- }
- }
- public static byte Rand8()
- {
- return Rand(1)[0];
- }
- public static bool Rand1()
- {
- return (Rand32() % 2) == 0;
- }
-
- // MD5
- public static byte[] HashMD5(byte[] data)
- {
- byte[] ret;
-
- RsaInner.Lock();
- try
- {
- ret = md5.ComputeHash(data);
- }
- finally
- {
- RsaInner.Unlock();
- }
-
- return ret;
- }
-
- // SHA1
- public static byte[] HashSHA1(byte[] data)
- {
- SHA1 sha1 = new SHA1Managed();
-
- return sha1.ComputeHash(data);
- }
-
- // SHA256
- public static byte[] HashSHA256(byte[] data)
- {
- SHA256 sha256 = new SHA256Managed();
-
- return sha256.ComputeHash(data);
- }
-
- public static byte[] PkcsPadding(byte[] srcData, int destSize)
- {
- int srcSize = srcData.Length;
-
- if ((srcSize + 11) > destSize)
- {
- throw new OverflowException();
- }
-
- int randSize = destSize - srcSize - 3;
- byte[] rand = Secure.Rand((uint)randSize);
-
- Buf b = new Buf();
- b.WriteByte(0x00);
- b.WriteByte(0x02);
- b.Write(rand);
- b.WriteByte(0x00);
- b.Write(srcData);
-
- return b.ByteData;
- }
- }
-
- public class CryptoConfigHelper
- {
- static object objLock = new Object();
- static bool flag = false;
-
- public static uint Init()
- {
- try
- {
- lock (objLock)
- {
- if (flag == false)
- {
- flag = true;
- Type t = typeof(CryptoConfig);
- Hashtable ht = (Hashtable)t.InvokeMember("DefaultOidHT", System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static,
- null, null, null);
- List values = new List();
-
- foreach (string key in ht.Keys)
- {
- string value = (string)ht[key];
-
- values.Add(value);
- }
-
- foreach (string s in values)
- {
- ht.Add(s, s);
- }
- }
- }
- }
- catch
- {
- }
-
- return 0;
- }
- }
-
- public static class ExeSignChecker
- {
- public static bool IsKernelModeSignedFile(string fileName)
- {
- return IsKernelModeSignedFile(File.ReadAllBytes(fileName));
- }
-
- public static bool IsKernelModeSignedFile(byte[] data)
- {
- string str = Str.AsciiEncoding.GetString(data);
-
- if (str.IndexOf("Microsoft Code Verification Root") != -1 &&
- str.IndexOf("http://crl.microsoft.com/pki/crl/products/MicrosoftCodeVerifRoot.crl") != -1)
- {
- return true;
- }
-
- return false;
- }
-
- enum SignChecker_MemoryAllocator { HGlobal, CoTaskMem };
- enum SignChecker_UiChoice { All = 1, NoUI, NoBad, NoGood };
- enum SignChecker_StateAction { Ignore = 0, Verify, Close, AutoCache, AutoCacheFlush };
- enum SignChecker_UnionChoice { File = 1, Catalog, Blob, Signer, Cert };
- enum SignChecker_RevocationCheckFlags { None = 0, WholeChain };
- enum SignChecker_TrustProviderFlags
- {
- UseIE4Trust = 1,
- NoIE4Chain = 2,
- NoPolicyUsage = 4,
- RevocationCheckNone = 16,
- RevocationCheckEndCert = 32,
- RevocationCheckChain = 64,
- RevocationCheckChainExcludeRoot = 128,
- Safer = 256,
- HashOnly = 512,
- UseDefaultOSVerCheck = 1024,
- LifetimeSigning = 2048
- };
- enum SignChecker_UIContext { Execute = 0, Install };
-
- [DllImport("Wintrust.dll", PreserveSig = true, SetLastError = false)]
- static extern uint WinVerifyTrust(IntPtr hWnd, IntPtr pgActionID, IntPtr pWinTrustData);
-
- sealed class SignCheckerUnmanagedPointer : IDisposable
- {
- private IntPtr m_ptr;
- private SignChecker_MemoryAllocator m_meth;
- public SignCheckerUnmanagedPointer(IntPtr ptr, SignChecker_MemoryAllocator method)
- {
- m_meth = method;
- m_ptr = ptr;
- }
-
- ~SignCheckerUnmanagedPointer()
- {
- Dispose(false);
- }
-
- void Dispose(bool disposing)
- {
- if (m_ptr != IntPtr.Zero)
- {
- if (m_meth == SignChecker_MemoryAllocator.HGlobal)
- {
- Marshal.FreeHGlobal(m_ptr);
- }
- else if (m_meth == SignChecker_MemoryAllocator.CoTaskMem)
- {
- Marshal.FreeCoTaskMem(m_ptr);
- }
- m_ptr = IntPtr.Zero;
- }
-
- if (disposing)
- {
- GC.SuppressFinalize(this);
- }
- }
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- public static implicit operator IntPtr(SignCheckerUnmanagedPointer ptr)
- {
- return ptr.m_ptr;
- }
- }
-
- struct WINTRUST_FILE_INFO : IDisposable
- {
- public WINTRUST_FILE_INFO(string fileName, Guid subject)
- {
- cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO));
- pcwszFilePath = fileName;
-
- if (subject != Guid.Empty)
- {
- tmp = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid)));
- Marshal.StructureToPtr(subject, tmp, false);
- }
- else
- {
- tmp = IntPtr.Zero;
- }
- hFile = IntPtr.Zero;
- }
- public uint cbStruct;
- [MarshalAs(UnmanagedType.LPTStr)]
- public string pcwszFilePath;
- public IntPtr hFile;
- public IntPtr tmp;
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- private void Dispose(bool disposing)
- {
- if (tmp != IntPtr.Zero)
- {
- Marshal.DestroyStructure(this.tmp, typeof(Guid));
- Marshal.FreeHGlobal(this.tmp);
- }
- }
- }
-
- [StructLayout(LayoutKind.Sequential)]
- struct WINTRUST_DATA : IDisposable
- {
- public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
- {
- this.cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA));
- pInfoStruct = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));
- Marshal.StructureToPtr(fileInfo, pInfoStruct, false);
- dwUnionChoice = SignChecker_UnionChoice.File;
- pPolicyCallbackData = IntPtr.Zero;
- pSIPCallbackData = IntPtr.Zero;
- dwUIChoice = SignChecker_UiChoice.NoUI;
- fdwRevocationChecks = SignChecker_RevocationCheckFlags.WholeChain;
- dwStateAction = SignChecker_StateAction.Ignore;
- hWVTStateData = IntPtr.Zero;
- pwszURLReference = IntPtr.Zero;
- dwProvFlags = SignChecker_TrustProviderFlags.RevocationCheckChain;
-
- dwUIContext = SignChecker_UIContext.Execute;
- }
-
- public uint cbStruct;
- public IntPtr pPolicyCallbackData;
- public IntPtr pSIPCallbackData;
- public SignChecker_UiChoice dwUIChoice;
- public SignChecker_RevocationCheckFlags fdwRevocationChecks;
- public SignChecker_UnionChoice dwUnionChoice;
- public IntPtr pInfoStruct;
- public SignChecker_StateAction dwStateAction;
- public IntPtr hWVTStateData;
- private IntPtr pwszURLReference;
- public SignChecker_TrustProviderFlags dwProvFlags;
- public SignChecker_UIContext dwUIContext;
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- private void Dispose(bool disposing)
- {
- if (dwUnionChoice == SignChecker_UnionChoice.File)
- {
- WINTRUST_FILE_INFO info = new WINTRUST_FILE_INFO();
- Marshal.PtrToStructure(pInfoStruct, info);
- info.Dispose();
- Marshal.DestroyStructure(pInfoStruct, typeof(WINTRUST_FILE_INFO));
- }
-
- Marshal.FreeHGlobal(pInfoStruct);
- }
- }
-
- public static bool CheckFileDigitalSignature(string fileName)
- {
- Guid wintrust_action_generic_verify_v2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
- WINTRUST_FILE_INFO fileInfo = new WINTRUST_FILE_INFO(fileName, Guid.Empty);
- WINTRUST_DATA data = new WINTRUST_DATA(fileInfo);
-
- uint ret = 0;
-
- using (SignCheckerUnmanagedPointer guidPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid))), SignChecker_MemoryAllocator.HGlobal))
- using (SignCheckerUnmanagedPointer wvtDataPtr = new SignCheckerUnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_DATA))), SignChecker_MemoryAllocator.HGlobal))
- {
- IntPtr pGuid = guidPtr;
- IntPtr pData = wvtDataPtr;
-
- Marshal.StructureToPtr(wintrust_action_generic_verify_v2, pGuid, false);
- Marshal.StructureToPtr(data, pData, false);
-
- ret = WinVerifyTrust(IntPtr.Zero, pGuid, pData);
- }
-
- if (ret != 0)
- {
- return false;
- }
-
- return true;
- }
- }
-}
-
-
diff --git a/src/BuildUtil/CoreUtil/Stb.cs b/src/BuildUtil/CoreUtil/Stb.cs
deleted file mode 100644
index 7fe4a627..00000000
--- a/src/BuildUtil/CoreUtil/Stb.cs
+++ /dev/null
@@ -1,281 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using System.Net.Mail;
-using System.Net.Mime;
-using System.Reflection;
-using CoreUtil;
-
-namespace CoreUtil
-{
- public class Stb
- {
- Dictionary entryList;
-
- public string this[string name]
- {
- get
- {
- if (entryList.ContainsKey(name.ToUpper()))
- {
- return entryList[name.ToUpper()].String;
- }
- else
- {
- return "";
- }
- }
- }
-
- public Stb(string filename)
- {
- init(IO.ReadFile(filename));
- }
-
- public Stb(byte[] data)
- {
- init(data);
- }
-
- void init(byte[] data)
- {
- entryList = new Dictionary();
- MemoryStream ms = new MemoryStream(data);
- StreamReader sr = new StreamReader(ms);
- string prefix = "";
-
- while (true)
- {
- string tmp = sr.ReadLine();
- if (tmp == null)
- {
- break;
- }
-
- StbEntry t = StbEntry.ParseTableLine(tmp, ref prefix);
- if (t != null)
- {
- if (entryList.ContainsKey(t.Name.ToUpper()) == false)
- {
- entryList.Add(t.Name.ToUpper(), t);
- }
- }
- }
- }
-
- const string standardStbFileName = "|strtable.stb";
- static string defaultStbFileName = standardStbFileName;
- static object lockObj = new object();
- static Stb defaultStb = null;
- public static string DefaultStbFileName
- {
- set
- {
- defaultStbFileName = value;
- }
-
- get
- {
- return defaultStbFileName;
- }
- }
- public static Stb DefaultStb
- {
- get
- {
- lock (lockObj)
- {
- if (defaultStb == null)
- {
- defaultStb = new Stb(Stb.DefaultStbFileName);
- }
-
- return defaultStb;
- }
- }
- }
- public static string SS(string name)
- {
- return DefaultStb[name];
- }
- public static uint II(string name)
- {
- return Str.StrToUInt(SS(name));
- }
- }
-
- public class StbEntry
- {
- string name;
- public string Name
- {
- get { return name; }
- }
-
- string str;
- public string String
- {
- get { return str; }
- }
-
- public StbEntry(string name, string str)
- {
- this.name = name;
- this.str = str;
- }
- public static StbEntry ParseTableLine(string line, ref string prefix)
- {
- int i, len;
- int string_start;
- int len_name;
- string name, name2;
-
- line = line.TrimStart(' ', '\t');
- len = line.Length;
- if (len == 0)
- {
- return null;
- }
-
- if (line[0] == '#' || (line[0] == '/' && line[1] == '/'))
- {
- return null;
- }
-
- bool b = false;
- len_name = 0;
- for (i = 0; i < line.Length; i++)
- {
- if (line[i] == ' ' || line[i] == '\t')
- {
- b = true;
- break;
- }
- len_name++;
- }
-
- if (b == false)
- {
- return null;
- }
-
- name = line.Substring(0, len_name);
-
- string_start = len_name;
- for (i = len_name; i < len; i++)
- {
- if (line[i] != ' ' && line[i] != '\t')
- {
- break;
- }
- string_start++;
- }
- if (i == len)
- {
- return null;
- }
-
- string str = line.Substring(string_start);
-
- str = UnescapeStr(str);
-
- if (Str.StrCmpi(name, "PREFIX"))
- {
- prefix = str;
- prefix = prefix.TrimStart();
-
- if (Str.StrCmpi(prefix, "$") || Str.StrCmpi(prefix, "NULL"))
- {
- prefix = "";
- }
-
- return null;
- }
-
- name2 = "";
-
- if (prefix != "")
- {
- name2 += prefix + "@";
- }
-
- name2 += name;
-
- return new StbEntry(name2, str);
- }
-
- public static string UnescapeStr(string str)
- {
- int i, len;
- string tmp;
-
- len = str.Length;
- tmp = "";
-
- for (i = 0; i < len; i++)
- {
- if (str[i] == '\\')
- {
- i++;
- switch (str[i])
- {
- case '\\':
- tmp += '\\';
- break;
-
- case ' ':
- tmp += ' ';
- break;
-
- case 'n':
- case 'N':
- tmp += '\n';
- break;
-
- case 'r':
- case 'R':
- tmp += '\r';
- break;
-
- case 't':
- case 'T':
- tmp += '\t';
- break;
- }
- }
- else
- {
- tmp += str[i];
- }
- }
-
- return tmp;
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Str.cs b/src/BuildUtil/CoreUtil/Str.cs
deleted file mode 100644
index 8caeeee6..00000000
--- a/src/BuildUtil/CoreUtil/Str.cs
+++ /dev/null
@@ -1,4306 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Runtime.Serialization.Formatters.Soap;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Xml;
-using System.Xml.Serialization;
-using System.Web.Mail;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- [FlagsAttribute]
- public enum PrintFFLags
- {
- Minus = 1,
- Plus = 2,
- Zero = 4,
- Blank = 8,
- Sharp = 16,
- }
-
- public class PrintFParsedParam
- {
- public bool Ok = false;
- public readonly PrintFFLags Flags = 0;
- public readonly int Width = 0;
- public readonly int Precision = 0;
- public readonly bool NoPrecision = true;
- public readonly string Type = "";
-
- static PrintFFLags charToFlag(char c)
- {
- switch (c)
- {
- case '-':
- return PrintFFLags.Minus;
-
- case '+':
- return PrintFFLags.Plus;
-
- case '0':
- return PrintFFLags.Zero;
-
- case ' ':
- return PrintFFLags.Blank;
-
- case '#':
- return PrintFFLags.Sharp;
- }
-
- return 0;
- }
-
- public string GetString(object param)
- {
- int i;
- StringBuilder sb;
- string tmp = "(error)";
- double f;
- bool signed = false;
-
- switch (this.Type)
- {
- case "c":
- case "C":
- if (param is char)
- {
- tmp += (char)param;
- }
- else if (param is string)
- {
- string s = (string)param;
- if (s.Length >= 1)
- {
- tmp += s[0];
- }
- }
- break;
-
- case "d":
- case "i":
- sb = new StringBuilder();
- int count = this.Width;
- if (this.Precision != 0)
- {
- count = this.Precision;
- }
- for (i = 1; i < this.Precision; i++)
- {
- sb.Append("#");
- }
- sb.Append("0");
-
- if (param is int)
- {
- tmp = ((int)param).ToString(sb.ToString());
- }
- else if (param is long)
- {
- tmp = ((long)param).ToString(sb.ToString());
- }
- else if (param is uint)
- {
- tmp = ((int)((uint)param)).ToString(sb.ToString());
- }
- else if (param is ulong)
- {
- tmp = ((long)((ulong)param)).ToString(sb.ToString());
- }
- else if (param is decimal)
- {
- tmp = ((decimal)param).ToString(sb.ToString());
- }
- signed = true;
-
- break;
-
- case "u":
- sb = new StringBuilder();
- for (i = 1; i < this.Precision; i++)
- {
- sb.Append("#");
- }
- sb.Append("0");
-
- if (param is int)
- {
- tmp = ((uint)((int)param)).ToString(sb.ToString());
- }
- else if (param is long)
- {
- tmp = ((ulong)((long)param)).ToString(sb.ToString());
- }
- else if (param is uint)
- {
- tmp = ((uint)param).ToString(sb.ToString());
- }
- else if (param is ulong)
- {
- tmp = ((ulong)param).ToString(sb.ToString());
- }
- else if (param is decimal)
- {
- tmp = ((decimal)param).ToString(sb.ToString());
- }
-
- break;
-
- case "x":
- case "X":
- sb = new StringBuilder();
- sb.Append(this.Type);
- sb.Append(this.Precision.ToString());
-
- if (param is int)
- {
- tmp = ((uint)((int)param)).ToString(sb.ToString());
- }
- else if (param is long)
- {
- tmp = ((ulong)((long)param)).ToString(sb.ToString());
- }
- else if (param is uint)
- {
- tmp = ((uint)param).ToString(sb.ToString());
- }
- else if (param is ulong)
- {
- tmp = ((ulong)param).ToString(sb.ToString());
- }
-
- break;
-
- case "e":
- case "E":
- case "f":
- f = 0;
-
- if (param is int)
- {
- f = (double)((int)param);
- }
- else if (param is long)
- {
- f = (double)((long)param);
- }
- else if (param is uint)
- {
- f = (double)((uint)param);
- }
- else if (param is ulong)
- {
- f = (double)((ulong)param);
- }
- else if (param is decimal)
- {
- f = (double)((long)param);
- }
- else if (param is float)
- {
- f = (double)((float)param);
- }
- else if (param is double)
- {
- f = (double)param;
- }
- else
- {
- break;
- }
-
- int prectmp = Precision;
- if (prectmp == 0 && NoPrecision)
- {
- prectmp = 6;
- }
-
- tmp = f.ToString(string.Format("{0}{1}", Type, prectmp));
-
- break;
-
- case "s":
- case "S":
- if (param == null)
- {
- tmp = "(null)";
- }
- else
- {
- tmp = param.ToString();
- }
- break;
- }
-
- int normalWidth = Str.GetStrWidth(tmp);
- int targetWidth = Math.Max(this.Width, normalWidth);
-
- if ((this.Flags & PrintFFLags.Plus) != 0)
- {
- if (signed)
- {
- if (tmp.StartsWith("-") == false)
- {
- tmp = "+" + tmp;
- }
- }
- }
- else
- {
- if ((this.Flags & PrintFFLags.Blank) != 0)
- {
- if (signed)
- {
- if (tmp.StartsWith("-") == false)
- {
- tmp = " " + tmp;
- }
- }
- }
- }
-
- if ((this.Flags & PrintFFLags.Minus) != 0)
- {
- int w = targetWidth - Str.GetStrWidth(tmp);
- if (w < 0)
- {
- w = 0;
- }
-
- tmp += Str.MakeCharArray(' ', w);
- }
- else if ((this.Flags & PrintFFLags.Zero) != 0)
- {
- int w = targetWidth - Str.GetStrWidth(tmp);
- if (w < 0)
- {
- w = 0;
- }
-
- tmp = Str.MakeCharArray('0', w) + tmp;
- }
- else
- {
- int w = targetWidth - Str.GetStrWidth(tmp);
- if (w < 0)
- {
- w = 0;
- }
-
- tmp = Str.MakeCharArray(' ', w) + tmp;
- }
-
- if ((this.Flags & PrintFFLags.Sharp) != 0)
- {
- if (Type == "x" || Type == "X")
- {
- tmp = "0x" + tmp;
- }
- }
-
- return tmp;
- }
-
- public PrintFParsedParam(string str)
- {
- Str.NormalizeString(ref str);
-
- if (str.StartsWith("%") == false)
- {
- return;
- }
-
- str = str.Substring(1);
-
- Queue q = new Queue();
- foreach (char c in str)
- {
- q.Enqueue(c);
- }
-
- while (q.Count >= 1)
- {
- char c = q.Peek();
- PrintFFLags f = charToFlag(c);
-
- if (f == 0)
- {
- break;
- }
-
- this.Flags |= f;
- q.Dequeue();
- }
-
- Queue q2 = new Queue();
-
- while (q.Count >= 1)
- {
- bool bf = false;
- char c = q.Peek();
-
- switch (c)
- {
- case 'h':
- case 'l':
- case 'I':
- case 'c':
- case 'C':
- case 'd':
- case 'i':
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
- case 'n':
- case 'p':
- case 's':
- case 'S':
- bf = true;
- break;
-
- default:
- q2.Enqueue(c);
- break;
- }
-
- if (bf)
- {
- break;
- }
-
- q.Dequeue();
- }
-
- string[] widthAndPrec = (new string(q2.ToArray())).Split('.');
-
- if (widthAndPrec.Length == 1)
- {
- this.Width = Str.StrToInt(widthAndPrec[0]);
- }
- else if (widthAndPrec.Length == 2)
- {
- this.Width = Str.StrToInt(widthAndPrec[0]);
- this.Precision = Str.StrToInt(widthAndPrec[1]);
- this.NoPrecision = false;
- }
-
- this.Width = Math.Max(this.Width, 0);
- this.Precision = Math.Max(this.Precision, 0);
-
-
- while (q.Count >= 1)
- {
- char c = q.Peek();
- bool bf = false;
-
- switch (c)
- {
- case 'c':
- case 'C':
- case 'd':
- case 'i':
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
- case 'a':
- case 'A':
- case 'n':
- case 'p':
- case 's':
- case 'S':
- bf = true;
- break;
-
- default:
- break;
- }
-
- if (bf)
- {
- break;
- }
-
- q.Dequeue();
- }
-
- this.Type = new string(q.ToArray());
- if (this.Type.Length >= 1)
- {
- this.Type = this.Type.Substring(0, 1);
- }
-
- this.Ok = (Str.IsEmptyStr(this.Type) == false);
- }
- }
-
- public class StrEqualityComparer : IEqualityComparer
- {
- bool caseSensitive;
-
- public StrEqualityComparer()
- {
- this.caseSensitive = false;
- }
-
- public StrEqualityComparer(bool caseSensitive)
- {
- this.caseSensitive = caseSensitive;
- }
-
- public bool Equals(string x, string y)
- {
- return x.Equals(y, caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase);
- }
-
- public int GetHashCode(string obj)
- {
- return obj.GetHashCode();
- }
- }
-
-
- public class StrComparer : IComparer
- {
- bool caseSensitive;
-
- public StrComparer()
- {
- this.caseSensitive = false;
- }
-
- public StrComparer(bool caseSensitive)
- {
- this.caseSensitive = caseSensitive;
- }
-
- public int Compare(string x, string y)
- {
- return string.Compare(x, y, !caseSensitive);
- }
- }
-
- public delegate bool RemoveStringFunction(string str);
-
- public static class Str
- {
- public static string NormalizeStrSoftEther(string str)
- {
- return NormalizeStrSoftEther(str, false);
- }
- public static string NormalizeStrSoftEther(string str, bool trim)
- {
- bool b = false;
- StringReader sr = new StringReader(str);
- StringWriter sw = new StringWriter();
- while (true)
- {
- string line = sr.ReadLine();
- if (line == null)
- {
- break;
- }
- if (b)
- {
- sw.WriteLine();
- }
- b = true;
- line = normalizeStrSoftEtherInternal(line);
- sw.Write(line);
- }
-
- int len = str.Length;
-
- try
- {
- if (str[len - 1] == '\n' || str[len - 1] == '\r')
- {
- sw.WriteLine();
- }
- }
- catch
- {
- }
-
- str = sw.ToString();
-
- if (trim)
- {
- str = str.Trim();
- }
-
- return str;
- }
- static string normalizeStrSoftEtherInternal(string str)
- {
- if (str.Trim().Length == 0)
- {
- return "";
- }
-
- int i;
- StringBuilder sb1 = new StringBuilder();
- for (i = 0; i < str.Length; i++)
- {
- char c = str[i];
-
- if (c == ' ' || c == ' ' || c == '\t')
- {
- sb1.Append(c);
- }
- else
- {
- break;
- }
- }
- string str2 = str.Substring(i).Trim();
-
- string str1 = sb1.ToString();
-
- str1 = ReplaceStr(str1, " ", " ");
- str1 = ReplaceStr(str1, "\t", " ");
-
- return str1 + normalizeStrSoftEtherInternal2(str2);
- }
- static string normalizeStrSoftEtherInternal2(string str)
- {
- NormalizeString(ref str, true, true, false, true);
- char[] chars = str.ToCharArray();
- StringBuilder sb = new StringBuilder();
-
- int i;
- for (i = 0; i < chars.Length; i++)
- {
- char c = chars[i];
- bool insert_space = false;
- bool insert_space2 = false;
-
- char c1 = (char)0;
- if (i >= 1)
- {
- c1 = chars[i - 1];
- }
-
- char c2 = (char)0;
- if (i < (chars.Length - 1))
- {
- c2 = chars[i + 1];
- }
-
- if (c == '\'' || c1 == '\'' || c2 == '\'' || c == '\"' || c1 == '\"' || c2 == '\"' || c == '>' || c1 == '>' || c2 == '>' || c == '<' || c1 == '<' || c2 == '<')
- {
- }
- else if (c == '(' || c == '[' || c == '{' || c == '<')
- {
- if (c1 != '「' && c1 != '『' && c1 != '。' && c1 != '、' && c1 != '・')
- {
- insert_space = true;
- }
- }
- else if (c == ')' || c == ']' || c == '}' || c == '>')
- {
- if (c2 != '.' && c2 != ',' && c2 != '。' && c2 != '、')
- {
- insert_space2 = true;
- }
- }
- else if (c == '~')
- {
- if (c1 != '~')
- {
- insert_space = true;
- }
-
- if (c2 != '~')
- {
- insert_space2 = true;
- }
- }
- else if (IsZenkaku(c) == false)
- {
- if (IsZenkaku(c1))
- {
- if (c != '.' && c != ',' && c != ';' && c != ':' && c1 != '※' && c1 != '〒' && c1 != '℡' && c1 != '「' && c1 != '『' && c1 != '。' && c1 != '、' && c1 != '・')
- {
- insert_space = true;
- }
- }
- }
- else
- {
- if (IsZenkaku(c1) == false)
- {
- if (c != '。' && c != '、' && c != '」' && c != '』' && c != '・' && c1 != '(' && c1 != '[' && c1 != '{' && c1 != '<' && c1 != ';' && c1 != ':')
- {
- insert_space = true;
- }
- }
- }
-
- if (insert_space)
- {
- sb.Append(' ');
- }
-
- sb.Append(c);
-
- if (insert_space2)
- {
- sb.Append(' ');
- }
- }
-
- str = sb.ToString();
-
- NormalizeString(ref str, true, true, false, true);
-
- return str;
- }
-
- public static bool IsZenkaku(char c)
- {
- return !((c >= (char)0) && (c <= (char)256));
- }
-
- public static string[] DivideStringMulti(string str, bool caseSensitive, params string[] keywords)
- {
- List ret = new List();
- int next = 0;
-
- while (true)
- {
- int foundIndex;
- string foundKeyword;
- int r = Str.SearchStrMulti(str, next, caseSensitive, out foundIndex, out foundKeyword, keywords);
- if (r == -1)
- {
- ret.Add(str.Substring(next));
- break;
- }
- else
- {
- ret.Add(str.Substring(next, r - next));
- ret.Add(foundKeyword);
- next = r + foundKeyword.Length;
- }
- }
-
- return ret.ToArray();
- }
-
- public static bool IsSuitableEncodingForString(string str, Encoding enc)
- {
- try
- {
- str = Str.NormalizeCrlf(str);
-
- byte[] utf1 = Str.Utf8Encoding.GetBytes(str);
-
- byte[] b = enc.GetBytes(str);
- string str2 = enc.GetString(b);
-
- byte[] utf2 = Str.Utf8Encoding.GetBytes(str2);
-
- return Util.CompareByte(utf1, utf2);
- }
- catch
- {
- return false;
- }
- }
-
- public static bool IsCharNumOrAlpha(char c)
- {
- if (c >= 'a' && c <= 'z')
- {
- return true;
- }
- if (c >= 'A' && c <= 'Z')
- {
- return true;
- }
- if (c >= '0' && c <= '9')
- {
- return true;
- }
- return false;
- }
- public static bool IsStringNumOrAlpha(string s)
- {
- foreach (char c in s)
- {
- if (IsCharNumOrAlpha(c) == false)
- {
- return false;
- }
- }
- return true;
- }
-
- public static string[] StrToStrLineBySplitting(string str)
- {
- StringReader r = new StringReader(str);
- List ret = new List();
-
- while (true)
- {
- string line = r.ReadLine();
- if (line == null)
- {
- break;
- }
-
- if (IsEmptyStr(line) == false)
- {
- ret.Add(line.Trim());
- }
- }
-
- return ret.ToArray();
- }
-
- public static string GetLeft(string str, int len)
- {
- if (str == null)
- {
- return null;
- }
- if (str.Length > len)
- {
- return str.Substring(0, len);
- }
- else
- {
- return str;
- }
- }
-
- public static string[] SplitStringForSearch(string str)
- {
- bool b = false;
- int i, len;
- len = str.Length;
- List ret = new List();
- string currentStr = "";
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
-
- if (c == '\"')
- {
- b = !b;
- if (b == false)
- {
- currentStr = currentStr.Trim();
- if (Str.IsEmptyStr(currentStr) == false)
- {
- ret.Add(currentStr);
- currentStr = "";
- }
- }
- }
- else
- {
- if (b == false && (c == ' ' || c == ' ' || c == '\t'))
- {
- currentStr = currentStr.Trim();
- if (Str.IsEmptyStr(currentStr) == false)
- {
- ret.Add(currentStr);
- currentStr = "";
- }
- }
- else
- {
- currentStr += c;
- }
- }
- }
-
- currentStr = currentStr.Trim();
- if (Str.IsEmptyStr(currentStr) == false)
- {
- ret.Add(currentStr);
- }
-
- return ret.ToArray();
- }
-
- public static string AppendZeroToNumString(string str, int numKeta)
- {
- int n = numKeta - str.Length;
-
- if (n >= 1)
- {
- return MakeCharArray('0', n) + str;
- }
- else
- {
- return str;
- }
- }
-
- public static Encoding CheckBOM(byte[] data)
- {
- int i;
- return CheckBOM(data, out i);
- }
- public static Encoding CheckBOM(byte[] data, out int bomNumBytes)
- {
- bomNumBytes = 0;
- try
- {
- if (data[0] == 0x00 && data[1] == 0x00 && data[2] == 0xfe && data[3] == 0xff)
- {
- bomNumBytes = 3;
- return Encoding.GetEncoding("utf-32BE");
- }
- else if (data[0] == 0xff && data[1] == 0xfe && data[2] == 0x00 && data[3] == 0x00)
- {
- bomNumBytes = 4;
- return Encoding.GetEncoding("utf-32");
- }
- else if (data[0] == 0xff && data[1] == 0xfe)
- {
- bomNumBytes = 2;
- return Encoding.GetEncoding("utf-16");
- }
- else if (data[0] == 0xfe && data[1] == 0xff)
- {
- bomNumBytes = 2;
- return Encoding.GetEncoding("unicodeFFFE");
- }
- else if (data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf)
- {
- bomNumBytes = 3;
- return Encoding.GetEncoding("utf-8");
- }
- else
- {
- return null;
- }
- }
- catch
- {
- return null;
- }
- }
-
- public static byte[] GetBOM(Encoding encoding)
- {
- if (Str.StrCmpi(encoding.BodyName, "utf-32BE"))
- {
- return new byte[] { 0x00, 0x00, 0xfe, 0xff };
- }
- else if (Str.StrCmpi(encoding.BodyName, "utf-32"))
- {
- return new byte[] {0xff, 0xfe, 0x00, 0x00 };
- }
- else if (Str.StrCmpi(encoding.BodyName, "utf-16"))
- {
- return new byte[] { 0xff, 0xfe };
- }
- else if (Str.StrCmpi(encoding.BodyName, "unicodeFFFE"))
- {
- return new byte[] { 0xfe, 0xff };
- }
- else if (Str.StrCmpi(encoding.BodyName, "utf-8"))
- {
- return new byte[] { 0xef, 0xbb, 0xbf };
- }
- else
- {
- return null;
- }
- }
-
- public static byte[] ConvertEncoding(byte[] srcData, Encoding destEncoding)
- {
- return ConvertEncoding(srcData, destEncoding, false);
- }
- public static byte[] ConvertEncoding(byte[] srcData, Encoding destEncoding, bool appendBom)
- {
- Encoding srcEncoding = GetEncoding(srcData);
- if (srcEncoding == null)
- {
- srcEncoding = Str.ShiftJisEncoding;
- }
-
- int nb;
- if (CheckBOM(srcData, out nb) != null)
- {
- srcData = Util.RemoveStartByteArray(srcData, nb);
- }
-
- string str = srcEncoding.GetString(srcData);
-
- byte[] b1 = null;
- if (appendBom)
- {
- b1 = GetBOM(destEncoding);
- }
- byte[] b2 = destEncoding.GetBytes(str);
-
- return Util.CombineByteArray(b1, b2);
- }
-
- public static string ReadTextFile(string filename)
- {
- byte[] data = IO.ReadFileData(filename);
- int bomSize = 0;
-
- Encoding enc = GetEncoding(data, out bomSize);
- if (enc == null)
- {
- enc = Str.Utf8Encoding;
- }
- if (bomSize >= 1)
- {
- data = Util.CopyByte(data, bomSize);
- }
-
- return enc.GetString(data);
- }
-
- public static void WriteTextFile(string filename, Encoding enc, bool writeBom)
- {
- Buf buf = new Buf();
- byte[] bom = GetBOM(enc);
- if (writeBom && bom != null && bom.Length >= 1)
- {
- buf.Write(bom);
- }
- buf.Write(enc.GetBytes(filename));
-
- buf.SeekToBegin();
-
- File.WriteAllBytes(filename, buf.Read());
- }
-
- public static Encoding GetEncoding(byte[] data)
- {
- int i;
- return GetEncoding(data, out i);
- }
- public static Encoding GetEncoding(byte[] data, out int bomSize)
- {
- const byte bESC = 0x1B;
- const byte bAT = 0x40;
- const byte bDollar = 0x24;
- const byte bAnd = 0x26;
- const byte bOP = 0x28;
- const byte bB = 0x42;
- const byte bD = 0x44;
- const byte bJ = 0x4A;
- const byte bI = 0x49;
- bomSize = 0;
-
- int len = data.Length;
- int binary = 0;
- int ucs2 = 0;
- int sjis = 0;
- int euc = 0;
- int utf8 = 0;
- byte b1, b2;
-
- Encoding bomEncoding = CheckBOM(data, out bomSize);
- if (bomEncoding != null)
- {
- return bomEncoding;
- }
-
- for (int i = 0; i < len; i++)
- {
- if (data[i] <= 0x06 || data[i] == 0x7F || data[i] == 0xFF)
- {
- //'binary'
- binary++;
- if (len - 1 > i && data[i] == 0x00
- && i > 0 && data[i - 1] <= 0x7F)
- {
- //smells like raw unicode
- ucs2++;
- }
- }
- }
-
-
- if (binary > 0)
- {
- if (ucs2 > 0)
- {
- //JIS
- //ucs2(Unicode)
-
- int n1 = 0, n2 = 0;
- for (int i = 0; i < (len / 2); i++)
- {
- byte e1 = data[i * 2];
- byte e2 = data[i * 2 + 1];
-
- if (e1 == 0 && e2 != 0)
- {
- n1++;
- }
- else if (e1 != 0 && e2 == 0)
- {
- n2++;
- }
- }
-
- if (n1 > n2)
- {
- return Encoding.GetEncoding("unicodeFFFE");
- }
- else
- {
- return System.Text.Encoding.Unicode;
- }
- }
- else
- {
- //binary
- return null;
- }
- }
-
- for (int i = 0; i < len - 1; i++)
- {
- b1 = data[i];
- b2 = data[i + 1];
-
- if (b1 == bESC)
- {
- if (b2 >= 0x80)
- //not Japanese
- //ASCII
- return System.Text.Encoding.ASCII;
- else if (len - 2 > i &&
- b2 == bDollar && data[i + 2] == bAT)
- //JIS_0208 1978
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- else if (len - 2 > i &&
- b2 == bDollar && data[i + 2] == bB)
- //JIS_0208 1983
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- else if (len - 5 > i &&
- b2 == bAnd && data[i + 2] == bAT && data[i + 3] == bESC &&
- data[i + 4] == bDollar && data[i + 5] == bB)
- //JIS_0208 1990
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- else if (len - 3 > i &&
- b2 == bDollar && data[i + 2] == bOP && data[i + 3] == bD)
- //JIS_0212
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- else if (len - 2 > i &&
- b2 == bOP && (data[i + 2] == bB || data[i + 2] == bJ))
- //JIS_ASC
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- else if (len - 2 > i &&
- b2 == bOP && data[i + 2] == bI)
- //JIS_KANA
- //JIS
- return System.Text.Encoding.GetEncoding(50220);
- }
- }
-
- for (int i = 0; i < len - 1; i++)
- {
- b1 = data[i];
- b2 = data[i + 1];
- if (((b1 >= 0x81 && b1 <= 0x9F) || (b1 >= 0xE0 && b1 <= 0xFC)) &&
- ((b2 >= 0x40 && b2 <= 0x7E) || (b2 >= 0x80 && b2 <= 0xFC)))
- {
- sjis += 2;
- i++;
- }
- }
- for (int i = 0; i < len - 1; i++)
- {
- b1 = data[i];
- b2 = data[i + 1];
- if (((b1 >= 0xA1 && b1 <= 0xFE) && (b2 >= 0xA1 && b2 <= 0xFE)) ||
- (b1 == 0x8E && (b2 >= 0xA1 && b2 <= 0xDF)))
- {
- euc += 2;
- i++;
- }
- else if (len - 2 > i &&
- b1 == 0x8F && (b2 >= 0xA1 && b2 <= 0xFE) &&
- (data[i + 2] >= 0xA1 && data[i + 2] <= 0xFE))
- {
- euc += 3;
- i += 2;
- }
- }
- for (int i = 0; i < len - 1; i++)
- {
- b1 = data[i];
- b2 = data[i + 1];
- if ((b1 >= 0xC0 && b1 <= 0xDF) && (b2 >= 0x80 && b2 <= 0xBF))
- {
- utf8 += 2;
- i++;
- }
- else if (len - 2 > i &&
- (b1 >= 0xE0 && b1 <= 0xEF) && (b2 >= 0x80 && b2 <= 0xBF) &&
- (data[i + 2] >= 0x80 && data[i + 2] <= 0xBF))
- {
- utf8 += 3;
- i += 2;
- }
- }
-
- if (euc > sjis && euc > utf8)
- //EUC
- return System.Text.Encoding.GetEncoding(51932);
- else if (sjis > euc && sjis > utf8)
- //SJIS
- return System.Text.Encoding.GetEncoding(932);
- else if (utf8 > euc && utf8 > sjis)
- //UTF8
- return System.Text.Encoding.UTF8;
-
- return null;
- }
-
- public static bool StartsWithMulti(string str, StringComparison comp, params string[] keys)
- {
- NormalizeString(ref str);
-
- foreach (string key in keys)
- {
- if (str.StartsWith(key, comp))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool IsCharForMail(char c)
- {
- switch (c)
- {
- case '<':
- case '>':
- case ' ':
- case ';':
- case ':':
- case '/':
- case '(':
- case ')':
- case '&':
- case ',':
- case '%':
- case '$':
- case '#':
- case '\"':
- case '\'':
- case '!':
- case '=':
- case '\\':
- return false;
- }
-
- if (c >= 0x80)
- {
- return false;
- }
-
- if (IsAscii(c) == false)
- {
- return false;
- }
-
- return true;
- }
-
- public static string LinkMailtoOnText(string text)
- {
- NormalizeString(ref text);
-
- StringBuilder sb = new StringBuilder();
-
- string tmp = "";
-
- int i;
- for (i = 0; i < text.Length; i++)
- {
- char c = text[i];
-
- if (IsCharForMail(c) == false)
- {
- if (Str.CheckMailAddress(tmp) == false)
- {
- tmp += c;
- sb.Append(tmp);
- tmp = "";
- }
- else
- {
- sb.AppendFormat("{0}", tmp);
- sb.Append(c);
- tmp = "";
- }
- }
- else
- {
- tmp += c;
- }
- }
- if (Str.CheckMailAddress(tmp) == false)
- {
- sb.Append(tmp);
- tmp = "";
- }
- else
- {
- sb.AppendFormat("{0}", tmp);
- tmp = "";
- }
-
- return sb.ToString();
- }
-
- public static string LinkUrlOnText(string text, string target)
- {
- int findStart = 0;
-
- NormalizeString(ref text);
- NormalizeString(ref target);
-
- StringBuilder sb = new StringBuilder();
-
- while (true)
- {
- int foundStrIndex;
- int foundIndex = FindStrings(text, findStart, StringComparison.InvariantCultureIgnoreCase, out foundStrIndex,
- "http://", "https://", "ftp://", "telnet://", "mailto://", "news://");
-
- if (foundIndex != -1)
- {
- int i;
- int endOfUrl = -1;
- for (i = foundIndex; i < text.Length; i++)
- {
- char c = text[i];
-
- if (IsValidForUrl(c) == false)
- {
- endOfUrl = i;
- break;
- }
-
- if (c == '<' || c == '&')
- {
- if (StartsWithMulti(text.Substring(i), StringComparison.InvariantCultureIgnoreCase,
- HtmlSpacing, HtmlCrlf, HtmlBr, HtmlLt, HtmlGt))
- {
- endOfUrl = i;
- break;
- }
- }
- }
-
- if (endOfUrl == -1)
- {
- endOfUrl = text.Length;
- }
-
- string url = text.Substring(foundIndex, endOfUrl - foundIndex);
- string beforeUrl = text.Substring(findStart, foundIndex - findStart);
-
- sb.Append(beforeUrl);
-
- if (Str.IsEmptyStr(target) == false)
- {
- sb.AppendFormat("{1}", url, url, target);
- }
- else
- {
- sb.AppendFormat("{1}", url, url);
- }
-
- findStart = endOfUrl;
- }
- else
- {
- sb.Append(text.Substring(findStart));
-
- break;
- }
- }
-
- return LinkMailtoOnText(sb.ToString());
- }
-
- public static int FindStrings(string str, int findStartIndex, StringComparison comp, out int foundKeyIndex, params string[] keys)
- {
- int ret = -1;
- foundKeyIndex = -1;
- int n = 0;
-
- foreach (string key in keys)
- {
- int i = str.IndexOf(key, findStartIndex, comp);
-
- if (i != -1)
- {
- if (ret == -1)
- {
- ret = i;
- foundKeyIndex = n;
- }
- else
- {
- if (ret > i)
- {
- ret = i;
- foundKeyIndex = n;
- }
- }
- }
-
- n++;
- }
-
- return ret;
- }
-
- public static bool IsValidForUrl(char c)
- {
- if (c >= '0' && c <= '9')
- {
- return true;
- }
- if (c >= 'a' && c <= 'z')
- {
- return true;
- }
- if (c >= 'A' && c <= 'Z')
- {
- return true;
- }
- switch (c)
- {
- case '_':
- case '-':
- case '?':
- case '!':
- case '\"':
- case ',':
- case '\'':
- case '/':
- case '\\':
- case '&':
- case ';':
- case '%':
- case '#':
- case '@':
- case '~':
- case ':':
- case '=':
- case '+':
- case '*':
- case '$':
- case '.':
- return true;
- }
-
- return false;
- }
-
- public static List RemoteStringFromList(List str, RemoveStringFunction func)
- {
- List ret = new List();
-
- foreach (string s in str)
- {
- if (func(s) == false)
- {
- ret.Add(s);
- }
- }
-
- return ret;
- }
-
- public const string ConstZenkaku = "`{}0123456789/*-+!”#$%&’()= ̄|¥[]@;:<>?_^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘";
- public const string ConstHankaku = "`{}0123456789/*-+!\"#$%&'()=~|\\[]@;:<>?_^ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'";
- public const string ConstKanaZenkaku = "ー「」アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァゥェォャュョッィ゛゜";
- public const string ConstKanaHankaku = "ー「」アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァゥェォャュョッィ゙゚";
-
- public static void RemoveSpace(ref string str)
- {
- NormalizeString(ref str);
-
- str = str.Replace(" ", "").Replace(" ", "").Replace("\t", "");
- }
-
- public static void TrimStartWith(ref string str, string key, StringComparison sc)
- {
- if (str.StartsWith(key, sc))
- {
- str = str.Substring(key.Length);
- }
- }
-
- public static void TrimEndsWith(ref string str, string key, StringComparison sc)
- {
- if (str.EndsWith(key, sc))
- {
- str = str.Substring(0, str.Length - key.Length);
- }
- }
-
- public static void RemoveSpaceChar(ref string str)
- {
- if (Str.IsEmptyStr(str))
- {
- return;
- }
-
- StringBuilder sb = new StringBuilder();
-
- foreach (char c in str)
- {
- if (c == ' ' || c == '\t' || c == ' ')
- {
- }
- else
- {
- sb.Append(c);
- }
- }
-
- str = sb.ToString();
- }
-
- public static void NormalizeStringStandard(ref string str)
- {
- NormalizeString(ref str, true, true, false, true);
- }
- public static void NormalizeString(ref string str, bool space, bool toHankaku, bool toZenkaku, bool toZenkakuKana)
- {
- NormalizeString(ref str);
-
- if (space)
- {
- str = NormalizeSpace(str);
- }
-
- if (toHankaku)
- {
- str = ZenkakuToHankaku(str);
- }
-
- if (toZenkaku)
- {
- str = HankakuToZenkaku(str);
- }
-
- if (toZenkakuKana)
- {
- str = KanaHankakuToZenkaku(str);
- }
- }
-
- public static string NormalizeSpace(string str)
- {
- NormalizeString(ref str);
- char[] sps =
- {
- ' ', ' ', '\t',
- };
-
- string[] tokens = str.Split(sps, StringSplitOptions.RemoveEmptyEntries);
-
- return Str.CombineStringArray(tokens, " ");
- }
-
- public static string KanaHankakuToZenkaku(string str)
- {
- NormalizeString(ref str);
-
- str = str.Replace("ガ", "ガ");
- str = str.Replace("ギ", "ギ");
- str = str.Replace("グ", "グ");
- str = str.Replace("ゲ", "ゲ");
- str = str.Replace("ゴ", "ゴ");
- str = str.Replace("ザ", "ザ");
- str = str.Replace("ジ", "ジ");
- str = str.Replace("ズ", "ズ");
- str = str.Replace("ゼ", "ゼ");
- str = str.Replace("ゾ", "ゾ");
- str = str.Replace("ダ", "ダ");
- str = str.Replace("ヂ", "ヂ");
- str = str.Replace("ヅ", "ヅ");
- str = str.Replace("デ", "デ");
- str = str.Replace("ド", "ド");
- str = str.Replace("バ", "バ");
- str = str.Replace("ビ", "ビ");
- str = str.Replace("ブ", "ブ");
- str = str.Replace("ベ", "ベ");
- str = str.Replace("ボ", "ボ");
-
- char[] a = str.ToCharArray();
- int i;
- for (i = 0; i < a.Length; i++)
- {
- int j = ConstKanaHankaku.IndexOf(a[i]);
-
- if (j != -1)
- {
- a[i] = ConstKanaZenkaku[j];
- }
- }
-
- return new string(a);
- }
-
- public static string ZenkakuToHankaku(string str)
- {
- NormalizeString(ref str);
-
- str = ReplaceStr(str, "“", " \"");
- str = ReplaceStr(str, "”", "\" ");
- str = ReplaceStr(str, "‘", "'");
- str = ReplaceStr(str, "’", "'");
-
- char[] a = str.ToCharArray();
- int i;
- for (i = 0; i < a.Length; i++)
- {
- int j = ConstZenkaku.IndexOf(a[i]);
-
- if (j != -1)
- {
- a[i] = ConstHankaku[j];
- }
- }
-
- return new string(a);
- }
-
- public static string HankakuToZenkaku(string str)
- {
- NormalizeString(ref str);
-
- str = KanaHankakuToZenkaku(str);
-
- char[] a = str.ToCharArray();
- int i;
- for (i = 0; i < a.Length; i++)
- {
- int j = ConstHankaku.IndexOf(a[i]);
-
- if (j != -1)
- {
- a[i] = ConstZenkaku[j];
- }
- }
-
- return new string(a);
- }
-
- public const string HtmlSpacing = " ";
- public const string HtmlCrlf = "
";
- public const string HtmlBr = "
";
- public const string HtmlLt = "<";
- public const string HtmlGt = ">";
- public const string HtmlAmp = "&";
- public const int HtmlNumTabChar = 8;
- public static string HtmlTab
- {
- get
- {
- int i;
- StringBuilder sb = new StringBuilder();
- for (i = 0; i < HtmlNumTabChar; i++)
- {
- sb.Append(HtmlSpacing);
- }
- return sb.ToString();
- }
- }
-
- public static string ToUrl(string str, Encoding e)
- {
- Str.NormalizeString(ref str);
- return HttpUtility.UrlEncode(str, e);
- }
-
- public static string FromUrl(string str, Encoding e)
- {
- Str.NormalizeString(ref str);
- return HttpUtility.UrlDecode(str, e);
- }
-
- public static string FromHtml(string str)
- {
- str = Str.ReplaceStr(str, HtmlCrlf, "\r\n", false);
-
- str = str.Replace(HtmlSpacing, " ");
-
- str = str.Replace(HtmlLt, "<").Replace(HtmlGt, ">").Replace(HtmlAmp, "&");
-
- str = NormalizeCrlf(str);
-
- return str;
- }
-
- public static string ToHtml(string str)
- {
- return ToHtml(str, false);
- }
- public static string ToHtml(string str, bool forceAllSpaceToTag)
- {
- str = NormalizeCrlf(str);
-
- str = str.Replace("&", HtmlAmp);
-
- str = str.Replace("<", HtmlLt).Replace(">", HtmlGt);
-
- if (str.IndexOf(' ') != -1)
- {
- if (forceAllSpaceToTag)
- {
- str = str.Replace(" ", HtmlSpacing);
- }
- else
- {
- int i;
- StringBuilder sb = new StringBuilder();
- bool flag = false;
-
- for (i = 0; i < str.Length; i++)
- {
- char c = str[i];
-
- if (c == ' ')
- {
- if (flag == false)
- {
- flag = true;
- sb.Append(' ');
- }
- else
- {
- sb.Append(HtmlSpacing);
- }
- }
- else
- {
- flag = false;
- sb.Append(c);
- }
- }
-
- str = sb.ToString();
- }
- }
-
- str = str.Replace("\t", HtmlTab);
-
- str = str.Replace("\r\n", HtmlCrlf);
-
- return str;
- }
-
- public static bool IsPrintable(char c)
- {
- if (c >= 256)
- {
- return true;
- }
-
- if (c >= 32 && c <= 126)
- {
- return true;
- }
-
- return false;
- }
- public static bool IsPrintable(string str)
- {
- foreach (char c in str)
- {
- if (IsPrintable(c) == false)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static string Unescape(string str)
- {
- StringBuilder sb = new StringBuilder();
-
- int i;
- for (i = 0; i < str.Length; i++)
- {
- char c = str[i];
-
- if (IsPrintable(c) && c != '\\')
- {
- sb.Append(c);
- }
- else
- {
- string s = "" + c;
- switch (c)
- {
- case '\r':
- s = "\\r";
- break;
-
- case '\n':
- s = "\\n";
- break;
-
- case '\0':
- s = "\\0";
- break;
-
- case '\t':
- s = "\\t";
- break;
-
- case '\\':
- s = "\\\\";
- break;
-
- default:
- s = "0x" + Convert.ToString((int)c, 16);
- break;
- }
- sb.Append(s);
- }
- }
-
- return sb.ToString();
- }
-
- public static string Escape(string str)
- {
- StringBuilder sb = new StringBuilder();
-
- int i, j, hex;
- string padding = "00000000";
- str = str + padding;
- StringBuilder sb2;
-
- for (i = 0; i < str.Length - padding.Length; i++)
- {
- char c = str[i];
- char d = c;
-
- if (c == '\\')
- {
- char c1 = str[i + 1];
-
- switch (c1)
- {
- case '\'':
- d = '\'';
- i++;
- break;
-
- case '?':
- d = '?';
- i++;
- break;
-
- case '\\':
- d = '\\';
- i++;
- break;
-
- case 't':
- d = '\t';
- i++;
- break;
-
- case 'r':
- d = '\r';
- i++;
- break;
-
- case 'n':
- d = '\n';
- i++;
- break;
-
- case ' ':
- d = ' ';
- i++;
- break;
-
- case ' ':
- d = ' ';
- i++;
- break;
-
- case '\t':
- d = '\t';
- i++;
- break;
-
- case '0':
- d = '\0';
- i++;
- break;
-
- case 'x':
- i++;
- sb2 = new StringBuilder();
- for (j = 0; j < 4; j++)
- {
- char c2 = str[++i];
-
- if ((c2 >= '0' && c2 <= '9') || (c2 >= 'a' && c2 <= 'f') || (c2 >= 'A' && c2 <= 'F'))
- {
- sb2.Append(c2);
- }
- else
- {
- i--;
- break;
- }
- }
- hex = Convert.ToInt32(sb2.ToString(), 16);
- d = (char)hex;
- break;
-
- default:
- if (c1 >= '0' && c1 <= '7')
- {
- sb2 = new StringBuilder();
- for (j = 0; j < 3; j++)
- {
- char c2 = str[++i];
-
- if (c2 >= '0' && c2 <= '7')
- {
- sb2.Append(c2);
- }
- else
- {
- i--;
- break;
- }
- }
- hex = Convert.ToInt32(sb2.ToString(), 8);
- d = (char)hex;
- }
- else
- {
- d = '\\';
- i++;
- }
- break;
- }
- }
-
- if (d != '\0')
- {
- sb.Append(d);
- }
- else
- {
- break;
- }
- }
-
- return sb.ToString();
- }
-
- public static int GetStrWidth(string str)
- {
- int ret = 0;
- foreach (char c in str)
- {
- if (c <= 255)
- {
- ret++;
- }
- else
- {
- ret += 2;
- }
- }
- return ret;
- }
-
- public static string TrimCrlf(string str)
- {
- int len;
- if (str == null)
- {
- return "";
- }
- len = str.Length;
- if (len == 0)
- {
- return "";
- }
-
- if (str[len - 1] == '\n')
- {
- if (len >= 2 && str[len - 2] == '\r')
- {
- str = str.Substring(0, len - 2);
- }
-
- str = str.Substring(0, len - 1);
- }
- else if (str[len - 1] == '\r')
- {
- str = str.Substring(0, len - 1);
- }
-
- return str;
- }
-
- public static bool IsAllUpperStr(string str)
- {
- int i, len;
- if (str == null)
- {
- return false;
- }
-
- len = str.Length;
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
-
- if ((c >= '0' && c <= '9') ||
- (c >= 'A' && c <= 'Z'))
- {
- }
- else
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static List StrArrayToList(string[] strArray)
- {
- List ret = new List();
-
- foreach (string s in strArray)
- {
- ret.Add(s);
- }
-
- return ret;
- }
-
- private static string[] __new_ParseCmdLine(string str)
- {
- List o;
- int i, len, mode;
- char c;
- StringBuilder tmp;
- bool ignore_space = false;
- if (str == null)
- {
- return new string[0];
- }
-
- o = new List();
- tmp = new StringBuilder();
-
- mode = 0;
- len = str.Length;
- for (i = 0; i < len; i++)
- {
- c = str[i];
-
- switch (mode)
- {
- case 0:
- if (c == ' ' || c == '\t')
- {
- }
- else
- {
- if (c == '\"')
- {
- if (str[i + 1] == '\"')
- {
- tmp.Append("\"");
- i++;
- }
- else
- {
- ignore_space = true;
- }
- }
- else
- {
- tmp.Append(c);
- }
- }
-
- mode = 1;
- break;
-
- case 1:
- if (ignore_space == false && (c == ' ' || c == '\t'))
- {
- o.Add(tmp.ToString());
-
- tmp = new StringBuilder();
- mode = 0;
- }
- else
- {
- if (c == '\"')
- {
- if (str[i + 1] == '\"')
- {
- tmp.Append("\"");
- i++;
- }
- else
- {
- if (ignore_space == false)
- {
- ignore_space = true;
- }
- else
- {
- ignore_space = false;
- }
- }
- }
- else
- {
- tmp.Append(c);
- }
- }
- break;
-
- }
- }
-
- if (tmp.Length >= 1)
- {
- o.Add(tmp.ToString());
- }
-
- List ret = new List();
- foreach (string s in o)
- {
- ret.Add(s);
- }
-
- return ret.ToArray();
- }
-
- public static int CompareString(string s1, string s2)
- {
- try
- {
- return string.Compare(s1, s2, true);
- }
- catch
- {
- return 0;
- }
- }
- public static int CompareStringCaseSensitive(string s1, string s2)
- {
- try
- {
- return string.Compare(s1, s2, false);
- }
- catch
- {
- return 0;
- }
- }
-
- public static string ReplaceStr(string str, string oldKeyword, string newKeyword)
- {
- return ReplaceStr(str, oldKeyword, newKeyword, false);
- }
- public static string ReplaceStr(string str, string oldKeyword, string newKeyword, bool caseSensitive)
- {
- int len_string, len_old, len_new;
- if (str == null || oldKeyword == null || newKeyword == null)
- {
- return null;
- }
-
- if (caseSensitive == false)
- {
- return str.Replace(oldKeyword, newKeyword);
- }
-
- int i, j, num;
- StringBuilder sb = new StringBuilder();
-
- len_string = str.Length;
- len_old = oldKeyword.Length;
- len_new = newKeyword.Length;
-
- i = j = num = 0;
-
- while (true)
- {
- i = SearchStr(str, oldKeyword, i, caseSensitive);
- if (i == -1)
- {
- sb.Append(str.Substring(j, len_string - j));
- break;
- }
-
- num++;
-
- sb.Append(str.Substring(j, i - j));
- sb.Append(newKeyword);
-
- i += len_old;
- j = i;
- }
-
- return sb.ToString();
- }
-
- public static int SearchStrMulti(string str, int start, bool caseSensitive, out int foundIndex, out string foundKeyword, params string[] keywords)
- {
- int i;
- foundIndex = -1;
- foundKeyword = "";
- int ret = -1;
- int min = int.MaxValue;
- for (i = 0; i < keywords.Length; i++)
- {
- string keyword = keywords[i];
- int r = Str.SearchStr(str, keyword, start, caseSensitive);
- if (r != -1)
- {
- if (min > r)
- {
- min = r;
- foundKeyword = str.Substring(r, keyword.Length);
- foundIndex = i;
- }
- }
- }
-
- if (foundIndex != -1)
- {
- ret = min;
- }
-
- return ret;
- }
-
- public static int SearchStr(string str, string keyword, int start)
- {
- return SearchStr(str, keyword, start, false);
- }
- public static int SearchStr(string str, string keyword, int start, bool caseSensitive)
- {
- if (str == null || keyword == null)
- {
- return -1;
- }
-
- try
- {
- return str.IndexOf(keyword, start, (caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase));
- }
- catch
- {
- return -1;
- }
- }
-
- public static void Printf(string fmt, params object[] args)
- {
- if (args.Length == 0)
- {
- Console.Write(fmt);
- }
- else
- {
- Console.Write(FormatC(fmt, args));
- }
- }
-
- public static string FormatC(string fmt)
- {
- return FormatC(fmt, new object[0]);
- }
- public static string FormatC(string fmt, params object[] args)
- {
- int i, len;
- StringBuilder tmp;
- List o;
- int mode = 0;
- int pos = 0;
- if (fmt == null)
- {
- return null;
- }
-
- len = fmt.Length;
- tmp = new StringBuilder();
- o = new List();
-
- mode = 0;
-
- for (i = 0; i < len; i++)
- {
- char c = fmt[i];
-
- if (mode == 0)
- {
- switch (c)
- {
- case '%':
- if (fmt[i + 1] == '%')
- {
- i++;
- tmp.Append("%");
- }
- else
- {
- mode = 1;
- o.Add(tmp.ToString());
- tmp = new StringBuilder();
-
- tmp.Append(c);
- }
- break;
-
- default:
- tmp.Append(c);
- break;
- }
- }
- else
- {
- switch (c)
- {
- case 'c':
- case 'C':
- case 'd':
- case 'i':
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
- case 'a':
- case 'A':
- case 'n':
- case 'p':
- case 's':
- case 'S':
- tmp.Append(c);
-
- PrintFParsedParam pp = new PrintFParsedParam(tmp.ToString());
- string s;
- if (pp.Ok)
- {
- s = pp.GetString(args[pos++]);
- }
- else
- {
- s = "(parse_error)";
- }
-
- o.Add(s);
-
- tmp = new StringBuilder();
- mode = 0;
- break;
-
- default:
- tmp.Append(c);
- break;
- }
- }
- }
-
- if (tmp.Length >= 1)
- {
- o.Add(tmp.ToString());
- }
-
- StringBuilder retstr = new StringBuilder();
- foreach (string stmp in o)
- {
- retstr.Append(stmp);
- }
-
- return retstr.ToString();
- }
-
- static Encoding asciiEncoding = Encoding.ASCII;
- public static Encoding AsciiEncoding
- {
- get { return asciiEncoding; }
- }
-
- static Encoding shiftJisEncoding = Encoding.GetEncoding("shift_jis");
- public static Encoding ShiftJisEncoding
- {
- get { return shiftJisEncoding; }
- }
-
- static Encoding iso2022JpEncoding = Encoding.GetEncoding("ISO-2022-JP");
- public static Encoding ISO2022JPEncoding
- {
- get { return iso2022JpEncoding; }
- }
-
- static Encoding eucJpEncoding = Encoding.GetEncoding("euc-jp");
- public static Encoding EucJpEncoding
- {
- get { return eucJpEncoding; }
- }
-
- static Encoding iso88591Encoding = Encoding.GetEncoding("iso-8859-1");
- public static Encoding ISO88591Encoding
- {
- get { return iso88591Encoding; }
- }
-
- static Encoding gb2312Encoding = Encoding.GetEncoding("gb2312");
- public static Encoding GB2312Encoding
- {
- get { return gb2312Encoding; }
- }
-
- static Encoding utf8Encoding = Encoding.UTF8;
- public static Encoding Utf8Encoding
- {
- get { return utf8Encoding; }
- }
-
- static Encoding uniEncoding = Encoding.Unicode;
- public static Encoding UniEncoding
- {
- get { return uniEncoding; }
- }
-
- public static void NormalizeString(ref string str)
- {
- if (str == null)
- {
- str = "";
- }
-
- str = str.Trim();
- }
-
- public static string PasswordPrompt()
- {
- Queue ret = new Queue();
- bool escape = false;
-
- while (true)
- {
- ConsoleKeyInfo ki = Console.ReadKey(true);
- char c = ki.KeyChar;
-
- if (c >= 0x20 && c <= 0x7e)
- {
- ret.Enqueue(c);
- Console.Write("*");
- }
- else if (c == 0x04 || c == 0x1a || c == 0x0d || c == 0x0a)
- {
- if (c == 0x04 || c == 0x1a)
- {
- escape = true;
- }
- break;
- }
- else if (c == 0x08)
- {
- Console.Write(c);
- Console.Write(" ");
- Console.Write(c);
-
- if (ret.Count >= 1)
- {
- ret.Dequeue();
- }
- }
- }
-
- Console.WriteLine();
-
- if (escape)
- {
- return null;
- }
-
- return new string(ret.ToArray());
- }
-
- public static bool CheckStrLen(string str, int maxLen)
- {
- if (str == null)
- {
- return false;
- }
-
- if (str.Length > maxLen)
- {
- return false;
- }
-
- return true;
- }
-
- public static bool IsSafe(string s)
- {
- foreach (char c in s)
- {
- if (IsSafe(c) == false)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public static bool IsSafe(char c)
- {
- char[] b = Path.GetInvalidFileNameChars();
-
- foreach (char bb in b)
- {
- if (bb == c)
- {
- return false;
- }
- }
-
- if (c == '\\' || c == '/')
- {
- return false;
- }
-
- return true;
- }
-
- public static string MakeSafePathName(string name)
- {
- char[] a = name.ToCharArray();
- char[] b = Path.GetInvalidFileNameChars();
- StringBuilder sb = new StringBuilder();
-
- int i;
- for (i = 0; i < a.Length; i++)
- {
- int j;
- bool ok = true;
-
- for (j = 0; j < b.Length; j++)
- {
- if (b[j] == a[i])
- {
- ok = false;
- break;
- }
- }
-
- if (a[i] == '\\' || a[i] == '/')
- {
- ok = true;
- a[i] = '\\';
- }
-
- string s;
-
- if (ok == false)
- {
- s = "_" + ((int)a[i]).ToString() + "_";
- }
- else
- {
- s = "" + a[i];
- }
-
- sb.Append(s);
- }
-
- return sb.ToString();
- }
-
- public static string MakeSafeFileName(string name)
- {
- char[] a = name.ToCharArray();
- char[] b = Path.GetInvalidFileNameChars();
- StringBuilder sb = new StringBuilder();
-
- int i;
- for (i = 0; i < a.Length; i++)
- {
- int j;
- bool ok = true;
-
- for (j = 0; j < b.Length; j++)
- {
- if (b[j] == a[i])
- {
- ok = false;
- break;
- }
- }
-
- string s;
-
- if (ok == false)
- {
- s = "_" + ((int)a[i]).ToString() + "_";
- }
- else
- {
- s = "" + a[i];
- }
-
- sb.Append(s);
- }
-
- return sb.ToString();
- }
-
- public static object CloneObject(object o)
- {
- return BinaryToObject(ObjectToBinary(o));
- }
-
- public static object AnyToObject(byte[] data)
- {
- if (data.Length >= 5)
- {
- if (Str.StrCmpi(Encoding.ASCII.GetString(data, 0, 5), "= '0' && c <= '9')
- {
- return true;
- }
- if (c >= 'A' && c <= 'Z')
- {
- return true;
- }
- if (c >= 'a' && c <= 'z')
- {
- return true;
- }
- if (c == '!' || c == '\"' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
- c == '(' || c == ')' || c == '-' || c == ' ' || c == '=' || c == '~' || c == '^' || c == '_' ||
- c == '\\' || c == '|' || c == '{' || c == '}' || c == '[' || c == ']' || c == '@' ||
- c == '*' || c == '+' || c == '.' || c == '<' || c == '>' ||
- c == ',' || c == '?' || c == '/' || c == ' ' || c == '^' || c == '\'')
- {
- return true;
- }
- return false;
- }
- public static bool IsAscii(string str)
- {
- foreach (char c in str)
- {
- if (IsAscii(c) == false)
- {
- return false;
- }
- }
- return true;
- }
-
- public static string GetBpsStr(int size)
- {
- return GetBpsStr(size);
- }
- public static string GetBpsStr(long size)
- {
- if (size >= 1000000000000L)
- {
- return ((double)(size) / 1000.0f / 1000.0f / 1000.0f / 1000.0f).ToString(".00") + " Tbps";
- }
- if (size >= 1000 * 1000 * 1000)
- {
- return ((double)(size) / 1000.0f / 1000.0f / 1000.0f).ToString(".00") + " Gbps";
- }
- if (size >= 1000 * 1000)
- {
- return ((double)(size) / 1000.0f / 1000.0f).ToString(".00") + " Mbps";
- }
- if (size >= 1000)
- {
- return ((double)(size) / 1000.0f).ToString(".00") + " Kbps";
- }
- return ((double)(size)).ToString() + " bps";
- }
-
- public static string GetFileSizeStr(int size)
- {
- return GetFileSizeStr(size);
- }
- public static string GetFileSizeStr(long size)
- {
- if (size >= 1099511627776L)
- {
- return ((double)(size) / 1024.0f / 1024.0f / 1024.0f / 1024.0f).ToString(".00") + " TB";
- }
- if (size >= 1024 * 1024 * 1024)
- {
- return ((double)(size) / 1024.0f / 1024.0f / 1024.0f).ToString(".00") + " GB";
- }
- if (size >= 1024 * 1024)
- {
- return ((double)(size) / 1024.0f / 1024.0f).ToString(".00") + " MB";
- }
- if (size >= 1024)
- {
- return ((double)(size) / 1024.0f).ToString(".00") + " KB";
- }
- return ((double)(size)).ToString() + " Bytes";
- }
-
- public static string IntToStr(int i)
- {
- return i.ToString();
- }
- public static string IntToStr(uint i)
- {
- return i.ToString();
- }
-
- public static string LongToStr(long i)
- {
- return i.ToString();
- }
- public static string LongToStr(ulong i)
- {
- return i.ToString();
- }
-
- public static bool StrToBool(string s)
- {
- if (s == null)
- {
- return false;
- }
-
- Str.NormalizeString(ref s, true, true, false, false);
-
- if (s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
-
- if (s.StartsWith("t", StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
-
- if (Str.StrToInt(s) != 0)
- {
- return true;
- }
-
- return false;
- }
-
- public static int StrToInt(string str)
- {
- try
- {
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return int.Parse(str);
- }
- catch
- {
- return 0;
- }
- }
- public static uint StrToUInt(string str)
- {
- try
- {
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return uint.Parse(str);
- }
- catch
- {
- return 0;
- }
- }
-
- public static long StrToLong(string str)
- {
- try
- {
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return long.Parse(str);
- }
- catch
- {
- return 0;
- }
- }
- public static ulong StrToULong(string str)
- {
- try
- {
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return ulong.Parse(str);
- }
- catch
- {
- return 0;
- }
- }
-
- public static bool IsStrDateTime(string str)
- {
- try
- {
- Str.NormalizeString(ref str, true, true, false, false);
- StrToDateTime(str);
- return true;
- }
- catch
- {
- return false;
- }
- }
- public static DateTime StrToDateTime(string str, bool toUtc)
- {
- return StrToDateTime(str).ToUniversalTime();
- }
- public static DateTime StrToDateTime(string str)
- {
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Trim();
- string[] sps =
- {
- " ",
- "_",
- " ",
- "\t",
- };
-
- string[] tokens = str.Split(sps, StringSplitOptions.RemoveEmptyEntries);
-
- if (tokens.Length != 2)
- {
- int r1 = str.IndexOf("年", StringComparison.InvariantCultureIgnoreCase);
- int r2 = str.IndexOf("月", StringComparison.InvariantCultureIgnoreCase);
- int r3 = str.IndexOf("日", StringComparison.InvariantCultureIgnoreCase);
-
- if (r1 != -1 && r2 != -1 && r3 != -1)
- {
- tokens = new string[2];
-
- tokens[0] = str.Substring(0, r3 + 1);
- tokens[1] = str.Substring(r3 + 1);
- }
- }
-
- if (tokens.Length == 2)
- {
- DateTime dt1 = StrToDate(tokens[0]);
- DateTime dt2 = StrToTime(tokens[1]);
-
- return dt1.Date + dt2.TimeOfDay;
- }
- else if (tokens.Length == 1)
- {
- if (tokens[0].Length == 14)
- {
- // yyyymmddhhmmss
- DateTime dt1 = StrToDate(tokens[0].Substring(0, 8));
- DateTime dt2 = StrToTime(tokens[0].Substring(8));
-
- return dt1.Date + dt2.TimeOfDay;
- }
- else if (tokens[0].Length == 12)
- {
- // yymmddhhmmss
- DateTime dt1 = StrToDate(tokens[0].Substring(0, 6));
- DateTime dt2 = StrToTime(tokens[0].Substring(6));
-
- return dt1.Date + dt2.TimeOfDay;
- }
- else
- {
- DateTime dt1 = StrToDate(tokens[0]);
-
- return dt1.Date;
- }
- }
-
- throw new ArgumentException();
- }
-
- public static bool IsStrTime(string str)
- {
- try
- {
- Str.NormalizeString(ref str, true, true, false, false);
- StrToTime(str);
- return true;
- }
- catch
- {
- return false;
- }
- }
- public static DateTime StrToTime(string str, bool toUtc)
- {
- return StrToTime(str).ToUniversalTime();
- }
- public static DateTime StrToTime(string str)
- {
- string[] sps =
- {
- "/",
- "-",
- ":",
- "時",
- "分",
- "秒",
- };
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Trim();
-
- string[] tokens;
-
- tokens = str.Split(sps, StringSplitOptions.RemoveEmptyEntries);
- if (tokens.Length == 3)
- {
- // hh:mm:ss
- string hourStr = tokens[0];
- string minuteStr = tokens[1];
- string secondStr = tokens[2];
- int hour = -1;
- int minute = -1;
- int second = -1;
-
- if ((hourStr.Length == 1 || hourStr.Length == 2) && IsNumber(hourStr))
- {
- hour = StrToInt(hourStr);
- }
- if ((minuteStr.Length == 1 || minuteStr.Length == 2) && IsNumber(minuteStr))
- {
- minute = StrToInt(minuteStr);
- }
- if ((secondStr.Length == 1 || secondStr.Length == 2) && IsNumber(secondStr))
- {
- second = StrToInt(secondStr);
- }
-
- if (hour < 0 || hour >= 25 || minute < 0 || minute >= 60 || second < 0 || second >= 60)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(2000, 1, 1, hour, minute, second);
- }
- else if (tokens.Length == 2)
- {
- // hh:mm
- string hourStr = tokens[0];
- string minuteStr = tokens[1];
- int hour = -1;
- int minute = -1;
- int second = 0;
-
- if ((hourStr.Length == 1 || hourStr.Length == 2) && IsNumber(hourStr))
- {
- hour = StrToInt(hourStr);
- }
- if ((minuteStr.Length == 1 || minuteStr.Length == 2) && IsNumber(minuteStr))
- {
- minute = StrToInt(minuteStr);
- }
-
- if (hour < 0 || hour >= 25 || minute < 0 || minute >= 60 || second < 0 || second >= 60)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(2000, 1, 1, hour, minute, second);
- }
- else if (tokens.Length == 1)
- {
- string hourStr = tokens[0];
- int hour = -1;
- int minute = 0;
- int second = 0;
-
- if ((hourStr.Length == 1 || hourStr.Length == 2) && IsNumber(hourStr))
- {
- // hh
- hour = StrToInt(hourStr);
- }
- else
- {
- if ((hourStr.Length == 4) && IsNumber(hourStr))
- {
- // hhmm
- int i = StrToInt(hourStr);
- hour = i / 100;
- minute = i % 100;
- }
- else if ((hourStr.Length == 6) && IsNumber(hourStr))
- {
- // hhmmss
- int i = StrToInt(hourStr);
- hour = i / 10000;
- minute = ((i % 10000) / 100);
- second = i % 100;
- }
- }
-
- if (hour < 0 || hour >= 25 || minute < 0 || minute >= 60 || second < 0 || second >= 60)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(2000, 1, 1, hour, minute, second);
- }
-
- throw new ArgumentException();
- }
-
- public static bool IsStrDate(string str)
- {
- try
- {
- Str.NormalizeString(ref str, true, true, false, false);
- StrToDate(str);
- return true;
- }
- catch
- {
- return false;
- }
- }
- public static DateTime StrToDate(string str, bool toUtc)
- {
- return StrToDate(str).ToUniversalTime();
- }
- public static DateTime StrToDate(string str)
- {
- string[] sps =
- {
- "/",
- "/",
- "-",
- ":",
- "年",
- "月",
- "日",
- };
- str = str.Trim();
- Str.NormalizeString(ref str, true, true, false, false);
-
- string[] youbi =
- {
- "月", "火", "水", "木", "金", "土", "日",
- };
-
- foreach (string ys in youbi)
- {
- string ys2 = string.Format("({0})", ys);
-
- str = str.Replace(ys2, "");
- }
-
- string[] tokens;
-
- tokens = str.Split(sps, StringSplitOptions.RemoveEmptyEntries);
- if (tokens.Length == 3)
- {
- // yyyy/mm/dd
- string yearStr = tokens[0];
- string monthStr = tokens[1];
- string dayStr = tokens[2];
- int year = 0;
- int month = 0;
- int day = 0;
-
- if ((yearStr.Length == 1 || yearStr.Length == 2) && IsNumber(yearStr))
- {
- year = 2000 + StrToInt(yearStr);
- }
- else if (yearStr.Length == 4 && IsNumber(yearStr))
- {
- year = StrToInt(yearStr);
- }
-
- if ((monthStr.Length == 1 || monthStr.Length == 2) && IsNumber(monthStr))
- {
- month = StrToInt(monthStr);
- }
- if ((dayStr.Length == 1 || dayStr.Length == 2) && IsNumber(dayStr))
- {
- day = StrToInt(dayStr);
- }
-
- if (year < 1800 || year >= 2100 || month <= 0 || month >= 13 || day <= 0 || day >= 32)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(year, month, day);
- }
- else if (tokens.Length == 1)
- {
- if (str.Length == 8)
- {
- // yyyymmdd
- string yearStr = str.Substring(0, 4);
- string monthStr = str.Substring(4, 2);
- string dayStr = str.Substring(6, 2);
- int year = int.Parse(yearStr);
- int month = int.Parse(monthStr);
- int day = int.Parse(dayStr);
-
- if (year < 1800 || year >= 2100 || month <= 0 || month >= 13 || day <= 0 || day >= 32)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(year, month, day);
- }
- else if (str.Length == 6)
- {
- // yymmdd
- string yearStr = str.Substring(0, 2);
- string monthStr = str.Substring(2, 2);
- string dayStr = str.Substring(4, 2);
- int year = int.Parse(yearStr) + 2000;
- int month = int.Parse(monthStr);
- int day = int.Parse(dayStr);
-
- if (year < 1800 || year >= 2100 || month <= 0 || month >= 13 || day <= 0 || day >= 32)
- {
- throw new ArgumentException();
- }
-
- return new DateTime(year, month, day);
- }
- }
-
- throw new ArgumentException();
- }
-
- public static string TimeToStr(DateTime dt)
- {
- return TimeToStr(dt, false);
- }
- public static string TimeToStr(DateTime dt, CoreLanguage lang)
- {
- return TimeToStr(dt, false, lang);
- }
- public static string TimeToStr(DateTime dt, bool toLocalTime)
- {
- return TimeToStr(dt, toLocalTime, CoreLanguageClass.CurrentThreadLanguage);
- }
- public static string TimeToStr(DateTime dt, bool toLocalTime, CoreLanguage lang)
- {
- string s = DateTimeToStr(dt, toLocalTime, lang);
-
- string[] tokens = s.Split(' ');
-
- return tokens[1];
- }
- public static string TimeToStrShort(DateTime dt)
- {
- return TimeToStrShort(dt, false);
- }
- public static string TimeToStrShort(DateTime dt, bool toLocalTime)
- {
- string s = DateTimeToStrShort(dt, toLocalTime);
-
- string[] tokens = s.Split('_');
-
- return tokens[1];
- }
-
- public static string DateToStr(DateTime dt)
- {
- return DateToStr(dt, false);
- }
- public static string DateToStr(DateTime dt, CoreLanguage lang)
- {
- return DateToStr(dt, false, lang);
- }
- public static string DateToStr(DateTime dt, bool toLocalTime)
- {
- return DateToStr(dt, toLocalTime, false);
- }
- public static string DateToStr(DateTime dt, bool toLocalTime, CoreLanguage lang)
- {
- return DateToStr(dt, toLocalTime, false, lang);
- }
- public static string DateToStr(DateTime dt, bool toLocalTime, bool noDayOfWeek)
- {
- return DateToStr(dt, toLocalTime, noDayOfWeek, CoreLanguageClass.CurrentThreadLanguage);
- }
- public static string DateToStr(DateTime dt, bool toLocalTime, bool noDayOfWeek, CoreLanguage lang)
- {
- string s = DateTimeToStr(dt, toLocalTime, lang);
-
- string[] tokens = s.Split(' ');
-
- string ret = tokens[0];
-
- if (noDayOfWeek)
- {
- string[] tokens2 = s.Split('(');
-
- ret = tokens2[0];
- }
-
- return ret;
- }
- public static string DateToStrShort(DateTime dt)
- {
- return DateToStrShort(dt, false);
- }
- public static string DateToStrShort(DateTime dt, bool toLocalTime)
- {
- string s = DateTimeToStrShort(dt, toLocalTime);
-
- string[] tokens = s.Split('_');
-
- return tokens[0];
- }
-
- public static string DayOfWeekToStr(CoreLanguage lang, int d)
- {
- if (lang == CoreLanguage.Japanese)
- {
- string[] youbi =
- {
- "日", "月", "火", "水", "木", "金", "土",
- };
-
- return youbi[d];
- }
- else
- {
- string[] youbi =
- {
- "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
- };
-
- return youbi[d];
- }
- }
-
- public static string DateTimeToStr(DateTime dt)
- {
- return DateTimeToStr(dt, false);
- }
- public static string DateTimeToStr(DateTime dt, CoreLanguage lang)
- {
- return DateTimeToStr(dt, false, lang);
- }
- public static string DateTimeToStr(DateTime dt, bool toLocalTime)
- {
- return DateTimeToStr(dt, toLocalTime, CoreLanguageClass.CurrentThreadLanguage);
- }
- public static string DateTimeToStr(DateTime dt, bool toLocalTime, CoreLanguage lang)
- {
- if (toLocalTime)
- {
- dt = dt.ToLocalTime();
- }
-
- if (lang == CoreLanguage.Japanese)
- {
- return dt.ToString("yyyy年M月d日") + "(" + DayOfWeekToStr(lang, (int)dt.DayOfWeek) + ")" + dt.ToString(" H時m分s秒");
- }
- else
- {
- return dt.ToString("yyyy-MM-dd(") + DayOfWeekToStr(lang, (int)dt.DayOfWeek) + dt.ToString(") H:mm:ss");
- }
- }
- public static string DateTimeToStrShort(DateTime dt)
- {
- return DateTimeToStrShort(dt, false);
- }
- public static string DateTimeToStrShort(DateTime dt, bool toLocalTime)
- {
- if (toLocalTime)
- {
- dt = dt.ToLocalTime();
- }
-
- return dt.ToString("yyyyMMdd_HHmmss");
- }
- public static string DateTimeToStrShortWithMilliSecs(DateTime dt)
- {
- return DateTimeToStrShortWithMilliSecs(dt, false);
- }
- public static string DateTimeToStrShortWithMilliSecs(DateTime dt, bool toLocalTime)
- {
- if (toLocalTime)
- {
- dt = dt.ToLocalTime();
- }
-
- long ticks = dt.Ticks % 10000000;
- if (ticks >= 9990000)
- {
- ticks = 9990000;
- }
-
- string msecStr = ((decimal)ticks / (decimal)10000000).ToString(".000");
-
- return dt.ToString("yyyyMMdd_HHmmss") + "." + msecStr.Split('.')[1];
- }
-
- public static string Base64ToSafe64(string str)
- {
- return str.Replace('=', '(').Replace('+', ')').Replace('/', '_');
- }
- public static string Safe64ToBase64(string str)
- {
- return str.Replace('(', '=').Replace(')', '+').Replace('_', '/');
- }
-
- public static string Base64Encode(byte[] data)
- {
- try
- {
- return Convert.ToBase64String(data);
- }
- catch
- {
- return "";
- }
- }
-
- public static byte[] Base64Decode(string str)
- {
- try
- {
- return Convert.FromBase64String(str);
- }
- catch
- {
- return new byte[0];
- }
- }
-
- public static byte[] StrToByte(string str)
- {
- Str.NormalizeString(ref str, true, true, false, false);
- return Base64Decode(Safe64ToBase64(str));
- }
-
- public static string Encode64(string str)
- {
- return Convert.ToBase64String(Encoding.UTF8.GetBytes(str)).Replace("/", "(").Replace("+", ")");
- }
-
- public static string Decode64(string str)
- {
- return Encoding.UTF8.GetString(Convert.FromBase64String(str.Replace(")", "+").Replace("(", "/")));
- }
-
-
- public static bool CheckMailAddress(string str)
- {
- str = str.Trim();
- if (str.Length == 0)
- {
- return false;
- }
-
- string[] tokens = str.Split('@');
-
- if (tokens.Length != 2)
- {
- return false;
- }
-
- string a = tokens[0];
- string b = tokens[1];
-
- if (a.Length == 0 || b.Length == 0)
- {
- return false;
- }
-
- if (b.IndexOf(".") == -1)
- {
- return false;
- }
-
- return IsAscii(str);
- }
-
- public static bool StrCmpi(string s1, string s2)
- {
- try
- {
- if (s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase))
- {
- return true;
- }
-
- return false;
- }
- catch
- {
- return false;
- }
- }
-
- public static bool StrCmp(string s1, string s2)
- {
- try
- {
- if (s1 == s2)
- {
- return true;
- }
-
- return false;
- }
- catch
- {
- return false;
- }
- }
- public static string ByteToHex(byte[] data)
- {
- return ByteToHex(data, "");
- }
- public static string ByteToHex(byte[] data, string paddingStr)
- {
- StringBuilder ret = new StringBuilder();
- foreach (byte b in data)
- {
- string s = b.ToString("X");
- if (s.Length == 1)
- {
- s = "0" + s;
- }
-
- ret.Append(s);
-
- if (paddingStr != null)
- {
- ret.Append(paddingStr);
- }
- }
-
- return ret.ToString().Trim();
- }
-
- public static byte[] HexToByte(string str)
- {
- try
- {
- List o = new List();
- string tmp = "";
- int i, len;
-
- str = str.ToUpper().Trim();
- len = str.Length;
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
- if (('0' <= c && c <= '9') || ('A' <= c && c <= 'F'))
- {
- tmp += c;
- if (tmp.Length == 2)
- {
- byte b = Convert.ToByte(tmp, 16);
- o.Add(b);
- tmp = "";
- }
- }
- else if (c == ' ' || c == ',' || c == '-' || c == ';')
- {
- }
- else
- {
- break;
- }
- }
-
- return o.ToArray();
- }
- catch
- {
- return new byte[0];
- }
- }
-
- public static string[] GetLines(string str)
- {
- List a = new List();
- StringReader sr = new StringReader(str);
- while (true)
- {
- string s = sr.ReadLine();
- if (s == null)
- {
- break;
- }
- a.Add(s);
- }
- return a.ToArray();
- }
-
- public static string LinesToStr(string[] lines)
- {
- StringWriter sw = new StringWriter();
- foreach (string s in lines)
- {
- sw.WriteLine(s);
- }
- return sw.ToString();
- }
-
- public static bool IsEmptyStr(string str)
- {
- if (str == null || str.Trim().Length == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public static bool IsSolidStr(string str)
- {
- return !IsEmptyStr(str);
- }
-
- public static bool IsSplitChar(char c, string splitStr)
- {
- if (splitStr == null)
- {
- splitStr = StrToken.DefaultSplitStr;
- }
-
- foreach (char t in splitStr)
- {
- string a = "" + t;
- string b = "" + c;
- if (Str.StrCmpi(a, b))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static bool GetKeyAndValue(string str, out string key, out string value)
- {
- return GetKeyAndValue(str, out key, out value, null);
- }
- public static bool GetKeyAndValue(string str, out string key, out string value, string splitStr)
- {
- uint mode = 0;
- string keystr = "", valuestr = "";
- if (splitStr == null)
- {
- splitStr = StrToken.DefaultSplitStr;
- }
-
- foreach (char c in str)
- {
- switch (mode)
- {
- case 0:
- if (IsSplitChar(c, splitStr) == false)
- {
- mode = 1;
- keystr += c;
- }
- break;
-
- case 1:
- if (IsSplitChar(c, splitStr) == false)
- {
- keystr += c;
- }
- else
- {
- mode = 2;
- }
- break;
-
- case 2:
- if (IsSplitChar(c, splitStr) == false)
- {
- mode = 3;
- valuestr += c;
- }
- break;
-
- case 3:
- valuestr += c;
- break;
- }
- }
-
- if (mode == 0)
- {
- value = "";
- key = "";
- return false;
- }
- else
- {
- value = valuestr;
- key = keystr;
- return true;
- }
- }
-
- public static int StrCmpRetInt(string s1, string s2)
- {
- return string.Compare(s1, s2, false);
- }
- public static int StrCmpiRetInt(string s1, string s2)
- {
- return string.Compare(s1, s2, true);
- }
-
- public static bool IsStrInList(string str, params string[] args)
- {
- return IsStrInList(str, true, args);
- }
- public static bool IsStrInList(string str, bool ignoreCase, params string[] args)
- {
- foreach (string s in args)
- {
- if (ignoreCase)
- {
- if (StrCmpi(str, s))
- {
- return true;
- }
- }
- else
- {
- if (StrCmp(str, s))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public static bool IsDouble(string str)
- {
- double v;
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return double.TryParse(str, out v);
- }
-
- public static bool IsLong(string str)
- {
- long v;
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return long.TryParse(str, out v);
- }
-
- public static bool IsInt(string str)
- {
- int v;
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
- return int.TryParse(str, out v);
- }
-
- public static bool IsNumber(string str)
- {
- str = str.Trim();
- Str.RemoveSpaceChar(ref str);
- Str.NormalizeString(ref str, true, true, false, false);
- str = str.Replace(",", "");
-
- foreach (char c in str)
- {
- if (IsNumber(c) == false)
- {
- return false;
- }
- }
-
- return true;
- }
- public static bool IsNumber(char c)
- {
- if (c >= '0' && c <= '9')
- {
- }
- else if (c == '-')
- {
- }
- else
- {
- return false;
- }
-
- return true;
- }
-
- public static bool InStr(string str, string keyword)
- {
- return InStr(str, keyword, false);
- }
- public static bool InStr(string str, string keyword, bool caseSensitive)
- {
- if (str.IndexOf(keyword, (caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) == -1)
- {
- return false;
- }
-
- return true;
- }
-
- public static string MakeCharArray(char c, int len)
- {
- return new string(c, len);
- }
-
- public static string NormalizeCrlf(string str)
- {
- return NormalizeCrlf(str, new byte[] { 13, 10 });
- }
- public static string NormalizeCrlf(string str, byte[] crlfData)
- {
- byte[] srcData = Str.Utf8Encoding.GetBytes(str);
- byte[] destData = NormalizeCrlf(srcData, crlfData);
- return Str.Utf8Encoding.GetString(destData);
- }
- public static byte[] NormalizeCrlf(byte[] srcData)
- {
- return NormalizeCrlf(srcData, new byte[] { 13, 10 });
- }
- public static byte[] NormalizeCrlf(byte[] srcData, byte[] crlfData)
- {
- Buf ret = new Buf();
-
- int i;
- Buf b = new Buf();
- for (i = 0; i < srcData.Length; i++)
- {
- bool isNewLine = false;
- if (srcData[i] == 13)
- {
- if (i < (srcData.Length - 1) && srcData[i + 1] == 10)
- {
- i++;
- }
- isNewLine = true;
- }
- else if (srcData[i] == 10)
- {
- isNewLine = true;
- }
-
- if (isNewLine)
- {
- ret.Write(b.ByteData);
- ret.Write(crlfData);
-
- b.Clear();
- }
- else
- {
- b.WriteByte(srcData[i]);
- }
- }
- ret.Write(b.ByteData);
-
- return ret.ByteData;
- }
-
- public static string[] UniqueToken(string[] t)
- {
- Dictionary o = new Dictionary();
- List ret = new List();
-
- foreach (string s in t)
- {
- string key = s.ToUpper();
-
- if (o.ContainsKey(key) == false)
- {
- o.Add(key, new Object());
-
- ret.Add(s);
- }
- }
-
- return ret.ToArray();
- }
-
- public static string ToStr3(long v)
- {
- bool neg = false;
-
- if (v < 0)
- {
- neg = true;
- v = v * (long)-1;
- }
-
- string tmp, tmp2;
- int i;
-
- tmp = Str.LongToStr(v);
-
- tmp2 = "";
- for (i = tmp.Length - 1; i >= 0; i--)
- {
- tmp2 += tmp[i];
- }
-
- int len = tmp.Length;
-
- tmp = "";
- for (i = 0; i < len; i++)
- {
- if (i != 0 && (i % 3) == 0)
- {
- tmp += ",";
- }
-
- tmp += tmp2[i];
- }
-
- char[] array = tmp.ToCharArray();
- Array.Reverse(array);
-
- string str = new string(array);
-
- if (neg)
- {
- str = "-" + str;
- }
-
- return str;
- }
-
- public static string[] ParseCmdLine(string str)
- {
- List o;
- int i, len, mode;
- string tmp;
- bool ignoreSpace = false;
-
- o = new List();
- mode = 0;
- len = str.Length;
-
- tmp = "";
-
- for (i = 0; i < len; i++)
- {
- char c = str[i];
-
- switch (mode)
- {
- case 0:
- if (c == ' ' || c == '\t')
- {
- }
- else
- {
- if (c == '\"')
- {
- if ((i != (len - 1)) && str[i + 1] == '\"')
- {
- tmp += '\"';
- i++;
- }
- else
- {
- ignoreSpace = true;
- }
- }
- else
- {
- tmp += c;
- }
-
- mode = 1;
- }
- break;
-
- case 1:
- if (ignoreSpace == false && (c == ' ' || c == '\t'))
- {
- o.Add(tmp);
- tmp = "";
- mode = 0;
- }
- else
- {
- if (c == '\"')
- {
- if ((i != (len - 1)) && str[i + 1] == '\"')
- {
- tmp += '\"';
- i++;
- }
- else
- {
- if (ignoreSpace == false)
- {
- ignoreSpace = true;
- }
- else
- {
- ignoreSpace = false;
- }
- }
- }
- else
- {
- tmp += c;
- }
- }
- break;
- }
- }
-
- if (tmp.Length != 0)
- {
- o.Add(tmp);
- tmp = "";
- }
-
- return o.ToArray();
- }
-
- public static string ObjectToXMLSimple(object o)
- {
- return ObjectToXMLSimple(o, o.GetType());
- }
- public static string ObjectToXMLSimple(object o, Type t)
- {
- XmlSerializer xs = new XmlSerializer(t);
-
- MemoryStream ms = new MemoryStream();
- xs.Serialize(ms, o);
-
- return Str.Utf8Encoding.GetString(ms.ToArray());
- }
-
- public static object XMLToObjectSimple(string str, Type t)
- {
- XmlSerializer xs = new XmlSerializer(t);
-
- MemoryStream ms = new MemoryStream();
- byte[] data = Str.Utf8Encoding.GetBytes(str);
- ms.Write(data, 0, data.Length);
- ms.Position = 0;
-
- return xs.Deserialize(ms);
- }
-
- public static bool IsStrOkForXML(string str)
- {
- try
- {
- XmlCheckObjectInternal o = new XmlCheckObjectInternal();
- o.Str = str;
-
- string xmlstr = ObjectToXMLSimple(o);
-
- XMLToObjectSimple(xmlstr, typeof(XmlCheckObjectInternal));
-
- return true;
- }
- catch
- {
- return false;
- }
- }
- }
-
- public class XmlCheckObjectInternal
- {
- public string Str;
- }
-
- public class StrToken
- {
- string[] tokens;
-
- public string[] Tokens
- {
- get { return tokens; }
- }
-
- public string this[uint index]
- {
- get { return tokens[index]; }
- }
-
- public uint NumTokens
- {
- get
- {
- return (uint)Tokens.Length;
- }
- }
-
- const string defaultSplitStr = " ,\t\r\n";
-
- public static string DefaultSplitStr
- {
- get { return defaultSplitStr; }
- }
-
- public StrToken(string[] tokens)
- {
- List a = new List();
- foreach (string s in tokens)
- {
- a.Add(s);
- }
-
- this.tokens = a.ToArray();
- }
-
- public StrToken(string str)
- : this(str, null)
- {
- }
- public StrToken(string str, string splitStr)
- {
- if (splitStr == null)
- {
- splitStr = defaultSplitStr;
- }
- int i, len;
- len = splitStr.Length;
- char[] chars = new char[len];
- for (i = 0; i < len; i++)
- {
- chars[i] = splitStr[i];
- }
- tokens = str.Split(chars, StringSplitOptions.RemoveEmptyEntries);
- }
- }
-
- public class StrData
- {
- string strValue;
-
- public string StrValue
- {
- get { return strValue; }
- }
-
- public uint IntValue
- {
- get
- {
- return Str.StrToUInt(strValue);
- }
- }
-
- public ulong Int64Value
- {
- get
- {
- return Str.StrToULong(strValue);
- }
- }
-
- public bool BoolValue
- {
- get
- {
- string s = strValue.Trim();
-
- if (Str.IsEmptyStr(s))
- {
- return false;
- }
- if (s.StartsWith("true", StringComparison.CurrentCultureIgnoreCase))
- {
- return true;
- }
- if ("true".StartsWith(s, StringComparison.CurrentCultureIgnoreCase))
- {
- return true;
- }
- if (s.StartsWith("yes", StringComparison.CurrentCultureIgnoreCase))
- {
- return true;
- }
- if ("yes".StartsWith(s, StringComparison.CurrentCultureIgnoreCase))
- {
- return true;
- }
-
- if (Str.StrToUInt(s) != 0)
- {
- return true;
- }
-
- return false;
- }
- }
-
- public StrData(string str)
- {
- if (str == null)
- {
- str = "";
- }
- strValue = str;
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Tar.cs b/src/BuildUtil/CoreUtil/Tar.cs
deleted file mode 100644
index 2cc7725a..00000000
--- a/src/BuildUtil/CoreUtil/Tar.cs
+++ /dev/null
@@ -1,359 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Runtime.InteropServices;
-
-namespace CoreUtil
-{
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- public struct TarHeader
- {
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
- public byte[] Name;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] Mode;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] UID;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] GID;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
- public byte[] Size;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
- public byte[] MTime;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] CheckSum;
-
- public byte TypeFlag;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
- public byte[] LinkName;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
- public byte[] Magic;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
- public byte[] Version;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
- public byte[] UName;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
- public byte[] GName;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] DevMajor;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
- public byte[] DevMinor;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 155)]
- public byte[] Prefix;
-
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
- public byte[] Padding;
-
- public TarHeader(bool dummy)
- {
- this.Name = new byte[100];
- this.Mode = new byte[8];
- this.UID = new byte[8];
- this.GID = new byte[8];
- this.Size = new byte[12];
- this.MTime = new byte[12];
- this.CheckSum = new byte[8];
- this.LinkName = new byte[100];
- this.Magic = new byte[6];
- this.Version = new byte[2];
- this.UName = new byte[32];
- this.GName = new byte[32];
- this.DevMajor = new byte[8];
- this.DevMinor = new byte[8];
- this.Prefix = new byte[155];
- this.Padding = new byte[12];
- this.TypeFlag = 0;
-
- this.Version[0] = 0x20;
- this.Version[1] = 0x00;
-
- byte[] data = Str.ShiftJisEncoding.GetBytes("ustar ");
- Util.CopyByte(this.Magic, 0, data, 0, 6);
- }
-
- public void SetName(string name, Encoding encoding)
- {
- byte[] data = encoding.GetBytes(name);
- if (data.Length <= 100)
- {
- Util.CopyByte(this.Name, 0, data, 0, data.Length);
- }
- else
- {
- Util.CopyByte(this.Name, 0, data, 0, 100);
- Util.CopyByte(this.Prefix, 0, data, 100, data.Length - 100);
- }
- }
-
- public void SetMode(string str)
- {
- StrToByteArray(this.Mode, str);
- }
-
- public void SetUID(string str)
- {
- StrToByteArray(this.UID, str);
- }
-
- public void SetGID(string str)
- {
- StrToByteArray(this.GID, str);
- }
-
- public void SetSize(long size)
- {
- if (size >= 0x1FFFFFFFF || size < 0)
- {
- throw new InvalidDataException("size");
- }
- StrToByteArray(this.Size, Str.AppendZeroToNumString(Convert.ToString(size, 8), 11));
- }
-
- public void SetMTime(DateTime dt)
- {
- uint t = Util.DateTimeToUnixTime(dt.ToUniversalTime());
-
- StrToByteArray(this.MTime, Str.AppendZeroToNumString(Convert.ToString(t, 8), 11));
- }
-
- public void CalcChecksum()
- {
- TarHeader h2 = this;
- Array.Clear(h2.CheckSum, 0, h2.CheckSum.Length);
- byte[] data = Util.StructToByte(h2);
- SetChecksum(data);
- }
-
- public void SetChecksum(byte[] data)
- {
- ulong sum = 0;
- int i;
- for (i = 0; i < data.Length; i++)
- {
- sum += (ulong)data[i];
- }
-
- sum += 0x100;
-
- StrToByteArray(this.CheckSum, Str.AppendZeroToNumString(Convert.ToString((long)sum, 8), 6));
- this.CheckSum[7] = 0x20;
- }
-
- public void SetTypeFlag(int flag)
- {
- this.TypeFlag = (byte)flag.ToString()[0];
- }
-
- public void SetUName(string str)
- {
- StrToByteArray(this.UName, str);
- }
-
- public void SetGName(string str)
- {
- StrToByteArray(this.GName, str);
- }
-
- public static void StrToByteArray(byte[] dst, string str)
- {
- Encoding e = Str.ShiftJisEncoding;
-
- byte[] d = e.GetBytes(str);
-
- Array.Clear(dst, 0, dst.Length);
- Util.CopyByte(dst, 0, d, 0, Math.Min(d.Length, dst.Length - 1));
- }
- }
-
- public static class TarUtil
- {
- public static TarHeader CreateTarHeader(string name, Encoding encoding, int type, long size, DateTime dt)
- {
- return CreateTarHeader(name, encoding, type, size, dt, "0000777");
- }
-
- public static TarHeader CreateTarHeader(string name, Encoding encoding, int type, long size, DateTime dt, string mode)
- {
- TarHeader h = new TarHeader(false);
-
- h.SetName(name, encoding);
-
- h.SetMode(mode);
- h.SetMTime(dt);
- h.SetName(name, encoding);
- h.SetSize(size);
- h.SetTypeFlag(type);
- h.SetGID("0000000");
- h.SetUID("0000000");
-
- h.CalcChecksum();
-
- return h;
- }
- }
-
- public class TarPacker
- {
- Fifo fifo;
- Dictionary dirList;
- Encoding encoding;
-
- public TarPacker()
- : this(Str.ShiftJisEncoding)
- {
- }
- public TarPacker(Encoding encoding)
- {
- fifo = new Fifo();
- dirList = new Dictionary(new StrEqualityComparer(true));
- this.encoding = encoding;
- }
-
- public void AddDirectory(string name, DateTime dt, string mode)
- {
- name = name.Replace('\\', '/');
- if (name.EndsWith("/") == false)
- {
- name = name + "/";
- }
-
- if (dirList.ContainsKey(name) == false)
- {
- TarHeader h = TarUtil.CreateTarHeader(name, encoding, 5, 0, dt, mode);
- fifo.Write(Util.StructToByte(h));
-
- dirList.Add(name, 0);
- }
- }
-
- public void AddDirectory(string name, DateTime dt)
- {
- AddDirectory(name, dt, "0000777");
- }
-
- long currentFileSize = 0;
- long currentPos = 0;
-
- public void AddFileSimple(string name, byte[] data, int pos, int len, DateTime dt)
- {
- AddFileSimple(name, data, pos, len, dt, "0000777", "0000777");
- }
-
- public void AddFileSimple(string name, byte[] data, int pos, int len, DateTime dt, string directory_mode, string mode)
- {
- AddFileStart(name, len, dt, directory_mode, mode);
- AddFileData(data, pos, len);
- }
-
- public void AddFileStart(string name, long size, DateTime dt)
- {
- AddFileStart(name, size, dt, "0000777", "0000777");
- }
-
- public void AddFileStart(string name, long size, DateTime dt, string directory_mode, string mode)
- {
- if (currentFileSize != 0 || currentPos != 0)
- {
- throw new ApplicationException("last file not completed.");
- }
-
- name = name.Replace('\\', '/');
- if (Str.InStr(name, "/", true))
- {
- AddDirectory(Path.GetDirectoryName(name), dt, directory_mode);
- }
-
- TarHeader h = TarUtil.CreateTarHeader(name, encoding, 0, size, dt, mode);
- fifo.Write(Util.StructToByte(h));
-
- currentFileSize = size;
- currentPos = 0;
- }
-
- public void AddFileData(byte[] data, int pos, int len)
- {
- long totalSize = currentPos + len;
-
- if (totalSize > currentFileSize)
- {
- throw new ApplicationException("totalSize > currentFileSize");
- }
-
- fifo.Write(data, pos, len);
-
- currentPos += len;
- if (currentPos >= currentFileSize)
- {
- long padding = ((currentFileSize + 511) / 512) * 512 - currentFileSize;
-
- byte[] pad = new byte[padding];
- Array.Clear(pad, 0, pad.Length);
- fifo.Write(pad, 0, pad.Length);
-
- currentFileSize = 0;
- currentPos = 0;
- }
- }
-
- public Fifo GeneratedData
- {
- get
- {
- return this.fifo;
- }
- }
-
- public void Finish()
- {
- byte[] data = new byte[1024];
- Array.Clear(data, 0, data.Length);
-
- fifo.Write(data);
- }
-
- public byte[] CompressToGZip()
- {
- GZipPacker g = new GZipPacker();
- byte[] data = this.fifo.Read();
-
- g.Write(data, 0, data.Length, true);
-
- return g.GeneratedData.Read();
- }
- }
-}
diff --git a/src/BuildUtil/CoreUtil/Thread.cs b/src/BuildUtil/CoreUtil/Thread.cs
deleted file mode 100644
index caa45e41..00000000
--- a/src/BuildUtil/CoreUtil/Thread.cs
+++ /dev/null
@@ -1,471 +0,0 @@
-// CoreUtil
-
-
-using System;
-using System.Threading;
-using System.Data;
-using System.Data.Sql;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Text;
-using System.Configuration;
-using System.Collections;
-using System.Collections.Generic;
-using System.Security.Cryptography;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.IO;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.Drawing.Drawing2D;
-using System.Diagnostics;
-using System.Web.Mail;
-using System.Net;
-using System.Net.Sockets;
-using System.Net.NetworkInformation;
-using System.Net.Mail;
-using System.Net.Mime;
-using CoreUtil;
-
-#pragma warning disable 0618
-
-namespace CoreUtil
-{
- class WorkerQueuePrivate
- {
- object lockObj = new object();
-
- List thread_list;
- ThreadProc thread_proc;
- int num_worker_threads;
- Queue