summaryrefslogtreecommitdiff
path: root/src/export/extract_version_4.c
blob: e014e2301417177a6db563a9e5cf30aa4cb3079b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <zlib.h>
#include "mystdlib.h"

#define XORLEN (29)
#define HUGEINBLOCK (128*1024)
#define HUGEBLOCK (4*1024*1024)

int main(int argc, char **argv) {
  unsigned const char xorkey [XORLEN] = "Just for Fun. Linus Torvalds.";
  unsigned char input  [HUGEINBLOCK];
  unsigned char output [HUGEBLOCK];
  char respath[32]; /* file_XXXXX\0 */
  int zres = 0, filenum = 0, resfile;
  size_t offs = 0, reported = 0;
  ssize_t temp = 0;
  MAP in;

  if( argc != 2 ) exit(111);
  in = map_file( argv[1], 1 );

  z_stream z;

  while( offs < in->size ) {
    /* std::min(remain, HUGEINBLOCK) */
    size_t inlen = in->size - offs;
    if (inlen > sizeof(input))
        inlen = sizeof(input);

    /* Copy in block large enough */
    memcpy(input, in->addr + offs, inlen);

    /* De-"crypt" */
    for (size_t i = 0; i < sizeof(xorkey); ++i )
      input[i] ^= xorkey[i];

    /* Prepare decompression struct */
    memset( &z, 0, sizeof(z));
    z.next_in  = input;  z.avail_in = inlen;
    z.next_out = output; z.avail_out = HUGEBLOCK;
    inflateInit( &z );
    zres = Z_OK;

    while( zres == Z_OK )
      zres = inflate( &z, Z_NO_FLUSH );

    if( zres != Z_STREAM_END ) {
      inflateEnd(&z);
      offs++;
      continue;
    }

    // fprintf( stderr, "%08X\n", (unsigned int)(offs));
    //old_offs = offs;
    snprintf( respath, sizeof(respath), "file_%05X", filenum++ );

    resfile = open( respath, O_RDWR | O_CREAT, 0644 );
    if( resfile < 0 ) {
      fprintf( stderr, "Could not open output file %s\n", respath );
      exit(1);
    }
    temp += write( resfile, output, z.total_out );
    close( resfile );
    offs += z.total_in;

    if( reported < ( offs * 10 ) / in->size ) {
      reported++;
      printf( "%zd%% ", 10 * reported );
      fflush( stdout );
    }

    inflateEnd(&z); memset( &z, 0, sizeof(z));
  }
  unmap_file(&in);
  if( reported < 10 )
    printf( "100%% " );
  fflush( stdout );
  if( !temp )
    exit(1);
  return 0;
}