/*---------------------------------------------------------------------------

  zipinfo.c

  This program reads great gobs of totally nifty information, including the
  central directory stuff, from ZIP archives ("zipfiles" for short).  It
  started as just a testbed for fooling with zipfiles, but at this point it
  is actually a useful utility.  It also became the basis for the rewrite of
  UnZip (3.16 -> 4.0), using the central directory for processing rather than
  the individual (local) file headers.

  The author finds it convenient to define an alias "ii" (under Unix and VMS)
  or to rename the executable to "ii.exe" (OS/2 and DOS).  This nicely comple-
  ments the common Unix "ll" long-listing alias (ls -lF), since zipinfo's de-
  fault action is to produce a Unix-like listing of the archive's contents.
  "ii zipfile" is easier to type than "zipinfo zipfile"...

  Another dandy product from your buddies at Newtware!

  ---------------------------------------------------------------------------

  To compile:  ZipInfo is now part of the regular UnZip compilation for the
     systems listed below; see the top of unzip.c for partial instructions.

  ---------------------------------------------------------------------------

  Source:     unzip51.zip (.tar.Z, etc.) for Unix, VMS, OS/2, MS-DOS and
              TOPS-20; see `Where' in source distribution for ftp, uucp and
              mail-server sites.
  Author:     Greg Roelofs, roe2@midway.uchicago.edu, 23 August 1990
  Copyright:  Portions copyright 1992 Greg Roelofs.  Portions adapted from
              unzip 3.1.  SizeOfEAs() by Kai Uwe Rommel.

  ---------------------------------------------------------------------------*/




#ifndef ZIPINFO
#  define ZIPINFO
#endif
#include "unzip.h"        /* ZIPINFO ==> Unix perms in non-Unix environments */

#define VERSION  "v1.04 of 22 Oct 92"  /* BETA version */

#define LFLAG    3        /* for short "ls -l" type listing */

#define EAID     0x0009   /* OS/2 extended-attributes extra field ID, for */
typedef struct {          /*  OS/2 info in OS/2 and non-OS/2 environments */
    unsigned short nID;
    unsigned short nSize;
    ulg lSize;
} EAHEADER, *PEAHEADER;




/**********************/
/*  Global Variables  */
/**********************/

#ifdef EBCDIC
   int  aflag=1;        /* this is so you can read it on the screen  */
#else                   /* (basically, entire program is "unzip -c") */
   int  aflag=0;
#endif
int lflag=(-1);         /* '-12slmv':  listing format */
int hflag=0;            /* '-h':  header line */
int tflag=0;            /* '-t':  totals line */
int zflag=0;            /* '-z':  zipfile comment */

uch *inbuf, *inptr;     /* input buffer (any size is legal) and pointer */
int incnt;

char zipfn[FILNAMSIZ];
int zipfd;              /* zipfile file handle */
longint ziplen;

uch *hold;
char local_hdr_sig[5] = "\120";    /* remaining signature bytes come later:  */
char central_hdr_sig[5] = "\120";  /*  must initialize at runtime so zipinfo */
char end_central_sig[5] = "\120";  /*  executable won't look like a zipfile  */
/* char extd_local_sig[5] = "\120"; */

cdir_file_hdr crec;     /* used in zipinfo.c, misc.c */
local_file_hdr lrec;
ecdir_rec ecrec;
struct stat statbuf;    /* used by main() */

int filespecs;          /* number of real file specifications to be matched */
int xfilespecs;         /* number of excluded filespecs to be matched */
int process_all_files;
longint real_ecrec_offset, expect_ecrec_offset;
longint extra_bytes=0;          /* used in zipinfo.c, misc.c */
longint cur_zipfile_bufstart;   /* find_end_central_dir, readbuf */

min_info info, *pInfo=(&info);

uch *extra_field = NULL;        /* used by VMS, Mac and OS/2 versions */
uch *outbuf;                    /* buffer for rle look-back, zipfile comment */
uch *outout;                    /* scratch pad for ASCII-native trans */

char filename[FILNAMSIZ];
char sig[5];
static char *fnames[2] = {"*", NULL};  /* default filenames vector */
char **pfnames = fnames, **pxnames = &fnames[1];

static ush hostnum;
static ush methnum;
static ush extnum;

char *EndSigMsg = "\nwarning:\
  didn't find end-of-central-dir signature at end of central dir.\n";
char *CentSigMsg =
  "error:  expected central file header signature not found (file #%u).\n";
char *SeekMsg =
  "error:  attempt to seek before beginning of zipfile\n%s";

#ifdef VMS
char *ReportMsg = "\
  (please check that you have transferred or created the zipfile in the\n\
  appropriate BINARY mode--this includes ftp, Kermit, AND unzip'd zipfiles)\n";
#else /* !VMS */
char *ReportMsg = "\
  (please check that you have transferred or created the zipfile in the\n\
  appropriate BINARY mode and that you have compiled unzip properly)\n";
#endif /* ?VMS */






/******************/
/*  Main program  */
/******************/

main(argc, argv)
    int    argc;
    char   *argv[];
{
    char   *s;
    int    c, error=FALSE, negative=0;
    int    hflag_slmv=TRUE, hflag_2=FALSE;  /* diff options => diff defaults */
    int    tflag_slm=TRUE, tflag_2v=FALSE;
    int    explicit_h=FALSE, explicit_t=FALSE;



/*---------------------------------------------------------------------------
    Everybody is now "NOTINT16," but this is a nice little piece of code, so
    just comment it out for future reference. :-)
  ---------------------------------------------------------------------------*/

#if 0
# ifndef KNOW_IT_WORKS  /* define this to save space, if things already work */
# ifndef DOS_OS2        /* already works (no RISCy OS/2's yet...) */
# ifndef NOTINT16       /* whole point is to see if this NEEDS defining */
    {
        int error=0;
        long testsig;
        static char *mach_type[3] = {"big-endian", "structure-padding",
                                     "big-endian and structure-padding"};

        strcpy((char *)&testsig,"012");
        if (testsig != 0x00323130)
            error = 1;
        if (sizeof(cdir_file_hdr) != CREC_SIZE)
            error += 2;
        if (error--)
            fprintf(stderr, "It appears that your machine is %s.  If errors\n\
occur, please try recompiling with \"NOTINT16\" defined (read the\n\
Makefile, or try \"make zipinfo\").\n\n", mach_type[error]);
    }
# endif /* !NOTINT16 */
# endif /* !DOS_OS2 */
# endif /* !KNOW_IT_WORKS */
#endif /* 0 */

/*---------------------------------------------------------------------------
    Put environment-variable options into the queue, then rip through any
    command-line options lurking about...
  ---------------------------------------------------------------------------*/

    envargs(&argc, &argv, ENV_ZIPINFO);

    while (--argc > 0 && (*++argv)[0] == '-') {
        s = argv[0] + 1;
        while ((c = *s++) != 0) {    /* "!= 0":  prevent Turbo C warning */
            switch (c) {
                case '-':
                    ++negative;
                    break;
                case '1':      /* shortest listing:  JUST filenames */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 1;
                    break;
                case '2':      /* just filenames, plus headers if specified */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 2;
                    break;
                case 'h':      /* header line */
                    if (negative)
                        hflag_2 = hflag_slmv = FALSE, negative = 0;
                    else {
                        hflag_2 = hflag_slmv = explicit_h = TRUE;
                        if (lflag == -1)
                            lflag = 0;
                    }
                    break;
                case 'l':      /* longer form of "ls -l" type listing */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 5;
                    break;
                case 'm':      /* medium form of "ls -l" type listing */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 4;
                    break;
                case 's':      /* default:  shorter "ls -l" type listing */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 3;
                    break;
                case 't':      /* totals line */
                    if (negative)
                        tflag_2v = tflag_slm = FALSE, negative = 0;
                    else {
                        tflag_2v = tflag_slm = explicit_t = TRUE;
                        if (lflag == -1)
                            lflag = 0;
                    }
                    break;
                case 'v':      /* turbo-verbose listing */
                    if (negative)
                        lflag = -2, negative = 0;
                    else
                        lflag = 10;
                    break;
                case 'z':      /* print zipfile comment */
                    if (negative)
                        zflag = negative = 0;
                    else
                        zflag = 1;
                    break;
                default:
                    error = TRUE;
                    break;
            }
        }
    }
    if ((argc-- == 0) || error)
        RETURN(usage(error));

    if (argc != 0)
        process_all_files = FALSE;
    else
        process_all_files = TRUE;   /* for speed */

    /* if no listing options given (or all negated), or if only -h/-t given
     * with individual files specified, use default listing format */
    if ((lflag < 0) || (!process_all_files && (lflag == 0)))
        lflag = LFLAG;

    /* set header and totals flags to default or specified values */
    switch (lflag) {
        case 0:   /* 0:  can only occur if either -t or -h explicitly given; */
        case 2:   /*  therefore set both flags equal to normally false value */
            hflag = hflag_2;
            tflag = tflag_2v;
            break;
        case 1:   /* only filenames, *always* */
            hflag = FALSE;
            tflag = FALSE;
            zflag = FALSE;
            break;
        case 3:
        case 4:
        case 5:
            hflag = (!process_all_files && !explicit_h)? FALSE : hflag_slmv;
            tflag = (!process_all_files && !explicit_t)? FALSE : tflag_slm;
            break;
        case 10:
            hflag = hflag_slmv;
            tflag = tflag_2v;
            break;
    }

/*---------------------------------------------------------------------------
    Now get the zipfile name from the command line and see if it exists as a
    regular (non-directory) file.  If not, append the ".zip" suffix.  We don't
    immediately check to see if this results in a good name, but we will do so
    later.  In the meantime, see if there are any member filespecs on the com-
    mand line, and if so, set the filename pointer to point at them.
  ---------------------------------------------------------------------------*/

    strcpy(zipfn, *argv++);
    if (stat(zipfn, &statbuf) || (statbuf.st_mode & S_IFMT) == S_IFDIR)
        strcat(zipfn, ZSUFX);
#ifdef UNIX  /* no extension on Unix exe's--might find zip, not zip.zip; etc. */
    else if (statbuf.st_mode & S_IXUSR)
        fprintf(stderr, "\nnote:  file [ %s ] may be an executable\n\n", zipfn);
#endif

    if (stat(zipfn, &statbuf)) {    /* try again */
        fprintf(stderr, "error:  can't find zipfile [ %s ]\n", zipfn);
        RETURN(PK_NOZIP);
    } else
        ziplen = statbuf.st_size;

    filespecs = argc;
    xfilespecs = 0;

    if (!process_all_files) {
        char **pp = argv-1;

        pfnames = argv;
        while (*++pp)
            if (!strcmp(*pp, "-x")) {
                if (pp > argv) {
                    *pp = 0;           /* terminate pfnames */
                    filespecs = pp - pfnames;
                } else {
                    pfnames = fnames;  /* defaults */
                    filespecs = 0;
                }
                pxnames = pp + 1;      /* excluded-names ptr starts after -x */
                xfilespecs = argc - filespecs - 1;
                break;                 /* skip rest of args */
            }
    }

/*---------------------------------------------------------------------------
    Okey dokey, we have everything we need to get started.  Let's roll.
  ---------------------------------------------------------------------------*/

    inbuf = (uch *)malloc(INBUFSIZ + 4);     /* 4 extra for hold[] (below) */
    outbuf = (uch *)malloc(OUTBUFSIZ + 1);   /* 1 extra for string termin. */
    if (aflag)                  /* if need an ascebc scratch, */
        outout = (uch *)malloc(OUTBUFSIZ);
    else                        /*  allocate it... */
        outout = outbuf;        /*  else just point to outbuf */

    if ((inbuf == NULL) || (outbuf == NULL) || (outout == NULL)) {
        fprintf(stderr, "error:  can't allocate zipinfo buffers\n");
        RETURN(PK_MEM);
    }
    hold = &inbuf[INBUFSIZ];    /* to check for boundary-spanning signatures */

    RETURN(process_zipfile());  /* keep passing errors back... */

} /* end main() */





/**********************/
/*  Function usage()  */
/**********************/

int usage(error)
    int error;
{
    FILE *usagefp;


/*---------------------------------------------------------------------------
    If user requested usage, send it to stdout; else send to stderr.
  ---------------------------------------------------------------------------*/

    if (error)
        usagefp = (FILE *)stderr;
    else
        usagefp = (FILE *)stdout;

    fprintf(usagefp, "\
   ZipInfo:  Zipfile Information Utility %s\n\
   (brought to you by Newtware, Inc., and the fine folks at Info-ZIP)\n\n\
   Usage:  zipinfo [-12smlvhtz] file[.zip] [list...] [-x xlist...]\n",
      VERSION);
    fprintf(usagefp, "\
     -1  list filenames ONLY, one per line (useful for pipes)\n\
     -2  list filenames only, but also allow -h, -t and -z options\n\
     -s  list zipfile info in short Unix \"ls -l\" format:  default\n\
     -m  list zipfile info in medium Unix \"ls -l\" format\n\
     -l  list zipfile info in long Unix \"ls -l\" format\n\
     -v  list zipfile information in verbose, multi-page format\n\
     -h  list header line\n\
     -t  list totals for files listed or for all files\n\
     -z  print zipfile comment\n\
     -x  exclude filenames that follow from listing\n");
/*
     -p  disable automatic \"more\" function (for pipes) [not implemented]\n");
 */

#ifdef VMS
    fprintf(usagefp, "\nRemember that non-lowercase filespecs must be quoted\
 in VMS (e.g., \"Makefile\").\n");
#endif

    if (error)
        return PK_PARAM;
    else
        return PK_COOL;   /* just wanted usage screen: no error */

} /* end function usage() */





/********************************/
/*  Function process_zipfile()  */
/********************************/

int process_zipfile()   /* return PK-type error code */
{
    int error=PK_COOL, error_in_archive;


/*---------------------------------------------------------------------------
    Open the zipfile for reading and in BINARY mode to prevent CR/LF trans-
    lation, which would corrupt the bitstreams.
  ---------------------------------------------------------------------------*/

#ifdef VMS
    if (check_format())   /* check for variable-length format */
        return PK_ERR;
#endif /* VMS */

    if (open_input_file())      /* this should never happen, given the */
        return PK_NOZIP;        /*   stat() test in main(), but... */

/*---------------------------------------------------------------------------
    Reconstruct the various PK signature strings, and find and process the
    end-of-central-directory header.
  ---------------------------------------------------------------------------*/

    strcat(local_hdr_sig, LOCAL_HDR_SIG);
    strcat(central_hdr_sig, CENTRAL_HDR_SIG);
    strcat(end_central_sig, END_CENTRAL_SIG);
/*  strcat(extd_local_sig, EXTD_LOCAL_SIG);  */

    /* check whole file in case a transfer protocol appended garbage */
    if ((error_in_archive = find_end_central_dir(ziplen)) != 0  ||
        (error_in_archive = process_end_central_dir()) > PK_WARN) {
        close(zipfd);
        return error_in_archive;
    }

/*---------------------------------------------------------------------------
    Test the end-of-central-directory info for incompatibilities (multi-disk
    archives) or inconsistencies (missing or extra bytes in zipfile).
  ---------------------------------------------------------------------------*/

    if (ecrec.number_this_disk != ecrec.num_disk_with_start_central_dir) {
        fprintf(stderr, "\n\
     Zipfile is part of a multi-disk archive, and this is not the disk on\
     which the central zipfile directory begins.\n");
        error_in_archive = PK_FIND;
    } else {
        if ((extra_bytes = real_ecrec_offset - expect_ecrec_offset) < 0) {
            fprintf(stderr, "\nerror:  missing %ld bytes in zipfile (\
attempting to process anyway)\n\n", -extra_bytes);
            error_in_archive = PK_ERR;
        } else if (extra_bytes > 0) {
            if ((ecrec.offset_start_central_directory == 0) &&
                (ecrec.size_central_directory != 0))   /* zip 1.5 -go bug */
            {
                fprintf(stderr, "\nerror:  NULL central directory offset (\
attempting to process anyway)\n\n");
                error_in_archive = PK_ERR;
            } else {
                fprintf(stderr, "\nwarning:  extra %ld bytes at beginning or\
 within zipfile\n          (attempting to process anyway)\n\n", extra_bytes);
                error_in_archive = PK_WARN;
            }
        }

    /*-----------------------------------------------------------------------
        Check for empty zipfile and exit now if so.
      -----------------------------------------------------------------------*/

        if (expect_ecrec_offset == 0L  &&  ecrec.size_central_directory == 0) {
            printf("%sEmpty zipfile.\n", lflag>9 ? "\n  " : "");
            close(zipfd);
            return (error_in_archive > PK_WARN)? error_in_archive : PK_WARN;
        }

    /*-----------------------------------------------------------------------
        Compensate for missing or extra bytes, and seek to where the start
        of central directory should be.  If header not found, uncompensate
        and try again (necessary for at least some Atari archives created
        with STZIP, as well as archives created by J.H. Holm's ZIPSPLIT 1.1).
      -----------------------------------------------------------------------*/

        LSEEK( ecrec.offset_start_central_directory )
        if ((readbuf(sig, 4) <= 0) || strncmp(sig, central_hdr_sig, 4)) {
            longint tmp = extra_bytes;

            extra_bytes = 0;
            LSEEK( ecrec.offset_start_central_directory )
            if ((readbuf(sig, 4) <= 0) || strncmp(sig, central_hdr_sig, 4)) {
                fprintf(stderr,
            "error:  start of central directory not found; zipfile corrupt.\n");
                fprintf(stderr, ReportMsg);
                close(zipfd);
                return PK_BADERR;
            }
            fprintf(stderr, "error:  reported length of central directory is \
%d bytes too long\n        (Atari STZIP zipfile?  J.H.Holm ZIPSPLIT 1.1 \
zipfile?).\n        Compensating...\n\n", -tmp);
            error_in_archive = PK_ERR;
        }

    /*-----------------------------------------------------------------------
        Seek to the start of the central directory one last time, since we
        have just read the first entry's signature bytes; then do the central
        directory and close the zipfile.
      -----------------------------------------------------------------------*/

        LSEEK( ecrec.offset_start_central_directory )
        if ((error = process_central_dir()) > error_in_archive)
            error_in_archive = error;    /* don't overwrite stronger error */
        if (lflag > 9)
            printf("\n");
    }

    close(zipfd);
    return error_in_archive;

} /* end function process_zipfile() */





/****************************************/
/*  Function process_end_central_dir()  */
/****************************************/

int process_end_central_dir()   /* return PK-type error code */
{
    int  error = PK_COOL;


/*--------------------------------------------------------------------------
    Print out various interesting things about the zipfile.
  ---------------------------------------------------------------------------*/

    /* header fits on one line, for anything up to 10GB and 10000 files: */
    if (hflag)
        printf((strlen(zipfn)<39)? "Archive:  %s   %ld bytes   %d file%s\n"
          : "Archive:  %s   %ld   %d\n", zipfn, ziplen,
          ecrec.total_entries_central_dir,
          (ecrec.total_entries_central_dir==1)? "":"s");

    /* verbose format */
    if (lflag > 9) {
        printf("\nEnd-of-central-directory record:\n");
        printf("-------------------------------\n\n");

        printf("\
  Actual offset of end-of-central-dir record:   %9ld (%.8lXh)\n\
  Expected offset of end-of-central-dir record: %9ld (%.8lXh)\n\
  (based on the length of the central directory and its expected offset)\n\n",
          real_ecrec_offset, real_ecrec_offset,
          expect_ecrec_offset, expect_ecrec_offset);

        if (ecrec.number_this_disk == 0) {
            printf("\
  This zipfile constitutes the sole disk of a single-part archive; its\n\
  central directory contains %u %s.  The central directory is %lu\n\
  (%.8lXh) bytes long, and its (expected) offset in bytes from the\n\
  beginning of the zipfile is %lu (%.8lXh).\n\n",
              ecrec.total_entries_central_dir,
              (ecrec.total_entries_central_dir == 1)? "entry" : "entries",
              ecrec.size_central_directory, ecrec.size_central_directory,
              ecrec.offset_start_central_directory,
              ecrec.offset_start_central_directory);
        } else {
            printf("\
  This zipfile constitutes disk %u of a multi-part archive.  The central\n\
  directory starts on disk %u; %u of its entries %s contained within\n\
  this zipfile, out of a total of %u %s.  The entire central\n\
  directory is %lu (%.8lXh) bytes long, and its offset in bytes from\n\
  the beginning of the zipfile in which it begins is %lu (%.8lXh).\n\n",
              ecrec.number_this_disk,
              ecrec.num_disk_with_start_central_dir,
              ecrec.num_entries_centrl_dir_ths_disk,
              (ecrec.num_entries_centrl_dir_ths_disk == 1)? "is" : "are",
              ecrec.total_entries_central_dir,
              (ecrec.total_entries_central_dir == 1) ? "entry" : "entries",
              ecrec.size_central_directory, ecrec.size_central_directory,
              ecrec.offset_start_central_directory,
              ecrec.offset_start_central_directory);
        }

    /*-----------------------------------------------------------------------
        Get the zipfile comment, if any, and print it out.  (Comment may be
        up to 64KB long.  May the fleas of a thousand camels infest the arm-
        pits of anyone who actually takes advantage of this fact.)
      -----------------------------------------------------------------------*/

        if (!ecrec.zipfile_comment_length)
            printf("  There is no zipfile comment.\n");
        else {
            printf("  The zipfile comment is %u bytes long and contains the following text:\n\n",
              ecrec.zipfile_comment_length );
            printf("======================== zipfile comment begins ==========================\n");
            if (do_string(ecrec.zipfile_comment_length, DISPLAY))
                error = PK_WARN;
            printf("\n========================= zipfile comment ends ===========================\n");
            if (error)
                printf("\n  The zipfile comment is truncated.\n");
        } /* endif (comment exists) */

    /* non-verbose mode:  print zipfile comment only if requested */
    } else if (zflag && ecrec.zipfile_comment_length) {
        if (do_string(ecrec.zipfile_comment_length,DISPLAY)) {
            fprintf(stderr, "\ncaution:  zipfile comment truncated\n");
            error = PK_WARN;
        }
    } /* endif (verbose) */

    return error;

} /* end function process_end_central_dir() */





/************************************/
/*  Function process_central_dir()  */
/************************************/

int process_central_dir()   /* return PK-type error code */
{
    int   do_this_file=FALSE, error, error_in_archive=PK_COOL;
    int   *fn_matched=NULL, *xn_matched=NULL;
    ush   j, members=0;
    ulg   c=0L, uc=0L;


/*---------------------------------------------------------------------------
    Malloc space for check on unmatched filespecs (no big deal if one or both
    are NULL).
  ---------------------------------------------------------------------------*/

    if (filespecs > 0  &&
        (fn_matched=(int *)malloc(filespecs*sizeof(int))) != NULL)
        for (j = 0;  j < filespecs;  ++j)
            fn_matched[j] = FALSE;

    if (xfilespecs > 0  &&
        (xn_matched=(int *)malloc(xfilespecs*sizeof(int))) != NULL)
        for (j = 0;  j < xfilespecs;  ++j)
            xn_matched[j] = FALSE;

/*---------------------------------------------------------------------------
    Set file pointer to start of central directory, then loop through cen-
    tral directory entries.  Check that directory-entry signature bytes are
    actually there (just a precaution), then process the entry.  We know
    the entire central directory is on this disk:  we wouldn't have any of
    this information unless the end-of-central-directory record was on this
    disk, and we wouldn't have gotten to this routine unless this is also
    the disk on which the central directory starts.  In practice, this had
    better be the *only* disk in the archive, but maybe someday we'll add
    multi-disk support.
  ---------------------------------------------------------------------------*/

    pInfo->lcflag = 0;   /* match(), do_string():  never TRUE in zipinfo */

    for (j = 0;  j < ecrec.total_entries_central_dir;  ++j) {
        if (readbuf(sig, 4) <= 0)
            return PK_EOF;
        if (strncmp(sig, central_hdr_sig, 4)) {  /* just to make sure */
            fprintf(stderr, CentSigMsg, j);  /* sig not found */
            return PK_BADERR;
        }
        if ((error = get_cdir_file_hdr()) != PK_COOL)
            return error;       /* only PK_EOF defined */
        if ((error = do_string(crec.filename_length, FILENAME)) != PK_COOL) {
          error_in_archive = error;   /* might be warning */
          if (error > PK_WARN)        /* fatal */
              return error;
        }

        if (!process_all_files) {    /* check if specified on command line */
            char  **pfn = pfnames-1;

            do_this_file = FALSE;
            while (*++pfn)
                if (match(filename, *pfn)) {
                    do_this_file = TRUE;
                    if (fn_matched)
                        fn_matched[pfn-pfnames] = TRUE;
                    break;       /* found match, so stop looping */
                }
            if (do_this_file) {  /* check if this is an excluded file */
                char  **pxn = pxnames-1;

                while (*++pxn)
                    if (match(filename, *pxn)) {
                        do_this_file = FALSE;
                        if (xn_matched)
                            xn_matched[pxn-pxnames] = TRUE;
                        break;
                    }
            }
        }

    /*-----------------------------------------------------------------------
        If current file was specified on command line, or if no names were
        specified, do the listing for this file.  Otherwise, get rid of the
        file comment and go back for the next file.
      -----------------------------------------------------------------------*/

        if (process_all_files || do_this_file) {
            switch (lflag) {
                case 1:
                case 2:
                    printf("%s\n", filename);
                    SKIP_(crec.extra_field_length)
                    SKIP_(crec.file_comment_length)
                    break;

                case 3:
                case 4:
                case 5:
                    if ((error = short_info()) != PK_COOL) {
                        error_in_archive = error;   /* might be warning */
                        if (error > PK_WARN)        /* fatal */
                            return error;
                    }
                    break;

                case 10:
#ifdef T20_VMS  /* GRR:  add cbreak-style "more" */
                    printf("\nCentral directory entry #%d:\n", j);
#else
                    /* formfeed/CR for piping to "more": */
                    printf("%s\nCentral directory entry #%d:\n", "\014", j);
#endif
                    printf("---------------------------\n\n");

                    if ((error = long_info()) != PK_COOL) {
                      error_in_archive = error;   /* might be warning */
                      if (error > PK_WARN)        /* fatal */
                          return error;
                    }
                    break;

                default:
                    SKIP_(crec.extra_field_length)
                    SKIP_(crec.file_comment_length)
                    break;

            } /* end switch (lflag) */

            c += crec.csize;
            uc += crec.ucsize;
            if (crec.general_purpose_bit_flag & 1)
                c -= 12;    /* if encrypted, don't count encryption header */
            ++members;

        } else {   /* not listing */
            SKIP_(crec.extra_field_length)
            SKIP_(crec.file_comment_length)

        } /* end if (list member?) */

    } /* end for-loop (j: member files) */

/*---------------------------------------------------------------------------
    Double check that we're back at the end-of-central-directory record.
  ---------------------------------------------------------------------------*/

    readbuf(sig, 4);
    if (strncmp(sig, end_central_sig, 4)) {     /* just to make sure again */
        fprintf(stderr, EndSigMsg);  /* didn't find end-of-central-dir sig */
        error_in_archive = PK_WARN;
    }

/*---------------------------------------------------------------------------
    Check that we actually found requested files; if so, print totals.
  ---------------------------------------------------------------------------*/

    if (tflag)
        printf(
          "%d file%s, %lu bytes uncompressed, %lu bytes compressed:  %d%%\n",
          members, (members==1)? "":"s", uc, c, (uc==0)? 0 : ((uc>2000000L)?
          ((int)((uc-c)/(uc/1000L))+5)/10 : ((int)((1000L*(uc-c))/uc)+5)/10) );

/*---------------------------------------------------------------------------
    Check for unmatched filespecs on command line and print warning if any
    found.
  ---------------------------------------------------------------------------*/

    if (fn_matched) {
        for (j = 0;  j < filespecs;  ++j)
            if (!fn_matched[j])
                fprintf(stderr, "caution: filename not matched:  %s\n",
                  pfnames[j]);
        free(fn_matched);
    }
    if (xn_matched) {
        for (j = 0;  j < xfilespecs;  ++j)
            if (!xn_matched[j])
                fprintf(stderr, "caution: excluded filename not matched:  %s\n",
                  pxnames[j]);
        free(xn_matched);
    }

    return error_in_archive;

} /* end function process_central_dir() */





/**************************/
/*  Function long_info()  */
/**************************/

int long_info()   /* return PK-type error code */
{
    int          error, error_in_archive=PK_COOL;
    ush          hostver, extver, xattr;
    char         workspace[12], attribs[22];
    static char  unkn[16];
    static char  *os[NUM_HOSTS+1] = {"MS-DOS, OS/2 or NT FAT", "Amiga",
                     "VAX VMS", "Unix", "VM/CMS", "Atari ST", "OS/2 or NT HPFS",
                     "Macintosh", "Z-System", "CP/M", "TOPS-20", "NT NTFS",
                     "unknown" };
    static char  *method[NUM_METHODS+1] = {"none (stored)", "shrunk",
                     "reduced (factor 1)", "reduced (factor 2)",
                     "reduced (factor 3)", "reduced (factor 4)",
                     "imploded", "tokenized", "deflated", unkn};
    static char  *dtype[4] = {"normal", "maximum", "fastest", "undefined"};


/*---------------------------------------------------------------------------
    Print out various interesting things about the compressed file.
  ---------------------------------------------------------------------------*/

    hostnum = MIN(crec.version_made_by[1], NUM_HOSTS);
    hostver = crec.version_made_by[0];
    extnum = MIN(crec.version_needed_to_extract[1], NUM_HOSTS);
    extver = crec.version_needed_to_extract[0];
    methnum = MIN(crec.compression_method, NUM_METHODS);
    if (methnum == NUM_METHODS)
        sprintf(unkn, "unknown (%d)", crec.compression_method);

    printf("  %s\n", filename);

    printf("\n  host operating system (created on):               %s\n",
      os[hostnum]);
    printf("  version of encoding software:                     %d.%d\n",
      hostver/10, hostver%10);
    printf("  minimum operating system compatibility required:  %s\n",
      os[extnum]);
    printf("  minimum software version required to extract:     %d.%d\n",
      extver/10, extver%10);
    printf("  compression method:                               %s\n",
      method[methnum]);
    if (methnum == IMPLODED) {
        printf("  size of sliding dictionary (implosion):           %cK\n",
          (crec.general_purpose_bit_flag & 2)? '8' : '4');
        printf("  number of Shannon-Fano trees (implosion):         %c\n",
          (crec.general_purpose_bit_flag & 4)? '3' : '2');
    } else if (methnum == DEFLATED) {
        ush  dnum=(crec.general_purpose_bit_flag>>1) & 3;
        printf("  compression sub-type (deflation):                 %s\n",
          dtype[dnum]);
    }
    printf("  file security status:                             %sencrypted\n",
      (crec.general_purpose_bit_flag & 1)? "" : "not ");
    printf("  extended local header:                            %s\n",
      (crec.general_purpose_bit_flag & 8)? "yes" : "no");
    /* print upper 3 bits for amusement? */
    printf("  file last modified on:                            %s\n",
      zipinfo_time(&crec.last_mod_file_date, &crec.last_mod_file_time));
    printf("  32-bit CRC value (hex):                           %.8lx\n",
      crec.crc32);
    printf("  compressed size:                                  %lu bytes\n",
      crec.csize);
    printf("  uncompressed size:                                %lu bytes\n",
      crec.ucsize);
    printf("  length of filename:                               %u characters\n",
      crec.filename_length);
    printf("  length of extra field:                            %u bytes\n",
      crec.extra_field_length);
    printf("  length of file comment:                           %u characters\n",
      crec.file_comment_length);
    printf("  disk number on which file begins:                 disk %u\n",
      crec.disk_number_start);
    printf("  apparent file type:                               %s\n",
      (crec.internal_file_attributes & 1)? "text" : "binary");
/*
    printf("  external file attributes (hex):                   %.8lx\n",
      crec.external_file_attributes);
 */
    xattr = (ush)((crec.external_file_attributes >> 16) & 0xFFFF);
    if (hostnum == VMS_) {
        char   *p=attribs, *q=attribs+1;
        int    i, j, k;

        for (k = 0;  k < 12;  ++k)
            workspace[k] = 0;
        if (xattr & S_IRUSR)
            workspace[0] = 'R';
        if (xattr & S_IWUSR) {
            workspace[1] = 'W';
            workspace[3] = 'D';
        }
        if (xattr & S_IXUSR)
            workspace[2] = 'E';
        if (xattr & S_IRGRP)
            workspace[4] = 'R';
        if (xattr & S_IWGRP) {
            workspace[5] = 'W';
            workspace[7] = 'D';
        }
        if (xattr & S_IXGRP)
            workspace[6] = 'E';
        if (xattr & S_IROTH)
            workspace[8] = 'R';
        if (xattr & S_IWOTH) {
            workspace[9] = 'W';
            workspace[11] = 'D';
        }
        if (xattr & S_IXOTH)
            workspace[10] = 'E';

        *p++ = '(';
        for (k = j = 0;  j < 3;  ++j) {    /* loop over groups of permissions */
            for (i = 0;  i < 4;  ++i, ++k)  /* loop over perms within a group */
                if (workspace[k])
                    *p++ = workspace[k];
            *p++ = ',';                       /* group separator */
            if (j == 0)
                while ((*p++ = *q++) != ','); /* system, owner perms are same */
        }
        *p-- = 0;
        *p = ')';   /* overwrite last comma */
        printf("  VMS file attributes (%06o octal):               %s\n",
          xattr, attribs);

    } else if (hostnum == AMIGA_) {
        switch (xattr & AMI_IFMT) {
            case AMI_IFDIR:  attribs[0] = 'd';  break;
            case AMI_IFREG:  attribs[0] = '-';  break;
            default:         attribs[0] = '?';  break;
        }
        attribs[1] = (xattr & AMI_IHIDDEN)?   'h' : '-';
        attribs[2] = (xattr & AMI_ISCRIPT)?   's' : '-';
        attribs[3] = (xattr & AMI_IPURE)?     'p' : '-';
        attribs[4] = (xattr & AMI_IARCHIVE)?  'a' : '-';
        attribs[5] = (xattr & AMI_IREAD)?     'r' : '-';
        attribs[6] = (xattr & AMI_IWRITE)?    'w' : '-';
        attribs[7] = (xattr & AMI_IEXECUTE)?  'e' : '-';
        attribs[8] = (xattr & AMI_IDELETE)?   'd' : '-';
        attribs[9] = 0;   /* better dlm the string */
        printf("  Amiga file attributes (%06o octal):             %s\n",
          xattr, attribs);

    } else if ((hostnum != FS_FAT_) && (hostnum != FS_HPFS_) &&
        (hostnum != FS_NTFS_)) {
        /* assume Unix-like */
        switch (xattr & UNX_IFMT) {
            case UNX_IFDIR:   attribs[0] = 'd';  break;
            case UNX_IFREG:   attribs[0] = '-';  break;
            case UNX_IFLNK:   attribs[0] = 'l';  break;
            case UNX_IFBLK:   attribs[0] = 'b';  break;
            case UNX_IFCHR:   attribs[0] = 'c';  break;
            case UNX_IFIFO:   attribs[0] = 'p';  break;
            case UNX_IFSOCK:  attribs[0] = 's';  break;
            default:          attribs[0] = '?';  break;
        }
        attribs[1] = (xattr & S_IRUSR)? 'r' : '-';
        attribs[4] = (xattr & S_IRGRP)? 'r' : '-';
        attribs[7] = (xattr & S_IROTH)? 'r' : '-';

        attribs[2] = (xattr & S_IWUSR)? 'w' : '-';
        attribs[5] = (xattr & S_IWGRP)? 'w' : '-';
        attribs[8] = (xattr & S_IWOTH)? 'w' : '-';

        if (xattr & S_IXUSR)
            attribs[3] = (xattr & UNX_ISUID)? 's' : 'x';
        else
            attribs[3] = (xattr & UNX_ISUID)? 'S' : '-';   /* S = undefined */
        if (xattr & S_IXGRP)
            attribs[6] = (xattr & UNX_ISGID)? 's' : 'x';   /* == UNX_ENFMT */
        else
            attribs[6] = (xattr & UNX_ISGID)? 'l' : '-';
        if (xattr & S_IXOTH)
            attribs[9] = (xattr & UNX_ISVTX)? 't' : 'x';   /* "sticky bit" */
        else
            attribs[9] = (xattr & UNX_ISVTX)? 'T' : '-';   /* T = undefined */
        attribs[10] = 0;

        printf("  Unix file attributes (%06o octal):              %s\n",
          xattr, attribs);

    } /* endif (hostnum: external attributes format) */

    if ((xattr=(ush)(crec.external_file_attributes & 0xFF)) == 0)
        printf("  MS-DOS file attributes (%02X hex):                  none\n",
          xattr);
    else if (xattr == 1)
        printf(
          "  MS-DOS file attributes (%02X hex):                  read-only\n",
          xattr);
    else
        printf(
         "  MS-DOS file attributes (%02X hex):                  %s%s%s%s%s%s\n",
          xattr, (xattr&1)?"rdo ":"", (xattr&2)?"hid ":"", (xattr&4)?"sys ":"",
          (xattr&8)?"lab ":"", (xattr&16)?"dir ":"", (xattr&32)?"arc":"");
    printf(
     "  offset of local header from start of archive:     %lu (%.8lXh) bytes\n",
      crec.relative_offset_local_header, crec.relative_offset_local_header);

/*---------------------------------------------------------------------------
    Skip the extra field, if any, and print the file comment, if any (the
    filename has already been printed, above).  That finishes up this file
    entry...
  ---------------------------------------------------------------------------*/

    if (crec.extra_field_length > 0) {
/* #ifdef OS2 */
#if TRUE
        ulg ea_size;
        if ((error = do_string(crec.extra_field_length, EXTRA_FIELD)) != 0) {
            error_in_archive = error;
            if (error > PK_WARN)   /* fatal:  can't continue */
                return error;
        }
        if ((ea_size = SizeOfEAs(extra_field)) != 0)
            printf("\n\
  This file has %lu bytes of OS/2 EA's in the local extra field.\n\
  (May not match OS/2 \"dir\" amount due to storage method.)\n\n",
              ea_size);
        else
            printf("\n  There is an unknown extra field (skipping).\n");
#else
        printf("\n  There is an extra field (skipping).\n");
        SKIP_(crec.extra_field_length)
#endif
    } else
        printf("\n");

    if (!crec.file_comment_length)
        printf("  There is no file comment.\n");
    else {
        printf("\
------------------------- file comment begins ----------------------------\n");
        if ((error = do_string(crec.file_comment_length, DISPLAY)) != PK_COOL) {
          error_in_archive = error;   /* might be warning */
          if (error > PK_WARN)   /* fatal */
              return error;
        }
        printf("\n\
-------------------------- file comment ends -----------------------------\n");
    }

    return error_in_archive;

} /* end function long_info() */





/**************************/
/*  Function SizeOfEAs()  */
/**************************/

ulg SizeOfEAs(extra_field)   /* Author: Kai Uwe Rommel */
    void   *extra_field;
{
    EAHEADER *pEAblock = (PEAHEADER)extra_field;

    if (extra_field != NULL  &&  pEAblock->nID == EAID)
        return pEAblock->lSize;

    return 0L;
}





/***************************/
/*  Function short_info()  */
/***************************/

int short_info()   /* return PK-type error code */
{
    int           k, error, error_in_archive=PK_COOL;
    ush           hostver, xattr;
    char          workspace[12], attribs[16];
    static char   impl[5]="i#:#", defl[5]="def#", unkn[8];
    static char   dtype[5]="NXF?";  /* normal, maximum, fastest, undefined */
    static char   *os[NUM_HOSTS+1] = {"fat", "ami", "vms", "unx", "cms",
                      "atr", "hpf", "mac", "zzz", "cpm", "t20", "ntf", "???" };
    static char   *method[NUM_METHODS+1] = {"stor", "shrk", "re:1", "re:2",
                      "re:3", "re:4", impl, "tokn", defl, unkn};


/*---------------------------------------------------------------------------
    Print out various interesting things about the compressed file.
  ---------------------------------------------------------------------------*/

    methnum = MIN(crec.compression_method, NUM_METHODS);
    hostnum = MIN(crec.version_made_by[1], NUM_HOSTS);
    hostver = crec.version_made_by[0];
/*
    extnum = MIN(crec.version_needed_to_extract[1], NUM_HOSTS);
    extver = crec.version_needed_to_extract[0];
 */

    if (methnum == IMPLODED) {
        impl[1] = (char) ((crec.general_purpose_bit_flag & 2)? '8' : '4');
        impl[3] = (char) ((crec.general_purpose_bit_flag & 4)? '3' : '2');
    } else if (methnum == DEFLATED) {
        ush  dnum=(crec.general_purpose_bit_flag>>1) & 3;
        defl[3] = dtype[dnum];
    } else if (methnum == NUM_METHODS) {   /* unknown */
        sprintf(unkn, "u%03d", crec.compression_method);
    }

    for (k = 0;  k < 15;  ++k)
        attribs[k] = ' ';
    attribs[15] = 0;

    xattr = (ush)((crec.external_file_attributes >> 16) & 0xFFFF);
    switch (hostnum) {
        case VMS_:
            {   char   *p=attribs;
                int    i, j;

                for (k = 0;  k < 12;  ++k)
                    workspace[k] = 0;
                if (xattr & S_IRUSR)
                    workspace[0] = 'R';
                if (xattr & S_IWUSR) {
                    workspace[1] = 'W';
                    workspace[3] = 'D';
                }
                if (xattr & S_IXUSR)
                    workspace[2] = 'E';
                if (xattr & S_IRGRP)
                    workspace[4] = 'R';
                if (xattr & S_IWGRP) {
                    workspace[5] = 'W';
                    workspace[7] = 'D';
                }
                if (xattr & S_IXGRP)
                  workspace[6] = 'E';
                if (xattr & S_IROTH)
                    workspace[8] = 'R';
                if (xattr & S_IWOTH) {
                    workspace[9] = 'W';
                    workspace[11] = 'D';
                }
                if (xattr & S_IXOTH)
                    workspace[10] = 'E';

                for (k = j = 0;  j < 3;  ++j) {     /* groups of permissions */
                    for (i = 0;  i < 4;  ++i, ++k)  /* perms within a group */
                        if (workspace[k])
                            *p++ = workspace[k];
                    *p++ = ',';                     /* group separator */
                }
                *--p = ' ';   /* overwrite last comma */
                if ((p - attribs) < 12)
                    sprintf(&attribs[12], "%d.%d", hostver/10, hostver%10);
            }
            break;

        case FS_FAT_:
        case FS_HPFS_:
        case FS_NTFS_:
            xattr = (ush)(crec.external_file_attributes & 0xFF);
            sprintf(attribs, "%s,%s,%s,%s", (xattr&32)?"arc":"",
              (xattr&2)?"hid":"", (xattr&1)?"rdo":"rw", (xattr&4)?"sys":"");
            if ((k = strlen(attribs)) < 15)
                attribs[k] = ' ';   /* overwrite '\0' */
            if (k < 12)
                sprintf(&attribs[12], "%d.%d", hostver/10, hostver%10);
            break;

        case AMIGA_:
            switch (xattr & AMI_IFMT) {
                case AMI_IFDIR:  attribs[0] = 'd';  break;
                case AMI_IFREG:  attribs[0] = '-';  break;
                default:         attribs[0] = '?';  break;
            }
            attribs[1] = (xattr & AMI_IHIDDEN)?   'h' : '-';
            attribs[2] = (xattr & AMI_ISCRIPT)?   's' : '-';
            attribs[3] = (xattr & AMI_IPURE)?     'p' : '-';
            attribs[4] = (xattr & AMI_IARCHIVE)?  'a' : '-';
            attribs[5] = (xattr & AMI_IREAD)?     'r' : '-';
            attribs[6] = (xattr & AMI_IWRITE)?    'w' : '-';
            attribs[7] = (xattr & AMI_IEXECUTE)?  'e' : '-';
            attribs[8] = (xattr & AMI_IDELETE)?   'd' : '-';
            sprintf(&attribs[12], "%d.%d", hostver/10, hostver%10);
            break;

        default:   /* assume Unix-like */
            switch (xattr & UNX_IFMT) {
                case UNX_IFDIR:   attribs[0] = 'd';  break;
                case UNX_IFREG:   attribs[0] = '-';  break;
                case UNX_IFLNK:   attribs[0] = 'l';  break;
                case UNX_IFBLK:   attribs[0] = 'b';  break;
                case UNX_IFCHR:   attribs[0] = 'c';  break;
                case UNX_IFIFO:   attribs[0] = 'p';  break;
                case UNX_IFSOCK:  attribs[0] = 's';  break;
                default:          attribs[0] = '?';  break;
            }
            attribs[1] = (xattr & S_IRUSR)? 'r' : '-';
            attribs[4] = (xattr & S_IRGRP)? 'r' : '-';
            attribs[7] = (xattr & S_IROTH)? 'r' : '-';
            attribs[2] = (xattr & S_IWUSR)? 'w' : '-';
            attribs[5] = (xattr & S_IWGRP)? 'w' : '-';
            attribs[8] = (xattr & S_IWOTH)? 'w' : '-';

            if (xattr & S_IXUSR)
                attribs[3] = (xattr & UNX_ISUID)? 's' : 'x';
            else
                attribs[3] = (xattr & UNX_ISUID)? 'S' : '-';  /* S==undefined */
            if (xattr & S_IXGRP)
                attribs[6] = (xattr & UNX_ISGID)? 's' : 'x';  /* == UNX_ENFMT */
            else
                attribs[6] = (xattr & UNX_ISGID)? 'l' : '-';
            if (xattr & S_IXOTH)
                attribs[9] = (xattr & UNX_ISVTX)? 't' : 'x';  /* "sticky bit" */
            else
                attribs[9] = (xattr & UNX_ISVTX)? 'T' : '-';  /* T==undefined */

            sprintf(&attribs[12], "%d.%d", hostver/10, hostver%10);
            break;

    } /* end switch (hostnum: external attributes format) */

    printf("%s %s %7lu %c%c", attribs, os[hostnum], crec.ucsize,
      (crec.general_purpose_bit_flag & 1)?
      ((crec.internal_file_attributes & 1)? 'T' : 'B') :   /* encrypted */
      ((crec.internal_file_attributes & 1)? 't' : 'b'),    /* plaintext */
      (crec.general_purpose_bit_flag & 8)? (crec.extra_field_length? 'X' : 'l')
                                        : (crec.extra_field_length? 'x' : '-'));
    if (lflag == 4) {
        longint c = (longint)crec.csize;
        longint uc = (longint)crec.ucsize;

        if (crec.general_purpose_bit_flag & 1)
            c -= 12;    /* if encrypted, don't count encryption header */
        /* risk signed overflow if blindly multiply: */
        printf("%3d%%", (uc==0)? 0 : ((uc>2000000L)?
          ((int)((uc-c)/(uc/1000L))+5)/10 : ((int)((1000L*(uc-c))/uc)+5)/10) );
    } else if (lflag == 5)
        printf(" %7lu", crec.csize);

    printf(" %s %s %s\n", method[methnum],
      zipinfo_time(&crec.last_mod_file_date, &crec.last_mod_file_time),
      filename);

/*---------------------------------------------------------------------------
    Skip the extra field and/or the file comment, if any (the filename has
    already been printed, above).  That finishes up this file entry...
  ---------------------------------------------------------------------------*/

    SKIP_(crec.extra_field_length)
    SKIP_(crec.file_comment_length)

    return error_in_archive;

} /* end function short_info() */





/*****************************/
/*  Function zipinfo_time()  */
/*****************************/

char *zipinfo_time(datez, timez)
    ush   *datez, *timez;
{
    ush           yr, mo, dy, hh, mm, ss;
    static char   d_t_str[21];
    static char   *month[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};



/*---------------------------------------------------------------------------
    Convert the file-modification date and time info to a string of the form
    "23 Feb 1990 17:15:00" or "23-Feb-91 17:15," depending on value of lflag.
  ---------------------------------------------------------------------------*/

    yr = ((*datez >> 9) & 0x7f) + 80;
    mo = ((*datez >> 5) & 0x0f) - 1;
    dy = *datez & 0x1f;

    hh = (*timez >> 11) & 0x1f;
    mm = (*timez >> 5) & 0x3f;
    ss = (*timez & 0x1f) * 2;

    if ((lflag >= 3) && (lflag <= 5))
        sprintf(d_t_str, "%2u-%s-%u %02u:%02u", dy, month[mo], yr, hh, mm);
    else if (lflag > 9)  /* verbose listing format */
        sprintf(d_t_str, "%u %s %u %02u:%02u:%02u", dy, month[mo], yr+1900,
          hh, mm, ss);

    return d_t_str;

} /* end function zipinfo_time() */
