zipc.c 47.5 KB
Newer Older
1 2 3 4 5
/*
 * Implementation of ZIP container mini-library.
 *
 *     https://github.com/michaelrsweet/zipc
 *
6 7 8 9
 * Define ZIPC_ONLY_READ to compile with just the ZIP reading code, or
 * ZIPC_ONLY_WRITE to compile with just the ZIP writing code.  Otherwise both
 * ZIP reader and writer code is built.
 *
Michael R Sweet's avatar
Michael R Sweet committed
10
 * Copyright 2017-2018 by Michael R Sweet.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Include necessary headers...
 */

38 39 40 41
#ifdef WIN32
#  define _CRT_SECURE_NO_WARNINGS	/* Disable warnings for standard library functions */
#endif /* WIN32 */

42 43 44 45
#include "zipc.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
46
#include <ctype.h>
47 48 49 50 51 52 53 54 55 56 57 58 59
#include <errno.h>
#include <time.h>
#include <zlib.h>


/*
 * Local constants...
 */

#define ZIPC_LOCAL_HEADER  0x04034b50	/* Start of a local file header */
#define ZIPC_DIR_HEADER    0x02014b50	/* File header in central directory */
#define ZIPC_END_RECORD    0x06054b50	/* End of central directory record */

60 61 62
#define ZIPC_MADE_BY       0x031e	/* Version made by UNIX using zip 2.0 */
#define ZIPC_DIR_VERSION   0x000a	/* Version needed: 1.0 */
#define ZIPC_FILE_VERSION  0x0014	/* Version needed: 2.0 */
63 64

#define ZIPC_FLAG_CMAX     0x0002	/* Maximum compression */
Michael Sweet's avatar
Michael Sweet committed
65 66
#define ZIPC_FLAG_MASK     0x7fff       /* Mask for "standard" flags we want to write */
#define ZIPC_FLAG_STREAMED 0x8000       /* Internal bit used to flag when we need to update the CRC and length fields */
67 68 69 70

#define ZIPC_COMP_STORE    0		/* No compression */
#define ZIPC_COMP_DEFLATE  8		/* Deflate compression */

71 72 73 74 75 76
#define ZIPC_INTERNAL_BIN  0x0000	/* Internal attributes = binary */
#define ZIPC_INTERNAL_TEXT 0x0001	/* Internal attributes = text */

#define ZIPC_EXTERNAL_DIR  0x41ed0010	/* External attributes = directory */
#define ZIPC_EXTERNAL_FILE 0x81a40000	/* External attributes = file */

77 78
#define ZIPC_READ_SIZE     8192         /* Size of buffered read buffer */

79 80 81 82 83 84 85 86

/*
 * Local types...
 */

struct _zipc_s
{
  FILE		*fp;			/* ZIP file */
87
  char          mode;                   /* Open mode - 'r' or 'w' */
88
  const char	*error;			/* Last error message */
89
  char          error_msg[256];         /* Formatted error message */
90
  size_t	alloc_files,		/* Allocated file entries in ZIP */
91 92 93
		num_files;		/* Number of file entries in ZIP */
  zipc_file_t	*files;			/* File entries in ZIP */
  z_stream	stream;			/* Deflate stream for current file */
94
  unsigned int	modtime;		/* MS-DOS modification date/time */
95 96 97 98 99 100
  char		buffer[16384];		/* Deflate buffer */
#ifndef ZIPC_ONLY_WRITE
  char          *readbuffer,            /* Read buffer */
                *readptr,               /* Current character in read buffer */
                *readend;               /* End of read buffer */
#endif /* !ZIPC_ONLY_WRITE */
101 102 103 104 105 106 107 108 109 110 111 112
};

struct _zipc_file_s
{
  zipc_t	*zc;			/* ZIP container */
  char		filename[256];		/* File/directory name */
  unsigned short flags;			/* General purpose bit flags */
  unsigned short method;		/* Compression method */
  unsigned int	crc32;			/* 32-bit CRC */
  size_t	compressed_size;	/* Size of file (compressed) */
  size_t	uncompressed_size;	/* Size of file (uncompressed) */
  size_t	offset;			/* Offset of this entry in file */
113 114
  unsigned short internal_attrs;	/* Internal attributes */
  unsigned int	external_attrs;		/* External attributes */
115 116 117
  size_t        local_size;             /* Size of local header */
  size_t        compressed_pos;         /* Current read position in stream */
  size_t        uncompressed_pos;       /* Current read position in file */
118 119 120 121 122 123 124
};


/*
 * Local functions...
 */

125 126 127 128 129 130
#ifndef ZIPC_ONLY_WRITE
static ssize_t		zipc_read(zipc_t *zc, void *buffer, size_t bytes);
static int              zipc_read_char(zipc_file_t *zf);
static ssize_t		zipc_read_file(zipc_file_t *zf, void *buffer, size_t bytes);
static unsigned		zipc_read_u16(zipc_t *zc);
static unsigned		zipc_read_u32(zipc_t *zc);
Michael R Sweet's avatar
Michael R Sweet committed
131
static void             zipc_xml_unescape(char *buffer);
132 133 134
#endif /* !ZIPC_ONLY_WRITE */
#ifndef ZIPC_ONLY_READ
static zipc_file_t	*zipc_add_file(zipc_t *zc, const char *filename, int compression);
Michael R Sweet's avatar
Michael R Sweet committed
135
static int		zipc_write(zipc_t *zc, const void *buffer, size_t bytes);
136 137 138 139 140
static int		zipc_write_dir_header(zipc_t *zc, zipc_file_t *zf);
static int		zipc_write_local_header(zipc_t *zc, zipc_file_t *zf);
static int		zipc_write_local_trailer(zipc_t *zc, zipc_file_t *zf);
static int		zipc_write_u16(zipc_t *zc, unsigned value);
static int		zipc_write_u32(zipc_t *zc, unsigned value);
141 142
#endif /* !ZIPC_ONLY_READ */
static const char       *zipc_zlib_status(int zstatus);
143 144 145


/*
146 147
 * 'zipcClose()' - Close a ZIP container, writing out the central directory as
 *                 needed.
148 149 150 151 152
 */

int					/* O - 0 on success, -1 on error */
zipcClose(zipc_t *zc)			/* I - ZIP container */
{
153
  int	status = 0;		        /* Return status */
154 155


156 157 158 159 160 161
#ifndef ZIPC_ONLY_READ
  if (zc->mode == 'w')
  {
    size_t	i;			/* Looping var */
    zipc_file_t	*zf;			/* Current file */
    long	start, end;		/* Central directory offsets */
162

163 164 165
   /*
    * First write the central directory headers...
    */
166

167
    start = ftell(zc->fp);
168

169 170
    for (i = zc->num_files, zf = zc->files; i > 0; i --, zf ++)
      status |= zipc_write_dir_header(zc, zf);
171

172
    end = ftell(zc->fp);
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
   /*
    * Then write the end of central directory block...
    */

    status |= zipc_write_u32(zc, ZIPC_END_RECORD);
    status |= zipc_write_u16(zc, 0); /* Disk number */
    status |= zipc_write_u16(zc, 0); /* Disk number containing directory */
    status |= zipc_write_u16(zc, (unsigned)zc->num_files);
    status |= zipc_write_u16(zc, (unsigned)zc->num_files);
    status |= zipc_write_u32(zc, (unsigned)(end - start));
    status |= zipc_write_u32(zc, (unsigned)start);
    status |= zipc_write_u16(zc, 0); /* file comment length */
  }
#endif /* !ZIPC_ONLY_READ */

#ifndef ZIPC_ONLY_WRITE
  if (zc->readbuffer)
    free(zc->readbuffer);
#endif /* !ZIPC_ONLY_WRITE */
193 194 195 196 197 198 199 200 201 202 203 204 205

  if (fclose(zc->fp))
    status = -1;

  if (zc->alloc_files)
    free(zc->files);

  free(zc);

  return (status);
}


206
#ifndef ZIPC_ONLY_READ
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/*
 * 'zipcCopyFile()' - Copy a file into a ZIP container.
 *
 * The file referenced by "srcname" will be efficiently copied into the ZIP
 * container with the name "dstname".
 *
 * The "compressed" value determines whether the file is compressed within the
 * container.
 */

int                                     /* O - 0 on success, -1 on error */
zipcCopyFile(zipc_t *zc,                /* I - ZIP container */
             const char *dstname,       /* I - Destination file (in ZIP container) */
             const char *srcname,       /* I - Source file (on disk) */
             int        text,           /* I - 0 for binary, 1 for text */
             int        compressed)     /* I - 0 for uncompressed, 1 for compressed */
{
  zipc_file_t   *dstfile;               /* Destination file */
  FILE          *srcfile;               /* Source file */
  char          buffer[65536];          /* Copy buffer */
  size_t        length;                 /* Number of bytes read */


230 231 232 233 234 235
  if (zc->mode != 'w')
  {
    zc->error = "Not opened for writing.";
    return (-1);
  }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 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 286
  if ((srcfile = fopen(srcname, text ? "r" : "rb")) == NULL)
  {
    zc->error = strerror(errno);
    return (-1);
  }

  if ((dstfile = zipcCreateFile(zc, dstname, compressed)) == NULL)
  {
    fclose(srcfile);
    return (-1);
  }

  if (text)
  {
   /*
    * Copy as text...
    */

    while (fgets(buffer, sizeof(buffer), srcfile))
    {
      if (zipcFilePuts(dstfile, buffer))
      {
        fclose(srcfile);
        zipcFileFinish(dstfile);
        return (-1);
      }
    }
  }
  else
  {
   /*
    * Copy as binary...
    */

    while ((length = fread(buffer, 1, sizeof(buffer), srcfile)) > 0)
    {
      if (zipcFileWrite(dstfile, buffer, length))
      {
        fclose(srcfile);
        zipcFileFinish(dstfile);
        return (-1);
      }
    }
  }

  fclose(srcfile);

  return (zipcFileFinish(dstfile));
}


287 288 289 290 291 292 293 294 295 296 297 298
/*
 * 'zipcCreateDirectory()' - Create a directory in a ZIP container.
 *
 * The "filename" value is the path within the ZIP container.  Directories are
 * separated by the forward slash ("/").
 */

int					/* O - 0 on success, -1 on error */
zipcCreateDirectory(
    zipc_t     *zc,			/* I - ZIP container */
    const char *filename)		/* I - Directory name */
{
299
  zipc_file_t	*zf;    		/* ZIP container file */
300 301 302
  int		status = 0;		/* Return status */


303 304 305 306 307 308 309
  if (zc->mode != 'w')
  {
    zc->error = "Not opened for writing.";
    return (-1);
  }

  if ((zf = zipc_add_file(zc, filename, 0)) != NULL)
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  {
    char *end = zf->filename + strlen(zf->filename);

    if (end > zf->filename && end < (zf->filename + sizeof(zf->filename) - 1) && end[-1] != '/')
      *end = '/';

    zf->crc32          = 0;
    zf->external_attrs = ZIPC_EXTERNAL_DIR;

    status |= zipc_write_local_header(zc, zf);
  }
  else
    status = -1;

  return (status);
}


328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
/*
 * 'zipcCreateFile()' - Create a ZIP container file.
 *
 * The "filename" value is the path within the ZIP container.  Directories are
 * separated by the forward slash ("/").
 *
 * The "compressed" value determines whether the file is compressed within the
 * container.
 */

zipc_file_t *				/* I - ZIP container file */
zipcCreateFile(
    zipc_t     *zc,			/* I - ZIP container */
    const char *filename,		/* I - Filename in container */
    int        compressed)		/* I - 0 for uncompressed, 1 for compressed */
{
344 345 346 347 348 349 350 351 352
  zipc_file_t	*zf;    		/* ZIP container file */


  if (zc->mode != 'w')
  {
    zc->error = "Not opened for writing.";
    return (NULL);
  }

353 354 355 356
 /*
  * Add the file and write the header...
  */

357
  zf = zipc_add_file(zc, filename, compressed);
Michael Sweet's avatar
Michael Sweet committed
358
  zf->flags |= ZIPC_FLAG_STREAMED;
359
  zf->external_attrs = ZIPC_EXTERNAL_FILE;
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

  if (zipc_write_local_header(zc, zf))
    return (NULL);
  else
    return (zf);
}


/*
 * 'zipcCreateFileWithString()' - Add a file whose contents are a string.
 *
 * This function should be used for short ZIP container files like mimetype
 * or container descriptions.
 *
 * Note: Files added this way are not compressed.
 */

int					/* O - 0 on success, -1 on failure */
zipcCreateFileWithString(
    zipc_t     *zc,			/* I - ZIP container */
    const char *filename,		/* I - Filename in container */
    const char *contents)		/* I - Contents of file */
{
383
  zipc_file_t	*zf;			/* ZIP container file */
384 385 386 387
  size_t	len = strlen(contents);	/* Length of contents */
  int		status = 0;		/* Return status */


388 389 390 391 392 393 394
  if (zc->mode != 'w')
  {
    zc->error = "Not opened for writing.";
    return (-1);
  }

  if ((zf = zipc_add_file(zc, filename, 0)) != NULL)
395 396 397
  {
    zf->uncompressed_size = len;
    zf->compressed_size   = len;
398
    zf->crc32             = crc32(zf->crc32, (const Bytef *)contents, (unsigned)len);
399
    zf->internal_attrs    = ZIPC_INTERNAL_TEXT;
400
    zf->external_attrs    = ZIPC_EXTERNAL_FILE;
401 402 403 404 405 406 407 408 409

    status |= zipc_write_local_header(zc, zf);
    status |= zipc_write(zc, contents, len);
  }
  else
    status = -1;

  return (status);
}
410
#endif /* !ZIPC_ONLY_READ */
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434


/*
 * 'zipcError()' - Return a message describing the last detected error.
 */

const char *				/* O - Error string or NULL */
zipcError(zipc_t *zc)			/* I - ZIP container */
{
  return (zc ? zc->error : NULL);
}


/*
 * 'zipcFileFinish()' - Finish writing to a file in a ZIP container.
 */

int					/* O - 0 on success, -1 on error */
zipcFileFinish(zipc_file_t *zf)		/* I - ZIP container file */
{
  int		status = 0;		/* Return status */
  zipc_t	*zc = zf->zc;		/* ZIP container */


435 436
#ifndef ZIPC_ONLY_READ
  if (zc->mode == 'w')
437
  {
438
    if (zf->method != ZIPC_COMP_STORE)
439
    {
440 441 442
      int zstatus;			/* Deflate status */

      while ((zstatus = deflate(&zc->stream, Z_FINISH)) != Z_STREAM_END)
443
      {
444 445 446 447 448 449 450 451 452 453 454 455
        if (zstatus < Z_OK && zstatus != Z_BUF_ERROR)
        {
          zc->error = zipc_zlib_status(zstatus);
          status = -1;
          break;
        }

        status |= zipc_write(zf->zc, zc->buffer, (size_t)((char *)zc->stream.next_out - zc->buffer));
        zf->compressed_size += (size_t)((char *)zc->stream.next_out - zc->buffer);

        zc->stream.next_out  = (Bytef *)zc->buffer;
        zc->stream.avail_out = sizeof(zc->buffer);
456 457
      }

458 459 460 461 462
      if ((char *)zc->stream.next_out > zc->buffer)
      {
        status |= zipc_write(zf->zc, zc->buffer, (size_t)((char *)zc->stream.next_out - zc->buffer));
        zf->compressed_size += (size_t)((char *)zc->stream.next_out - zc->buffer);
      }
463

464
      deflateEnd(&zc->stream);
465 466
    }

467
    status |= zipc_write_local_trailer(zc, zf);
468
  }
469
#endif /* !ZIPC_ONLY_READ */
470

471 472 473 474 475 476 477
#ifndef ZIPC_ONLY_WRITE
#  ifndef ZIPC_ONLY_READ
  else
#  endif /* !ZIPC_ONLY_READ */
  if (zc->mode == 'r' && zf->method != ZIPC_COMP_STORE)
    inflateEnd(&zc->stream);
#endif /* !ZIPC_ONLY_WRITE */
478 479 480 481 482

  return (status);
}


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 521 522 523 524 525 526 527
#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipcFileGets()' - Read a line from a file.
 *
 * The trailing newline is omitted from the string for the line.
 */

int                                     /* O - 0 on success, -1 on error */
zipcFileGets(zipc_file_t *zf,           /* I - ZIP container file */
             char        *line,         /* I - Line string buffer */
             size_t      linesize)      /* I - Size of buffer */
{
  char  ch,                             /* Current character */
        *lineptr,                       /* Pointer into buffer */
        *lineend;                       /* Pointer to end of buffer */


 /*
  * Read the line...
  */

  lineptr = line;
  lineend = line + linesize - 1;

  while ((ch = zipc_read_char(zf)) > 0)
  {
    if (ch == '\n')
      break;
    else if (ch == '\r')
      continue;
    else if (lineptr < lineend)
      *lineptr++ = ch;
  }

  *lineptr = '\0';

  if (lineptr == line)
    return (-1);
  else
    return (0);
}
#endif /* !ZIPC_ONLY_WRITE */


#ifndef ZIPC_ONLY_READ
528 529 530
/*
 * 'zipcFilePrintf()' - Write a formatted string to a file.
 *
531
 * The "zf" value is the one returned by the @link zipcCreateFile@ function
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
 * used to create the ZIP container file.
 *
 * The "format" value is a standard printf format string and is followed by
 * any arguments needed by the string.
 */

int					/* O - 0 on success, -1 on error */
zipcFilePrintf(zipc_file_t *zf,		/* I - ZIP container file */
	       const char  *format,	/* I - Printf-style format string */
	       ...)			/* I - Additional arguments as needed */
{
  char		buffer[8192];		/* Format buffer */
  va_list	ap;			/* Pointer to additional arguments */


547 548 549 550 551 552
  if (zf->zc->mode != 'w')
  {
    zf->zc->error = "Not opened for writing.";
    return (-1);
  }

553 554 555 556 557 558 559 560 561
  va_start(ap, format);
  if (vsnprintf(buffer, sizeof(buffer), format, ap) < 0)
  {
    zf->zc->error = strerror(errno);
    va_end(ap);
    return (-1);
  }
  va_end(ap);

562 563
  zf->internal_attrs = ZIPC_INTERNAL_TEXT;

564 565 566 567 568 569 570
  return (zipcFileWrite(zf, buffer, strlen(buffer)));
}


/*
 * 'zipcFilePuts()' - Write a string to a file.
 *
571
 * The "zf" value is the one returned by the @link zipcCreateFile@ function
572 573 574 575 576 577 578 579 580 581
 * used to create the ZIP container file.
 *
 * The "s" value is literal string that is written to the file.  No newline is
 * added.
 */

int					/* O - 0 on success, -1 on error */
zipcFilePuts(zipc_file_t *zf,		/* I - ZIP container file */
               const char  *s)		/* I - String to write */
{
582 583 584 585 586 587
  if (zf->zc->mode != 'w')
  {
    zf->zc->error = "Not opened for writing.";
    return (-1);
  }

588 589
  zf->internal_attrs = ZIPC_INTERNAL_TEXT;

590 591
  return (zipcFileWrite(zf, s, strlen(s)));
}
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
#endif /* !ZIPC_ONLY_READ */


#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipcFileRead()' - Read data from a ZIP container file.
 *
 * The "zf" value is the one returned by the @link zipcOpenFile@ function used
 * to open the ZIP container file.
 *
 * The "data" value points to a buffer to hold the bytes that are read.
 */

ssize_t                                 /* O - Number of bytes read or -1 on error */
zipcFileRead(zipc_file_t *zf,           /* I - ZIP container file */
             void        *data,         /* I - Read buffer */
             size_t      bytes)         /* I - Maximum number of bytes to read */
{
  ssize_t       rbytes;                 /* Bytes read */
  zipc_t        *zc = zf->zc;           /* ZIP container */


  if (zc->mode != 'r')
  {
    zc->error = "Not opened for reading.";
    return (-1);
  }

  if ((zf->uncompressed_pos + bytes) > zf->uncompressed_size)
    bytes = zf->uncompressed_size - zf->uncompressed_pos;

  if (zc->readptr && zc->readptr < zc->readend)
  {
    rbytes = zc->readend - zc->readptr;
    if (rbytes > bytes)
      rbytes = bytes;

    memcpy(data, zc->readptr, rbytes);
    zc->readptr += rbytes;
  }
  else
    rbytes = zipc_read_file(zf, data, bytes);

  if (rbytes > 0)
    zf->uncompressed_pos += rbytes;

  return (rbytes);
}
#endif /* !ZIPC_ONLY_WRITE */
641 642


643
#ifndef ZIPC_ONLY_READ
644 645 646
/*
 * 'zipcFileWrite()' - Write data to a ZIP container file.
 *
647
 * The "zf" value is the one returned by the @link zipcCreateFile@ function
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
 * used to create the ZIP container file.
 *
 * The "data" value points to the bytes to be written.
 *
 * The "bytes" value specifies the number of bytes to write.
 */

int					/* O - 0 on success, -1 on error */
zipcFileWrite(zipc_file_t *zf,		/* I - ZIP container file */
	      const void  *data,	/* I - Data to write */
	      size_t      bytes)	/* I - Number of bytes to write */
{
  int		status = 0;		/* Return status */
  zipc_t	*zc = zf->zc;		/* ZIP container */


664 665 666 667 668 669
  if (zc->mode != 'w')
  {
    zc->error = "Not opened for writing.";
    return (-1);
  }

670
  zf->uncompressed_size += bytes;
671
  zf->crc32             = crc32(zf->crc32, (const Bytef *)data, (unsigned)bytes);
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696

  if (zf->method == ZIPC_COMP_STORE)
  {
   /*
    * Store the contents as literal data...
    */

    status = zipc_write(zc, data, bytes);
    zf->compressed_size += bytes;
  }
  else
  {
   /*
    * Deflate (compress) the contents...
    */

    int	zstatus;			/* Deflate status */

    zc->stream.next_in  = (Bytef *)data;
    zc->stream.avail_in = (unsigned)bytes;

    while (zc->stream.avail_in > 0)
    {
      if (zc->stream.avail_out < (int)(sizeof(zc->buffer) / 8))
      {
697 698
	status |= zipc_write(zf->zc, zc->buffer, (size_t)((char *)zc->stream.next_out - zc->buffer));
	zf->compressed_size += (size_t)((char *)zc->stream.next_out - zc->buffer);
699 700 701 702 703 704 705 706 707

	zc->stream.next_out  = (Bytef *)zc->buffer;
	zc->stream.avail_out = sizeof(zc->buffer);
      }

      zstatus = deflate(&zc->stream, Z_NO_FLUSH);

      if (zstatus < Z_OK && zstatus != Z_BUF_ERROR)
      {
708
        zc->error = zipc_zlib_status(zstatus);
709 710 711 712 713 714 715 716 717 718
        status = -1;
        break;
      }
    }
  }

  return (status);
}


719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipcFileXMLGets()' - Read an XML fragment from a file.
 *
 * An XML fragment is an element like "<element attr='value'>", "some text", and
 * "</element>".
 */

int                                     /* O - 0 on success, -1 on error */
zipcFileXMLGets(zipc_file_t *zf,        /* I - ZIP container file */
                char        *fragment,  /* I - Fragment string buffer */
                size_t      fragsize)   /* I - Size of buffer */
{
  char  ch,                             /* Current character */
        *fragptr,                       /* Pointer into buffer */
        *fragend;                       /* Pointer to end of buffer */


 /*
  * Read the fragment...
  */

  fragptr = fragment;
  fragend = fragment + fragsize - 1;

  if ((ch = zipc_read_char(zf)) <= 0)
  {
    *fragment = '\0';
    return (-1);
  }

  *fragptr++ = ch;

  if (ch == '<')
  {
   /*
    * Read element...
    */

    while ((ch = zipc_read_char(zf)) > 0)
    {
      if (fragptr < fragend)
        *fragptr++ = ch;

      if (ch == '>')
        break;
      else if (ch == '\"' || ch == '\'')
      {
       /*
        * Read quoted string...
        */

        char quote = ch;

        while ((ch = zipc_read_char(zf)) > 0)
        {
          if (fragptr < fragend)
            *fragptr++ = ch;

          if (ch == quote)
            break;
        }
      }
    }

    *fragptr++ = '\0';
  }
  else
  {
   /*
    * Read text...
    */

    while ((ch = zipc_read_char(zf)) > 0)
    {
      if (ch == '<')
      {
        zf->zc->readptr --;
        break;
      }
      else if (fragptr < fragend)
        *fragptr++ = ch;
    }

    *fragptr++ = '\0';

    zipc_xml_unescape(fragment);
  }

  return (0);
}
#endif /* !ZIPC_ONLY_WRITE */


813 814 815
/*
 * 'zipcFileXMLPrintf()' - Write a formatted XML string to a file.
 *
816
 * The "zf" value is the one returned by the @link zipcCreateFile@ function
817 818
 * used to create the ZIP container file.
 *
819 820 821
 * The "format" value is a printf-style format string supporting "%d", "%f",
 * "%s", and "%%" and is followed by any arguments needed by the string.
 * Strings ("%s") are escaped as needed.
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
 */

int					/* O - 0 on success, -1 on error */
zipcFileXMLPrintf(
    zipc_file_t *zf,			/* I - ZIP container file */
    const char  *format,		/* I - Printf-style format string */
    ...)				/* I - Additional arguments as needed */
{
  int		status = 0;		/* Return status */
  va_list	ap;			/* Pointer to additional arguments */
  char		buffer[65536],		/* Buffer */
		*bufend = buffer + sizeof(buffer) - 6,
					/* End of buffer less "&quot;" */
		*bufptr = buffer;	/* Pointer into buffer */
  const char	*s;			/* String pointer */
837 838 839
  int		d;			/* Integer */
  double        f;                      /* Real/floating point number */

840

841 842 843 844 845
  if (zf->zc->mode != 'w')
  {
    zf->zc->error = "Not opened for writing.";
    return (-1);
  }
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

  va_start(ap, format);

  while (*format && bufptr < bufend)
  {
    if (*format == '%')
    {
      format ++;

      switch (*format)
      {
        case '%' : /* Substitute a single % */
            format ++;

            *bufptr++ = '%';
            break;

        case 'd' : /* Substitute a single integer */
            format ++;

            d = va_arg(ap, int);
            snprintf(bufptr, bufend - bufptr, "%d", d);
            bufptr += strlen(bufptr);
            break;

871 872 873 874 875 876 877 878
        case 'f' : /* Substitute a single real number */
            format ++;

            f = va_arg(ap, double);
            snprintf(bufptr, bufend - bufptr, "%f", f);
            bufptr += strlen(bufptr);
            break;

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
        case 's' : /* Substitute a single string */
            format ++;

            s = va_arg(ap, const char *);
            while (*s && bufptr < bufend)
            {
              switch (*s)
              {
                case '&' : /* &amp; */
                    *bufptr++ = '&';
                    *bufptr++ = 'a';
                    *bufptr++ = 'm';
                    *bufptr++ = 'p';
                    *bufptr++ = ';';
                    break;
                case '<' : /* &lt; */
                    *bufptr++ = '&';
                    *bufptr++ = 'l';
                    *bufptr++ = 't';
                    *bufptr++ = ';';
                    break;
                case '>' : /* &gt; */
                    *bufptr++ = '&';
                    *bufptr++ = 'g';
                    *bufptr++ = 't';
                    *bufptr++ = ';';
                    break;
                case '\"' : /* &quot; */
                    *bufptr++ = '&';
                    *bufptr++ = 'q';
                    *bufptr++ = 'u';
                    *bufptr++ = 'o';
                    *bufptr++ = 't';
                    *bufptr++ = ';';
                    break;
                default :
                    *bufptr++ = *s;
                    break;
              }

              s ++;
            }

            if (*s)
            {
	      format += strlen(format);
              status = -1;
              zf->zc->error = "Not enough memory to hold XML string.";
            }
            break;

        default : /* Something else we don't support... */
            format += strlen(format);
            status = -1;
933
            zf->zc->error = "Unsupported format character - only %%, %d, %f, and %s are supported.";
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
            break;
      }
    }
    else
      *bufptr++ = *format++;
  }

  va_end(ap);

  if (*format)
  {
    status = -1;
    zf->zc->error = "Not enough memory to hold XML string.";
  }

  if (bufptr > buffer)
950 951 952 953 954
  {
    zf->internal_attrs = ZIPC_INTERNAL_TEXT;

    status |= zipcFileWrite(zf, buffer, (size_t)(bufptr - buffer));
  }
955 956 957

  return (status);
}
958
#endif /* !ZIPC_ONLY_READ */
959 960 961 962 963


/*
 * 'zipcOpen()' - Open a ZIP container.
 *
964 965
 * Currently the only supported "mode" values are "r" to read a ZIP container
 * and "w" to write a ZIP container.
966 967 968 969 970 971 972 973 974 975
 */

zipc_t *				/* O - ZIP container */
zipcOpen(const char *filename,		/* I - Filename of container */
         const char *mode)		/* I - Open mode ("w") */
{
  zipc_t	*zc;			/* ZIP container */


 /*
976
  * Only support read and write mode for now...
977 978
  */

979 980 981
#ifdef ZIPC_ONLY_READ
  if (strcmp(mode, "r"))
#elif defined(ZIPC_ONLY_WRITE)
982
  if (strcmp(mode, "w"))
983 984 985
#else
  if (strcmp(mode, "r") && strcmp(mode, "w"))
#endif /* ZIPC_ONLY_READ */
986 987 988 989 990 991 992 993 994
  {
    errno = EINVAL;
    return (NULL);
  }

 /*
  * Allocate memory...
  */

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
  if ((zc = calloc(1, sizeof(zipc_t))) == NULL)
    return (NULL);

  zc->mode = *mode;

#ifndef ZIPC_ONLY_WRITE
  if (zc->mode == 'r')
  {
   /*
    * Open for reading...
    */

    zipc_file_t *zf;                    /* Current file */
    long        offset;                 /* Current offset */
    unsigned    signature,              /* Header signature */
                version,                /* Version needed to extract */
                flags,                  /* General purpose flags */
                method,                 /* Compression method */
                modtime,                /* Last modification date/time */
                crc32,                  /* CRC-32 of file data */
                compressed_size,        /* Compressed file size */
                uncompressed_size,      /* Uncompressed file size */
                cfile_len,              /* Length of container filename */
                extra_field_len;        /* Length of extra data */
//  unsigned      internal_attrs,         /* Internal attributes */
//                external_attrs;         /* External attributes */
    char        cfile[256];             /* Container filename from header */
    int         done = 0;               /* Done reading? */


   /*
    * Open the container file...
    */

    if ((zc->fp = fopen(filename, "rb")) == NULL)
    {
      free(zc);
      return (NULL);
    }

   /*
    * Read all of the file headers...
    */

    while (!done && (signature = zipc_read_u32(zc)) != 0xffffffff)
    {
      switch (signature)
      {
        case ZIPC_LOCAL_HEADER :
            offset            = ftell(zc->fp) - 4;
            version           = zipc_read_u16(zc);
            flags             = zipc_read_u16(zc);
            method            = zipc_read_u16(zc);
            modtime           = zipc_read_u32(zc);
            crc32             = zipc_read_u32(zc);
            compressed_size   = zipc_read_u32(zc);
            uncompressed_size = zipc_read_u32(zc);
            cfile_len         = zipc_read_u16(zc);
            extra_field_len   = zipc_read_u16(zc);

            if (cfile_len > (sizeof(cfile) - 1))
            {
              zc->error = "Filename too long.";
              done = 1;
              break;
            }

            if (zipc_read(zc, cfile, cfile_len) < cfile_len)
            {
              done = 1;
              break;
            }

            cfile[cfile_len] = '\0';

            if (extra_field_len > 0)
              fseek(zc->fp, extra_field_len, SEEK_CUR);

            if (zc->num_files >= zc->alloc_files)
            {
              zc->alloc_files += 10;

              if (!zc->files)
                zf = malloc(zc->alloc_files * sizeof(zipc_file_t));
              else
                zf = realloc(zc->files, zc->alloc_files * sizeof(zipc_file_t));

              if (!zf)
              {
                zc->error = strerror(errno);
                return (NULL);
              }

              zc->files = zf;
            }

            zf = zc->files + zc->num_files;
            zc->num_files ++;

            memset(zf, 0, sizeof(zipc_file_t));

            strncpy(zf->filename, cfile, sizeof(zf->filename) - 1);
            zf->zc                = zc;
            zf->flags             = flags;
            zf->method            = method;
            zf->crc32             = crc32;
            zf->compressed_size   = compressed_size;
            zf->uncompressed_size = uncompressed_size;
            zf->offset            = (size_t)offset;
            zf->local_size        = (size_t)(ftell(zc->fp) - offset);

            fseek(zc->fp, compressed_size, SEEK_CUR);
            break;

       default :
           snprintf(zc->error_msg, sizeof(zc->error_msg), "Unknown ZIP signature 0x%08x.", signature);
           zc->error = zc->error_msg;

           fprintf(stderr, "zipcOpen: %s\n", zc->error_msg);

       case ZIPC_DIR_HEADER :
       case ZIPC_END_RECORD :
           done = 1;
           break;
      }
    }
  }
#endif /* !ZIPC_ONLY_WRITE */

#ifndef ZIPC_ONLY_READ
#  ifndef ZIPC_ONLY_WRITE
  else
#  endif /* !ZIPC_ONLY_WRITE */
  if (zc->mode == 'w')
1129
  {
1130 1131 1132 1133
   /*
    * Open for writing...
    */

1134 1135 1136 1137 1138 1139 1140
    time_t	curtime;		/* Current timestamp */
    struct tm	*curdate;		/* Current date/time */

   /*
    * Open the container file...
    */

1141
    if ((zc->fp = fopen(filename, "w+b")) == NULL)
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    {
      free(zc);
      return (NULL);
    }

   /*
    * Get the current date/time and convert it to the packed MS-DOS format:
    *
    *     Bits    Description
    *     ------  -----------
1152 1153 1154
    *     0-4     Seconds / 2 (0-29)
    *     5-10    Minute (0-59)
    *     11-15   Hour (0-23)
1155 1156 1157 1158 1159 1160
    *     16-20   Day (1-31)
    *     21-24   Month (1-12)
    *     25-31   Years since 1980
    */

    curtime = time(NULL);
1161 1162 1163 1164 1165 1166 1167 1168
    curdate = localtime(&curtime);

    zc->modtime = (unsigned)(curdate->tm_sec / 2) |
                  ((unsigned)curdate->tm_min << 5) |
                  ((unsigned)curdate->tm_hour << 11) |
                  ((unsigned)curdate->tm_mday << 16) |
                  ((unsigned)(curdate->tm_mon + 1) << 21) |
                  ((unsigned)(curdate->tm_year - 80) << 25);
1169
  }
1170
#endif /* !ZIPC_ONLY_READ */
1171 1172 1173 1174 1175

  return (zc);
}


1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipcOpenFile()' - Open a file in a ZIP container.
 */

zipc_file_t *                           /* O - File */
zipcOpenFile(zipc_t     *zc,            /* I - ZIP container */
             const char *filename)      /* I - Name of file */
{
  size_t        count;                  /* Number of files */
  zipc_file_t   *current;               /* Current file */


  for (count = zc->num_files, current = zc->files; count > 0; count --, current ++)
  {
    if (!strcmp(filename, current->filename))
    {
      fseek(zc->fp, current->offset + current->local_size, SEEK_SET);

      if (current->method == ZIPC_COMP_DEFLATE)
      {
        zc->stream.zalloc = (alloc_func)0;
        zc->stream.zfree  = (free_func)0;
        zc->stream.opaque = (voidpf)0;

        inflateInit2(&zc->stream, -15);

        zc->stream.next_in  = (Bytef *)zc->buffer;
        zc->stream.avail_in = 0;
      }

      current->compressed_pos   = 0;
      current->uncompressed_pos = 0;

      zc->readptr = NULL;

      return (current);
    }
  }

 /*
  * If we get here we didn't find the file...
  */

  zc->error = strerror(ENOENT);

  return (NULL);
}


/*
 * 'zipcXMLGetAttribute()' - Get the value of an attribute in an XML fragment.
 *
 * "element" is an XML element fragment returned by @link zipcFileXMLGets@.
 */

const char *                            /* O - Attribute value string or @code NULL@ */
zipcXMLGetAttribute(
    const char *element,                /* I - XML element fragment */
    const char *attrname,               /* I - Attribute name */
    char       *buffer,                 /* I - Value buffer */
    size_t     bufsize)                 /* I - Size of value buffer */
{
  size_t        attrlen;                /* Length of attribute name */
  char          quote,                  /* Quote character to skip */
                *bufptr,                /* Pointer into buffer */
                *bufend;                /* End of buffer */


 /*
  * Make sure we have an element fragment...
  */

  if (*element != '<' || element[1] == '/')
  {
    *buffer = '\0';

    return (NULL);
  }

 /*
  * Skip the element name...
  */

  while (*element && !isspace(*element & 255))
    element ++;

 /*
  * Find the named attribute...
  */

  attrlen = strlen(attrname);

  while (*element && *element != '>')
  {
   /*
    * Skip leading whitespace...
    */

    while (*element && isspace(*element & 255))
      element ++;

   /*
    * See if we have the attribute...
    */

    if (!strncmp(element, attrname, attrlen) && element[attrlen] == '=')
    {
     /*
      * Yes, copy the value...
      */

      element += attrlen + 1;

      quote = *element++;

      if (quote != '\"' && quote != '\'')
        break;                          /* Bad value - must be quoted */

      for (bufptr = buffer, bufend = buffer + bufsize - 1; *element && *element != quote; element ++)
      {
        if (bufptr < bufend)
          *bufptr++ = *element;
      }

      *bufptr = '\0';

      zipc_xml_unescape(buffer);

      return (buffer);
    }
    else
    {
     /*
      * Not a matching attribute, skip it...
      */

      if ((element = strchr(element, '=')) == NULL)
        break;

      element ++;
      quote = *element++;

      if (quote != '\"' && quote != '\'')
        break;                          /* Bad value - must be quoted */

      if ((element = strchr(element, quote)) == NULL)
        break;

      element ++;
    }
  }

 /*
  * If we get this far we didn't find it...
  */

  *buffer = '\0';

  return (NULL);
}
#endif /* !ZIPC_ONLY_WRITE */


#ifndef ZIPC_ONLY_READ
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
/*
 * 'zipc_add_file()' - Add a file to the ZIP container.
 */

static zipc_file_t *			/* O - New file */
zipc_add_file(zipc_t     *zc,		/* I - ZIP container */
              const char *filename,	/* I - Name of file in container */
              int        compression)	/* I - 0 = uncompressed, 1 = compressed */
{
  zipc_file_t	*temp;			/* File(s) */


  if (zc->num_files >= zc->alloc_files)
  {
   /*
    * Allocate more files...
    */

    zc->alloc_files += 10;

    if (!zc->files)
      temp = malloc(zc->alloc_files * sizeof(zipc_file_t));
    else
      temp = realloc(zc->files, zc->alloc_files * sizeof(zipc_file_t));

    if (!temp)
    {
      zc->error = strerror(errno);
      return (NULL);
    }

    zc->files = temp;
  }

  temp = zc->files + zc->num_files;
  zc->num_files ++;

  memset(temp, 0, sizeof(zipc_file_t));

  strncpy(temp->filename, filename, sizeof(temp->filename) - 1);

  temp->zc     = zc;
  temp->crc32  = crc32(0, NULL, 0);
1384
  temp->offset = (size_t)ftell(zc->fp);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

  if (compression)
  {
    temp->flags  = ZIPC_FLAG_CMAX;
    temp->method = ZIPC_COMP_DEFLATE;

    zc->stream.zalloc = (alloc_func)0;
    zc->stream.zfree  = (free_func)0;
    zc->stream.opaque = (voidpf)0;

    deflateInit2(&zc->stream, Z_BEST_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);

    zc->stream.next_out  = (Bytef *)zc->buffer;
    zc->stream.avail_out = sizeof(zc->buffer);
  }

  return (temp);
}
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
#endif /* !ZIPC_ONLY_READ */


#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipc_read()' - Read from the ZIP container and capture any error.
 */

static ssize_t                          /* O - Bytes read or -1 on error */
zipc_read(zipc_t *zc,                   /* I - ZIP container */
          void   *buffer,               /* I - Read buffer */
          size_t bytes)                 /* I - Maximum bytes to read */
{
  ssize_t       rbytes;                 /* Bytes read */


  if ((rbytes = (ssize_t)fread(buffer, 1, bytes, zc->fp)) > 0)
    return (rbytes);

  zc->error = strerror(ferror(zc->fp));

  return (-1);
}


/*
 * 'zipc_read_char()' - Read a character from a ZIP container file.
 */

static int                              /* O - Character from file or -1 on EOF */
zipc_read_char(zipc_file_t *zf)         /* I - ZIP container file */
{
  zipc_t        *zc = zf->zc;           /* ZIP container */


  if (zc->readptr >= zc->readend || !zc->readptr)
  {
    ssize_t     bytes;                  /* Bytes read */

    if (!zc->readbuffer)
      zc->readbuffer = malloc(ZIPC_READ_SIZE);

    if ((bytes = zipc_read_file(zf, zc->readbuffer, ZIPC_READ_SIZE)) <= 0)
      return (-1);

    zc->readend = zc->readbuffer + bytes;
    zc->readptr = zc->readbuffer;
  }

  zf->uncompressed_pos ++;

  return (*zc->readptr++);
}
1456 1457


1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
/*
 * 'zipc_read_file()' - Read data from a ZIP container file.
 */

static ssize_t                          /* O - Number of bytes read or -1 on error */
zipc_read_file(zipc_file_t *zf,         /* I - ZIP container file */
               void        *data,       /* I - Read buffer */
               size_t      bytes)       /* I - Maximum number of bytes to read */
{
  ssize_t       rbytes;                 /* Bytes read */
  zipc_t        *zc = zf->zc;           /* ZIP container */


  if ((zf->uncompressed_pos + bytes) > zf->uncompressed_size)
    bytes = zf->uncompressed_size - zf->uncompressed_pos;

  if (zf->method == ZIPC_COMP_STORE)
  {
   /*
    * Read literal data...
    */

    rbytes = zipc_read(zc, data, bytes);
  }
  else
  {
   /*
    * Read deflated (compressed) data...
    */

    int	zstatus;			/* Deflate status */

    zc->stream.next_out  = (Bytef *)data;
    zc->stream.avail_out = (unsigned)bytes;

    do
    {
      if (zc->stream.avail_in == 0)
      {
        size_t  cbytes = zf->compressed_size - zf->compressed_pos;
                                        /* Compressed bytes left */

        if (cbytes > sizeof(zc->buffer))
          cbytes = sizeof(zc->buffer);

        if ((rbytes = zipc_read(zc, zc->buffer, cbytes)) < 0)
        {
          zc->error = strerror(errno);
          return (-1);
        }

        zc->stream.next_in  = (Bytef *)zc->buffer;
        zc->stream.avail_in = (unsigned)rbytes;
      }

      zstatus = inflate(&zc->stream, Z_NO_FLUSH);

      if (zstatus < Z_OK && zstatus != Z_BUF_ERROR)
      {
        zc->error = zipc_zlib_status(zstatus);
        return (-1);
      }
    }
    while (zc->stream.avail_out > 0 && zf->compressed_pos < zf->compressed_size);

    rbytes = bytes - zc->stream.avail_out;
  }

  return (rbytes);
}


/*
 * 'zipc_read_u16()' - Read a 16-bit unsigned integer from the ZIP container.
 */

static unsigned                         /* O - Integer or 0xffff on error */
zipc_read_u16(zipc_t *zc)               /* I - ZIP container */
{
  unsigned char	buffer[2];		/* Buffer */


  if (zipc_read(zc, buffer, sizeof(buffer)) != sizeof(buffer))
    return (0xffff);

  return ((buffer[1] << 8) | buffer[0]);
}


/*
 * 'zipc_read_u32()' - Read a 32-bit unsigned integer from the ZIP container.
 */

static unsigned                         /* O - Integer or 0xffffffff on error */
zipc_read_u32(zipc_t *zc)               /* I - ZIP container */
{
  unsigned char	buffer[4];		/* Buffer */


  if (zipc_read(zc, buffer, sizeof(buffer)) != sizeof(buffer))
    return (0xffff);

  return ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
}
#endif /* !ZIPC_ONLY_WRITE */


#ifndef ZIPC_ONLY_READ
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
/*
 * 'zipc_write()' - Write bytes to a ZIP container.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write(zipc_t     *zc,		/* I - ZIP container */
           const void *buffer,		/* I - Buffer to write */
           size_t     bytes)		/* I - Number of bytes */
{
  if (fwrite(buffer, bytes, 1, zc->fp))
    return (0);

  zc->error = strerror(ferror(zc->fp));

  return (-1);
}


/*
 * 'zipc_write_dir_header()' - Write a central directory file header.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write_dir_header(
    zipc_t      *zc,			/* I - ZIP container */
    zipc_file_t *zf)			/* I - ZIP container file */
{
  int		status = 0;		/* Return status */
  size_t	filenamelen = strlen(zf->filename);
					/* Length of filename */

  status |= zipc_write_u32(zc, ZIPC_DIR_HEADER);
  status |= zipc_write_u16(zc, ZIPC_MADE_BY);
1599
  status |= zipc_write_u16(zc, zf->external_attrs == ZIPC_EXTERNAL_DIR ? ZIPC_DIR_VERSION : ZIPC_FILE_VERSION);
1600 1601 1602 1603
  status |= zipc_write_u16(zc, zf->flags);
  status |= zipc_write_u16(zc, zf->method);
  status |= zipc_write_u32(zc, zc->modtime);
  status |= zipc_write_u32(zc, zf->crc32);
1604 1605 1606
  status |= zipc_write_u32(zc, (unsigned)zf->compressed_size);
  status |= zipc_write_u32(zc, (unsigned)zf->uncompressed_size);
  status |= zipc_write_u16(zc, (unsigned)filenamelen);
1607 1608 1609
  status |= zipc_write_u16(zc, 0); /* extra field length */
  status |= zipc_write_u16(zc, 0); /* comment length */
  status |= zipc_write_u16(zc, 0); /* disk number start */
1610 1611 1612
  status |= zipc_write_u16(zc, zf->internal_attrs);
  status |= zipc_write_u32(zc, zf->external_attrs);
  status |= zipc_write_u32(zc, (unsigned)zf->offset);
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
  status |= zipc_write(zc, zf->filename, filenamelen);

  return (status);
}


/*
 * 'zipc_write_local_header()' - Write a local file header.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write_local_header(
    zipc_t      *zc,			/* I - ZIP container */
    zipc_file_t *zf)			/* I - ZIP container file */
{
  int		status = 0;		/* Return status */
  size_t	filenamelen = strlen(zf->filename);
					/* Length of filename */

  status |= zipc_write_u32(zc, ZIPC_LOCAL_HEADER);
1633
  status |= zipc_write_u16(zc, zf->external_attrs == ZIPC_EXTERNAL_DIR ? ZIPC_DIR_VERSION : ZIPC_FILE_VERSION);
Michael Sweet's avatar
Michael Sweet committed
1634
  status |= zipc_write_u16(zc, zf->flags & ZIPC_FLAG_MASK);
1635 1636 1637
  status |= zipc_write_u16(zc, zf->method);
  status |= zipc_write_u32(zc, zc->modtime);
  status |= zipc_write_u32(zc, zf->uncompressed_size == 0 ? 0 : zf->crc32);
1638 1639 1640
  status |= zipc_write_u32(zc, (unsigned)zf->compressed_size);
  status |= zipc_write_u32(zc, (unsigned)zf->uncompressed_size);
  status |= zipc_write_u16(zc, (unsigned)filenamelen);
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
  status |= zipc_write_u16(zc, 0); /* extra field length */
  status |= zipc_write(zc, zf->filename, filenamelen);

  return (status);
}


/*
 * 'zipc_write_local_trailer()' - Write a local file trailer.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write_local_trailer(
    zipc_t      *zc,			/* I - ZIP container */
    zipc_file_t *zf)			/* I - ZIP container file */
{
  int	status = 0;			/* Return status */
1658 1659


Michael Sweet's avatar
Michael Sweet committed
1660 1661 1662 1663 1664
  if (zf->flags & ZIPC_FLAG_STREAMED)
  {
   /*
    * Update the CRC-32, compressed size, and uncompressed size fields...
    */
1665

1666
    fseek(zc->fp, (long)(zf->offset + 14), SEEK_SET);
1667

Michael Sweet's avatar
Michael Sweet committed
1668 1669 1670
    status |= zipc_write_u32(zc, zf->crc32);
    status |= zipc_write_u32(zc, (unsigned)zf->compressed_size);
    status |= zipc_write_u32(zc, (unsigned)zf->uncompressed_size);
1671

Michael Sweet's avatar
Michael Sweet committed
1672
    fseek(zc->fp, 0, SEEK_END);
1673

Michael Sweet's avatar
Michael Sweet committed
1674 1675
    zf->flags &= ZIPC_FLAG_MASK;
  }
1676

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  return (status);
}


/*
 * 'zipc_write_u16()' - Write a 16-bit unsigned integer.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write_u16(zipc_t   *zc,		/* I - ZIP container */
               unsigned value)		/* I - Value to write */
{
  unsigned char	buffer[2];		/* Buffer */


  buffer[0] = (unsigned char)value;
  buffer[1] = (unsigned char)(value >> 8);

  return (zipc_write(zc, buffer, sizeof(buffer)));
}


/*
 * 'zipc_write_u32()' - Write a 32-bit unsigned integer.
 */

static int				/* I - 0 on success, -1 on error */
zipc_write_u32(zipc_t   *zc,		/* I - ZIP container */
               unsigned value)		/* I - Value to write */
{
  unsigned char	buffer[4];		/* Buffer */


  buffer[0] = (unsigned char)value;
  buffer[1] = (unsigned char)(value >> 8);
  buffer[2] = (unsigned char)(value >> 16);
  buffer[3] = (unsigned char)(value >> 24);

  return (zipc_write(zc, buffer, sizeof(buffer)));
}
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
#endif /* !ZIPC_ONLY_READ */


#ifndef ZIPC_ONLY_WRITE
/*
 * 'zipc_xml_unescape()' - Replace &foo; with corresponding characters.
 */

static void
zipc_xml_unescape(char *buffer)         /* I - Buffer */
{
  char  *inptr,                         /* Current input pointer */
        *outptr;                        /* Current output pointer */


 /*
  * See if there are any escaped characters to work with...
  */

  if ((inptr = strchr(buffer, '&')) == NULL)
    return;                             /* Nope */

  for (outptr = inptr; *inptr;)
  {
    if (*inptr == '&' && strchr(inptr + 1, ';'))
    {
     /*
      * Figure out what kind of escaped character we have...
      */

      inptr ++;
      if (!strncmp(inptr, "amp;", 4))
      {
        inptr += 4;
        *outptr++ = '&';
      }
      else if (!strncmp(inptr, "lt;", 3))
      {
        inptr += 3;
        *outptr++ = '<';
      }
      else if (!strncmp(inptr, "gt;", 3))
      {
        inptr += 3;
        *outptr++ = '>';
      }
      else if (!strncmp(inptr, "quot;", 5))
      {
        inptr += 5;
        *outptr++ = '\"';
      }
      else if (!strncmp(inptr, "apos;", 5))
      {
        inptr += 5;
        *outptr++ = '\'';
      }
      else if (*inptr == '#')
      {
       /*
        * Numeric, copy character over as UTF-8...
        */

        int ch;                         /* Numeric character value */

        inptr ++;
        if (*inptr == 'x')
          ch = (int)strtol(inptr, NULL, 16);
        else
          ch = (int)strtol(inptr, NULL, 10);

        if (ch < 0x80)
        {
         /*
          * US ASCII
          */

          *outptr++ = ch;
        }
        else if (ch < 0x800)
        {
         /*
          * Two-byte UTF-8
          */

          *outptr++ = 0xc0 | (ch >> 6);
          *outptr++ = 0x80 | (ch & 0x3f);
        }
        else if (ch < 0x10000)
        {
         /*
          * Three-byte UTF-8
          */

          *outptr++ = 0xe0 | (ch >> 12);
          *outptr++ = 0x80 | ((ch >> 6) & 0x3f);
          *outptr++ = 0x80 | (ch & 0x3f);
        }
        else
        {
         /*
          * Four-byte UTF-8
          */

          *outptr++ = 0xf0 | (ch >> 18);
          *outptr++ = 0x80 | ((ch >> 12) & 0x3f);
          *outptr++ = 0x80 | ((ch >> 6) & 0x3f);
          *outptr++ = 0x80 | (ch & 0x3f);
        }

        inptr = strchr(inptr, ';') + 1;
      }
      else
      {
       /*
        * Something else not supported by XML...
        */

        *outptr++ = '&';
      }
    }
    else
    {
     /*
      * Copy literal...
      */

      *outptr++ = *inptr++;
    }
  }

  *outptr = '\0';
}
#endif /* !ZIPC_ONLY_WRITE */


/*
 * 'zipc_zlib_status()' - Return a string corresponding to the given ZLIB status.
 */

static const char *                     /* O - Error string */
zipc_zlib_status(int zstatus)           /* I - Status */
{
  switch (zstatus)
  {
    case Z_ERRNO :
        return (strerror(errno));

    case Z_OK :
        return ("OK");

    case Z_STREAM_END :
        return ("End of stream.");

    case Z_NEED_DICT :
        return ("Need dictionary.");

    case Z_STREAM_ERROR :
        return ("Error in stream.");

    case Z_DATA_ERROR :
        return ("Error in data");

    case Z_MEM_ERROR :
        return ("Unable to allocate memory.");

    case Z_BUF_ERROR :
        return ("Unable to fill buffer.");

    case Z_VERSION_ERROR :
        return ("Version mismatch.");

    default :
        return ("Unknown status");
  }
}