1 /*
2    miniunz.c
3    Version 1.01e, February 12th, 2005
4 
5    Copyright (C) 1998-2005 Gilles Vollant
6 */
7 
8 
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <time.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 
16 #ifdef unix
17 # include <unistd.h>
18 # include <utime.h>
19 #else
20 # include <direct.h>
21 # include <io.h>
22 #endif
23 
24 #include "unzip.h"
25 
26 #define CASESENSITIVITY (0)
27 #define WRITEBUFFERSIZE (8192)
28 #define MAXFILENAME (256)
29 
30 #ifdef WIN32
31 #define USEWIN32IOAPI
32 #include "iowin32.h"
33 #endif
34 /*
35   mini unzip, demo of unzip package
36 
37   usage :
38   Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
39 
40   list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
41     if it exists
42 */
43 
44 
45 /* change_file_date : change the date/time of a file
46     filename : the filename of the file where date/time must be modified
47     dosdate : the new date at the MSDos format (4 bytes)
48     tmu_date : the SAME new date at the tm_unz format */
change_file_date(filename,dosdate,tmu_date)49 void change_file_date(filename,dosdate,tmu_date)
50     const char *filename;
51     uLong dosdate;
52     tm_unz tmu_date;
53 {
54 #ifdef WIN32
55   HANDLE hFile;
56   FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
57 
58   hFile = CreateFile(filename,GENERIC_READ | GENERIC_WRITE,
59                      0,NULL,OPEN_EXISTING,0,NULL);
60   GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
61   DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
62   LocalFileTimeToFileTime(&ftLocal,&ftm);
63   SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
64   CloseHandle(hFile);
65 #else
66 #ifdef unix
67   struct utimbuf ut;
68   struct tm newdate;
69   newdate.tm_sec = tmu_date.tm_sec;
70   newdate.tm_min=tmu_date.tm_min;
71   newdate.tm_hour=tmu_date.tm_hour;
72   newdate.tm_mday=tmu_date.tm_mday;
73   newdate.tm_mon=tmu_date.tm_mon;
74   if (tmu_date.tm_year > 1900)
75       newdate.tm_year=tmu_date.tm_year - 1900;
76   else
77       newdate.tm_year=tmu_date.tm_year ;
78   newdate.tm_isdst=-1;
79 
80   ut.actime=ut.modtime=mktime(&newdate);
81   utime(filename,&ut);
82 #endif
83 #endif
84 }
85 
86 
87 /* mymkdir and change_file_date are not 100 % portable
88    As I don't know well Unix, I wait feedback for the unix portion */
89 
mymkdir(dirname)90 int mymkdir(dirname)
91     const char* dirname;
92 {
93     int ret=0;
94 #ifdef WIN32
95     ret = mkdir(dirname);
96 #else
97 #ifdef unix
98     ret = mkdir (dirname,0775);
99 #endif
100 #endif
101     return ret;
102 }
103 
makedir(newdir)104 int makedir (newdir)
105     char *newdir;
106 {
107   char *buffer ;
108   char *p;
109   int  len = (int)strlen(newdir);
110 
111   if (len <= 0)
112     return 0;
113 
114   buffer = (char*)malloc(len+1);
115   strcpy(buffer,newdir);
116 
117   if (buffer[len-1] == '/') {
118     buffer[len-1] = '\0';
119   }
120   if (mymkdir(buffer) == 0) {
121     free(buffer);
122     return 1;
123   }
124 
125   p = buffer+1;
126   while (1)
127     {
128       char hold;
129 
130       while(*p && *p != '\\' && *p != '/')
131         p++;
132       hold = *p;
133       *p = 0;
134       if ((mymkdir(buffer) == -1) && (errno == ENOENT))
135         {
136           printf("couldn't create directory %s\n",buffer);
137           free(buffer);
138           return 0;
139         }
140       if (hold == 0)
141         break;
142       *p++ = hold;
143     }
144   free(buffer);
145   return 1;
146 }
147 
do_banner()148 void do_banner()
149 {
150     printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
151     printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
152 }
153 
do_help()154 void do_help()
155 {
156     printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
157            "  -e  Extract without pathname (junk paths)\n" \
158            "  -x  Extract with pathname\n" \
159            "  -v  list files\n" \
160            "  -l  list files\n" \
161            "  -d  directory to extract into\n" \
162            "  -o  overwrite files without prompting\n" \
163            "  -p  extract crypted file using password\n\n");
164 }
165 
166 
do_list(uf)167 int do_list(uf)
168     unzFile uf;
169 {
170     uLong i;
171     unz_global_info gi;
172     int err;
173 
174     err = unzGetGlobalInfo (uf,&gi);
175     if (err!=UNZ_OK)
176         printf("error %d with zipfile in unzGetGlobalInfo\n",err);
177     printf(" Length  Method   Size  Ratio   Date    Time   CRC-32     Name\n");
178     printf(" ------  ------   ----  -----   ----    ----   ------     ----\n");
179     for (i=0;i<gi.number_entry;i++)
180     {
181         char filename_inzip[256];
182         unz_file_info file_info;
183         uLong ratio=0;
184         const char *string_method;
185         char charCrypt=' ';
186         err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
187         if (err!=UNZ_OK)
188         {
189             printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
190             break;
191         }
192         if (file_info.uncompressed_size>0)
193             ratio = (file_info.compressed_size*100)/file_info.uncompressed_size;
194 
195         /* display a '*' if the file is crypted */
196         if ((file_info.flag & 1) != 0)
197             charCrypt='*';
198 
199         if (file_info.compression_method==0)
200             string_method="Stored";
201         else
202         if (file_info.compression_method==Z_DEFLATED)
203         {
204             uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
205             if (iLevel==0)
206               string_method="Defl:N";
207             else if (iLevel==1)
208               string_method="Defl:X";
209             else if ((iLevel==2) || (iLevel==3))
210               string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
211         }
212         else
213             string_method="Unkn. ";
214 
215         printf("%7lu  %6s%c%7lu %3lu%%  %2.2lu-%2.2lu-%2.2lu  %2.2lu:%2.2lu  %8.8lx   %s\n",
216                file_info.uncompressed_size,string_method,
217                charCrypt,
218                file_info.compressed_size,
219                ratio,
220                (uLong)file_info.tmu_date.tm_mon + 1,
221                (uLong)file_info.tmu_date.tm_mday,
222                (uLong)file_info.tmu_date.tm_year % 100,
223                (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
224                (uLong)file_info.crc,filename_inzip);
225         if ((i+1)<gi.number_entry)
226         {
227             err = unzGoToNextFile(uf);
228             if (err!=UNZ_OK)
229             {
230                 printf("error %d with zipfile in unzGoToNextFile\n",err);
231                 break;
232             }
233         }
234     }
235     return 0;
236 }
237 
238 
do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)239 int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
240     unzFile uf;
241     const int* popt_extract_without_path;
242     int* popt_overwrite;
243     const char* password;
244 {
245     char filename_inzip[256];
246     char* filename_withoutpath;
247     char* p;
248     int err=UNZ_OK;
249     FILE *fout=NULL;
250     void* buf;
251     uInt size_buf;
252 
253     unz_file_info file_info;
254     uLong ratio=0;
255     err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
256 
257     if (err!=UNZ_OK)
258     {
259         printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
260         return err;
261     }
262 
263     size_buf = WRITEBUFFERSIZE;
264     buf = (void*)malloc(size_buf);
265     if (buf==NULL)
266     {
267         printf("Error allocating memory\n");
268         return UNZ_INTERNALERROR;
269     }
270 
271     p = filename_withoutpath = filename_inzip;
272     while ((*p) != '\0')
273     {
274         if (((*p)=='/') || ((*p)=='\\'))
275             filename_withoutpath = p+1;
276         p++;
277     }
278 
279     if ((*filename_withoutpath)=='\0')
280     {
281         if ((*popt_extract_without_path)==0)
282         {
283             printf("creating directory: %s\n",filename_inzip);
284             mymkdir(filename_inzip);
285         }
286     }
287     else
288     {
289         const char* write_filename;
290         int skip=0;
291 
292         if ((*popt_extract_without_path)==0)
293             write_filename = filename_inzip;
294         else
295             write_filename = filename_withoutpath;
296 
297         err = unzOpenCurrentFilePassword(uf,password);
298         if (err!=UNZ_OK)
299         {
300             printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
301         }
302 
303         if (((*popt_overwrite)==0) && (err==UNZ_OK))
304         {
305             char rep=0;
306             FILE* ftestexist;
307             ftestexist = fopen(write_filename,"rb");
308             if (ftestexist!=NULL)
309             {
310                 fclose(ftestexist);
311                 do
312                 {
313                     char answer[128];
314                     int ret;
315 
316                     printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
317                     ret = scanf("%1s",answer);
318                     if (ret != 1)
319                     {
320                        exit(EXIT_FAILURE);
321                     }
322                     rep = answer[0] ;
323                     if ((rep>='a') && (rep<='z'))
324                         rep -= 0x20;
325                 }
326                 while ((rep!='Y') && (rep!='N') && (rep!='A'));
327             }
328 
329             if (rep == 'N')
330                 skip = 1;
331 
332             if (rep == 'A')
333                 *popt_overwrite=1;
334         }
335 
336         if ((skip==0) && (err==UNZ_OK))
337         {
338             fout=fopen(write_filename,"wb");
339 
340             /* some zipfile don't contain directory alone before file */
341             if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
342                                 (filename_withoutpath!=(char*)filename_inzip))
343             {
344                 char c=*(filename_withoutpath-1);
345                 *(filename_withoutpath-1)='\0';
346                 makedir(write_filename);
347                 *(filename_withoutpath-1)=c;
348                 fout=fopen(write_filename,"wb");
349             }
350 
351             if (fout==NULL)
352             {
353                 printf("error opening %s\n",write_filename);
354             }
355         }
356 
357         if (fout!=NULL)
358         {
359             printf(" extracting: %s\n",write_filename);
360 
361             do
362             {
363                 err = unzReadCurrentFile(uf,buf,size_buf);
364                 if (err<0)
365                 {
366                     printf("error %d with zipfile in unzReadCurrentFile\n",err);
367                     break;
368                 }
369                 if (err>0)
370                     if (fwrite(buf,err,1,fout)!=1)
371                     {
372                         printf("error in writing extracted file\n");
373                         err=UNZ_ERRNO;
374                         break;
375                     }
376             }
377             while (err>0);
378             if (fout)
379                     fclose(fout);
380 
381             if (err==0)
382                 change_file_date(write_filename,file_info.dosDate,
383                                  file_info.tmu_date);
384         }
385 
386         if (err==UNZ_OK)
387         {
388             err = unzCloseCurrentFile (uf);
389             if (err!=UNZ_OK)
390             {
391                 printf("error %d with zipfile in unzCloseCurrentFile\n",err);
392             }
393         }
394         else
395             unzCloseCurrentFile(uf); /* don't lose the error */
396     }
397 
398     free(buf);
399     return err;
400 }
401 
402 
do_extract(uf,opt_extract_without_path,opt_overwrite,password)403 int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
404     unzFile uf;
405     int opt_extract_without_path;
406     int opt_overwrite;
407     const char* password;
408 {
409     uLong i;
410     unz_global_info gi;
411     int err;
412     FILE* fout=NULL;
413 
414     err = unzGetGlobalInfo (uf,&gi);
415     if (err!=UNZ_OK)
416         printf("error %d with zipfile in unzGetGlobalInfo\n",err);
417 
418     for (i=0;i<gi.number_entry;i++)
419     {
420         if (do_extract_currentfile(uf,&opt_extract_without_path,
421                                       &opt_overwrite,
422                                       password) != UNZ_OK)
423             break;
424 
425         if ((i+1)<gi.number_entry)
426         {
427             err = unzGoToNextFile(uf);
428             if (err!=UNZ_OK)
429             {
430                 printf("error %d with zipfile in unzGoToNextFile\n",err);
431                 break;
432             }
433         }
434     }
435     return 0;
436 }
437 
do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)438 int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
439     unzFile uf;
440     const char* filename;
441     int opt_extract_without_path;
442     int opt_overwrite;
443     const char* password;
444 {
445     int err = UNZ_OK;
446     if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
447     {
448         printf("file %s not found in the zipfile\n",filename);
449         return 2;
450     }
451 
452     if (do_extract_currentfile(uf,&opt_extract_without_path,
453                                &opt_overwrite,
454                                password) == UNZ_OK)
455         return 0;
456     else
457         return 1;
458 }
459 
460 
main(argc,argv)461 int main(argc,argv)
462     int argc;
463     char *argv[];
464 {
465     const char *zipfilename=NULL;
466     const char *filename_to_extract=NULL;
467     const char *password=NULL;
468     char filename_try[MAXFILENAME+16] = "";
469     int i;
470     int opt_do_list=0;
471     int opt_do_extract=1;
472     int opt_do_extract_withoutpath=0;
473     int opt_overwrite=0;
474     int opt_extractdir=0;
475     const char *dirname=NULL;
476     unzFile uf=NULL;
477 
478     do_banner();
479     if (argc==1)
480     {
481         do_help();
482         return 0;
483     }
484     else
485     {
486         for (i=1;i<argc;i++)
487         {
488             if ((*argv[i])=='-')
489             {
490                 const char *p=argv[i]+1;
491 
492                 while ((*p)!='\0')
493                 {
494                     char c=*(p++);;
495                     if ((c=='l') || (c=='L'))
496                         opt_do_list = 1;
497                     if ((c=='v') || (c=='V'))
498                         opt_do_list = 1;
499                     if ((c=='x') || (c=='X'))
500                         opt_do_extract = 1;
501                     if ((c=='e') || (c=='E'))
502                         opt_do_extract = opt_do_extract_withoutpath = 1;
503                     if ((c=='o') || (c=='O'))
504                         opt_overwrite=1;
505                     if ((c=='d') || (c=='D'))
506                     {
507                         opt_extractdir=1;
508                         dirname=argv[i+1];
509                     }
510 
511                     if (((c=='p') || (c=='P')) && (i+1<argc))
512                     {
513                         password=argv[i+1];
514                         i++;
515                     }
516                 }
517             }
518             else
519             {
520                 if (zipfilename == NULL)
521                     zipfilename = argv[i];
522                 else if ((filename_to_extract==NULL) && (!opt_extractdir))
523                     filename_to_extract = argv[i] ;
524             }
525         }
526     }
527 
528     if (zipfilename!=NULL)
529     {
530 #        ifdef USEWIN32IOAPI
531         zlib_filefunc_def ffunc;
532 #        endif
533 
534         strncpy(filename_try, zipfilename,MAXFILENAME-1);
535         /* strncpy doesnt append the trailing NULL, of the string is too long. */
536         filename_try[ MAXFILENAME ] = '\0';
537 
538 #        ifdef USEWIN32IOAPI
539         fill_win32_filefunc(&ffunc);
540         uf = unzOpen2(zipfilename,&ffunc);
541 #        else
542         uf = unzOpen(zipfilename);
543 #        endif
544         if (uf==NULL)
545         {
546             strcat(filename_try,".zip");
547 #            ifdef USEWIN32IOAPI
548             uf = unzOpen2(filename_try,&ffunc);
549 #            else
550             uf = unzOpen(filename_try);
551 #            endif
552         }
553     }
554 
555     if (uf==NULL)
556     {
557         printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
558         return 1;
559     }
560     printf("%s opened\n",filename_try);
561 
562     if (opt_do_list==1)
563         return do_list(uf);
564     else if (opt_do_extract==1)
565     {
566         if (opt_extractdir && chdir(dirname))
567         {
568           printf("Error changing into %s, aborting\n", dirname);
569           exit(-1);
570         }
571 
572         if (filename_to_extract == NULL)
573             return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password);
574         else
575             return do_extract_onefile(uf,filename_to_extract,
576                                       opt_do_extract_withoutpath,opt_overwrite,password);
577     }
578     unzCloseCurrentFile(uf);
579 
580     return 0;
581 }
582