• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2    minizip.c
3    Version 1.1, February 14h, 2010
4    sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
5 
6          Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
7 
8          Modifications of Unzip for Zip64
9          Copyright (C) 2007-2008 Even Rouault
10 
11          Modifications for Zip64 support on both zip and unzip
12          Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
13 */
14 
15 
16 #if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
17         #ifndef __USE_FILE_OFFSET64
18                 #define __USE_FILE_OFFSET64
19         #endif
20         #ifndef __USE_LARGEFILE64
21                 #define __USE_LARGEFILE64
22         #endif
23         #ifndef _LARGEFILE64_SOURCE
24                 #define _LARGEFILE64_SOURCE
25         #endif
26         #ifndef _FILE_OFFSET_BIT
27                 #define _FILE_OFFSET_BIT 64
28         #endif
29 #endif
30 
31 #if defined(__APPLE__) || defined(__HAIKU__) || defined(MINIZIP_FOPEN_NO_64)
32 // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
33 #define FOPEN_FUNC(filename, mode) fopen(filename, mode)
34 #define FTELLO_FUNC(stream) ftello(stream)
35 #define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
36 #else
37 #define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
38 #define FTELLO_FUNC(stream) ftello64(stream)
39 #define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
40 #endif
41 
42 
43 
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 
51 #ifdef _WIN32
52 # include <direct.h>
53 # include <io.h>
54 #else
55 # include <unistd.h>
56 # include <utime.h>
57 # include <sys/types.h>
58 # include <sys/stat.h>
59 #endif
60 
61 #include "zip.h"
62 
63 #ifdef _WIN32
64         #define USEWIN32IOAPI
65         #include "iowin32.h"
66 #endif
67 
68 
69 
70 #define WRITEBUFFERSIZE (16384)
71 #define MAXFILENAME (256)
72 
73 #ifdef _WIN32
74 /* f: name of file to get info on, tmzip: return value: access,
75    modification and creation times, dt: dostime */
filetime(const char * f,tm_zip * tmzip,uLong * dt)76 static int filetime(const char *f, tm_zip *tmzip, uLong *dt)
77 {
78   int ret = 0;
79   {
80       FILETIME ftLocal;
81       HANDLE hFind;
82       WIN32_FIND_DATAA ff32;
83 
84       hFind = FindFirstFileA(f,&ff32);
85       if (hFind != INVALID_HANDLE_VALUE)
86       {
87         FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
88         FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
89         FindClose(hFind);
90         ret = 1;
91       }
92   }
93   return ret;
94 }
95 #else
96 #if defined(unix) || defined(__APPLE__)
97 /* f: name of file to get info on, tmzip: return value: access,
98    modification and creation times, dt: dostime */
filetime(const char * f,tm_zip * tmzip,uLong * dt)99 static int filetime(const char *f, tm_zip *tmzip, uLong *dt)
100 {
101   (void)dt;
102   int ret = 0;
103   struct stat s;        /* results of stat() */
104   struct tm* filedate;
105   time_t tm_t = 0;
106 
107   if (strcmp(f,"-") != 0)
108   {
109     char name[MAXFILENAME + 1];
110     size_t len = strlen(f);
111     if (len > MAXFILENAME)
112       len = MAXFILENAME;
113 
114     strncpy(name, f,MAXFILENAME - 1);
115     /* strncpy doesn't append the trailing NULL, of the string is too long. */
116     name[ MAXFILENAME ] = '\0';
117 
118     if (name[len - 1] == '/')
119       name[len - 1] = '\0';
120     /* not all systems allow stat'ing a file with / appended */
121     if (stat(name,&s) == 0)
122     {
123       tm_t = s.st_mtime;
124       ret = 1;
125     }
126   }
127   filedate = localtime(&tm_t);
128 
129   tmzip->tm_sec  = filedate->tm_sec;
130   tmzip->tm_min  = filedate->tm_min;
131   tmzip->tm_hour = filedate->tm_hour;
132   tmzip->tm_mday = filedate->tm_mday;
133   tmzip->tm_mon  = filedate->tm_mon ;
134   tmzip->tm_year = filedate->tm_year;
135 
136   return ret;
137 }
138 #else
139 /* f: name of file to get info on, tmzip: return value: access,
140    modification and creation times, dt: dostime */
filetime(const char * f,tm_zip * tmzip,uLong * dt)141 static int filetime(const char *f, tm_zip *tmzip, uLong *dt)
142 {
143     (void)f;
144     (void)tmzip;
145     (void)dt;
146     return 0;
147 }
148 #endif
149 #endif
150 
151 
152 
153 
check_exist_file(const char * filename)154 static int check_exist_file(const char* filename)
155 {
156     FILE* ftestexist;
157     int ret = 1;
158     ftestexist = FOPEN_FUNC(filename,"rb");
159     if (ftestexist == NULL)
160         ret = 0;
161     else
162         fclose(ftestexist);
163     return ret;
164 }
165 
do_banner(void)166 static void do_banner(void)
167 {
168     printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
169     printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
170 }
171 
do_help(void)172 static void do_help(void)
173 {
174     printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
175            "  -o  Overwrite existing file.zip\n" \
176            "  -a  Append to existing file.zip\n" \
177            "  -0  Store only\n" \
178            "  -1  Compress faster\n" \
179            "  -9  Compress better\n\n" \
180            "  -j  exclude path. store only the file name.\n\n");
181 }
182 
183 /* calculate the CRC32 of a file,
184    because to encrypt a file, we need known the CRC32 of the file before */
getFileCrc(const char * filenameinzip,void * buf,unsigned long size_buf,unsigned long * result_crc)185 static int getFileCrc(const char* filenameinzip, void* buf, unsigned long size_buf, unsigned long* result_crc)
186 {
187    unsigned long calculate_crc=0;
188    int err = ZIP_OK;
189    FILE * fin = FOPEN_FUNC(filenameinzip,"rb");
190 
191    unsigned long size_read = 0;
192    /* unsigned long total_read = 0; */
193    if (fin == NULL)
194    {
195        err = ZIP_ERRNO;
196    }
197 
198     if (err == ZIP_OK)
199         do
200         {
201             err = ZIP_OK;
202             size_read = fread(buf,1,size_buf,fin);
203             if (size_read < size_buf)
204                 if (feof(fin) == 0)
205             {
206                 printf("error in reading %s\n",filenameinzip);
207                 err = ZIP_ERRNO;
208             }
209 
210             if (size_read > 0)
211                 calculate_crc = crc32_z(calculate_crc,buf,size_read);
212             /* total_read += size_read; */
213 
214         } while ((err == ZIP_OK) && (size_read > 0));
215 
216     if (fin)
217         fclose(fin);
218 
219     *result_crc=calculate_crc;
220     printf("file %s crc %lx\n", filenameinzip, calculate_crc);
221     return err;
222 }
223 
isLargeFile(const char * filename)224 static int isLargeFile(const char* filename)
225 {
226   int largeFile = 0;
227   ZPOS64_T pos = 0;
228   FILE* pFile = FOPEN_FUNC(filename, "rb");
229 
230   if(pFile != NULL)
231   {
232     FSEEKO_FUNC(pFile, 0, SEEK_END);
233     pos = (ZPOS64_T)FTELLO_FUNC(pFile);
234 
235                 printf("File : %s is %llu bytes\n", filename, pos);
236 
237     if(pos >= 0xffffffff)
238      largeFile = 1;
239 
240                 fclose(pFile);
241   }
242 
243  return largeFile;
244 }
245 
main(int argc,char * argv[])246 int main(int argc, char *argv[])
247 {
248     int i;
249     int opt_overwrite = 0;
250     int opt_compress_level = Z_DEFAULT_COMPRESSION;
251     int opt_exclude_path = 0;
252     int zipfilenamearg = 0;
253     char filename_try[MAXFILENAME + 16];
254     int zipok;
255     int err = 0;
256     size_t size_buf = 0;
257     void* buf = NULL;
258     const char* password = NULL;
259 
260 
261     do_banner();
262     if (argc == 1)
263     {
264         do_help();
265         return 0;
266     }
267     else
268     {
269         for (i = 1;i < argc; i++)
270         {
271             if ((*argv[i]) == '-')
272             {
273                 const char *p = argv[i] + 1;
274 
275                 while ((*p) != '\0')
276                 {
277                     char c = *(p++);
278                     if ((c == 'o') || (c == 'O'))
279                         opt_overwrite = 1;
280                     if ((c == 'a') || (c == 'A'))
281                         opt_overwrite = 2;
282                     if ((c >= '0') && (c <= '9'))
283                         opt_compress_level = c-'0';
284                     if ((c == 'j') || (c == 'J'))
285                         opt_exclude_path = 1;
286 
287                     if (((c == 'p') || (c == 'P')) && (i + 1 < argc))
288                     {
289                         password=argv[i + 1];
290                         i++;
291                     }
292                 }
293             }
294             else
295             {
296                 if (zipfilenamearg == 0)
297                 {
298                     zipfilenamearg = i ;
299                 }
300             }
301         }
302     }
303 
304     size_buf = WRITEBUFFERSIZE;
305     buf = (void*)malloc(size_buf);
306     if (buf == NULL)
307     {
308         printf("Error allocating memory\n");
309         return ZIP_INTERNALERROR;
310     }
311 
312     if (zipfilenamearg == 0)
313     {
314         zipok = 0;
315     }
316     else
317     {
318         int i,len;
319         int dot_found=0;
320 
321         zipok = 1 ;
322         strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME - 1);
323         /* strncpy doesn't append the trailing NULL, of the string is too long. */
324         filename_try[ MAXFILENAME ] = '\0';
325 
326         len=(int)strlen(filename_try);
327         for (i = 0;i < len; i++)
328             if (filename_try[i] == '.')
329                 dot_found = 1;
330 
331         if (dot_found == 0)
332             strcat(filename_try,".zip");
333 
334         if (opt_overwrite == 2)
335         {
336             /* if the file don't exist, we not append file */
337             if (check_exist_file(filename_try) == 0)
338                 opt_overwrite = 1;
339         }
340         else
341         if (opt_overwrite == 0)
342             if (check_exist_file(filename_try) != 0)
343             {
344                 char rep = 0;
345                 do
346                 {
347                     char answer[128];
348                     int ret;
349                     printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
350                     ret = scanf("%1s",answer);
351                     if (ret != 1)
352                     {
353                        exit(EXIT_FAILURE);
354                     }
355                     rep = answer[0] ;
356                     if ((rep>='a') && (rep<='z'))
357                         rep -= 0x20;
358                 }
359                 while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));
360                 if (rep == 'N')
361                     zipok = 0;
362                 if (rep == 'A')
363                     opt_overwrite = 2;
364             }
365     }
366 
367     if (zipok == 1)
368     {
369         zipFile zf;
370         int errclose;
371 #        ifdef USEWIN32IOAPI
372         zlib_filefunc64_def ffunc;
373         fill_win32_filefunc64A(&ffunc);
374         zf = zipOpen2_64(filename_try,(opt_overwrite == 2) ? 2 : 0,NULL,&ffunc);
375 #        else
376         zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
377 #        endif
378 
379         if (zf == NULL)
380         {
381             printf("error opening %s\n",filename_try);
382             err = ZIP_ERRNO;
383         }
384         else
385             printf("creating %s\n",filename_try);
386 
387         for (i=zipfilenamearg + 1;(i < argc) && (err == ZIP_OK); i++)
388         {
389             if (!((((*(argv[i])) == '-') || ((*(argv[i])) == '/')) &&
390                   ((argv[i][1] == 'o') || (argv[i][1] == 'O') ||
391                    (argv[i][1] == 'a') || (argv[i][1] == 'A') ||
392                    (argv[i][1] == 'p') || (argv[i][1] == 'P') ||
393                    ((argv[i][1] >= '0') && (argv[i][1] <= '9'))) &&
394                   (strlen(argv[i]) == 2)))
395             {
396                 FILE * fin = NULL;
397                 size_t size_read;
398                 const char* filenameinzip = argv[i];
399                 const char *savefilenameinzip;
400                 zip_fileinfo zi;
401                 unsigned long crcFile = 0;
402                 int zip64 = 0;
403 
404                 zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
405                 zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
406                 zi.dosDate = 0;
407                 zi.internal_fa = 0;
408                 zi.external_fa = 0;
409                 filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
410 
411 /*
412                 err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
413                                  NULL,0,NULL,0,NULL / * comment * /,
414                                  (opt_compress_level != 0) ? Z_DEFLATED : 0,
415                                  opt_compress_level);
416 */
417                 if ((password != NULL) && (err == ZIP_OK))
418                     err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
419 
420                 zip64 = isLargeFile(filenameinzip);
421 
422                                                          /* The path name saved, should not include a leading slash. */
423                /*if it did, windows/xp and dynazip couldn't read the zip file. */
424                  savefilenameinzip = filenameinzip;
425                  while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
426                  {
427                      savefilenameinzip++;
428                  }
429 
430                  /*should the zip file contain any path at all?*/
431                  if( opt_exclude_path )
432                  {
433                      const char *tmpptr;
434                      const char *lastslash = 0;
435                      for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
436                      {
437                          if( *tmpptr == '\\' || *tmpptr == '/')
438                          {
439                              lastslash = tmpptr;
440                          }
441                      }
442                      if( lastslash != NULL )
443                      {
444                          savefilenameinzip = lastslash+1; // base filename follows last slash.
445                      }
446                  }
447 
448                  /**/
449                 err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
450                                  NULL,0,NULL,0,NULL /* comment*/,
451                                  (opt_compress_level != 0) ? Z_DEFLATED : 0,
452                                  opt_compress_level,0,
453                                  /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
454                                  -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
455                                  password,crcFile, zip64);
456 
457                 if (err != ZIP_OK)
458                     printf("error in opening %s in zipfile\n",filenameinzip);
459                 else
460                 {
461                     fin = FOPEN_FUNC(filenameinzip,"rb");
462                     if (fin == NULL)
463                     {
464                         err = ZIP_ERRNO;
465                         printf("error in opening %s for reading\n",filenameinzip);
466                     }
467                 }
468 
469                 if (err == ZIP_OK)
470                     do
471                     {
472                         err = ZIP_OK;
473                         size_read = fread(buf,1,size_buf,fin);
474                         if (size_read < size_buf)
475                             if (feof(fin) == 0)
476                         {
477                             printf("error in reading %s\n",filenameinzip);
478                             err = ZIP_ERRNO;
479                         }
480 
481                         if (size_read > 0)
482                         {
483                             err = zipWriteInFileInZip (zf,buf,(unsigned)size_read);
484                             if (err<0)
485                             {
486                                 printf("error in writing %s in the zipfile\n",
487                                                  filenameinzip);
488                             }
489 
490                         }
491                     } while ((err == ZIP_OK) && (size_read > 0));
492 
493                 if (fin)
494                     fclose(fin);
495 
496                 if (err<0)
497                     err = ZIP_ERRNO;
498                 else
499                 {
500                     err = zipCloseFileInZip(zf);
501                     if (err != ZIP_OK)
502                         printf("error in closing %s in the zipfile\n",
503                                     filenameinzip);
504                 }
505             }
506         }
507         errclose = zipClose(zf,NULL);
508         if (errclose != ZIP_OK)
509             printf("error in closing %s\n",filename_try);
510     }
511     else
512     {
513        do_help();
514     }
515 
516     free(buf);
517     return 0;
518 }
519