Subversion Repositories SvarDOS

Rev

Rev 1609 | Rev 1964 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
219 mateuszvis 1
/*
268 mateuszvis 2
 * This file is part of pkg (SvarDOS)
3
 * Copyright (C) 2012-2021 Mateusz Viste.
219 mateuszvis 4
 *
5
 * Simple library providing functions to unzip files from zip archives.
6
 */
7
 
8
#include <stdio.h>     /* printf(), FILE, fclose()... */
9
#include <stdlib.h>    /* NULL */
10
#include <string.h>    /* memset() */
11
#include <time.h>      /* mktime() */
12
#include <utime.h>     /* utime() */
13
#include <unistd.h>   /* unlink() */
14
 
15
#include "crc32.h"
1963 mateusz.vi 16
#include "helpers.h"
219 mateuszvis 17
#include "kprintf.h"
268 mateuszvis 18
#include "inf.h"   /* INFLATE support */
219 mateuszvis 19
 
20
#include "libunzip.h"  /* include self for control */
21
 
22
 
23
/* converts a "DOS format" timestamp into unix timestamp. The DOS timestamp is constructed an array of 4 bytes, that contains following data at the bit level:
24
 * HHHHHMMM MMMSSSSS YYYYYYYM MMMDDDDD
25
 *  where:
26
 * day of month is always within 1-31 range;
27
 * month is always within 1-12 range;
28
 * year starts from 1980 and continues for 127 years
29
 * seconds are actually not 0-59 but rather 0-29 as there are only 32 possible values – to get actual seconds multiply this field by 2;
30
 * minutes are always within 0-59 range;
31
 * hours are always within 0-23 range.     */
268 mateuszvis 32
static time_t dostime2unix(const unsigned char *buff) {
219 mateuszvis 33
  struct tm curtime;
34
  time_t result;
35
  memset(&curtime, 0, sizeof(curtime)); /* make sure to set everything in curtime to 0's */
36
  curtime.tm_sec = (buff[0] & 31) << 1; /* seconds (0..60) */
37
  curtime.tm_min = (((buff[1] << 8) | buff[0]) >> 5) & 63 ; /* minutes after the hour (0..59) */
38
  curtime.tm_hour = (buff[1] >> 3); /* hours since midnight (0..23) */
39
  curtime.tm_mday = buff[2] & 31; /* day of the month (1..31) */
40
  curtime.tm_mon = ((((buff[3] << 8) | buff[2]) >> 5) & 15) - 1; /* months since January (0, 11) */
41
  curtime.tm_year = (buff[3] >> 1) + 80; /* years since 1900 */
42
  curtime.tm_wday = 0; /* days since Sunday (0..6) - leave 0, mktime() will set it */
43
  curtime.tm_yday = 0; /* days since January 1 (0..365]) - leave 0, mktime() will set it */
44
  curtime.tm_isdst = -1; /* Daylight Saving Time flag. Positive if DST is in effect, zero if not and negative if no information is available */
45
  result = mktime(&curtime);
46
  if (result == (time_t)-1) return(0);
47
  return(result);
48
}
49
 
50
 
51
/* opens a zip file and provides the list of files in the archive.
52
   returns a pointer to a ziplist (linked list) with all records, or NULL on error.
53
   The ziplist is allocated automatically, and must be freed via zip_freelist. */
54
struct ziplist *zip_listfiles(FILE *fd) {
55
  struct ziplist *reslist = NULL;
56
  struct ziplist *newentry;
57
  unsigned long entrysig;
58
  unsigned short filenamelen, extrafieldlen, filecommentlen;
59
  unsigned long compfilelen;
60
  int centraldirectoryfound = 0;
61
  unsigned int ux;
62
  unsigned char hdrbuff[64];
63
 
64
  rewind(fd);  /* make sure the file cursor is at the very beginning of the file */
65
 
66
  for (;;) { /* read entry after entry */
67
    int x, eofflag;
68
    long longbuff;
69
    entrysig = 0;
70
    eofflag = 0;
71
    /* read the entry signature first */
72
    for (x = 0; x < 32; x += 8) {
73
      if ((longbuff = fgetc(fd)) == EOF) {
74
        eofflag = 1;
75
        break;
76
      }
77
      entrysig |= (longbuff << x);
78
    }
79
    if (eofflag != 0) break;
80
    /* printf("sig: 0x%08x\n", entrysig); */
81
    if (entrysig == 0x04034b50ul) { /* local file */
82
      unsigned int generalpurposeflags;
83
      /* read and parse the zip header */
84
      fread(hdrbuff, 1, 26, fd);
85
      /* read filename's length so I can allocate the proper amound of mem */
86
      filenamelen = hdrbuff[23];
87
      filenamelen <<= 8;
88
      filenamelen |= hdrbuff[22];
89
      /* create new entry and link it into the list */
90
      newentry = calloc(sizeof(struct ziplist) + filenamelen, 1);
91
      if (newentry == NULL) {
613 mateuszvis 92
        kitten_printf(2, 14, "libunzip"); /* "Out of memory! (%s)" */
1963 mateusz.vi 93
        outputnl("");
219 mateuszvis 94
        zip_freelist(&reslist);
95
        break;
96
      }
97
      newentry->nextfile = reslist;
98
      newentry->flags = 0;
99
      reslist = newentry;
100
      /* read further areas of the header, and fill zip entry */
101
      generalpurposeflags = hdrbuff[3];  /* parse the general */
102
      generalpurposeflags <<= 8;         /* purpose flags and */
103
      generalpurposeflags |= hdrbuff[2]; /* save them for later */
104
      newentry->compmethod = hdrbuff[4] | (hdrbuff[5] << 8);
105
      newentry->timestamp = dostime2unix(&hdrbuff[6]);
106
      newentry->crc32 = 0;
107
      for (x = 13; x >= 10; x--) {
108
        newentry->crc32 <<= 8;
109
        newentry->crc32 |= hdrbuff[x];
110
      }
111
      newentry->compressedfilelen = 0;
112
      for (x = 17; x >= 14; x--) {
113
        newentry->compressedfilelen <<= 8;
114
        newentry->compressedfilelen |= hdrbuff[x];
115
      }
116
      newentry->filelen = 0;
117
      for (x = 21; x >= 18; x--) {
118
        newentry->filelen <<= 8;
119
        newentry->filelen |= hdrbuff[x];
120
      }
121
      extrafieldlen = hdrbuff[25];
122
      extrafieldlen <<= 8;
123
      extrafieldlen |= hdrbuff[24];
124
      /* printf("Filename len: %d / extrafield len: %d / compfile len: %ld / filelen: %ld\n", filenamelen, extrafieldlen, newentry->compressedfilelen, newentry->filelen); */
125
      /* check general purpose flags */
126
      if ((generalpurposeflags & 1) != 0) newentry->flags |= ZIP_FLAG_ENCRYPTED;
127
      /* parse the filename */
128
      for (ux = 0; ux < filenamelen; ux++) newentry->filename[ux] = fgetc(fd); /* store filename */
129
      if (newentry->filename[filenamelen - 1] == '/') newentry->flags |= ZIP_FLAG_ISADIR; /* if filename ends with / it's a dir. Note that ZIP forbids the usage of '\' in ZIP paths anyway */
130
      /* printf("Filename: %s (%ld bytes compressed)\n", newentry->filename, newentry->compressedfilelen); */
131
      newentry->dataoffset = ftell(fd) + extrafieldlen;
132
      /* skip rest of fields and data */
133
      fseek(fd, (extrafieldlen + newentry->compressedfilelen), SEEK_CUR);
134
    } else if (entrysig == 0x02014b50ul) { /* central directory */
135
      centraldirectoryfound = 1;
136
      /* parse header now */
137
      fread(hdrbuff, 1, 42, fd);
138
      filenamelen = hdrbuff[22] | (hdrbuff[23] << 8);
139
      extrafieldlen = hdrbuff[24] | (hdrbuff[25] << 8);
140
      filecommentlen = hdrbuff[26] | (hdrbuff[27] << 8);
141
      compfilelen = 0;
142
      for (x = 17; x >= 14; x--) {
143
        compfilelen <<= 8;
144
        compfilelen |= hdrbuff[x];
145
      }
146
      /* printf("central dir\n"); */
147
      /* skip rest of fields and data */
148
      fseek(fd, (filenamelen + extrafieldlen + compfilelen + filecommentlen), SEEK_CUR);
149
    } else if (entrysig == 0x08074b50ul) { /* Data descriptor header */
150
      /* no need to read the header we just have to skip it */
151
      fseek(fd, 12, SEEK_CUR); /* the header is 3x4 bytes (CRC + compressed len + uncompressed len) */
152
    } else { /* unknown sig */
613 mateuszvis 153
      kitten_printf(8, 1, entrysig); /* "unknown zip sig: 0x%08lx" */
1963 mateusz.vi 154
      outputnl("");
219 mateuszvis 155
      zip_freelist(&reslist);
156
      break;
157
    }
158
  }
159
  /* if we got no central directory record, the file is incomplete */
160
  if (centraldirectoryfound == 0) zip_freelist(&reslist);
161
  return(reslist);
162
}
163
 
164
 
165
 
166
/* unzips a file. zipfd points to the open zip file, curzipnode to the entry to extract, and fulldestfilename is the destination file where to unzip it. returns 0 on success, non-zero otherwise. */
268 mateuszvis 167
int zip_unzip(FILE *zipfd, struct ziplist *curzipnode, const char *fulldestfilename) {
1609 mateusz.vi 168
  #define buffsize (12 * 1024) /* bigger buffer is better, but pkg has to work on a 256K PC so let's not get too crazy with RAM */
219 mateuszvis 169
  FILE *filefd;
170
  unsigned long cksum;
171
  int extract_res;
172
  unsigned char *buff;
173
  struct utimbuf filetimestamp;
174
 
175
  /* first of all, check we support the compression method */
176
  switch (curzipnode->compmethod) {
295 mateuszvis 177
    case ZIP_METH_STORE:
178
    case ZIP_METH_DEFLATE:
219 mateuszvis 179
      break;
180
    default: /* unsupported compression method, sorry */
181
      return(-1);
182
      break;
183
  }
184
 
185
  /* open the dst file */
186
  filefd = fopen(fulldestfilename, "wb");
187
  if (filefd == NULL) return(-2);  /* failed to open the dst file */
188
 
189
  /* allocate buffers for data I/O */
190
  buff = malloc(buffsize);
191
  if (buff == NULL) {
192
    fclose(filefd);
193
    unlink(fulldestfilename); /* remove the failed file once it is closed */
194
    return(-6);
195
  }
196
 
197
  if (fseek(zipfd, curzipnode->dataoffset, SEEK_SET) != 0) { /* set the reading position inside the zip file */
198
    free(buff);
199
    fclose(filefd);
200
    unlink(fulldestfilename); /* remove the failed file once it is closed */
201
    return(-7);
202
  }
203
  extract_res = -255;
204
 
205
  cksum = crc32_init(); /* init the crc32 */
206
 
207
  if (curzipnode->compmethod == 0) { /* if the file is stored, copy it over */
208
    long i, toread;
209
    extract_res = 0;   /* assume we will succeed */
210
    for (i = 0; i < curzipnode->filelen;) {
211
      toread = curzipnode->filelen - i;
212
      if (toread > buffsize) toread = buffsize;
213
      if (fread(buff, toread, 1, zipfd) != 1) extract_res = -3;   /* read a chunk of data */
214
      crc32_feed(&cksum, buff, toread); /* update the crc32 checksum */
215
      if (fwrite(buff, toread, 1, filefd) != 1) extract_res = -4; /* write data chunk to dst file */
216
      i += toread;
217
    }
218
  } else if (curzipnode->compmethod == 8) {  /* if the file is deflated, inflate it */
1609 mateusz.vi 219
    /* use 1/3 of my buffer as input and 2/3 as output */
220
    extract_res = inf(zipfd, filefd, buff, buffsize / 3, buff + (buffsize / 3), buffsize / 3 * 2, &cksum, curzipnode->compressedfilelen);
219 mateuszvis 221
  }
222
 
223
  /* clean up memory, close the dst file and terminates crc32 */
224
  free(buff);
225
  fclose(filefd);   /* close the dst file */
226
  crc32_finish(&cksum);
227
 
228
  /* printf("extract_res=%d / cksum_expected=%08lX / cksum_obtained=%08lX\n", extract_res, curzipnode->crc32, cksum); */
229
  if (extract_res != 0) {  /* was the extraction process successful? */
230
    unlink(fulldestfilename); /* remove the failed file */
231
    return(extract_res);
232
  }
233
  if (cksum != curzipnode->crc32) { /* is the crc32 ok after extraction? */
234
    unlink(fulldestfilename); /* remove the failed file */
235
    return(-9);
236
  }
237
  /* Set the timestamp of the new file to what was set in the zip file */
238
  filetimestamp.actime  = curzipnode->timestamp;
239
  filetimestamp.modtime = curzipnode->timestamp;
240
  utime(fulldestfilename, &filetimestamp);
241
  return(0);
1609 mateusz.vi 242
#undef buffsize
219 mateuszvis 243
}
244
 
245
 
246
 
247
/* Call this to free a ziplist computed by zip_listfiles() */
248
void zip_freelist(struct ziplist **ziplist) {
249
  struct ziplist *zipentrytobefreed;
250
  while (*ziplist != NULL) { /* iterate through the linked list and free all nodes */
251
    zipentrytobefreed = *ziplist;
252
    *ziplist = zipentrytobefreed->nextfile;
253
    /* free the node entry */
254
    free(zipentrytobefreed);
255
  }
256
  *ziplist = NULL;
257
}