go my file uploader

This commit is contained in:
AirDog46
2025-05-13 19:45:22 +03:00
commit c5fab8aa94
708 changed files with 343216 additions and 0 deletions

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ProcessHackerSetup", "ProcessHackerSetup\ProcessHackerSetup.vcxproj", "{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}.Debug|Win32.ActiveCfg = Debug|Win32
{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}.Debug|Win32.Build.0 = Debug|Win32
{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}.Release|Win32.ActiveCfg = Release|Win32
{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5C00734F-F50A-49FC-9D2A-F6EE51ECB00F}</ProjectGuid>
<RootNamespace>ProcessHackerSetup</RootNamespace>
<WindowsTargetPlatformVersion>10.0.10586.0</WindowsTargetPlatformVersion>
<ProjectName>ProcessHackerSetup</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(ProjectDir)bin\$(Configuration)$(PlatformArchitecture)\</OutDir>
<IntDir>$(ProjectDir)obj\$(Configuration)$(PlatformArchitecture)\</IntDir>
<GenerateManifest>true</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(ProjectDir)bin\$(Configuration)$(PlatformArchitecture)\</OutDir>
<IntDir>$(ProjectDir)obj\$(Configuration)$(PlatformArchitecture)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<AdditionalIncludeDirectories>..\..\..\phnt\include;..\..\..\phlib\include;include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<MinimalRebuild>false</MinimalRebuild>
<CallingConvention>StdCall</CallingConvention>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PreprocessorDefinitions>_PHLIB_;_WINDOWS;WIN32;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<StringPooling>true</StringPooling>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>uxtheme.lib;phlib.lib;ntdll.lib;%(AdditionalDependencies)</AdditionalDependencies>
<UACExecutionLevel>RequireAdministrator</UACExecutionLevel>
<AdditionalLibraryDirectories>..\..\..\phlib\bin\$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Full</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<AdditionalIncludeDirectories>..\..\..\phnt\include;..\..\..\phlib\include;include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<CallingConvention>StdCall</CallingConvention>
<PreprocessorDefinitions>_PHLIB_;_WINDOWS;WIN32;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<SDLCheck>true</SDLCheck>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<StringPooling>true</StringPooling>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>uxtheme.lib;phlib.lib;ntdll.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\..\..\phlib\bin\$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<UACExecutionLevel>RequireAdministrator</UACExecutionLevel>
<SubSystem>Windows</SubSystem>
<MinimumRequiredVersion>5.01</MinimumRequiredVersion>
<SetChecksum>true</SetChecksum>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="setup\download.c" />
<ClCompile Include="setup\extract.c" />
<ClCompile Include="lib\appsup.c" />
<ClCompile Include="lib\miniz\miniz.c" />
<ClCompile Include="lib\netio.c" />
<ClCompile Include="main.c" />
<ClCompile Include="page1.c" />
<ClCompile Include="page2.c" />
<ClCompile Include="page3.c" />
<ClCompile Include="page4.c" />
<ClCompile Include="page5.c" />
<ClCompile Include="lib\progress.c" />
<ClCompile Include="lib\superclass.c" />
<ClCompile Include="setup\reset.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="include\setup.h" />
<ClInclude Include="include\appsup.h" />
<ClInclude Include="lib\miniz\miniz.h" />
<ClInclude Include="include\netio.h" />
<ClInclude Include="resource.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="resource.rc" />
</ItemGroup>
<ItemGroup>
<Manifest Include="resources\app.manifest">
<SubType>Designer</SubType>
</Manifest>
</ItemGroup>
<ItemGroup>
<Image Include="resources\ProcessHacker.ico" />
<Image Include="resources\ProcessHacker.png" />
</ItemGroup>
<ItemGroup>
<Text Include="resources\Licence.txt" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Resource Files\Images">
<UniqueIdentifier>{3f81aff6-dff1-4573-bb20-ac132fa9297b}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\lib">
<UniqueIdentifier>{7a7dfb06-20d6-4ea2-8992-26ea6e6cf1d9}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\lib">
<UniqueIdentifier>{c6910170-43ca-47cd-b0cf-f8fae8c47669}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\setup">
<UniqueIdentifier>{c394360d-d423-4249-a23e-70558948e7f2}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="page1.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="page2.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="page5.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="page4.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="page3.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="lib\appsup.c">
<Filter>Source Files\lib</Filter>
</ClCompile>
<ClCompile Include="lib\netio.c">
<Filter>Source Files\lib</Filter>
</ClCompile>
<ClCompile Include="lib\miniz\miniz.c">
<Filter>Source Files\lib</Filter>
</ClCompile>
<ClCompile Include="setup\download.c">
<Filter>Source Files\setup</Filter>
</ClCompile>
<ClCompile Include="setup\extract.c">
<Filter>Source Files\setup</Filter>
</ClCompile>
<ClCompile Include="setup\reset.c">
<Filter>Source Files\setup</Filter>
</ClCompile>
<ClCompile Include="lib\progress.c">
<Filter>Source Files\lib</Filter>
</ClCompile>
<ClCompile Include="lib\superclass.c">
<Filter>Source Files\lib</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="include\setup.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="lib\miniz\miniz.h">
<Filter>Header Files\lib</Filter>
</ClInclude>
<ClInclude Include="include\appsup.h">
<Filter>Header Files\lib</Filter>
</ClInclude>
<ClInclude Include="include\netio.h">
<Filter>Header Files\lib</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Image Include="resources\ProcessHacker.ico">
<Filter>Resource Files\Images</Filter>
</Image>
<Image Include="resources\ProcessHacker.png">
<Filter>Resource Files\Images</Filter>
</Image>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<Text Include="resources\Licence.txt">
<Filter>Resource Files</Filter>
</Text>
</ItemGroup>
<ItemGroup>
<Manifest Include="resources\app.manifest">
<Filter>Resource Files</Filter>
</Manifest>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,79 @@
#ifndef _APPSUP_H
#define _APPSUP_H
extern PWSTR Version;
extern PWSTR DownloadURL;
extern HWND _hwndProgress;
#define STATUS_MSG(Format, ...) \
{ \
PPH_STRING msgString = PhFormatString(Format, __VA_ARGS__); \
if (msgString) \
{ \
SetDlgItemText(_hwndProgress, IDC_MAINHEADER1, msgString->Buffer); \
DEBUG_MSG(L"%s\n", msgString->Buffer); \
PhDereferenceObject(msgString); \
} \
}
typedef struct _STOPWATCH
{
LARGE_INTEGER StartCounter;
LARGE_INTEGER EndCounter;
LARGE_INTEGER Frequency;
} STOPWATCH, *PSTOPWATCH;
PPH_STRING GetSystemTemp(VOID);
PPH_STRING BrowseForFolder(
_In_opt_ HWND DialogHandle,
_In_opt_ PCWSTR Title
);
VOID InitializeFont(
_In_ HWND ControlHandle,
_In_ LONG Height,
_In_ LONG Weight
);
VOID StopwatchInitialize(
__out PSTOPWATCH Stopwatch
);
VOID StopwatchStart(
_Inout_ PSTOPWATCH Stopwatch
);
ULONG StopwatchGetMilliseconds(
_In_ PSTOPWATCH Stopwatch
);
BOOLEAN CreateLink(
_In_ PWSTR DestFilePath,
_In_ PWSTR FilePath,
_In_ PWSTR FileParentDir,
_In_ PWSTR FileComment
);
PWSTR XmlParseToken(
_In_ PWSTR XmlString,
_In_ PWSTR XmlTokenName
);
HBITMAP LoadPngImageFromResources(
_In_ PCWSTR Name
);
_Maybenull_
PPH_STRING GetProcessHackerInstallPath(
VOID
);
BOOLEAN CreateDirectoryPath(
_In_ PPH_STRING DirectoryPath
);
#endif _APPSUP_H

View File

@@ -0,0 +1,71 @@
#ifndef _PH_NETIO_H
#define _PH_NETIO_H
#pragma comment(lib, "Winhttp.lib")
#include <winhttp.h>
typedef struct _HTTP_SESSION
{
HINTERNET SessionHandle;
HINTERNET ConnectionHandle;
HINTERNET RequestHandle;
} HTTP_SESSION, *P_HTTP_SESSION;
typedef struct _HTTP_PARSED_URL
{
WCHAR HttpMethod[10];
WCHAR HttpServer[200];
WCHAR HttpPath[200];
} *HTTP_PARSED_URL;
P_HTTP_SESSION HttpSocketCreate(VOID);
BOOLEAN HttpConnect(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR ServerName,
_In_ INTERNET_PORT ServerPort
);
BOOLEAN HttpBeginRequest(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR MethodType,
_In_ PCWSTR UrlPath,
_In_ ULONG Flags
);
BOOLEAN HttpSendRequest(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ ULONG TotalLength
);
BOOLEAN HttpEndRequest(
_Inout_ P_HTTP_SESSION HttpSocket
);
BOOLEAN HttpAddRequestHeaders(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR RequestHeaders
);
PPH_STRING HttpGetRequestHeaderString(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR RequestHeader
);
ULONG HttpGetRequestHeaderDword(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ ULONG Flags
);
PPH_STRING HttpDownloadString(
_Inout_ P_HTTP_SESSION HttpSocket
);
BOOLEAN HttpParseURL(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR Url,
_Out_ HTTP_PARSED_URL* HttpParsedUrl
);
#endif

View File

@@ -0,0 +1,126 @@
#ifndef _SETUP_H
#define _SETUP_H
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "WindowsCodecs.lib")
#define CINTERFACE
#define COBJMACROS
#include <ph.h>
#include <guisup.h>
#include <prsht.h>
#include <WindowsX.h>
#include <Wincodec.h>
#include <uxtheme.h>
#include <Shlwapi.h>
#include "..\resource.h"
// PropertySheet Control IDs
#define IDD_PROPSHEET_ID 1006 // ID of the propsheet dialog template in comctl32.dll
#define IDC_PROPSHEET_APPLYNOW 0x3021
#define IDC_PROPSHEET_DLGFRAME 0x3022
#define IDC_PROPSHEET_BACK 0x3023
#define IDC_PROPSHEET_NEXT 0x3024
#define IDC_PROPSHEET_FINISH 0x3025
#define IDC_PROPSHEET_DIVIDER 0x3026
#define IDC_PROPSHEET_TOPDIVIDER 0x3027
// Debug Macro
#ifdef _DEBUG
#define DEBUG_MSG(Format, ...) \
{ \
PPH_STRING debugString = PhFormatString(Format, __VA_ARGS__); \
if (debugString) \
{ \
OutputDebugString(debugString->Buffer); \
PhDereferenceObject(debugString); \
} \
}
#else
#define DEBUG_MSG(Format, ...)
#endif
extern PPH_STRING SetupInstallPath;
INT_PTR CALLBACK PropSheetPage1_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
);
INT_PTR CALLBACK PropSheetPage2_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
);
INT_PTR CALLBACK PropSheetPage3_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
);
INT_PTR CALLBACK PropSheetPage4_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
);
INT_PTR CALLBACK PropSheetPage5_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
);
VOID StartProgress(VOID);
VOID _SetProgressTime(VOID);
VOID SetProgress(
_In_ LONG Completed,
_In_ LONG Total
);
_Check_return_
BOOLEAN ProcessHackerShutdown(
VOID
);
_Check_return_
BOOLEAN RemoveAppCompatEntries(
VOID
);
_Check_return_
ULONG KphUninstall(
VOID
);
BOOLEAN SetupDownloadBuild(
_In_ PVOID Arguments
);
BOOLEAN SetupResetCurrentInstall(
_In_ PVOID Arguments
);
BOOLEAN SetupExtractBuild(
_In_ PVOID Arguments
);
LRESULT CALLBACK SubclassWindowProc(
_In_ HWND hWnd,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam,
_In_ UINT_PTR uIdSubclass,
_In_ DWORD_PTR dwRefData
);
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,785 @@
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
//#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
// get/set file times, and the C run-time funcs that get/set times won't be called.
// The current downside is the times written to your archives will be from 1979.
//#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
//#define MINIZ_NO_MALLOC
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#if MINIZ_X86_OR_X64_CPU
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
// Compression strategies.
enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void(*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
enum
{
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum
{
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum
{
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s
{
const unsigned char *next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char *next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char *msg; // error msg (unused)
struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void *opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream *mz_streamp;
// Returns the version string of miniz.c.
const char *mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
// mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
// with more input data, or with more room in the output buffer (except when using single call decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the error code is invalid.
const char *mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum
{
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct _mz_zip_archive_file_stat
{
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t(*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
typedef size_t(*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum _mz_zip_mode
{
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef struct _mz_zip_archive
{
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
mz_uint m_total_files;
mz_zip_mode m_zip_mode;
mz_uint m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef enum _mz_zip_flags
{
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and modified times.
// This function only extracts files, not archive directory records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
// the archive is finalized the file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by the end of central directory record.
// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
// An archive must be manually finalized by calling this function for it to be valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
// Note for the archive to be valid, it must have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
enum
{
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
// The caller must call mz_free() on the returned block when it's no longer needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int(*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum
{
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum
{
TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct
{
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag
{
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).
enum
{
TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.
// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).
// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum
{
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
// Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
// Compresses an image to a compressed PNG file in memory.
// On entry:
// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pLen_out will be set to the size of the PNG image file.
// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool(*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
#else
enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
#endif
// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
typedef enum
{
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1,
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum
{
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct
{
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
// If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
// tdefl_compress_buffer() always consumes the entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
// window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#endif // MINIZ_HEADER_INCLUDED

View File

@@ -0,0 +1,327 @@
#include <setup.h>
#include "netio.h"
static VOID HttpSocketFree(
_In_ __deref_out PVOID Object
)
{
P_HTTP_SESSION httpSocket = (P_HTTP_SESSION)Object;
if (httpSocket->RequestHandle)
WinHttpCloseHandle(httpSocket->RequestHandle);
if (httpSocket->ConnectionHandle)
WinHttpCloseHandle(httpSocket->ConnectionHandle);
if (httpSocket->SessionHandle)
WinHttpCloseHandle(httpSocket->SessionHandle);
}
P_HTTP_SESSION HttpSocketCreate(VOID)
{
P_HTTP_SESSION httpSocket;
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig = { 0 };
httpSocket = (P_HTTP_SESSION)PhAllocate(sizeof(HTTP_SESSION));
memset(httpSocket, 0, sizeof(HTTP_SESSION));
WinHttpGetIEProxyConfigForCurrentUser(&proxyConfig);
httpSocket->SessionHandle = WinHttpOpen(
NULL,
proxyConfig.lpszProxy ? WINHTTP_ACCESS_TYPE_NAMED_PROXY : WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
proxyConfig.lpszProxy ? proxyConfig.lpszProxy : WINHTTP_NO_PROXY_NAME,
proxyConfig.lpszProxy ? proxyConfig.lpszProxyBypass : WINHTTP_NO_PROXY_BYPASS,
0
);
return httpSocket;
}
BOOLEAN HttpConnect(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR ServerName,
_In_ INTERNET_PORT ServerPort
)
{
// Create the HTTP connection handle.
HttpSocket->ConnectionHandle = WinHttpConnect(
HttpSocket->SessionHandle,
ServerName,
ServerPort,
0
);
if (HttpSocket->ConnectionHandle)
return TRUE;
return FALSE;
}
BOOLEAN HttpBeginRequest(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR MethodType,
_In_ PCWSTR UrlPath,
_In_ ULONG Flags
)
{
HttpSocket->RequestHandle = WinHttpOpenRequest(
HttpSocket->ConnectionHandle,
MethodType,
UrlPath,
NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
Flags
);
if (HttpSocket->RequestHandle)
return TRUE;
return FALSE;
}
BOOLEAN HttpSendRequest(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ ULONG TotalLength
)
{
return WinHttpSendRequest(
HttpSocket->RequestHandle,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
WINHTTP_NO_REQUEST_DATA,
0,
TotalLength,
0
) == TRUE;
}
BOOLEAN HttpEndRequest(
_Inout_ P_HTTP_SESSION HttpSocket
)
{
return WinHttpReceiveResponse(HttpSocket->RequestHandle, NULL) == TRUE;
}
BOOLEAN HttpAddRequestHeaders(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR RequestHeaders
)
{
return WinHttpAddRequestHeaders(HttpSocket->RequestHandle, RequestHeaders, -1L, WINHTTP_ADDREQ_FLAG_ADD) == TRUE;
}
//PVOID HttpGetRequestHeaderValue(
// _Inout_ P_HTTP_SESSION HttpSocket,
// _In_ LPCWSTR RequestHeader,
// _In_ ULONG Flags
// )
//{
// PVOID buffer = NULL;
// ULONG bufferSize = 0;
// LRESULT keyResult = NO_ERROR;
//
// // Get the length of the data...
// if (!WinHttpQueryHeaders(
// HttpSocket->RequestHandle,
// Flags,
// RequestHeader,
// WINHTTP_NO_OUTPUT_BUFFER,
// &bufferSize,
// WINHTTP_NO_HEADER_INDEX
// ))
// {
// if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
// return NULL;
// }
//
// // Allocate the buffer...
// buffer = PhAllocate(bufferSize, NULL);
//
// // Query the value...
// if (!WinHttpQueryHeaders(
// HttpSocket->RequestHandle,
// Flags,
// RequestHeader,
// buffer,
// &bufferSize,
// WINHTTP_NO_HEADER_INDEX
// ))
// {
// if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
// return NULL;
// }
//
// if (buffer)
// return buffer;
//
// PhFree(buffer);
// return NULL;
//}
PPH_STRING HttpGetRequestHeaderString(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR RequestHeader
)
{
ULONG bufferSize = 0;
PPH_STRING stringBuffer = NULL;
// Get the length of the data...
if (!WinHttpQueryHeaders(
HttpSocket->RequestHandle,
WINHTTP_QUERY_CUSTOM,
RequestHeader,
WINHTTP_NO_OUTPUT_BUFFER,
&bufferSize,
WINHTTP_NO_HEADER_INDEX
))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return NULL;
}
// Allocate the buffer...
stringBuffer = PhCreateStringEx(NULL, bufferSize);
// Query the data value...
if (WinHttpQueryHeaders(
HttpSocket->RequestHandle,
WINHTTP_QUERY_CUSTOM,
RequestHeader,
stringBuffer->Buffer,
&bufferSize,
WINHTTP_NO_HEADER_INDEX
))
{
return stringBuffer;
}
PhDereferenceObject(stringBuffer);
return NULL;
}
ULONG HttpGetRequestHeaderDword(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ ULONG Flags
)
{
ULONG dwordResult = 0;
ULONG dwordLength = sizeof(ULONG);
ULONG dwordResultTemp = 0;
if (WinHttpQueryHeaders(
HttpSocket->RequestHandle,
Flags | WINHTTP_QUERY_FLAG_NUMBER,
NULL,
&dwordResultTemp,
&dwordLength,
WINHTTP_NO_HEADER_INDEX
))
{
dwordResult = dwordResultTemp;
}
return dwordResult;
}
PPH_STRING HttpDownloadString(
_Inout_ P_HTTP_SESSION HttpSocket
)
{
PSTR tempDataPtr = NULL;
PPH_STRING tempHttpString = NULL;
PPH_STRING hashETag = NULL;
PPH_STRING finalHexString = NULL;
ULONG dataLength = 0;
ULONG returnLength = 0;
ULONG allocatedLength = PAGE_SIZE;
BYTE buffer[PAGE_SIZE];
tempDataPtr = (PSTR)PhAllocate(allocatedLength);
while (WinHttpReadData(HttpSocket->RequestHandle, buffer, PAGE_SIZE, &returnLength))
{
if (returnLength == 0)
break;
if (allocatedLength < dataLength + returnLength)
{
allocatedLength *= 2;
tempDataPtr = (PSTR)PhReAllocate(tempDataPtr, allocatedLength);
}
memcpy(tempDataPtr + dataLength, buffer, returnLength);
memset(buffer, 0, returnLength);
dataLength += returnLength;
}
// Add space for the null terminator..
if (allocatedLength < dataLength + 1)
{
allocatedLength++;
tempDataPtr = (PSTR)PhReAllocate(tempDataPtr, allocatedLength);
}
// Ensure that the buffer is null-terminated.
tempDataPtr[dataLength] = 0;
tempHttpString = PhConvertMultiByteToUtf16(tempDataPtr);
if (hashETag)
{
PhDereferenceObject(hashETag);
}
if (finalHexString)
{
PhDereferenceObject(finalHexString);
}
if (tempDataPtr)
{
PhFree(tempDataPtr);
}
return tempHttpString;
}
BOOLEAN HttpParseURL(
_Inout_ P_HTTP_SESSION HttpSocket,
_In_ PCWSTR Url,
_Out_ HTTP_PARSED_URL* HttpParsedUrl
)
{
URL_COMPONENTS httpUrlComponents;
memset(&httpUrlComponents, 0, sizeof(URL_COMPONENTS));
httpUrlComponents.dwStructSize = sizeof(URL_COMPONENTS);
httpUrlComponents.dwSchemeLength = (ULONG)-1;
httpUrlComponents.dwHostNameLength = (ULONG)-1;
httpUrlComponents.dwUrlPathLength = (ULONG)-1;
if (WinHttpCrackUrl(
Url,
0,//(ULONG)wcslen(Url),
0,
&httpUrlComponents
))
{
HTTP_PARSED_URL httpParsedUrl = PhAllocate(sizeof(struct _HTTP_PARSED_URL));
memset(httpParsedUrl, 0, sizeof(struct _HTTP_PARSED_URL));
wmemcpy(httpParsedUrl->HttpMethod, httpUrlComponents.lpszScheme, httpUrlComponents.dwSchemeLength);
wmemcpy(httpParsedUrl->HttpServer, httpUrlComponents.lpszHostName, httpUrlComponents.dwHostNameLength);
wmemcpy(httpParsedUrl->HttpPath, httpUrlComponents.lpszUrlPath, httpUrlComponents.dwUrlPathLength);
*HttpParsedUrl = httpParsedUrl;
return TRUE;
}
return FALSE;
}

View File

@@ -0,0 +1,256 @@
#include <setup.h>
#include <Windows.h>
#include "appsup.h"
#include "netio.h"
#define TIME_DAYS_IN_YEAR 365
#define TIME_HOURS_IN_DAY 24
#define TIME_MINUTES_IN_HOUR 60
#define TIME_SECONDS_IN_MINUTE 60
HWND _hwndProgress = NULL;
static BOOLEAN _TotalChanged = FALSE;
static BOOLEAN _CompletedChanged = FALSE;
static STOPWATCH InstallTimer = { 0 };
static volatile LONG _Completed = 0; // progress completed
static volatile LONG _Total = 0; // total progress
static volatile LONG _PrevRate = 0; // previous progress rate (used for computing time remaining)
static volatile LONG _PrevTickCount = 0; // the tick count when we last updated the progress time
static volatile LONG _PrevCompleted = 0; // the amount we had completed when we last updated the progress time
static volatile LONG _LastUpdatedTimeRemaining = 0; // tick count when we last update the "Time remaining" field, we only update it every 5 seconds
static volatile LONG _LastUpdatedTickCount = 0; // tick count when SetProgress was last called, used to calculate the rate
static volatile LONG _NumTimesSetProgressCalled = 0; // how many times has the user called SetProgress?
VOID StartProgress(VOID)
{
StopwatchInitialize(&InstallTimer);
StopwatchStart(&InstallTimer);
_PrevRate = 0;
_PrevCompleted = 0;
_Completed = 0; // progress completed
//_dwTotal = 0;
_PrevRate = 0; // previous progress rate (used for computing time remaining)
_PrevTickCount = 0; // the tick count when we last updated the progress time
_PrevCompleted = 0; // the amount we had completed when we last updated the progress time
_LastUpdatedTimeRemaining = 0;// tick count when we last update the "Time remaining" field, we only update it every 5 seconds
_LastUpdatedTickCount = 0; // tick count when SetProgress was last called, used to calculate the rate
_NumTimesSetProgressCalled = 0;// how many times has the user called SetProgress?
SetProgress(0, 0);
}
VOID _SetProgressTime(VOID)
{
volatile LONG dwTotal = 0;
volatile LONG dwCompleted = 0;
volatile LONG dwCurrentRate = 0;
volatile LONG dwTickDelta = 0;
volatile LONG dwLeft = 0;
volatile LONG dwCurrentTickCount = 0;
volatile LONG dwAverageRate = 0;
LONG dwSecondsLeft = 0;
LONG dwTickCount = 0;
LONG time_taken = 0;
LONG download_speed = 0;
PPH_STRING timeRemainingString = NULL;
InterlockedIncrement(&_NumTimesSetProgressCalled);
InterlockedExchange(&dwTotal, _Total);
InterlockedExchange(&dwCompleted, _Completed);
InterlockedExchange(&dwCurrentTickCount, _LastUpdatedTickCount);
dwLeft = dwTotal - dwCompleted;
dwTickDelta = dwCurrentTickCount - _PrevTickCount;
dwTickCount = StopwatchGetMilliseconds(&InstallTimer);
if (_TotalChanged)
{
_TotalChanged = FALSE;
SendDlgItemMessage(_hwndProgress, IDC_PROGRESS1, PBM_SETRANGE32, 0, (LPARAM)dwTotal);
}
if (_CompletedChanged)
{
_CompletedChanged = FALSE;
SendDlgItemMessage(_hwndProgress, IDC_PROGRESS1, PBM_SETPOS, (WPARAM)dwCompleted, 0);
}
if (dwCompleted <= _PrevCompleted)
{
// we are going backwards...
dwCurrentRate = (_PrevRate ? _PrevRate : 2);
}
else
{
// calculate the current rate in points per tenth of a second
dwTickDelta /= 100;
if (dwTickDelta == 0)
dwTickDelta = __max(dwTickDelta, 1); // Protect from divide by zero
dwCurrentRate = (dwCompleted - _PrevCompleted) / dwTickDelta;
}
// we divide the TickDelta by 100 to give tenths of seconds, so if we have recieved an update faster than that, just skip it
//if (dwTickDelta < 100)
// return;
// time remaining in seconds (we take a REAL average to smooth out random fluxuations)
dwAverageRate = (ULONG)((dwCurrentRate + (__int64)_PrevRate * _NumTimesSetProgressCalled) / (_NumTimesSetProgressCalled + 1));
dwAverageRate = __max(dwAverageRate, 1); // Protect from divide by zero
dwSecondsLeft = (dwLeft / dwAverageRate) / 10;
// Skip the first five calls (we need an average)...
//if (_NumTimesSetProgressCalled > 5)// ((dwSecondsLeft >= MIN_MINTIME4FEEDBACK) && (_iNumTimesSetProgressCalled >= 5))
{
time_taken = dwCurrentTickCount - dwTickDelta;
time_taken = __max(time_taken, 1); // Protect from divide by zero
download_speed = (dwCompleted / time_taken) * 1024;
//if (download_speed)
{
LONGLONG nPercent = 0;
PPH_STRING statusRemaningBytesString = PhFormatSize(dwCompleted, -1);
PPH_STRING statusLengthString = PhFormatSize(dwTotal, -1);
PPH_STRING statusSpeedString = PhFormatSize(download_speed, -1);
if (dwTotal)
{
// Will scaling it up cause a wrap?
if ((100 * 100) <= dwTotal)
{
// Yes, so scale down.
nPercent = (dwCompleted / (dwTotal / 100));
}
else
{
// No, so scale up.
nPercent = ((100 * dwCompleted) / dwTotal);
}
}
PPH_STRING statusText1 = PhFormatString(L"Transfer rate: %s/s ", statusSpeedString->Buffer);
PPH_STRING statusText2 = PhFormatString(L"Downloaded: %s of %s (%u%% Completed)",
statusRemaningBytesString->Buffer,
statusLengthString->Buffer,
nPercent
);
SetDlgItemText(_hwndProgress, IDC_REMAINTIME, statusText1->Buffer);
SetDlgItemText(_hwndProgress, IDC_REMAINTIME3, statusText2->Buffer);
PhDereferenceObject(statusText2);
PhDereferenceObject(statusText1);
PhDereferenceObject(statusSpeedString);
PhDereferenceObject(statusLengthString);
PhDereferenceObject(statusRemaningBytesString);
}
// Is it more than an hour?
if (dwSecondsLeft > (TIME_SECONDS_IN_MINUTE * TIME_MINUTES_IN_HOUR))
{
LONGLONG dwMinutes = dwSecondsLeft / TIME_SECONDS_IN_MINUTE;
LONGLONG dwHours = dwMinutes / TIME_MINUTES_IN_HOUR;
LONGLONG dwDays = dwHours / TIME_HOURS_IN_DAY;
if (dwDays)
{
dwHours %= TIME_HOURS_IN_DAY;
// It's more than a day, so display days and hours.
if (dwDays == 1)
{
if (dwHours == 1)
timeRemainingString = PhFormatString(L"Remaining time: %u day and %u hour", dwHours, dwMinutes);
else
timeRemainingString = PhFormatString(L"Remaining time: %u day and %u hours", dwHours, dwMinutes);
}
else
{
if (dwHours == 1)
timeRemainingString = PhFormatString(L"Remaining time: %u days and %u hour", dwHours, dwMinutes);
else
timeRemainingString = PhFormatString(L"Remaining time: %u days and %u hours", dwHours, dwMinutes);
}
}
else
{
// It's less than a day, so display hours and minutes.
dwMinutes %= TIME_MINUTES_IN_HOUR;
if (dwHours == 1)
{
if (dwMinutes == 1)
timeRemainingString = PhFormatString(L"Remaining time: %u hour and %u minute", dwHours, dwMinutes);
else
timeRemainingString = PhFormatString(L"Remaining time: %u hour and %u minutes", dwHours, dwMinutes);
}
else
{
if (dwMinutes == 1)
timeRemainingString = PhFormatString(L"Remaining time: %u hours and %u minute", dwHours, dwMinutes);
else
{
ULONG stime = dwSecondsLeft %= TIME_MINUTES_IN_HOUR;
timeRemainingString = PhFormatString(L"Remaining time: %u hours, %u minutes and %u seconds", dwHours, dwMinutes, stime);
}
}
}
}
else
{
if (dwSecondsLeft > TIME_SECONDS_IN_MINUTE)
{
ULONG time = dwSecondsLeft / TIME_SECONDS_IN_MINUTE;
ULONG stime = dwSecondsLeft %= TIME_MINUTES_IN_HOUR;
timeRemainingString = PhFormatString(L"Remaining time: %u minutes and %u seconds", time, stime);
}
else
{
if (dwSecondsLeft > 0)
{
// Round up to 5 seconds so it doesn't look so random
//ULONG stime = ((dwSecondsLeft + 4) / 5) * 5;
timeRemainingString = PhFormatString(L"Remaining time: %u seconds", dwSecondsLeft);
}
else
{
timeRemainingString = PhFormatString(L"Remaining time: 0 seconds");
}
}
}
// update the Time remaining field
SetDlgItemText(_hwndProgress, IDC_REMAINTIME2, timeRemainingString->Buffer);
PhDereferenceObject(timeRemainingString);
}
// we are updating now, so set all the stuff for next time
InterlockedExchange(&_LastUpdatedTimeRemaining, dwTickCount);
InterlockedExchange(&_PrevRate, dwAverageRate);
InterlockedExchange(&_PrevTickCount, dwCurrentTickCount);
InterlockedExchange(&_PrevCompleted, dwCompleted);
}
VOID SetProgress(
_In_ LONG Completed,
_In_ LONG Total
)
{
if (InterlockedCompareExchange(&_Completed, _Completed, Completed) != Completed)
{
InterlockedExchange(&_Completed, Completed);
_CompletedChanged = TRUE;
}
if (InterlockedCompareExchange(&_Total, _Total, Total) != Total)
{
InterlockedExchange(&_Total, Total);
_TotalChanged = TRUE;
}
InterlockedExchange(&_LastUpdatedTickCount, StopwatchGetMilliseconds(&InstallTimer));
}

View File

@@ -0,0 +1,247 @@
#include <setup.h>
#pragma comment(lib, "Msimg32.lib")
//_Success_(return != NULL)
INT GetWindowWidth(HWND hwnd)
{
RECT rect = { 0 };
GetWindowRect(hwnd, &rect);
return (rect.right - rect.left);
}
INT GetWindowHeight(HWND hwnd)
{
RECT rect = { 0 };
GetWindowRect(hwnd, &rect);
return (rect.bottom - rect.top);
}
INT GetClientWindowWidth(HWND hwnd)
{
RECT rect = { 0 };
GetClientRect(hwnd, &rect);
return (rect.right - rect.left);
}
INT GetClientWindowHeight(HWND hwnd)
{
RECT rect = { 0 };
GetClientRect(hwnd, &rect);
return (rect.bottom - rect.top);
}
static VOID InflateClientRect(
_Inout_ PRECT rect,
_In_ INT x,
_In_ INT y
)
{
rect->left -= x;
rect->top -= y;
rect->right += x;
rect->bottom += y;
}
static VOID FrameClientRect(
_In_ HDC hdc,
_In_ const PRECT rect,
_In_ HBRUSH hbrush
)
{
if ((rect->right <= rect->left) || (rect->bottom <= rect->top))
return;
HBRUSH prevBrush = SelectObject(hdc, hbrush);
PatBlt(hdc, rect->left, rect->top, 1, rect->bottom - rect->top, PATCOPY);
PatBlt(hdc, rect->right - 1, rect->top, 1, rect->bottom - rect->top, PATCOPY);
PatBlt(hdc, rect->left, rect->top, rect->right - rect->left, 1, PATCOPY);
PatBlt(hdc, rect->left, rect->bottom - 1, rect->right - rect->left, 1, PATCOPY);
if (prevBrush)
{
SelectObject(hdc, prevBrush);
}
}
static VOID FillClientRect(
_In_ HDC hdc,
_In_ const PRECT rect,
_In_ HBRUSH hbrush
)
{
HBRUSH prevBrush = SelectObject(hdc, hbrush);
PatBlt(
hdc,
rect->left,
rect->top,
rect->right - rect->left,
rect->bottom - rect->top,
PATCOPY
);
if (prevBrush)
{
SelectObject(hdc, prevBrush);
}
}
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb760816.aspx
VOID DrawProgressBarControl(
_In_ HWND WindowHandle,
_In_ HDC WindowDC,
_In_ RECT ClientRect
)
{
INT curValue = SendMessage(WindowHandle, PBM_GETPOS, 0, 0);
INT maxValue = SendMessage(WindowHandle, PBM_GETRANGE, 0, 0);
FLOAT percent = ((FLOAT)curValue / (FLOAT)maxValue) * 100.f;
int oldBkMode = SetBkMode(WindowDC, TRANSPARENT);
// Fill window background
FillClientRect(WindowDC, &ClientRect, GetSysColorBrush(COLOR_3DFACE));
// Draw window border
FrameClientRect(WindowDC, &ClientRect, GetStockBrush(LTGRAY_BRUSH));
if (curValue < 1)
{
return;
}
//if (maxValue < 1)
//{
// return;
//}
InflateClientRect(
&ClientRect,
-GetSystemMetrics(SM_CXBORDER) * 2,
-GetSystemMetrics(SM_CYBORDER) * 2
);
// Set progress fill length
ClientRect.right = ((LONG)(ClientRect.left + ((ClientRect.right - ClientRect.left) * percent) / 100));
// Draw progress fill border
//FrameClientRect(WindowDC, &ClientRect, GetStockBrush(BLACK_BRUSH));
//InflateClientRect(
// &ClientRect,
// -GetSystemMetrics(SM_CXBORDER),
// -GetSystemMetrics(SM_CYBORDER)
// );
HBRUSH brush = GetSysColorBrush(COLOR_HIGHLIGHT);// CreateSolidBrush(RGB(48, 190, 50));
FillClientRect(WindowDC, &ClientRect, brush);
DeleteObject(brush);
// draw background last?
//SubtractRect()
SetBkMode(WindowDC, oldBkMode);
}
LRESULT CALLBACK SubclassWindowProc(
_In_ HWND hWnd,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam,
_In_ UINT_PTR uIdSubclass,
_In_ DWORD_PTR dwRefData
)
{
switch (uMsg)
{
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
PAINTSTRUCT paintStruct;
RECT clientRect;
GetClientRect(hWnd, &clientRect);
if (BeginPaint(hWnd, &paintStruct))
{
SetBkMode(paintStruct.hdc, TRANSPARENT);
//if (BeginBufferedPaint_I)
//{
// HDC bufferedHdc = NULL;
// HPAINTBUFFER bufferedHandle = NULL;
// if (bufferedHandle = BeginBufferedPaint_I(
// paintStruct.hdc,
// &clientRect,
// BPBF_COMPATIBLEBITMAP,
// NULL,
// &bufferedHdc
// ))
// {
// if (uIdSubclass == IDC_PROGRESS1)
// {
// DrawProgressBarControl(hWnd, bufferedHdc, clientRect);
// }
// if (EndBufferedPaint_I)
// {
// EndBufferedPaint_I(bufferedHandle, TRUE);
// }
// }
// else
// {
// DrawProgressBarControl(hWnd, paintStruct.hdc, clientRect);
// }
//}
//else
{
DrawProgressBarControl(hWnd, paintStruct.hdc, clientRect);
}
EndPaint(hWnd, &paintStruct);
}
return 1;
}
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
//VOID SetupSuperSubclass(VOID)
//{
// WNDCLASSEX windowClassInfo = { sizeof(WNDCLASSEX) };
//
// if (GetClassInfoEx(NULL, WC_BUTTON, &windowClassInfo))
// {
// parentWndProc = windowClassInfo.lpfnWndProc; // save the original message handler
// windowClassInfo.lpfnWndProc = WindowProc; // Set our new message handler
//
// UnregisterClass(WC_BUTTON, NULL);
// RegisterClassEx(&windowClassInfo);
//
// return TRUE;
// }
//
// return FALSE;
//}

View File

@@ -0,0 +1,120 @@
#include <setup.h>
PPH_STRING SetupInstallPath = NULL;
static VOID PvpInitializeDpi(
VOID
)
{
HDC hdc;
if (hdc = GetDC(NULL))
{
PhGlobalDpi = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(NULL, hdc);
}
}
INT CALLBACK MainPropSheet_Callback(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
case PSCB_INITIALIZED:
{
}
break;
case PSCB_PRECREATE:
{
if (lParam)
{
((LPDLGTEMPLATE)lParam)->style |= WS_MINIMIZEBOX;
}
}
break;
}
return FALSE;
}
INT WINAPI wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ PWSTR lpCmdLine,
_In_ INT nCmdShow
)
{
PROPSHEETPAGE propSheetPage = { sizeof(PROPSHEETPAGE) };
PROPSHEETHEADER propSheetHeader = { sizeof(PROPSHEETHEADER) };
HPROPSHEETPAGE pages[5];
if (!NT_SUCCESS(PhInitializePhLibEx(0, 0, 0)))
return 1;
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
PhApplicationName = L"Process Hacker - Setup";
PhGuiSupportInitialization();
PvpInitializeDpi();
propSheetHeader.dwFlags =
PSH_NOAPPLYNOW |
PSH_NOCONTEXTHELP |
PSH_USECALLBACK |
PSH_WIZARD_LITE;
propSheetHeader.hInstance = PhLibImageBase;
propSheetHeader.pszIcon = MAKEINTRESOURCE(IDI_ICON1);
propSheetHeader.pfnCallback = MainPropSheet_Callback;
propSheetHeader.phpage = pages;
// page
memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
propSheetPage.dwFlags = PSP_USETITLE;
propSheetPage.pszTitle = PhApplicationName;
propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG1);
propSheetPage.pfnDlgProc = PropSheetPage1_WndProc;
pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);
// page
memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
propSheetPage.dwFlags = PSP_USETITLE;
propSheetPage.pszTitle = PhApplicationName;
propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG2);
propSheetPage.pfnDlgProc = PropSheetPage2_WndProc;
pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);
// page
memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG3);
propSheetPage.pfnDlgProc = PropSheetPage3_WndProc;
pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);
// page
memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
propSheetPage.dwFlags = PSP_USETITLE;
propSheetPage.pszTitle = PhApplicationName;
propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG4);
propSheetPage.pfnDlgProc = PropSheetPage4_WndProc;
pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);
// page
memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));
propSheetPage.dwSize = sizeof(PROPSHEETPAGE);
propSheetPage.dwFlags = PSP_USETITLE;
propSheetPage.pszTitle = PhApplicationName;
propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG5);
propSheetPage.pfnDlgProc = PropSheetPage5_WndProc;
pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);
PhModalPropertySheet(&propSheetHeader);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,130 @@
#include <setup.h>
#include <appsup.h>
VOID LoadSetupIcons(
_In_ HWND hwndDlg
)
{
HBITMAP smallIconHandle = (HBITMAP)LoadImage(
PhLibImageBase,
MAKEINTRESOURCE(IDI_ICON1),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_DEFAULTCOLOR
);
HBITMAP largeIconHandle = (HBITMAP)LoadImage(
PhLibImageBase,
MAKEINTRESOURCE(IDI_ICON1),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_DEFAULTCOLOR
);
SendMessage(GetParent(hwndDlg), WM_SETICON, ICON_SMALL, (LPARAM)smallIconHandle);
SendMessage(GetParent(hwndDlg), WM_SETICON, ICON_BIG, (LPARAM)largeIconHandle);
DeleteObject(largeIconHandle);
DeleteObject(smallIconHandle);
}
VOID LoadSetupImage(
_In_ HWND hwndDlg
)
{
HBITMAP imageBitmap = LoadPngImageFromResources(MAKEINTRESOURCE(IDB_PNG1));
// The image control uses a large square frame so that we can use the VS designer easily.
// Remove the frame style and apply the bitmap style.
PhSetWindowStyle(
GetDlgItem(hwndDlg, IDC_PROJECT_ICON),
SS_BITMAP | SS_BLACKFRAME,
SS_BITMAP
);
SendMessage(
GetDlgItem(hwndDlg, IDC_PROJECT_ICON),
STM_SETIMAGE,
IMAGE_BITMAP,
(LPARAM)imageBitmap
);
DeleteObject(imageBitmap);
}
BOOL PropSheetPage1_OnInitDialog(
_In_ HWND hwndDlg,
_In_ HWND hwndFocus,
_Inout_ LPARAM lParam
)
{
LoadSetupIcons(hwndDlg);
LoadSetupImage(hwndDlg);
// Center the dialog window on the desktop
PhCenterWindow(GetParent(hwndDlg), NULL);
SetForegroundWindow(GetParent(hwndDlg));
// Set the fonts
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER), 24, FW_SEMIBOLD);
InitializeFont(GetDlgItem(hwndDlg, IDC_SUBHEADER), 0, FW_NORMAL);
// Enable the themed dialog background texture.
EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
BOOL PropSheetPage1_OnNotify(
_In_ HWND hwndDlg,
_In_ INT idCtrl,
_Inout_ LPNMHDR lpNmh
)
{
LPPSHNOTIFY pageNotify = (LPPSHNOTIFY)lpNmh;
switch (pageNotify->hdr.code)
{
case PSN_SETACTIVE:
{
HWND hwPropSheet = pageNotify->hdr.hwndFrom;
// Disable the back button on Welcome page.
//PropSheet_SetWizButtons(hwPropSheet, PSWIZB_NEXT);
// Hide the back button on the Welcome page.
ShowWindow(GetDlgItem(hwPropSheet, IDC_PROPSHEET_BACK), SW_HIDE);
}
break;
case PSN_KILLACTIVE:
{
HWND hwPropSheet = pageNotify->hdr.hwndFrom;
// Enable the back button for other pages.
//PropSheet_SetWizButtons(hwPropSheet, PSWIZB_NEXT | PSWIZB_BACK);
// Show the back button for other pages.
ShowWindow(GetDlgItem(hwPropSheet, IDC_PROPSHEET_BACK), SW_SHOW);
}
break;
}
return FALSE;
}
INT_PTR CALLBACK PropSheetPage1_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hwndDlg, WM_INITDIALOG, PropSheetPage1_OnInitDialog);
HANDLE_MSG(hwndDlg, WM_NOTIFY, PropSheetPage1_OnNotify);
}
return FALSE;
}

View File

@@ -0,0 +1,131 @@
#include <setup.h>
#include <appsup.h>
VOID LoadEulaText(
_In_ HWND hwndDlg
)
{
HRSRC resourceHandle;
HGLOBAL resourceData;
PVOID resourceBuffer;
resourceHandle = FindResource(PhLibImageBase, MAKEINTRESOURCE(IDR_TXT1), L"TXT");
if (resourceHandle)
{
resourceData = LoadResource(PhLibImageBase, resourceHandle);
if (resourceData)
{
resourceBuffer = LockResource(resourceData);
if (resourceBuffer)
{
PPH_STRING eulaTextString = PhConvertMultiByteToUtf16(resourceBuffer);
SetWindowText(GetDlgItem(hwndDlg, IDC_EDIT1), eulaTextString->Buffer);
PhDereferenceObject(eulaTextString);
}
}
FreeResource(resourceHandle);
}
}
BOOL PropSheetPage2_OnInitDialog(
_In_ HWND hwndDlg,
_In_ HWND hwndFocus,
_Inout_ LPARAM lParam
)
{
// Set the fonts.
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER), -17, FW_SEMIBOLD);
// Set the default radio button state to 'do not accept'.
Button_SetCheck(GetDlgItem(hwndDlg, IDC_RADIO2), BST_CHECKED);
LoadEulaText(hwndDlg);
// Enable the themed dialog background texture.
EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
BOOL PropSheetPage2_OnNotify(
_In_ HWND hwndDlg,
_In_ INT idCtrl,
_Inout_ LPNMHDR lpNmh
)
{
LPPSHNOTIFY pageNotify = (LPPSHNOTIFY)lpNmh;
switch (pageNotify->hdr.code)
{
case PSN_SETACTIVE:
{
HWND hwPropSheet = pageNotify->hdr.hwndFrom;
#ifndef DEBUG
// Disable the property sheet Next button, the user must accept the EULA to continue.
PropSheet_SetWizButtons(hwPropSheet, PSWIZB_BACK);
#endif
}
break;
case PSN_QUERYINITIALFOCUS:
{
// Set the default control as the 'do not accept' radio button.
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LPARAM)GetDlgItem(hwndDlg, IDC_RADIO2));
}
return TRUE;
}
return FALSE;
}
BOOL PropSheetPage2_OnCommand(
_In_ HWND hwndDlg,
_In_ INT id,
_In_ HWND hwndCtl,
_In_ UINT codeNotify
)
{
switch (id)
{
case IDC_RADIO1:
case IDC_RADIO2:
{
if (Button_GetCheck(GetDlgItem(hwndDlg, IDC_RADIO1)) == BST_CHECKED)
{
// The user has agreed to the EULA, enable the Next button.
PropSheet_SetWizButtons(GetParent(hwndDlg), PSWIZB_NEXT | PSWIZB_BACK);
}
else
{
// The user did not agree, disable the next button.
PropSheet_SetWizButtons(GetParent(hwndDlg), PSWIZB_BACK);
}
}
break;
}
return FALSE;
}
INT_PTR CALLBACK PropSheetPage2_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hwndDlg, WM_INITDIALOG, PropSheetPage2_OnInitDialog);
HANDLE_MSG(hwndDlg, WM_NOTIFY, PropSheetPage2_OnNotify);
HANDLE_MSG(hwndDlg, WM_COMMAND, PropSheetPage2_OnCommand);
}
return FALSE;
}

View File

@@ -0,0 +1,144 @@
#include <setup.h>
#include <appsup.h>
VOID LoadInstallDirectory(
_In_ HWND hwndDlg
)
{
if (SetupInstallPath = GetProcessHackerInstallPath())
{
// We must make sure the install path ends with a backslash since
// this string is wcscat' with our zip extraction paths.
if (PathAddBackslash(SetupInstallPath->Buffer))
{
//PathSearchAndQualify()
}
}
// If the string is null or empty, use the default installation path.
if (PhIsNullOrEmptyString(SetupInstallPath))
{
//SetupInstallPath = PhGetKnownLocation(CSIDL_PROGRAM_FILES, L"\\Process Hacker 2\\settings.xml");
// TODO: Find a better method that handles Program Files on different drives than C:
// (It's common for some poeple to do this)
if (WindowsVersion >= WINDOWS_7)
{
PPH_STRING defaultInstallPath;
PPH_STRING expandedString;
// TODO: Does ProgramW6432 work on 32bit?
defaultInstallPath = PhCreateString(L"%ProgramW6432%\\Process Hacker 2\\");
if (expandedString = PhExpandEnvironmentStrings(&defaultInstallPath->sr))
{
SetupInstallPath = expandedString;
}
}
}
if (PhIsNullOrEmptyString(SetupInstallPath))
{
SetupInstallPath = PhCreateString(L"C:\\Program Files\\Process Hacker 2\\");
}
SetDlgItemText(hwndDlg, IDC_INSTALL_DIRECTORY, SetupInstallPath->Buffer);
}
BOOL PropSheetPage3_OnInitDialog(
_In_ HWND hwndDlg,
_In_ HWND hwndFocus,
_Inout_ LPARAM lParam
)
{
// Set the fonts.
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER), -17, FW_SEMIBOLD);
// Set the default checkboxes.
Button_SetCheck(GetDlgItem(hwndDlg, IDC_CHECK1), TRUE);
Button_SetCheck(GetDlgItem(hwndDlg, IDC_CHECK6), TRUE);
if (WindowsVersion >= WINDOWS_VISTA)
{
SendMessage(
GetDlgItem(hwndDlg, IDC_INSTALL_DIRECTORY),
EM_SETMARGINS,
EC_LEFTMARGIN | EC_RIGHTMARGIN,
MAKELPARAM(0, 0)
);
}
LoadInstallDirectory(hwndDlg);
// Enable the themed dialog background texture.
EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
BOOL PropSheetPage3_OnNotify(
_In_ HWND hwndDlg,
_In_ INT idCtrl,
_Inout_ LPNMHDR lpNmh
)
{
LPPSHNOTIFY pageNotify = (LPPSHNOTIFY)lpNmh;
switch (pageNotify->hdr.code)
{
case PSN_QUERYINITIALFOCUS:
{
// Set the default control as the browse button.
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LPARAM)GetDlgItem(hwndDlg, IDC_FOLDER_BROWSE));
}
return TRUE;
}
return FALSE;
}
BOOL PropSheetPage3_OnCommand(
_In_ HWND hwndDlg,
_In_ INT id,
_In_ HWND hwndCtl,
_In_ UINT codeNotify
)
{
switch (id)
{
case IDC_FOLDER_BROWSE:
{
PPH_STRING installFolder;
installFolder = BrowseForFolder(hwndDlg, L"Select installation folder");
if (installFolder)
{
PhSwapReference(&SetupInstallPath, installFolder);
SetDlgItemText(hwndDlg, IDC_INSTALL_DIRECTORY, SetupInstallPath->Buffer);
}
}
break;
}
return FALSE;
}
INT_PTR CALLBACK PropSheetPage3_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hwndDlg, WM_INITDIALOG, PropSheetPage3_OnInitDialog);
HANDLE_MSG(hwndDlg, WM_NOTIFY, PropSheetPage3_OnNotify);
HANDLE_MSG(hwndDlg, WM_COMMAND, PropSheetPage3_OnCommand);
}
return FALSE;
}

View File

@@ -0,0 +1,120 @@
#include <setup.h>
#include <appsup.h>
NTSTATUS DownloadThread(
_In_ PVOID Arguments
)
{
BOOLEAN setupSuccess = FALSE;
// Download the latest build
if (setupSuccess = SetupDownloadBuild(Arguments))
{
// Reset the current installation
if (setupSuccess = SetupResetCurrentInstall(Arguments))
{
// Extract and install the latest build
if (setupSuccess = SetupExtractBuild(Arguments))
{
PostMessage(Arguments, PSM_SETCURSELID, 0, IDD_DIALOG5);
}
}
}
if (!setupSuccess)
{
// Retry download...
PostMessage(Arguments, PSM_SETCURSELID, 0, IDD_DIALOG4);
}
return STATUS_SUCCESS;
}
BOOL PropSheetPage4_OnInitDialog(
_In_ HWND hwndDlg,
_In_ HWND hwndFocus,
_Inout_ LPARAM lParam
)
{
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER), -17, FW_SEMIBOLD);
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER1), -12, FW_SEMIBOLD);
SetWindowSubclass(
GetDlgItem(hwndDlg, IDC_PROGRESS1),
SubclassWindowProc,
IDC_PROGRESS1,
0
);
// Enable the themed dialog background texture.
EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
BOOL PropSheetPage4_OnNotify(
_In_ HWND hwndDlg,
_In_ INT idCtrl,
_Inout_ LPNMHDR lpNmh
)
{
LPPSHNOTIFY pageNotify = (LPPSHNOTIFY)lpNmh;
switch (pageNotify->hdr.code)
{
case PSN_SETACTIVE:
{
HWND hwPropSheet = pageNotify->hdr.hwndFrom;
// Disable Next/Back buttons
PropSheet_SetWizButtons(hwPropSheet, 0);
_hwndProgress = hwndDlg;
SetTimer(hwndDlg, 1, 100, NULL);
PhCreateThread(0, DownloadThread, hwPropSheet);
}
break;
case PSN_QUERYCANCEL:
{
//if (UpdateResetState == InstallStateResetting || UpdateResetState == InstallStateInstalling)
//PropSheet_CancelToClose(GetParent(hwndDlg));
//EnableMenuItem(GetSystemMenu(GetParent(hwndDlg), FALSE), SC_CLOSE, MF_GRAYED);
//EnableMenuItem(GetSystemMenu(GetParent(hwndDlg), FALSE), SC_CLOSE, MF_ENABLED);
//SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LPARAM)TRUE);
//return TRUE;
}
break;
case PSN_KILLACTIVE:
{
KillTimer(hwndDlg, 1);
}
break;
}
return FALSE;
}
INT_PTR CALLBACK PropSheetPage4_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hwndDlg, WM_INITDIALOG, PropSheetPage4_OnInitDialog);
HANDLE_MSG(hwndDlg, WM_NOTIFY, PropSheetPage4_OnNotify);
case WM_TIMER:
{
_SetProgressTime();
}
break;
}
return FALSE;
}

View File

@@ -0,0 +1,79 @@
#include <setup.h>
#include <appsup.h>
static VOID LoadSetupImage(
_In_ HWND hwndDlg
)
{
HBITMAP imageBitmap = LoadPngImageFromResources(MAKEINTRESOURCE(IDB_PNG1));
// The image control uses a large square frame so that we can use the VS dialog designer more easily.
// Remove the frame style and apply the bitmap style.
PhSetWindowStyle(
GetDlgItem(hwndDlg, IDC_PROJECT_ICON),
SS_BITMAP | SS_BLACKFRAME,
SS_BITMAP
);
SendMessage(
GetDlgItem(hwndDlg, IDC_PROJECT_ICON),
STM_SETIMAGE,
IMAGE_BITMAP,
(LPARAM)imageBitmap
);
DeleteObject(imageBitmap);
}
BOOL PropSheetPage5_OnInitDialog(
_In_ HWND hwndDlg,
_In_ HWND hwndFocus,
_Inout_ LPARAM lParam
)
{
// Set the fonts.
InitializeFont(GetDlgItem(hwndDlg, IDC_MAINHEADER), -17, FW_SEMIBOLD);
LoadSetupImage(hwndDlg);
// Enable the themed dialog background texture.
EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
BOOL PropSheetPage5_OnNotify(
_In_ HWND hwndDlg,
_In_ INT idCtrl,
_Inout_ LPNMHDR lpNmh
)
{
LPPSHNOTIFY pageNotify = (LPPSHNOTIFY)lpNmh;
switch (pageNotify->hdr.code)
{
case PSN_SETACTIVE:
{
Button_SetText(GetDlgItem(pageNotify->hdr.hwndFrom, IDCANCEL), L"Close");
}
break;
}
return FALSE;
}
INT_PTR CALLBACK PropSheetPage5_WndProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_Inout_ WPARAM wParam,
_Inout_ LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hwndDlg, WM_INITDIALOG, PropSheetPage5_OnInitDialog);
HANDLE_MSG(hwndDlg, WM_NOTIFY, PropSheetPage5_OnNotify);
}
return FALSE;
}

Binary file not shown.

View File

@@ -0,0 +1,234 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright <20> 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
<EFBFBD>This License<73> refers to version 3 of the GNU General Public License.
<EFBFBD>Copyright<EFBFBD> also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
<EFBFBD>The Program<61> refers to any copyrightable work licensed under this License. Each licensee is addressed as <20>you<6F>. <20>Licensees<65> and <20>recipients<74> may be individuals or organizations.
To <20>modify<66> a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a <20>modified version<6F> of the earlier work or a work <20>based on<6F> the earlier work.
A <20>covered work<72> means either the unmodified Program or a work based on the Program.
To <20>propagate<74> a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To <20>convey<65> a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays <20>Appropriate Legal Notices<65> to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The <20>source code<64> for a work means the preferred form of the work for making modifications to it. <20>Object code<64> means any non-source form of a work.
A <20>Standard Interface<63> means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The <20>System Libraries<65> of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A <20>Major Component<6E>, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The <20>Corresponding Source<63> for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to <20>keep intact all notices<65>.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an <20>aggregate<74> if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A <20>User Product<63> is either (1) a <20>consumer product<63>, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, <20>normally used<65> refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
<EFBFBD>Installation Information<6F> for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
<EFBFBD>Additional permissions<6E> are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered <20>further restrictions<6E> within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An <20>entity transaction<6F> is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A <20>contributor<6F> is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's <20>contributor version<6F>.
A contributor's <20>essential patent claims<6D> are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, <20>control<6F> includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a <20>patent license<73> is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To <20>grant<6E> such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. <20>Knowingly relying<6E> means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is <20>discriminatory<72> if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License <20>or any later version<6F> applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM <20>AS IS<49> WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the <20>copyright<68> line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an <20>about box<6F>.
You should also get your employer (if you work as a programmer) or school, if any, to sign a <20>copyright disclaimer<65> for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
Process Hacker is distributed under the GNU GPL version 3,
with the following exception:
Permission is granted to dynamically (but not statically) link this
program with independent modules, regardless of the license terms of
these independent modules, provided that this program is not modified
in any way. An independent module is a module which is not derived
from or based on this program. If you modify this program, this
additional permission no longer applies unless authorized by the
copyright holders.

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity name="ProcessHackerSetup" processorArchitecture="*" version="1.0.0.0" type="win32" />
<description>Process Hacker Setup</description>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
</application>
</compatibility>
<asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>false</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>

View File

@@ -0,0 +1,294 @@
#include <setup.h>
#include <appsup.h>
#include <netio.h>
PWSTR Version = NULL;
PWSTR DownloadURL = NULL;
BOOLEAN QueryBuildServerThread(
_Inout_ P_HTTP_SESSION HttpSocket
)
{
BOOLEAN isSuccess = FALSE;
PPH_STRING xmlStringData = NULL;
__try
{
STATUS_MSG(L"Connecting to build server...\n");
Sleep(500);
if (!HttpConnect(HttpSocket, L"wj32.org", INTERNET_DEFAULT_HTTPS_PORT))
{
STATUS_MSG(L"HttpConnect: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Connected to build server...\n");
Sleep(500);
if (!HttpBeginRequest(HttpSocket, NULL, L"/processhacker/update.php", WINHTTP_FLAG_SECURE))
{
STATUS_MSG(L"HttpBeginRequest: %u\n", GetLastError());
__leave;
}
if (!HttpAddRequestHeaders(HttpSocket, L"ProcessHacker-OsBuild: 0x0D06F00D"))
{
STATUS_MSG(TEXT("HttpAddRequestHeaders: %u\n"), GetLastError());
__leave;
}
if (!HttpSendRequest(HttpSocket, 0))
{
STATUS_MSG(L"HttpSendRequest: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Querying build server...");
Sleep(500);
if (!HttpEndRequest(HttpSocket))
{
STATUS_MSG(L"HttpEndRequest: %u\n", GetLastError());
__leave;
}
if (!(xmlStringData = HttpDownloadString(HttpSocket)))
{
STATUS_MSG(L"HttpDownloadString: %u\n", GetLastError());
__leave;
}
Version = PhFormatString(
L"%s.%s",
XmlParseToken(xmlStringData->Buffer, L"ver"),
XmlParseToken(xmlStringData->Buffer, L"rev")
)->Buffer;
DownloadURL = PhFormatString(
L"https://github.com/processhacker2/processhacker2/releases/download/v%s/processhacker-%s-bin.zip",
XmlParseToken(xmlStringData->Buffer, L"ver"),
XmlParseToken(xmlStringData->Buffer, L"ver")
)->Buffer;
STATUS_MSG(L"Found build: %s\n", Version);
isSuccess = TRUE;
}
__finally
{
if (xmlStringData)
{
PhDereferenceObject(xmlStringData);
}
}
return isSuccess;
}
BOOLEAN SetupDownloadBuild(
_In_ PVOID Arguments
)
{
ULONG contentLength = 0;
BOOLEAN isDownloadSuccess = FALSE;
P_HTTP_SESSION httpSocket = NULL;
HTTP_PARSED_URL urlComponents = NULL;
HANDLE tempFileHandle = NULL;
ULONG writeLength = 0;
ULONG readLength = 0;
ULONG totalLength = 0;
ULONG bytesDownloaded = 0;
ULONG downloadedBytes = 0;
ULONG contentLengthSize = sizeof(ULONG);
PH_HASH_CONTEXT hashContext;
IO_STATUS_BLOCK isb;
BYTE buffer[PAGE_SIZE];
StartProgress();
SendDlgItemMessage(Arguments, IDC_PROGRESS1, PBM_SETSTATE, PBST_NORMAL, 0);
httpSocket = HttpSocketCreate();
__try
{
if (!QueryBuildServerThread(httpSocket))
__leave;
if (!HttpParseURL(httpSocket, DownloadURL, &urlComponents))
{
STATUS_MSG(L"HttpParseURL: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Connecting to download server...\n");
if (!HttpConnect(httpSocket, urlComponents->HttpServer, INTERNET_DEFAULT_HTTPS_PORT))
{
STATUS_MSG(L"HttpConnect: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Connected to download server...\n");
if (!HttpBeginRequest(httpSocket, NULL, urlComponents->HttpPath, WINHTTP_FLAG_SECURE))
{
STATUS_MSG(L"HttpBeginRequest: %u\n", GetLastError());
__leave;
}
if (!HttpAddRequestHeaders(httpSocket, L"User-Agent: 0x0D06F00D"))
{
STATUS_MSG(L"HttpAddRequestHeaders: %u\n", GetLastError());
__leave;
}
if (!HttpSendRequest(httpSocket, 0))
{
STATUS_MSG(L"HttpSendRequest: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Querying download server...");
if (!HttpEndRequest(httpSocket))
{
STATUS_MSG(L"HttpEndRequest: %u\n", GetLastError());
__leave;
}
contentLength = HttpGetRequestHeaderDword(httpSocket, WINHTTP_QUERY_CONTENT_LENGTH);
if (contentLength == 0)
{
STATUS_MSG(L"HttpGetRequestHeaderDword: %u\n", GetLastError());
__leave;
}
STATUS_MSG(L"Downloading latest build %s...\n", Version);
// Create output file
if (!NT_SUCCESS(PhCreateFileWin32(
&tempFileHandle,
L"processhacker-2.38-bin.zip",
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_TEMPORARY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OVERWRITE_IF,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT
)))
{
__leave;
}
// Initialize hash algorithm.
PhInitializeHash(&hashContext, Sha1HashAlgorithm);
// Zero the buffer.
memset(buffer, 0, PAGE_SIZE);
// Download the data.
while (WinHttpReadData(httpSocket->RequestHandle, buffer, PAGE_SIZE, &bytesDownloaded))
{
// If we get zero bytes, the file was uploaded or there was an error
if (bytesDownloaded == 0)
break;
// Update the hash of bytes we downloaded.
PhUpdateHash(&hashContext, buffer, bytesDownloaded);
// Write the downloaded bytes to disk.
if (!NT_SUCCESS(NtWriteFile(
tempFileHandle,
NULL,
NULL,
NULL,
&isb,
buffer,
bytesDownloaded,
NULL,
NULL
)))
{
__leave;
}
downloadedBytes += (DWORD)isb.Information;
// Check the number of bytes written are the same we downloaded.
if (bytesDownloaded != isb.Information)
__leave;
// Update the GUI progress.
// TODO: Update on GUI thread.
//{
// //int percent = MulDiv(100, downloadedBytes, contentLength);
// FLOAT percent = ((FLOAT)downloadedBytes / contentLength * 100);
// PPH_STRING totalDownloaded = PhFormatSize(downloadedBytes, -1);
// PPH_STRING totalLength = PhFormatSize(contentLength, -1);
//
// PPH_STRING dlLengthString = PhFormatString(
// L"%s of %s (%.0f%%)",
// totalDownloaded->Buffer,
// totalLength->Buffer,
// percent
// );
//
// // Update the progress bar position
// SendMessage(context->ProgressHandle, PBM_SETPOS, (ULONG)percent, 0);
// Static_SetText(context->StatusHandle, dlLengthString->Buffer);
//
// PhDereferenceObject(dlLengthString);
// PhDereferenceObject(totalDownloaded);
// PhDereferenceObject(totalLength);
//}
SetProgress(downloadedBytes, contentLength);
}
// Compute hash result (will fail if file not downloaded correctly).
//if (PhFinalHash(&hashContext, &hashBuffer, 20, NULL))
//{
// // Allocate our hash string, hex the final hash result in our hashBuffer.
// PPH_STRING hexString = PhBufferToHexString(hashBuffer, 20);
//
// if (PhEqualString(hexString, context->Hash, TRUE))
// {
// //hashSuccess = TRUE;
// }
//
// PhDereferenceObject(hexString);
//}
//
// //if (_tcsstr(hashETag->Buffer, finalHexString->Buffer))
// {
// //DEBUG_MSG(TEXT("Hash success: %s (%s)\n"), SetupFileName->Buffer, finalHexString->Buffer);
// }
// //else
// //{
// // SendDlgItemMessage(_hwndProgress, IDC_PROGRESS1, PBM_SETSTATE, PBST_ERROR, 0);
// // SetDlgItemText(_hwndProgress, IDC_MAINHEADER, TEXT("Retrying download... Hash error."));
// // DEBUG_MSG(TEXT("Hash error (retrying...): %s\n"), SetupFileName->Buffer);
// //}
isDownloadSuccess = TRUE;
}
__finally
{
if (tempFileHandle)
{
NtClose(tempFileHandle);
}
if (urlComponents)
{
PhFree(urlComponents);
}
}
return TRUE;
}

View File

@@ -0,0 +1,228 @@
#include <setup.h>
#include <appsup.h>
#include "..\lib\miniz\miniz.h"
struct
{
PSTR FileName;
PWSTR ExtractFileName;
} SetupFiles_X64[] =
{
{ "CHANGELOG.txt", L"CHANGELOG.txt" },
{ "COPYRIGHT.txt", L"COPYRIGHT.txt" },
{ "LICENSE.txt", L"LICENSE.txt" },
{ "README.txt", L"README.txt" },
{ "x64/peview.exe", L"peview.exe" },
{ "x64/ProcessHacker.exe", L"ProcessHacker.exe" },
{ "x64/kprocesshacker.sys", L"kprocesshacker.sys" },
{ "x64/plugins/DotNetTools.dll", L"plugins\\DotNetTools.dll" },
{ "x64/plugins/ExtendedNotifications.dll", L"plugins\\ExtendedNotifications.dll" },
{ "x64/plugins/ExtendedServices.dll", L"plugins\\ExtendedServices.dll" },
{ "x64/plugins/ExtendedTools.dll", L"plugins\\ExtendedTools.dll" },
{ "x64/plugins/HardwareDevices.dll", L"plugins\\HardwareDevices.dll" },
{ "x64/plugins/NetworkTools.dll", L"plugins\\NetworkTools.dll" },
{ "x64/plugins/OnlineChecks.dll", L"plugins\\OnlineChecks.dll" },
{ "x64/plugins/SbieSupport.dll", L"plugins\\SbieSupport.dll" },
{ "x64/plugins/ToolStatus.dll", L"plugins\\ToolStatus.dll" },
{ "x64/plugins/Updater.dll", L"plugins\\Updater.dll" },
{ "x64/plugins/UserNotes.dll", L"plugins\\UserNotes.dll" },
{ "x64/plugins/WindowExplorer.dll", L"plugins\\WindowExplorer.dll" },
{ "x86/ProcessHacker.exe", L"x86\\ProcessHacker.exe" },
{ "x86/plugins/DotNetTools.dll", L"x86\\plugins\\DotNetTools.dll" },
};
BOOLEAN SetupExtractBuild(
_In_ PVOID Arguments
)
{
BOOLEAN isInstallSuccess = FALSE;
mz_uint64 totalLength = 0;
mz_uint64 total_size = 0;
mz_uint64 downloadedBytes = 0;
PPH_STRING totalSizeStr = NULL;
mz_bool status = MZ_FALSE;
mz_zip_archive zip_archive;
memset(&zip_archive, 0, sizeof(zip_archive));
STATUS_MSG(L"Extracting update %s...", Version);
Sleep(1000);
StartProgress();
__try
{
if (!CreateDirectoryPath(SetupInstallPath))
{
__leave;
}
// TODO: Move existing folder items.
if (!(status = mz_zip_reader_init_file(&zip_archive, "processhacker-2.38-bin.zip", 0)))
{
__leave;
}
// Get filesize information for extract progress
for (mz_uint i = 0; i < ARRAYSIZE(SetupFiles_X64); i++)
{
mz_uint index = mz_zip_reader_locate_file(
&zip_archive,
SetupFiles_X64[i].FileName,
NULL,
0
);
mz_zip_archive_file_stat file_stat;
if (!mz_zip_reader_file_stat(&zip_archive, index, &file_stat))
{
//mz_zip_reader_end(&zip_archive);
//break;
}
total_size += file_stat.m_uncomp_size;
DEBUG_MSG(L"Filename: \"%hs\", Uncompressed size: %I64u, Compressed size: %I64u\r\n",
file_stat.m_filename,
file_stat.m_uncomp_size,
file_stat.m_comp_size
);
}
totalSizeStr = PhFormatSize(total_size, -1);
DEBUG_MSG(L"Opened Zip: %hs (%s)\r\n", "processhacker-2.38-bin.zip", totalSizeStr->Buffer);
for (ULONG i = 0; i < ARRAYSIZE(SetupFiles_X64); i++)
{
mz_ulong file_crc32 = MZ_CRC32_INIT;
IO_STATUS_BLOCK isb;
HANDLE fileHandle;
ULONG indexOfFileName = -1;
PPH_STRING fullSetupPath;
PPH_STRING extractPath;
mz_uint file_index;
mz_zip_archive_file_stat file_stat;
size_t bufferLength = 0;
extractPath = PhConcatStrings(2,
SetupInstallPath->Buffer,
SetupFiles_X64[i].ExtractFileName
);
// Create the directory if it does not exist.
if (fullSetupPath = PhGetFullPath(extractPath->Buffer, &indexOfFileName))
{
PPH_STRING directoryPath;
if (indexOfFileName == -1)
__leave;
if (directoryPath = PhSubstring(fullSetupPath, 0, indexOfFileName))
{
if (!CreateDirectoryPath(directoryPath))
{
PhDereferenceObject(directoryPath);
PhDereferenceObject(fullSetupPath);
__leave;
}
PhDereferenceObject(directoryPath);
}
PhDereferenceObject(fullSetupPath);
}
STATUS_MSG(L"Extracting: %s\r\n", SetupFiles_X64[i].ExtractFileName);
Sleep(100);
// Create output file
if (!NT_SUCCESS(PhCreateFileWin32(
&fileHandle,
extractPath->Buffer,
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OVERWRITE_IF,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT
)))
{
DEBUG_MSG(L"PhCreateFileWin32 Failed\r\n");
__leave;
}
file_index = mz_zip_reader_locate_file(
&zip_archive,
SetupFiles_X64[i].FileName,
NULL,
0
);
if (file_index == -1)
{
__leave;
}
if (!mz_zip_reader_file_stat(&zip_archive, file_index, &file_stat))
{
__leave;
}
PVOID buffer = mz_zip_reader_extract_to_heap(
&zip_archive,
file_index,
&bufferLength,
0
);
// Update the hash
file_crc32 = mz_crc32(file_crc32, buffer, bufferLength);
// Write the downloaded bytes to disk.
if (!NT_SUCCESS(NtWriteFile(
fileHandle,
NULL,
NULL,
NULL,
&isb,
buffer,
bufferLength,
NULL,
NULL
)))
{
__leave;
}
if (isb.Information != bufferLength && file_crc32 != file_stat.m_crc32)
{
// Corrupted file.
__leave;
}
totalLength += (mz_uint64)bufferLength;
SetProgress((LONG)totalLength, (LONG)total_size);
NtClose(fileHandle);
mz_free(buffer);
}
isInstallSuccess = TRUE;
}
__finally
{
// Close the archive
mz_zip_reader_end(&zip_archive);
}
Sleep(3000);
return TRUE;
}

View File

@@ -0,0 +1,168 @@
#include <setup.h>
#include <appsup.h>
BOOLEAN SetupResetCurrentInstall(
_In_ PVOID Arguments
)
{
STATUS_MSG(L"Setting up for first time use...");
ProcessHackerShutdown();
ULONG err = ERROR_SERVICE_DOES_NOT_EXIST;
do
{
Sleep(1000);
err = KphUninstall();
} while (err != ERROR_SERVICE_DOES_NOT_EXIST);
RemoveAppCompatEntries();
//PPH_STRING clientPath = GetProcessHackerInstallPath();
//PPH_STRING startmenu = GetKnownLocation(CSIDL_COMMON_PROGRAMS, TEXT("\\ProcessHacker2"));
//PPH_STRING desktopShortcutString = GetKnownLocation(CSIDL_DESKTOPDIRECTORY, TEXT("\\Process Hacker 2.lnk"));
//PPH_STRING startmenuShortcutString = GetKnownLocation(CSIDL_COMMON_PROGRAMS, TEXT("\\Process Hacker 2.lnk"));
//PPH_STRING startmenuStartupShortcutString = GetKnownLocation(CSIDL_COMMON_PROGRAMS, TEXT("\\Startup\\Process Hacker 2.lnk"));
STATUS_MSG(L"Cleaning up...\n");
Sleep(1000);
//PPH_STRING clientPathString = StringFormat(TEXT("%s\\ProcessHacker.exe"), SetupInstallPath->Buffer);
//PPH_STRING uninstallPath = StringFormat(TEXT("%s\\ProcessHacker-Setup.exe"), SetupInstallPath->Buffer);
//PPH_STRING clientPathArgsString = StringFormat(TEXT("\"%s\\ProcessHacker.exe\""), SetupInstallPath->Buffer);
//PPH_STRING clientPathExeString = StringFormat(TEXT("\"%s\" \"%%1\""), clientPathString->Buffer);
// Create the Uninstall key...
//HKEY keyHandle = RegistryCreateKey(
// HKEY_LOCAL_MACHINE,
// TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ProcessHacker2"),
// KEY_ALL_ACCESS | KEY_WOW64_32KEY
// );
//
//if (keyHandle)
//{
// RegistrySetString(keyHandle, TEXT("DisplayName"), TEXT("Process Hacker"));
// RegistrySetString(keyHandle, TEXT("InstallLocation"), SetupInstallPath->Buffer);
// RegistrySetString(keyHandle, TEXT("UninstallString"), uninstallPath->Buffer);
// RegistrySetString(keyHandle, TEXT("DisplayIcon"), uninstallPath->Buffer);
// RegistrySetString(keyHandle, TEXT("Publisher"), TEXT("Electronic Arts, Inc."));
// RegistrySetString(keyHandle, TEXT("URLInfoAbout"), TEXT("http://wj32.org/ProcessHacker"));
// RegistrySetString(keyHandle, TEXT("HelpLink"), TEXT("http://wj32.org/ProcessHacker"));
// RegistrySetDword(keyHandle, TEXT("NoModify"), 1);
// RegistrySetDword(keyHandle, TEXT("NoRepair"), 1);
// RegCloseKey(keyHandle);
//}
//if (IsCreateDesktopSelected)
//{
// PPH_STRING desktopFolderString = GetKnownLocation(
// CSIDL_DESKTOPDIRECTORY,
// TEXT("\\ProcessHacker.lnk")
// );
// //if (!CreateLink(
// // desktopFolderString->Buffer, clientPathString->Buffer, SetupInstallPath->Buffer,
// // TEXT("")
// // ))
// //{
// // DEBUG_MSG(TEXT("ERROR CreateDesktopLink: %u\n"), GetLastError());
// //}
// PhFree(desktopFolderString);
//}
//if (IsCreateStartSelected)
//{
// PPH_STRING startmenuFolderString = GetKnownLocation(
// CSIDL_COMMON_PROGRAMS,
// TEXT("\\ProcessHacker.lnk")
// );
// //if (!CreateLink(
// // startmenuFolderString->Buffer, clientPathString->Buffer, SetupInstallPath->Buffer,
// // TEXT("")
// // ))
// //{
// // DEBUG_MSG(TEXT("ERROR CreateStartLink: %u\n"), GetLastError());
// //}
// PhFree(startmenuFolderString);
//}
//if (IsCreateRunStartupSelected)
//{
// PPH_STRING startmenuStartupString = GetKnownLocation(
// CSIDL_COMMON_STARTUP,
// TEXT("\\ProcessHacker.lnk")
// );
// //if (!CreateLink(
// // startmenuStartupString->Buffer, clientPathString->Buffer, SetupInstallPath->Buffer,
// // TEXT("")
// // ))
// //{
// // DEBUG_MSG(TEXT("ERROR CreateLinkStartup: %u\n"), GetLastError());
// //}
// PhFree(startmenuStartupString);
//}
// GetCachedImageIndex Test
//{
// SHFOLDERCUSTOMSETTINGS fcs = { sizeof(SHFOLDERCUSTOMSETTINGS) };
// fcs.dwMask = FCSM_ICONFILE;
// fcs.pszIconFile = TEXT("ProcessHacker.exe");
// fcs.cchIconFile = _tcslen(TEXT("ProcessHacker.exe")) * sizeof(TCHAR);
// fcs.iIconIndex = 0;
// if (SUCCEEDED(SHGetSetFolderCustomSettings(&fcs, SetupInstallPath->Buffer, FCS_FORCEWRITE)))
// {
// SHFILEINFO shellFolderInfo = { 0 };
// if (SHGetFileInfo(SetupInstallPath->Buffer, 0, &shellFolderInfo, sizeof(SHFILEINFO), SHGFI_ICONLOCATION))
// {
// PPH_STRING fileName = FileGetBaseName(shellFolderInfo.szDisplayName);
// INT shellIconIndex = Shell_GetCachedImageIndex(
// fileName->Buffer,
// shellFolderInfo.iIcon,
// 0
// );
// SHUpdateImage(
// fileName->Buffer,
// shellFolderInfo.iIcon,
// 0,
// shellIconIndex
// );
// SHChangeNotify(SHCNE_UPDATEIMAGE, SHCNF_DWORD, NULL, (PVOID)shellIconIndex);
// PhFree(fileName);
// }
// }
//}
//_tspawnl(_P_DETACH, clientPathString->Buffer, clientPathArgsString->Buffer, NULL);
//if (clientPathExeString)
// PhFree(clientPathExeString);
//if (clientPathArgsString)
// PhFree(clientPathArgsString);
//if (uninstallPath)
// PhFree(uninstallPath);
//if (clientPathString)
// PhFree(clientPathString);
return TRUE;
}