Hi all!
Who be created function for a compression of a content in cgi to the program written on C?
Share a simple example!
Has written the for gzip and deflate but does not work: (
Code:
#include <stdio.h>
#include <assert.h>
/**/
#include <zlib.h>
static void *g_zalloc_wrapper(voidpf opaque, uInt items, uInt size) {
void *ptr = malloc(items * size);
return ptr;
}
static void g_zfree_wrapper(voidpf opaque, voidpf address) {
free(address);
}
/// gzip = 1 > gzip, gzip = 0 > deflate
static int zlib_encode(Bytef *mg, int gzip)
{
static int gz_magic[2] = {0x1f, 0x8b};
#define OS_CODE 0x03 /*FIXME */
z_stream stream;
//char *new_body;
stream.next_in = mg;
stream.avail_in = strlen(mg);
stream.total_in = 0;
//new_body =
stream.next_out = malloc(strlen(mg) + 75); /* overly generous */
assert(stream.next_out);
stream.avail_out = strlen(mg) + 64;
stream.total_out = 0;
stream.zalloc = g_zalloc_wrapper;
stream.zfree = g_zfree_wrapper;
stream.opaque = NULL;
stream.data_type = Z_ASCII;
/*
*/
if (deflateInit2(
&stream,
3 /* compression level, 1-9, default 6 (Z_DEFAULT_COMPRESSION) */,
Z_DEFLATED,
((gzip!=0)?16:0)+15 /* gzip headers? (16) + window size (15b) */,
3 /* memory level, 1-9, default 8 */,
Z_DEFAULT_STRATEGY
) != Z_OK) {
/* failed to initialize, bail out */
deflateEnd(&stream);
return -1;
}
while (stream.avail_in != 0) {
switch(deflate(&stream, Z_FINISH)) {
case Z_STREAM_END: /* success */
break;
case Z_OK: /* need more buffer space !? bail out... */
deflateEnd(&stream);
return -1;
default: /* other error cases */
deflateEnd(&stream);
return -1;
}
}
if(gzip!=0)
{
printf("Content-Encoding: gzip\n\r");
}
else
{
printf("Content-Encoding: deflate\n\r");
}
printf("Content-type: text/html\n\r\n\r");
int ifd = dup(fileno(stdout));
FILE *Out = fdopen(ifd, "w+b");
if(gzip!=0) {
char *s2[10];
s2[0] = gz_magic[0];
s2[1] = gz_magic[1];
s2[2] = Z_DEFLATED;
s2[3] = s2[4] = s2[5] = s2[6] = s2[7] = s2[8] = 0;
s2[9] = OS_CODE;
fwrite(&s2 , 10 , 1 ,Out);
}
fwrite(&stream.next_out , stream.total_out , 1 ,Out);
if(gzip!=0) {
char *trailer[9];
uLong crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const Bytef *) mg, strlen(mg));
/* write crc & stream.total_in in LSB order */
trailer[0] = (char) crc & 0xFF;
trailer[1] = (char) (crc >> 8) & 0xFF;
trailer[2] = (char) (crc >> 16) & 0xFF;
trailer[3] = (char) (crc >> 24) & 0xFF;
trailer[4] = (char) stream.total_in & 0xFF;
trailer[5] = (char) (stream.total_in >> 8) & 0xFF;
trailer[6] = (char) (stream.total_in >> 16) & 0xFF;
trailer[7] = (char) (stream.total_in >> 24) & 0xFF;
trailer[8] = '\0';
fwrite(&trailer , 9 , 1 ,Out);
}
deflateEnd(&stream);
}
int main()
{
zlib_encode ("<html>test</html>", 0);
}