Skip to content

Instantly share code, notes, and snippets.

@odzhan
Last active March 30, 2024 01:39
Show Gist options
  • Save odzhan/0b5caa6c6063b64e1b6e5bdc6d01b4d9 to your computer and use it in GitHub Desktop.
Save odzhan/0b5caa6c6063b64e1b6e5bdc6d01b4d9 to your computer and use it in GitHub Desktop.
Deflate Compression On Windows
/**
BSD 3-Clause License
Copyright (c) 2019 Odzhan. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Windows.h>
#include <stdio.h>
#include <inttypes.h>
#include <limits.h>
#include "zlib.h"
#define DEFLATE 1
#define INFLATE 2
typedef int (WINAPI *ums_deflate_init_t)(z_streamp stream, int level, const char * version, int stream_size);
typedef int (WINAPI *ums_deflate_t)(z_streamp stream, int flush);
typedef int (WINAPI *ums_inflate_init_t)(z_streamp stream, const char * version, int stream_size);
typedef int (WINAPI *ums_inflate_t)(z_streamp stream, int flush);
static uint32_t file_diff(uint32_t new_len, uint32_t old_len) {
if (new_len <= UINT_MAX / 100) {
new_len *= 100;
} else {
old_len /= 100;
}
if (old_len == 0) {
old_len = 1;
}
return (100 - (new_len / old_len));
}
VOID xstrerror (PCHAR fmt, ...){
PCHAR error=NULL;
va_list arglist;
CHAR buffer[1024];
DWORD dwError=GetLastError();
va_start(arglist, fmt);
_vsnprintf(buffer, ARRAYSIZE(buffer), fmt, arglist);
va_end (arglist);
if (FormatMessage (
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&error, 0, NULL))
{
printf(" [ %s : %s\n", buffer, error);
LocalFree (error);
} else {
printf(" [ %s error : %08lX\n", buffer, dwError);
}
}
DWORD CompressBuffer(LPVOID inbuf, DWORD inlen, HANDLE outfile) {
SIZE_T outlen, len;
LPVOID outbuf;
DWORD wr;
HMODULE m;
z_stream ds;
ums_deflate_t ums_deflate;
ums_deflate_init_t ums_deflate_init;
int err;
m = LoadLibrary("PresentationNative_v0300.dll");
ums_deflate_init = (ums_deflate_init_t)GetProcAddress(m, "ums_deflate_init");
ums_deflate = (ums_deflate_t)GetProcAddress(m, "ums_deflate");
if(ums_deflate_init == NULL || ums_deflate == NULL) {
printf(" [ unable to resolve deflate API.\n");
return 0;
}
// allocate memory for compressed data
outbuf = malloc(inlen);
if(outbuf != NULL) {
// Compress data and write data to outbuf.
ds.zalloc = Z_NULL;
ds.zfree = Z_NULL;
ds.opaque = Z_NULL;
ds.avail_in = (uInt)inlen; // size of input
ds.next_in = (Bytef *)inbuf; // input buffer
ds.avail_out = (uInt)inlen; // size of output buffer
ds.next_out = (Bytef *)outbuf; // output buffer
if(ums_deflate_init(&ds, Z_BEST_COMPRESSION, "1", sizeof(ds)) == Z_OK) {
if((err = ums_deflate(&ds, Z_FINISH)) == Z_STREAM_END) {
// write the original length first
WriteFile(outfile, &inlen, sizeof(DWORD), &wr, NULL);
// then the data
WriteFile(outfile, outbuf, ds.avail_out, &wr, NULL);
} else {
printf(" [ ums_deflate() : %x\n", err);
}
} else {
printf(" [ ums_deflate_init()\n");
}
free(outbuf);
}
return 1;
}
DWORD DecompressBuffer(LPVOID inbuf, DWORD inlen, HANDLE outfile) {
SIZE_T outlen, len;
LPVOID outbuf;
DWORD wr;
HMODULE m;
z_stream ds;
ums_inflate_t ums_inflate;
ums_inflate_init_t ums_inflate_init;
m = LoadLibrary("PresentationNative_v0300.dll");
ums_inflate_init = (ums_inflate_init_t)GetProcAddress(m, "ums_inflate_init");
ums_inflate = (ums_inflate_t)GetProcAddress(m, "ums_inflate");
if(ums_inflate_init == NULL || ums_inflate == NULL) {
printf(" [ unable to resolve inflate API.\n");
return 0;
}
// allocate memory for decompressed data
outlen = *(DWORD*)inbuf;
outbuf = malloc(outlen*2);
if(outbuf != NULL) {
// decompress data and write data to outbuf.
ds.zalloc = Z_NULL;
ds.zfree = Z_NULL;
ds.opaque = Z_NULL;
ds.avail_in = (uInt)inlen - 8; // size of input
ds.next_in = (Bytef*)inbuf + 4; // input buffer
ds.avail_out = (uInt)outlen*2; // size of output buffer
ds.next_out = (Bytef*)outbuf; // output buffer
printf(" [ initializing inflate...\n");
if(ums_inflate_init(&ds, "1", sizeof(ds)) == Z_OK) {
printf(" [ inflating...\n");
if(ums_inflate(&ds, Z_FINISH) == Z_STREAM_END) {
WriteFile(outfile, outbuf, ds.avail_out, &wr, NULL);
} else {
printf(" [ ums_inflate()\n");
}
} else {
printf(" [ ums_inflate_init()\n");
}
free(outbuf);
} else {
printf(" [ malloc()\n");
}
return 1;
}
// map a file for reading
DWORD CompressOrDecompress(BOOL compress, const char *infile, const char *outfile) {
HANDLE fin, fout, map;
LPVOID inbuf;
DWORD inlen, outlen, err;
LARGE_INTEGER fs;
// open input file for reading
fin = CreateFile(infile, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
// error? exit
if(fin == INVALID_HANDLE_VALUE) {
xstrerror("CreateFile");
return GetLastError();
}
// read the file size
GetFileSizeEx(fin, &fs);
if(fs.QuadPart == 0) {
printf("file is empty\n");
return 0;
}
inlen = fs.LowPart;
// create file mapping
map = CreateFileMapping(fin, NULL, PAGE_READONLY, 0, 0, NULL);
if(map != NULL) {
// map a view of the file
inbuf = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if(inbuf != NULL) {
// open output file for writing
fout = CreateFile(outfile, GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
// if file opened
if(fout != INVALID_HANDLE_VALUE) {
// compress?
if(compress == DEFLATE) {
err = CompressBuffer(inbuf, inlen, fout);
} else {
err = DecompressBuffer(inbuf, inlen, fout);
}
GetFileSizeEx(fout, &fs);
outlen = fs.LowPart;
CloseHandle(fout);
} else {
xstrerror("CreateFile");
}
// unmap view
UnmapViewOfFile(inbuf);
} else {
xstrerror("MapViewOfFile");
}
// close mapping
CloseHandle(map);
} else {
xstrerror("CreateFileMapping");
}
// close input file
CloseHandle(fin);
// return the ratio
return (compress == DEFLATE) ? file_diff(outlen, inlen) : file_diff(inlen, outlen);
}
static char* get_param (int argc, char *argv[], int *i) {
int n = *i;
if (argv[n][2] != 0) {
return &argv[n][2];
}
if ((n+1) < argc) {
*i = n + 1;
return argv[n+1];
}
printf(" [ %c%c requires parameter\n", argv[n][0], argv[n][1]);
exit (0);
}
void usage(void) {
printf(" usage: winflate [options] -i <infile> -o <outfile>\n");
printf(" -c Compress\n");
printf(" -d Decompress\n");
printf(" -i <infile> Input file\n");
printf(" -o <outfile> Output file\n\n");
exit(-1);
}
int main(int argc, char *argv[]) {
DWORD ratio, i, compress = 0;
PCHAR infile = NULL, outfile = NULL;
printf("\n");
printf(" [ DEFLATE compression utility v0.1\n");
printf(" [ Copyright (c) 2019 Odzhan\n\n");
if(argc < 3) {
usage();
}
// for each argument
for(i=1; i<argc; i++) {
// is this a switch?
if(argv[i][0] == '/' || argv[i][0] == '-') {
switch(argv[i][1]) {
// compress?
case 'c':
compress = DEFLATE;
break;
// decompress?
case 'd':
compress = INFLATE;
break;
// input file
case 'i':
infile = get_param(argc, argv, &i);
break;
// output file
case 'o':
outfile = get_param(argc, argv, &i);
break;
default:
usage();
}
} else {
usage();
}
}
// no input?
if(infile == NULL) {
printf(" [ no input file specified.\n");
return 0;
}
// no output?
if(outfile == NULL) {
printf(" [ no output file specified.\n");
return 0;
}
// no mode selected?
if(compress == 0) {
printf(" [ use -c for compression or -d for decompression.\n");
return 0;
}
printf(" [ %s %s to %s\n",
compress == DEFLATE ? "compressing" : "decompressing",
infile, outfile);
// 1=compress, 2=decompress
ratio = CompressOrDecompress(compress, infile, outfile);
printf(" [ file size %s by %"PRId32"%%\n",
compress == DEFLATE ? "reduced" : "increased", ratio);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment