Subversion Repositories SvarDOS

Rev

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

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