minizip.c 14.7 KB
Newer Older
M
Mark Adler 已提交
1 2
/*
   minizip.c
M
Mark Adler 已提交
3
   Version 1.1, February 14h, 2010
M
Mark Adler 已提交
4
   sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
M
Mark Adler 已提交
5

M
Mark Adler 已提交
6
         Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
M
Mark Adler 已提交
7

M
Mark Adler 已提交
8 9
         Modifications of Unzip for Zip64
         Copyright (C) 2007-2008 Even Rouault
M
Mark Adler 已提交
10

M
Mark Adler 已提交
11 12
         Modifications for Zip64 support on both zip and unzip
         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
M
Mark Adler 已提交
13 14
*/

M
Mark Adler 已提交
15

M
Mark Adler 已提交
16
#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
M
Mark Adler 已提交
17 18 19 20 21 22 23 24 25 26 27 28
        #ifndef __USE_FILE_OFFSET64
                #define __USE_FILE_OFFSET64
        #endif
        #ifndef __USE_LARGEFILE64
                #define __USE_LARGEFILE64
        #endif
        #ifndef _LARGEFILE64_SOURCE
                #define _LARGEFILE64_SOURCE
        #endif
        #ifndef _FILE_OFFSET_BIT
                #define _FILE_OFFSET_BIT 64
        #endif
M
Mark Adler 已提交
29 30
#endif

M
Mark Adler 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43
#ifdef __APPLE__
// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
#define FTELLO_FUNC(stream) ftello(stream)
#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
#else
#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
#define FTELLO_FUNC(stream) ftello64(stream)
#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
#endif



M
Mark Adler 已提交
44 45 46 47 48 49 50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>

M
Mark Adler 已提交
51 52 53 54
#ifdef _WIN32
# include <direct.h>
# include <io.h>
#else
M
Mark Adler 已提交
55 56 57 58 59 60 61 62
# include <unistd.h>
# include <utime.h>
# include <sys/types.h>
# include <sys/stat.h>
#endif

#include "zip.h"

M
Mark Adler 已提交
63
#ifdef _WIN32
M
Mark Adler 已提交
64 65
        #define USEWIN32IOAPI
        #include "iowin32.h"
M
Mark Adler 已提交
66 67 68 69 70 71 72
#endif



#define WRITEBUFFERSIZE (16384)
#define MAXFILENAME (256)

M
Mark Adler 已提交
73
#ifdef _WIN32
M
Mark Adler 已提交
74 75 76 77 78 79 80 81 82
uLong filetime(f, tmzip, dt)
    char *f;                /* name of file to get info on */
    tm_zip *tmzip;             /* return value: access, modific. and creation times */
    uLong *dt;             /* dostime */
{
  int ret = 0;
  {
      FILETIME ftLocal;
      HANDLE hFind;
M
Mark Adler 已提交
83
      WIN32_FIND_DATAA ff32;
M
Mark Adler 已提交
84

M
Mark Adler 已提交
85
      hFind = FindFirstFileA(f,&ff32);
M
Mark Adler 已提交
86 87 88 89 90 91 92 93 94 95 96
      if (hFind != INVALID_HANDLE_VALUE)
      {
        FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
        FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
        FindClose(hFind);
        ret = 1;
      }
  }
  return ret;
}
#else
M
Mark Adler 已提交
97
#ifdef unix || __APPLE__
M
Mark Adler 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
uLong filetime(f, tmzip, dt)
    char *f;               /* name of file to get info on */
    tm_zip *tmzip;         /* return value: access, modific. and creation times */
    uLong *dt;             /* dostime */
{
  int ret=0;
  struct stat s;        /* results of stat() */
  struct tm* filedate;
  time_t tm_t=0;

  if (strcmp(f,"-")!=0)
  {
    char name[MAXFILENAME+1];
    int len = strlen(f);
    if (len > MAXFILENAME)
      len = MAXFILENAME;

    strncpy(name, f,MAXFILENAME-1);
    /* strncpy doesnt append the trailing NULL, of the string is too long. */
    name[ MAXFILENAME ] = '\0';

    if (name[len - 1] == '/')
      name[len - 1] = '\0';
    /* not all systems allow stat'ing a file with / appended */
    if (stat(name,&s)==0)
    {
      tm_t = s.st_mtime;
      ret = 1;
    }
  }
  filedate = localtime(&tm_t);

  tmzip->tm_sec  = filedate->tm_sec;
  tmzip->tm_min  = filedate->tm_min;
  tmzip->tm_hour = filedate->tm_hour;
  tmzip->tm_mday = filedate->tm_mday;
  tmzip->tm_mon  = filedate->tm_mon ;
  tmzip->tm_year = filedate->tm_year;

  return ret;
}
#else
uLong filetime(f, tmzip, dt)
    char *f;                /* name of file to get info on */
    tm_zip *tmzip;             /* return value: access, modific. and creation times */
    uLong *dt;             /* dostime */
{
    return 0;
}
#endif
#endif




int check_exist_file(filename)
    const char* filename;
{
    FILE* ftestexist;
    int ret = 1;
M
Mark Adler 已提交
158
    ftestexist = FOPEN_FUNC(filename,"rb");
M
Mark Adler 已提交
159 160 161 162 163 164 165 166 167
    if (ftestexist==NULL)
        ret = 0;
    else
        fclose(ftestexist);
    return ret;
}

void do_banner()
{
M
Mark Adler 已提交
168
    printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
M
Mark Adler 已提交
169
    printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
M
Mark Adler 已提交
170 171 172 173
}

void do_help()
{
M
Mark Adler 已提交
174
    printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
M
Mark Adler 已提交
175 176 177 178
           "  -o  Overwrite existing file.zip\n" \
           "  -a  Append to existing file.zip\n" \
           "  -0  Store only\n" \
           "  -1  Compress faster\n" \
M
Mark Adler 已提交
179 180
           "  -9  Compress better\n\n" \
           "  -j  exclude path. store only the file name.\n\n");
M
Mark Adler 已提交
181 182 183 184 185 186 187 188
}

/* calculate the CRC32 of a file,
   because to encrypt a file, we need known the CRC32 of the file before */
int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
{
   unsigned long calculate_crc=0;
   int err=ZIP_OK;
M
Mark Adler 已提交
189
   FILE * fin = FOPEN_FUNC(filenameinzip,"rb");
190

M
Mark Adler 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
   unsigned long size_read = 0;
   unsigned long total_read = 0;
   if (fin==NULL)
   {
       err = ZIP_ERRNO;
   }

    if (err == ZIP_OK)
        do
        {
            err = ZIP_OK;
            size_read = (int)fread(buf,1,size_buf,fin);
            if (size_read < size_buf)
                if (feof(fin)==0)
            {
                printf("error in reading %s\n",filenameinzip);
                err = ZIP_ERRNO;
            }

            if (size_read>0)
                calculate_crc = crc32(calculate_crc,buf,size_read);
            total_read += size_read;

        } while ((err == ZIP_OK) && (size_read>0));

    if (fin)
        fclose(fin);

    *result_crc=calculate_crc;
M
Mark Adler 已提交
220
    printf("file %s crc %lx\n", filenameinzip, calculate_crc);
M
Mark Adler 已提交
221 222 223
    return err;
}

M
Mark Adler 已提交
224 225 226 227
int isLargeFile(const char* filename)
{
  int largeFile = 0;
  ZPOS64_T pos = 0;
M
Mark Adler 已提交
228
  FILE* pFile = FOPEN_FUNC(filename, "rb");
M
Mark Adler 已提交
229 230 231

  if(pFile != NULL)
  {
M
Mark Adler 已提交
232 233
    int n = FSEEKO_FUNC(pFile, 0, SEEK_END);
    pos = FTELLO_FUNC(pFile);
M
Mark Adler 已提交
234

M
Mark Adler 已提交
235
                printf("File : %s is %lld bytes\n", filename, pos);
M
Mark Adler 已提交
236

M
Mark Adler 已提交
237 238 239
    if(pos >= 0xffffffff)
     largeFile = 1;

M
Mark Adler 已提交
240
                fclose(pFile);
M
Mark Adler 已提交
241
  }
M
Mark Adler 已提交
242

M
Mark Adler 已提交
243 244 245
 return largeFile;
}

M
Mark Adler 已提交
246 247 248 249 250 251 252
int main(argc,argv)
    int argc;
    char *argv[];
{
    int i;
    int opt_overwrite=0;
    int opt_compress_level=Z_DEFAULT_COMPRESSION;
M
Mark Adler 已提交
253
    int opt_exclude_path=0;
M
Mark Adler 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    int zipfilenamearg = 0;
    char filename_try[MAXFILENAME+16];
    int zipok;
    int err=0;
    int size_buf=0;
    void* buf=NULL;
    const char* password=NULL;


    do_banner();
    if (argc==1)
    {
        do_help();
        return 0;
    }
    else
    {
        for (i=1;i<argc;i++)
        {
            if ((*argv[i])=='-')
            {
                const char *p=argv[i]+1;

                while ((*p)!='\0')
                {
                    char c=*(p++);;
                    if ((c=='o') || (c=='O'))
                        opt_overwrite = 1;
                    if ((c=='a') || (c=='A'))
                        opt_overwrite = 2;
                    if ((c>='0') && (c<='9'))
                        opt_compress_level = c-'0';
M
Mark Adler 已提交
286 287
                    if ((c=='j') || (c=='J'))
                        opt_exclude_path = 1;
M
Mark Adler 已提交
288 289 290 291 292 293 294 295 296

                    if (((c=='p') || (c=='P')) && (i+1<argc))
                    {
                        password=argv[i+1];
                        i++;
                    }
                }
            }
            else
M
Mark Adler 已提交
297
            {
M
Mark Adler 已提交
298
                if (zipfilenamearg == 0)
M
Mark Adler 已提交
299
                {
M
Mark Adler 已提交
300
                    zipfilenamearg = i ;
M
Mark Adler 已提交
301 302
                }
            }
M
Mark Adler 已提交
303 304 305 306 307 308 309 310 311 312 313 314
        }
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
        printf("Error allocating memory\n");
        return ZIP_INTERNALERROR;
    }

    if (zipfilenamearg==0)
M
Mark Adler 已提交
315
    {
M
Mark Adler 已提交
316
        zipok=0;
M
Mark Adler 已提交
317
    }
M
Mark Adler 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    else
    {
        int i,len;
        int dot_found=0;

        zipok = 1 ;
        strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
        /* strncpy doesnt append the trailing NULL, of the string is too long. */
        filename_try[ MAXFILENAME ] = '\0';

        len=(int)strlen(filename_try);
        for (i=0;i<len;i++)
            if (filename_try[i]=='.')
                dot_found=1;

        if (dot_found==0)
            strcat(filename_try,".zip");

        if (opt_overwrite==2)
        {
            /* if the file don't exist, we not append file */
            if (check_exist_file(filename_try)==0)
                opt_overwrite=1;
        }
        else
        if (opt_overwrite==0)
            if (check_exist_file(filename_try)!=0)
            {
                char rep=0;
                do
                {
                    char answer[128];
                    int ret;
                    printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
                    ret = scanf("%1s",answer);
                    if (ret != 1)
                    {
                       exit(EXIT_FAILURE);
                    }
                    rep = answer[0] ;
                    if ((rep>='a') && (rep<='z'))
                        rep -= 0x20;
                }
                while ((rep!='Y') && (rep!='N') && (rep!='A'));
                if (rep=='N')
                    zipok = 0;
                if (rep=='A')
                    opt_overwrite = 2;
            }
    }

    if (zipok==1)
    {
        zipFile zf;
        int errclose;
#        ifdef USEWIN32IOAPI
M
Mark Adler 已提交
374 375 376
        zlib_filefunc64_def ffunc;
        fill_win32_filefunc64A(&ffunc);
        zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
M
Mark Adler 已提交
377
#        else
M
Mark Adler 已提交
378
        zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
M
Mark Adler 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
#        endif

        if (zf == NULL)
        {
            printf("error opening %s\n",filename_try);
            err= ZIP_ERRNO;
        }
        else
            printf("creating %s\n",filename_try);

        for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
        {
            if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
                  ((argv[i][1]=='o') || (argv[i][1]=='O') ||
                   (argv[i][1]=='a') || (argv[i][1]=='A') ||
                   (argv[i][1]=='p') || (argv[i][1]=='P') ||
                   ((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
                  (strlen(argv[i]) == 2)))
            {
                FILE * fin;
                int size_read;
                const char* filenameinzip = argv[i];
M
Mark Adler 已提交
401
                const char *savefilenameinzip;
M
Mark Adler 已提交
402 403
                zip_fileinfo zi;
                unsigned long crcFile=0;
M
Mark Adler 已提交
404
                int zip64 = 0;
M
Mark Adler 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

                zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
                zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
                zi.dosDate = 0;
                zi.internal_fa = 0;
                zi.external_fa = 0;
                filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);

/*
                err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
                                 NULL,0,NULL,0,NULL / * comment * /,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level);
*/
                if ((password != NULL) && (err==ZIP_OK))
                    err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
M
Mark Adler 已提交
421

M
Mark Adler 已提交
422 423
                zip64 = isLargeFile(filenameinzip);

M
Mark Adler 已提交
424
                                                         /* The path name saved, should not include a leading slash. */
M
Mark Adler 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
               /*if it did, windows/xp and dynazip couldn't read the zip file. */
                 savefilenameinzip = filenameinzip;
                 while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
                 {
                     savefilenameinzip++;
                 }

                 /*should the zip file contain any path at all?*/
                 if( opt_exclude_path )
                 {
                     const char *tmpptr;
                     const char *lastslash = 0;
                     for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
                     {
                         if( *tmpptr == '\\' || *tmpptr == '/')
                         {
                             lastslash = tmpptr;
                         }
                     }
                     if( lastslash != NULL )
                     {
                         savefilenameinzip = lastslash+1; // base filename follows last slash.
                     }
                 }

                 /**/
                err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
M
Mark Adler 已提交
452 453 454 455 456
                                 NULL,0,NULL,0,NULL /* comment*/,
                                 (opt_compress_level != 0) ? Z_DEFLATED : 0,
                                 opt_compress_level,0,
                                 /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
                                 -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
M
Mark Adler 已提交
457
                                 password,crcFile, zip64);
M
Mark Adler 已提交
458 459 460 461 462

                if (err != ZIP_OK)
                    printf("error in opening %s in zipfile\n",filenameinzip);
                else
                {
M
Mark Adler 已提交
463
                    fin = FOPEN_FUNC(filenameinzip,"rb");
M
Mark Adler 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
                    if (fin==NULL)
                    {
                        err=ZIP_ERRNO;
                        printf("error in opening %s for reading\n",filenameinzip);
                    }
                }

                if (err == ZIP_OK)
                    do
                    {
                        err = ZIP_OK;
                        size_read = (int)fread(buf,1,size_buf,fin);
                        if (size_read < size_buf)
                            if (feof(fin)==0)
                        {
                            printf("error in reading %s\n",filenameinzip);
                            err = ZIP_ERRNO;
                        }

                        if (size_read>0)
                        {
                            err = zipWriteInFileInZip (zf,buf,size_read);
                            if (err<0)
                            {
                                printf("error in writing %s in the zipfile\n",
                                                 filenameinzip);
                            }

                        }
                    } while ((err == ZIP_OK) && (size_read>0));

                if (fin)
                    fclose(fin);

                if (err<0)
                    err=ZIP_ERRNO;
                else
                {
                    err = zipCloseFileInZip(zf);
                    if (err!=ZIP_OK)
                        printf("error in closing %s in the zipfile\n",
                                    filenameinzip);
                }
            }
        }
        errclose = zipClose(zf,NULL);
        if (errclose != ZIP_OK)
            printf("error in closing %s\n",filename_try);
    }
    else
    {
       do_help();
    }

    free(buf);
    return 0;
}