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