Esempio n. 1
0
static int write_central_and_end (zfile *zf, const char *tempzip)
{
    guint32 c = zf->tempzn;  /* get start of central */
    guint32 t = 0;
    zlist *z;
    int k = 0, err = 0;

    trace(1, "writing central directory\n");

    for (z = zfiles; z != NULL; z = z->nxt) {
	if (z->mark == MARK_DELETE) {
	    continue;
	}
	if ((err = put_central_header(z, zf->fp)) != ZE_OK) {
	    return ziperr(err, tempzip);
	}
	zf->tempzn += 4 + CENHEAD + z->namelen + z->cextlen + z->comlen;
	t += z->csize;
	k++;
    }

    t = zf->tempzn - c; /* compute length of central */
    if ((err = put_end_dir(k, t, c, zf->zcomlen, zf->zcomment, zf->fp)) != ZE_OK) {
	ziperr(err, tempzip);
    }

    return err;
}
Esempio n. 2
0
static int real_delete_files (zfile *zf)
{
    int attr = 0;         /* attributes of zip file */
    FILE *fr = NULL;      /* for reading from original zipfile */
    char tempzip[FILENAME_MAX]; /* filename for temp zipfile */
    int err = 0;

    *tempzip = '\0';

    err = zipfile_write_check(zf, ZIP_DO_DELETE, &attr);
    if (err) {
	return err;
    }

    trace(1, "opening original zip file for reading\n");
    fr = fopen(zf->fname, "rb");
    if (fr == NULL) {
	return ziperr(ZE_NAME, zf->fname);
    }

    strcpy(tempzip, zf->fname);
    zf->fp = ztempfile(tempzip);
    if (zf->fp == NULL) {
	fprintf(stderr, " real_delete_files: ztempfile failed\n");
	fclose(fr);
	ziperr(ZE_TEMP, tempzip);
	return ZE_TEMP;
    }

    /* reset to start of file */
    zf->tempzn = 0;

    err = process_delfiles(zf, fr);

    if (!err) {
	err = write_central_and_end(zf, tempzip);
    }

    fclose(zf->fp);
    zf->fp = NULL;
    fclose(fr);
	
    if (!err) {
	/* Replace old zip file with new zip file, leaving only the new one */
	trace(1, "moving %s into position as %s\n", tempzip, zf->fname);
	err = replace_file(zf->fname, tempzip);
	if (err) {
	    ziperr(err, "was replacing %s", zf->fname);
	} else if (attr) {
	    chmod(zf->fname, attr);
	}
    }

    if (err && *tempzip != '\0') {
	/* clean up */
	gretl_remove(tempzip);
    }

    return err;
}
Esempio n. 3
0
static int zip_finish (zfile *zf)
{
    int err = 0;

    if (zf->fname != NULL) {
	free(zf->fname);
	zf->fname = NULL;
    }

    if (zf->zcomment != NULL) {
	free(zf->zcomment);
	zf->zcomment = NULL;
    }

    /* delete input files in the zfiles list? */
    if (delete_inputs(zf->opt)) {
	err = delete_input_files();
	if (err != ZE_OK) {
	    ziperr(err, "was deleting moved files and directories");
	    return err;
	}
    }

    free_zfiles(zf);

    return err;
}
Esempio n. 4
0
static int process_zfiles (zfile *zf, FILE *x, zlist ***pw, int *openerr)
{
    zlist **w = &zfiles;  
    zlist *z; 
    int err = 0;

    *pw = NULL;

    while ((z = *w) != NULL) {
	if (z->mark == MARK_ZIP) {
	    /* zip it up */
	    trace(2, "z->mark = MARK_ZIP for %s, doing zipup, tempzn = %d\n",
		  z->name, zf->tempzn);
	    if ((err = zipup(zf, z)) != ZE_OK && 
		err != ZE_OPEN && err != ZE_MISS) {
		ziperr(err, "was zipping %s", z->name);
		return err;
	    }
	    if (err == ZE_OPEN || err == ZE_MISS) {
		*openerr = 1;
		if (err == ZE_OPEN) {
		    perror(z->zname);
		} 
		if ((err = zipcopy(zf, z, x, zf->fp)) != ZE_OK) {
		    ziperr(err, "was copying %s", z->name);
		    return err;
		}
		z->mark = MARK_NONE;
	    }
	} else {
	    /* copy the original entry verbatim */
	    trace(2, "not marked: %s, doing zipcopy, tempzn = %d\n",
		  z->name, zf->tempzn);
	    if ((err = zipcopy(zf, z, x, zf->fp)) != ZE_OK) {
		ziperr(err, "was copying %s", z->zname);
		return err;
	    }
	}
	w = &z->nxt;
    }

    *pw = w;

    return err;
}
Esempio n. 5
0
static int check_matches (const char **fnames, char *matches)
{
    int i, nf = 0, ngot = 0;
    int err = 0;

    for (i=0; fnames[i] != NULL; i++) {
	nf++;
	if (matches[i]) {
	    ngot++;
	}
    }

    if (nf > 0 && ngot == 0) {
	err = ziperr(ZE_ZNAME, "no requested files were found");
    } else if (ngot < nf) {
	err = ziperr(ZE_ZNAME, "found only %d files out of %d requested",
		     ngot, nf);
    }

    return err;
}
Esempio n. 6
0
static int process_zipfile (zfile *zf, const char *targ, int task)
{
    int err = 0;

    zf->fname = g_strdup(targ);

    if (zf->fname == NULL) {
	err = ziperr(ZE_MEM, "was processing arguments");
    }

    if (!err) {
	err = read_zipfile(zf, task);
    }	

    return err;
}
Esempio n. 7
0
static int zipfile_write_check (zfile *zf, int task, int *attr)
{
    FILE *fp = NULL;
    char *fmode = "w";
    int err = 0;

    /* Note: if task != ZIP_DO_NEW, then a NULL value
       for zfiles means that zf->fname is non-existent
       or empty, but if task == ZIP_DO_NEW we don't
       do an initial read of zf->fname, so zfiles will
       be NULL regardless; its value is uninformative.
    */

    if (task == ZIP_DO_NEW) {
	/* overwriting: don't destroy the original archive until we're
	   fairly confident we have a good replacement */
	if (gretl_file_test(zf->fname, G_FILE_TEST_EXISTS)) {
	    fmode = "r+";
	}
    } else if (zfiles != NULL || zf->zstart != 0) {
	fmode = "r+";
    }

    trace(2, "testing fopen on '%s', mode %s\n", zf->fname, fmode);

    fp = fopen(zf->fname, fmode);
    if (fp == NULL) {
	err = ziperr(ZE_CREAT, zf->fname);
    } else {
	fclose(fp);
    }

    *attr = get_file_attributes(zf->fname);

    if (task != ZIP_DO_NEW && zfiles == NULL && zf->zstart == 0) {
	trace(2, "removing old file '%s'\n", zf->fname);
	gretl_remove(zf->fname);
    }

    return err;
}
Esempio n. 8
0
char *GetComment(char *filename)
{
    BPTR lk;
    static struct FileInfoBlock *fib = NULL;

    if (!filename) {
        if (fib) FreeMem(fib, sizeof(*fib));
        fib = NULL;
        return NULL;
    }
    if (!fib) {
        if (!(fib = AllocMem(sizeof(*fib), MEMF_PUBLIC)))
            ziperr(ZE_MEM, "was checking filenotes");
    }
    if (!(lk = Lock(filename, ACCESS_READ)))
        return NULL;
    if (!Examine(lk, fib))
        fib->fib_Comment[0] = '\0';
    UnLock(lk);
    return fib->fib_Comment[0] ? &fib->fib_Comment[0] : NULL;
}
Esempio n. 9
0
static int process_delfiles (zfile *zf, FILE *fr)
{
    zlist *z, **w = &zfiles;  
    int err = 0;

    while ((z = *w) != NULL) {
	if (z->mark == MARK_DELETE) {
	    trace(1, "'%s': marked for deletion: skipping\n", z->zname);
	} else {
	    trace(2, "'%s': not marked for deletion: doing zipcopy, tempzn = %d\n",
		  z->name, zf->tempzn);
	    if ((err = zipcopy(zf, z, fr, zf->fp))) {
		ziperr(err, "was copying %s", z->zname);
		return err;
	    }
	}
	w = &z->nxt;
    }

    return err;
}
Esempio n. 10
0
// RCV 1.605 Added
static void SetExclFilters(struct Globals *pG)
{
  register int i;

  if (pG->pcount)
  {
    if ((pG->patterns = (struct plist*)MALLOC(pG->pcount *sizeof(struct plist)))
      == NULL)
    {
      ziperr(ZEN_MEM05, pG);
      return ;
    }

    for (i = 0; i < pG->pcount; i++)
    {
      register char *p = pG->ExternalList[i].zname; // Replace forward slashes.
      if (p)
        while (*p)
          if (*p++ == '/')
            *(p - 1) = '\\';
      pG->patterns[i].zname = ex2in(pG->ExternalList[i].zname, NULL, pG);
    }
  }
}
Esempio n. 11
0
void _abort(void)               /* called when ^C is pressed */
{
    close_leftover_open_dirs();
    ziperr(ZE_ABORT, "^C");
}
unsigned long
vms_zip_cmdline (int *argc_p, char ***argv_p)
{
/*
**  Routine:    vms_zip_cmdline
**
**  Function:
**
**      Parse the DCL command line and create a fake argv array to be
**      handed off to Zip.
**
**      NOTE: the argv[] is built as we go, so all the parameters are
**      checked in the appropriate order!!
**
**  Formal parameters:
**
**      argc_p          - Address of int to receive the new argc
**      argv_p          - Address of char ** to receive the argv address
**
**  Calling sequence:
**
**      status = vms_zip_cmdline (&argc, &argv);
**
**  Returns:
**
**      SS$_NORMAL      - Success.
**      SS$_INSFMEM     - A malloc() or realloc() failed
**      SS$_ABORT       - Bad time value
**
*/
    register unsigned long status;
    char options[48];
    char *the_cmd_line;                 /* buffer for argv strings */
    unsigned long cmdl_size;            /* allocated size of buffer */
    unsigned long cmdl_len;             /* used size of buffer */
    char *ptr;
    int  x, len;

    int new_argc;
    char **new_argv;

    struct dsc$descriptor_d work_str;
    struct dsc$descriptor_d foreign_cmdline;

    init_dyndesc(work_str);
    init_dyndesc(foreign_cmdline);

    /*
    **  See if the program was invoked by the CLI (SET COMMAND) or by
    **  a foreign command definition.  Check for /YYZ_ZIP, which is a
    **  valid default qualifier solely for this test.
    */
    show_VMSCLI_help = TRUE;
    status = check_cli(&cli_yyz);
    if (!(status & 1)) {
        lib$get_foreign(&foreign_cmdline);
        /*
        **  If nothing was returned or the first character is a "-", then
        **  assume it's a UNIX-style command and return.
        */
        if (foreign_cmdline.dsc$w_length == 0)
            return (SS$_NORMAL);
        if ((*(foreign_cmdline.dsc$a_pointer) == '-') ||
            ((foreign_cmdline.dsc$w_length > 1) &&
             (*(foreign_cmdline.dsc$a_pointer) == '"') &&
             (*(foreign_cmdline.dsc$a_pointer + 1) == '-'))) {
            show_VMSCLI_help = FALSE;
            return (SS$_NORMAL);
        }

        str$concat(&work_str, &zip_command, &foreign_cmdline);
        status = cli$dcl_parse(&work_str, &zip_clitable, lib$get_input,
                        lib$get_input, 0);
        if (!(status & 1)) return (status);
    }

    /*
    **  There's always going to be a new_argv[] because of the image name.
    */
    if ((the_cmd_line = (char *) malloc(cmdl_size = ARGBSIZE_UNIT)) == NULL)
        return (SS$_INSFMEM);

    strcpy(the_cmd_line, "zip");
    cmdl_len = sizeof("zip");

    /*
    **  First, check to see if any of the regular options were specified.
    */

    options[0] = '-';
    ptr = &options[1];          /* Point to temporary buffer */

    /*
    **  Delete the specified files from the zip file?
    */
    status = cli$present(&cli_delete);
    if (status & 1)
        *ptr++ = 'd';

    /*
    **  Freshen (only changed files).
    */
    status = cli$present(&cli_freshen);
    if (status & 1)
        *ptr++ = 'f';

    /*
    **  Delete the files once they've been added to the zip file.
    */
    status = cli$present(&cli_move);
    if (status & 1)
        *ptr++ = 'm';

    /*
    **  Add changed and new files.
    */
    status = cli$present(&cli_update);
    if (status & 1)
        *ptr++ = 'u';

    /*
    **  Check for the compression level (-0 through -9).
    */
    status = cli$present(&cli_level);
    if (status & 1) {

        unsigned long binval;

        status = cli$get_value(&cli_level, &work_str);
        status = ots$cvt_tu_l(&work_str, &binval);
        if (!(status & 1) || (binval > 9)) {
           return (SS$_ABORT);
        }
        *ptr++ = binval + '0';
    }

    /*
    **  Adjust offsets of zip archive entries.
    */
    status = cli$present(&cli_adjust);
    if (status & 1)
        *ptr++ = 'A';

    /*
    **  Add comments?
    */
    status = cli$present(&cli_comments);
    if (status & 1) {
/*        while ((status = cli$get_value(&cli_comments, &work_str)) & 1) {
            if (strncmp(work_str.dsc$a_pointer,"ZIP",3) == 0)
                *ptr++ = 'z';
            if (strncmp(work_str.dsc$a_pointer,"FIL",3) == 0)
                *ptr++ = 'c';
        } */
        if ((status = cli$present(&cli_comment_zipfile)) & 1)
            *ptr++ = 'z';
        if ((status = cli$present(&cli_comment_files)) & 1)
            *ptr++ = 'c';
    }

    /*
    **  Do not add/modify directory entries.
    */
    status = cli$present(&cli_dirnames);
    if (!(status & 1))
        *ptr++ = 'D';

    /*
    **  Encrypt?
    */
    status = cli$present(&cli_encrypt);
    if (status & 1)
        if ((status = cli$get_value(&cli_encrypt, &work_str)) & 1) {
            x = cmdl_len;
            cmdl_len += work_str.dsc$w_length + 4;
            CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
            strcpy(&the_cmd_line[x], "-P");
            strncpy(&the_cmd_line[x+3], work_str.dsc$a_pointer,
                    work_str.dsc$w_length);
            the_cmd_line[cmdl_len-1] = '\0';
        } else {
            *ptr++ = 'e';
        }

    /*
    **  Fix the zip archive structure.
    */
    status = cli$present(&cli_fix_archive);
    if (status & 1) {
        *ptr++ = 'F';
        if ((status = cli$present(&cli_fix_full)) & 1) {
            *ptr++ = 'F';
        }
    }

    /*
    **  Append (allow growing of existing zip file).
    */
    status = cli$present(&cli_append);
    if (status & 1)
        *ptr++ = 'g';

    /*
    **  Show the help.
    */
    status = cli$present(&cli_help);
    if (status & 1)
        *ptr++ = 'h';

    /*
    **  Junk path names (directory specs).
    */
    status = cli$present(&cli_junk);
    if (status & 1)
        *ptr++ = 'j';

    /*
    **  Simulate zip file made by PKZIP.
    */
    status = cli$present(&cli_pkzip);
    if (status & 1)
        *ptr++ = 'k';

    /*
    **  Translate end-of-line.
    */
    status = cli$present(&cli_translate_eol);
    if (status & 1) {
        *ptr++ = 'l';
        if ((status = cli$present(&cli_transl_eol_crlf)) & 1) {
            *ptr++ = 'l';
        }
    }

    /*
    **  Show the software license.
    */
    status = cli$present(&cli_license);
    if (status & 1)
        *ptr++ = 'L';

    /*
    **  Set zip file time to time of latest file in it.
    */
    status = cli$present(&cli_latest);
    if (status & 1)
        *ptr++ = 'o';

    /*
    **  Store full path (default).
    */
    status = cli$present(&cli_full_path);
    if (status == CLI$_PRESENT)
        *ptr++ = 'p';
    else if (status == CLI$_NEGATED)
        *ptr++ = 'j';

    /*
    **  Junk Zipfile prefix (SFX stub etc.).
    */
    status = cli$present(&cli_unsfx);
    if (status & 1)
        *ptr++ = 'J';

    /*
    **  Recurse through subdirectories.
    */
    status = cli$present(&cli_recurse);
    if (status & 1) {
        if ((status = cli$present(&cli_recurse_fnames)) & 1)
            *ptr++ = 'R';
        else
            *ptr++ = 'r';
    }

    /*
    **  Be verbose.
    */
    status = cli$present(&cli_verbose);
    if (status & 1) {
        int i;
        int verbo = 0;

        /* /VERBOSE */
        if ((status = cli$present(&cli_verbose_command)) & 1)
        {
            /* /VERBOSE = COMMAND */
            verbose_command = 1;
        }

        /* Note that any or all of the following options may be
           specified, and the maximum one is used.
        */
        if ((status = cli$present(&cli_verbose_normal)) & 1)
            /* /VERBOSE [ = NORMAL ] */
            verbo = 1;
        if ((status = cli$present(&cli_verbose_more)) & 1)
            /* /VERBOSE = MORE */
            verbo = 2;
        if ((status = cli$present(&cli_verbose_debug)) & 1) {
            /* /VERBOSE = DEBUG */
            verbo = 3;
        }
        for (i = 0; i < verbo; i++)
            *ptr++ = 'v';
    }

    /*
    **  Quiet mode.
    **  (Quiet mode is processed after verbose, because a "-v" modifier
    **  resets "noisy" to 1.)
    */
    status = cli$present(&cli_quiet);
    if (status & 1)
        *ptr++ = 'q';

    /*
    **  Suppress creation of any extra field.
    */
    status = cli$present(&cli_extra_fields);
    if (!(status & 1))
        *ptr++ = 'X';

    /*
    **  Save the VMS file attributes (and all allocated blocks?).
    */
    status = cli$present(&cli_vms);
    if (status & 1) {
        /* /VMS */
        *ptr++ = 'V';
        if ((status = cli$present(&cli_vms_all)) & 1) {
            /* /VMS = ALL */
            *ptr++ = 'V';
        }
    }

    /*
    **  Keep the VMS version number as part of the file name when stored.
    */
    status = cli$present(&cli_keep_version);
    if (status & 1)
        *ptr++ = 'w';

    /*
    **  `Batch' processing: read filenames to archive from stdin
    **  or the specified file.
    */
    status = cli$present(&cli_batch);
    if (status & 1) {
        status = cli$get_value(&cli_batch, &work_str);
        if (status & 1) {
            work_str.dsc$a_pointer[work_str.dsc$w_length] = '\0';
            if ((stdin = freopen(work_str.dsc$a_pointer, "r", stdin)) == NULL)
            {
                sprintf(errbuf, "could not open list file: %s",
                        work_str.dsc$a_pointer);
                ziperr(ZE_PARMS, errbuf);
            }
        }
        *ptr++ = '@';
    }

    /*
    **  Now copy the final options string to the_cmd_line.
    */
    len = ptr - &options[0];
    if (len > 1) {
        options[len] = '\0';
        x = cmdl_len;
        cmdl_len += len + 1;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], options);
    }

    /*
    **
    **  OK.  We've done all the regular options, so check for -b (temporary
    **  file path), -t (exclude before time), -n (special suffixes), zipfile,
    **  files to zip, and exclude list.
    **
    */
    status = cli$present(&cli_temp_path);
    if (status & 1) {
        status = cli$get_value(&cli_temp_path, &work_str);
        x = cmdl_len;
        cmdl_len += work_str.dsc$w_length + 4;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-b");
        strncpy(&the_cmd_line[x+3], work_str.dsc$a_pointer,
                work_str.dsc$w_length);
        the_cmd_line[cmdl_len-1] = '\0';
    }

    /*
    **  Demand that all input files exist (and wildcards match something).
    */
#define OPT_MM  "-MM"           /* Input file specs must exist. */
    status = cli$present(&cli_must_match);
    if (status & 1) {
        x = cmdl_len;
        cmdl_len += strlen( OPT_MM)+ 1;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy( &the_cmd_line[ x], OPT_MM);
    }

    /*
    **  Handle "-t mmddyyyy".
    */
    status = cli$present(&cli_since);
    if (status & 1) {
        char since_time[9];

        status = get_time(&cli_since, &since_time[0]);
        if (!(status & 1)) return (status);

        /*
        **  Now let's add the option "-t mmddyyyy" to the new command line.
        */
        x = cmdl_len;
        cmdl_len += (3 + 9);
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-t");
        strcpy(&the_cmd_line[x+3], since_time);
    }

    /*
    **  Handle "-tt mmddyyyy".
    */
    status = cli$present(&cli_before);
    if (status & 1) {
        char before_time[9];

        status = get_time(&cli_before, &before_time[0]);
        if (!(status & 1)) return (status);

        /*
        **  Now let's add the option "-tt mmddyyyy" to the new command line.
        */
        x = cmdl_len;
        cmdl_len += (4 + 9);
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-tt");
        strcpy(&the_cmd_line[x+4], before_time);
    }

    /*
    **  Handle "-n suffix:suffix:...".  (File types to store only.)
    */
    status = cli$present(&cli_store_types);
    if (status & 1) {
        x = cmdl_len;
        cmdl_len += 3;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-n");

        status = get_list(&cli_store_types, &foreign_cmdline, ':',
                          &the_cmd_line, &cmdl_size, &cmdl_len);
        if (!(status & 1)) return (status);
    }

    /*
    **  Now get the specified zip file name.
    */
    status = cli$present(&cli_zipfile);
    if (status & 1) {
        status = cli$get_value(&cli_zipfile, &work_str);

        x = cmdl_len;
        cmdl_len += work_str.dsc$w_length + 1;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strncpy(&the_cmd_line[x], work_str.dsc$a_pointer,
                work_str.dsc$w_length);
        the_cmd_line[cmdl_len-1] = '\0';

    }

    /*
    **  Run through the list of input files.
    */
    status = cli$present(&cli_infile);
    if (status & 1) {
        status = get_list(&cli_infile, &foreign_cmdline, '\0',
                          &the_cmd_line, &cmdl_size, &cmdl_len);
        if (!(status & 1)) return (status);
    }

    /*
    **  List file containing exclude patterns present? ("*****@*****.**")
    */
    status = cli$present(&cli_exlist);
    if (status & 1) {
        status = cli$get_value(&cli_exlist, &work_str);
        x = cmdl_len;
        cmdl_len += work_str.dsc$w_length + 4;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strncpy(&the_cmd_line[x], "-x@", 3);
        strncpy(&the_cmd_line[x+3], work_str.dsc$a_pointer,
                work_str.dsc$w_length);
        the_cmd_line[cmdl_len-1] = '\0';
    }

    /*
    **  Any files to exclude? ("-x file file")
    */
    status = cli$present(&cli_exclude);
    if (status & 1) {
        x = cmdl_len;
        cmdl_len += 3;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-x");

        status = get_list(&cli_exclude, &foreign_cmdline, '\0',
                          &the_cmd_line, &cmdl_size, &cmdl_len);
        if (!(status & 1)) return (status);
    }

    /*
    **  List file containing include patterns present? ("*****@*****.**")
    */
    status = cli$present(&cli_inlist);
    if (status & 1) {
        status = cli$get_value(&cli_inlist, &work_str);
        x = cmdl_len;
        cmdl_len += work_str.dsc$w_length + 4;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strncpy(&the_cmd_line[x], "-i@", 3);
        strncpy(&the_cmd_line[x+3], work_str.dsc$a_pointer,
                work_str.dsc$w_length);
        the_cmd_line[cmdl_len-1] = '\0';
    }

    /*
    **  Any files to include? ("-i file file")
    */
    status = cli$present(&cli_include);
    if (status & 1) {
        x = cmdl_len;
        cmdl_len += 3;
        CHECK_BUFFER_ALLOCATION(the_cmd_line, cmdl_size, cmdl_len)
        strcpy(&the_cmd_line[x], "-i");

        status = get_list(&cli_exclude, &foreign_cmdline, '\0',
                          &the_cmd_line, &cmdl_size, &cmdl_len);
        if (!(status & 1)) return (status);
    }


    /*
    **  We have finished collecting the strings for the argv vector,
    **  release unused space.
    */
    if ((the_cmd_line = (char *) realloc(the_cmd_line, cmdl_len)) == NULL)
        return (SS$_INSFMEM);

    /*
    **  Now that we've built our new UNIX-like command line, count the
    **  number of args and build an argv array.
    */
    for (new_argc = 0, x = 0; x < cmdl_len; x++)
        if (the_cmd_line[x] == '\0')
            new_argc++;

    /*
    **  Allocate memory for the new argv[].  The last element of argv[]
    **  is supposed to be NULL, so allocate enough for new_argc+1.
    */
    if ((new_argv = (char **) calloc(new_argc+1, sizeof(char *))) == NULL)
        return (SS$_INSFMEM);

    /*
    **  For each option, store the address in new_argv[] and convert the
    **  separating blanks to nulls so each argv[] string is terminated.
    */
    for (ptr = the_cmd_line, x = 0; x < new_argc; x++) {
        new_argv[x] = ptr;
        ptr += strlen(ptr) + 1;
    }
    new_argv[new_argc] = NULL;

#if defined(TEST) || defined(DEBUG)
    printf("new_argc    = %d\n", new_argc);
    for (x = 0; x < new_argc; x++)
        printf("new_argv[%d] = %s\n", x, new_argv[x]);
#endif /* TEST || DEBUG */

    /* Show the complete UNIX command line, if requested. */
    if (verbose_command != 0)
    {
        printf( "   UNIX command line args (argc = %d):\n", new_argc);
        for (x = 0; x < new_argc; x++)
            printf( "%s\n", new_argv[ x]);
        printf( "\n");
    }

    /*
    **  All finished.  Return the new argc and argv[] addresses to Zip.
    */
    *argc_p = new_argc;
    *argv_p = new_argv;

    return (SS$_NORMAL);
}
Esempio n. 13
0
// Add, update, freshen, or delete zip entries in a zip file. argc; /*
//   Number of tokens in command line. argv; /* Command line tokens.
int ZipProcess(struct Globals *pG)
{
  int a; // attributes of zip file
  ulg c; // start of central directory
  struct flist *f; // steps through "found" linked list
  int i; // arg counter, root directory flag
  int k; // next argument type, marked counter, comment size, entry count
  int marks; // replaces k as marked counter
  ulg n; // total of entry len's

  // int o; /* true if there were any ZEN_OPEN errors
  char *p; // steps through option arguments
  int r; // temporary variable
  ulg t; // file time, length of central directory
  //  int           first_listarg = 0;  // index of first arg of "process these files" list
  struct zlist *v; // temporary variable
  struct zlist **w; // pointer to last link in "zfiles" list
  struct zlist *z; // steps through "zfiles" linked list
  int altered; // RP 173 counter for altered comments

  int DestType; // 1.75  destination drive type
  unsigned long TotFiles = 0;
  unsigned /* long */__int64 TotSize = 0;
  unsigned long KeptCnt = 0; // number of 'kept' files
  unsigned __int64 KeptSize = 0; // size of 'kept' files
  unsigned long ofs; // current file offset
  int fsz; // file size;
  int No_File = 0; // 1.75 try if file does not exist
  long hi;

  // Process arguments
  diag("processing lists", pG);

  if (pG->verbose)
  {
    switch (pG->action)
    {
      case ADD:
        diag("action = ADD", pG);
        break;
      case UPDATE:
        diag("action = UPDATE", pG);
        break;
      case FRESHEN:
        diag("action = FRESHEN", pG);
        break;
      case PURGE:
        diag("action = PURGE", pG);
    }

    // zcount is no. of entries in linked-list
    // zfiles is name of the linked-list of filenames for the archive
    Inform(pG, 0, IDIAG, "zcount=%d (no. of files in ZIP already)", pG->zcount);
  }

  // if first_listarg is 0, then we didn't got any fspecs on cmd line
  if (pG->doall && (pG->action == UPDATE || pG->action == FRESHEN))
  {
    // if -update or -freshen with no args, do all, but, when present, apply
    //   filters
    for (z = pG->zfiles; z != NULL; z = z->nxt)
    {
      z->mark = pG->pcount ? filter(z->zname, pG): 1;
    }
  }

  if ((r = check_dup(pG)) != ZEN_OK)
  // remove duplicates in list
    return (ziperr(r, pG));

  // Check option combinations
  // ?????
  if (pG->action == PURGE && (pG->dispose || pG->recurse || pG->key))
    return (ziperr(ZEN_PARMS12, pG));
  if (pG->linkput && pG->dosify)
  {
    Inform(pG, 0, IWARNING, "can't use -y with -k, -y ignored");
    pG->linkput = 0;
  }

  // AllowGrow is the "allow append" indicator
  if (!pG->zcount && ((pG->action == ADD) || (pG->action == UPDATE)))
    pG->AllowGrow = 55;
  //1;   // RP173 - create new file normally

  // if zcount is 0, then zipfile doesn't exist, or is empty
  if (pG->zcount == 0 && ((pG->action != ADD && pG->action != UPDATE) || !pG
    ->AllowGrow))
  {
    // RCV150199 added UPDATE
    Inform(pG, 0, IWARNING, "%s: not found or empty", pG->zipfile);
    if (pG->zcount)
      FREE(pG->zsort);
    return 0;
  }

  if (pG->zcount)
  {
    FREE(pG->zsort);
    pG->zsort = NULL;
  }

  DestType = DriveType(pG->zipfile);
  if (pG->verbose < 0)
    Inform(pG, 0, IDIAG, "Destination type = %d", DestType);

  // RP - check destination type - if CD set tempath to Windows Temp
  if (pG->tempath == NULL && (DestType != DRIVE_FIXED && DestType !=
    DRIVE_RAMDISK))
  {
    unsigned int plen;
    plen = GetTempPath(2047, pG->ewemsg);
    if (plen && (pG->tempath = (char*)MALLOC(plen + 1)) != NULL)
      lstrcpy(pG->tempath, pG->ewemsg);
    else
      return (ziperr(ZEN_MEM10, pG));
  }

  // If -b not specified, set temporary path to zipfile path
  if (pG->tempath == NULL && ((p = strrchr(pG->zipfile, '\\')) != NULL || (p =
    strrchr(pG->zipfile, ':')) != NULL))
  {
    if (*p == ':')
      p++;
    if ((pG->tempath = (char*)MALLOC((int)(p - pG->zipfile) + 1)) == NULL)
      return (ziperr(ZEN_MEM10, pG));
    r =  *p;
    *p = 0;
    lstrcpy(pG->tempath, pG->zipfile);
    *p = (char)r;
  }

  // NOTE: "k" is being redefined below this point. Now, it going to
  // track the no. of marked files in the "zfiles" linked list.
  // For each marked entry in "zfiles" linked list, if not deleting, check
  //   if a corresponding "external" file exists. If updating or freshening,
  //   compare date of "external" file with entry in orig zipfile. Unmark if it
  //   external file doesn't exist or is too old, else mark it. Entries that
  //   are marked will cause that file to be rezipped.
  diag("checking marked entries", pG);

  marks = 0; // Initialize marked count

  // zfiles is name of the linked-list of filenames for the archive
  #ifdef USE_STRM_INPUT
    if (!pG->UseInStream)
  #endif
  for (z = pG->zfiles; z != NULL; z = z->nxt)
  {
    if (z->mark)
    {
      ulg FileAttr;
      #ifdef USE_EF_UX_TIME
        ztimbuf f_utim, z_utim;
      #endif
      #ifdef USE_EF_UX_TIME
        if (pG->action != PURGE && ((t = filetime(z->name, &FileAttr, (long*)
          NULL, &f_utim, pG)) == 0 || t < pG->before || ((pG->action == UPDATE
          || pG->action == FRESHEN) && (get_ef_ux_ztime(z, &z_utim) ?
          f_utim.modtime <= z_utim.modtime: t <= z->tim)) || (pG->ArchiveFiles
          && pG->action == FRESHEN && !(FileAttr &A_ARCHIVE))))
        {
          z->mark = 0;
          z->trash = t && t >= pG->before; // delete if -um or -fm
          if (pG->verbose)
          {
            Inform(pG, 0, 0, "%s %s", z->name, z->trash ? "up to date" :
              "missing or early");
          }
        }
        else
          marks++;
        // incr. number of marked entries
      #else
        if (pG->action != PURGE)
        {
          t = filetime(z->name, &FileAttr, &fsz /* NULL */, NULL, pG);
          //           && (
          //               (t = filetime( z->name, &FileAttr, &fsz /*NULL*/, NULL, pG )) == 0
          if ((t == 0 || t < pG->before || ((pG->action == UPDATE || pG->action
            == FRESHEN) && t <= z->tim) || (pG->ArchiveFiles && pG->action ==
            FRESHEN && !(FileAttr &A_ARCHIVE))) || ( /* (int) */fsz <  - 2))
          // RP - check size
          {
            z->mark = 0;
            z->trash = (t && t >= pG->before) || ( /* (int) */fsz <  - 2);
              // delete if -um or -fm
            //              z->trash = t && t >= pG->before;  // delete if -um or -fm
            if (pG->verbose)
            {
              Inform(pG, 0, 0, "%s %s", z->name, z->trash ? (int)fsz <  - 2 ?
                "now too big" : "up to date": "missing or early");
              //                    z->trash ? "up to date" : "missing or early" );
            }
          }
          else
          {
            TotSize += fsz;
            TotFiles++;
            marks++;
          }
        }
        else
        // PURGE
          marks++;
        // incr. number of marked entries
      #endif
    }
  }

  #ifdef USE_STRM_INPUT
    if (pG->UseInStream)
      marks = 1;
  #endif

  // RP - verify file specified to 'Purge'
  if (pG->action == PURGE && !marks)
    return (ziperr(ZEN_NONE03, pG));

  // Remove entries from "found" linked list if: Action is PURGE or FRESHEN
  //   or No "external" matching file is found, or if found, but is too old or
  //   The external file is equal to the ziparchive name while ziparchive name
  //   != "-" If filetime() returns any valid time, then at least we know the
  //   file was found.
  diag("checking new entries", pG);

  // fileio.c built the found list
  #ifdef USE_STRM_INPUT
    if (!pG->UseInStream)
  #endif
  for (f = pG->found; f != NULL;)
  {
    int sz = 0;
    if (pG->action == PURGE || pG->action == FRESHEN || (t = filetime(f->name,
      (ulg*)NULL, &sz, (ztimbuf*)NULL, pG)) == 0
    //         || (t = filetime( f->name, ( ulg * )NULL, ( long * )NULL, ( ztimbuf * )NULL, pG )) == 0
     || t < pG->before || (namecmp(GetFullPath(pG, f->name), pG->zipfile) == 0
       && strcmp(pG->zipfile, "-")) || (sz <  - 2))
    {
      if (sz <  - 2)
        Inform(pG, ZEN_SIZE04, IWARNING, "%s is too large", f->name); 
      if (pG->verbose && t < pG->before)
      {
        Inform(pG, 0, IDIAG, "rejecting %s as too early", f->name );
      }
      if (pG->verbose < 0)
        Inform(pG, 0, IDIAG, "expel being called for %s", f->name);
      f = fexpel(f, pG); // delete an entry in the list.
    }
    else
    // file found, and not too old.
      f = f->nxt;
    // save this one, link it up.
  }

  if (pG->found == NULL)
    diag("found list empty - a", pG);
  else
    diag("found list has at least one entry - a", pG);

  if ( /* ( pG->action == UPDATE || pG->action == FRESHEN ) && */(pG->adjust <=
    0))
    pG->adjust = 0;

  // Make sure there's something left to do RP adjust always 1
  if (marks == 0 && pG->found == NULL && !(pG->zfiles != NULL && (pG->latest ||
    pG->adjust || pG->junk_sfx)))
  {
    // FOUND WAS NULL HERE, so just figure out which error message to show
    //   the user
    if (pG->action == UPDATE || pG->action == FRESHEN)
    {
      finish(pG);
      Inform(pG, 0, IWARNING, "no files %s", (pG->action == UPDATE) ? "updated"
        : "freshened");
      return 0;
    }
    else if (pG->zfiles == NULL && (pG->latest || pG->adjust || pG->junk_sfx))
    {
      return (ziperr(ZEN_NAME01, pG));
    }
    else if (pG->recurse && (pG->pcount == 0) && (!pG->doall))
    //first_listarg > 0) )
    {
      // add the list of filenames from cmd line to error msg
      ///      for ( i = first_listarg; i < argc; i++ )
      ///        lstrcat( lstrcat( pG->errbuf, " " ), argv[i] );
      return (ziperr(ZEN_NONE01, pG));
    }
    else
      return (ziperr(ZEN_NONE02, pG));
  }

  // AllowGrow is false if writing temporary file
  pG->AllowGrow = (pG->AllowGrow && (marks == 0)
    // is allowed and no changes to existing
   && (pG->zipbeg || pG->zfiles != NULL) // something to append to
  );

  // continue on to add new files
  a = 0;

  // ignore self-extracting code in front of the zip file (for -J)
  if (pG->junk_sfx)
    pG->zipbeg = 0;

  // Count files and sizes which we have to Keep; RP Added
  w = &pG->zfiles;
  while ((z =  *w) != NULL)
  {
    if (pG->global_abort_sw)
      return (ziperr(ZEN_ABORT, pG));
    if (!z->mark)
    {
      KeptSize += (z->siz + (ulg)(4+LOCHEAD) + (ulg)z->nam + (ulg)z->ext);
      if (z->lflg &8)
        KeptSize += 16;
      KeptCnt++;
    }

    w = &z->nxt;
  }

  //Inform( pG, 0, IDIAG, "Kept = %u %Lu Total = %u %Lu", KeptCnt, KeptSize, TotFiles, TotSize );
  // Count files and sizes which we have to process; RCV Added
  // First the files in the old zip file...
  // RP - already calculated with new sizes
  // And the found list...
  for (f = pG->found; f != NULL; f = f->nxt)
  {
    if (pG->global_abort_sw)
      return (ziperr(ZEN_ABORT, pG));
    TotSize += f->len;
    TotFiles++;
  }
  //    Inform( pG, 0, IDIAG, "Found = %u %u", tc, ts );
  // OPEN ZIP FILE and temporary output file
  //  diag( "opening zip file and creating temporary zip file", pG );
  pG->hInz = INVALID_HANDLE_VALUE; //0;
  pG->hTempzf = INVALID_HANDLE_VALUE;
  pG->tempzn = 0;


  if (!pG->AllowGrow)
  {
    // check file exists
    No_File = access(pG->zipfile, 0) && errno == ENOENT;
    if (No_File && DestType == DRIVE_FIXED || DestType == DRIVE_RAMDISK)
    {
      // create file using given name
      diag("in dllzip - ready to create new file", pG);
      if ((pG->hOutz = CreateFile(pG->zipfile, GENERIC_WRITE, 0, NULL,
        CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL)) !=
        INVALID_HANDLE_VALUE)
      {
        pG->tempzip = pG->zipfile;

        pG->hTempzf = pG->hOutz;
        pG->AllowGrow =  - 1; // new files do grow
      }
    }
  }

  if (pG->AllowGrow > 0)
  {
    // zipfile is not stdout, and we are allowed to append
    // AllowGrow is true if we're just appending (-g)
    diag("in dllzip - ready to open for appending", pG);
    if ((pG->hOutz = CreateFile(pG->zipfile, GENERIC_READ | GENERIC_WRITE, 0,
      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
      NULL)) == INVALID_HANDLE_VALUE)
      return (ziperr(ZEN_NAME02, pG));
    pG->tempzip = pG->zipfile;

    pG->hTempzf = pG->hOutz;

    /* long */
    hi = 0;
    if (SetFilePointer(pG->hOutz, pG->cenbeg, &hi, FILE_BEGIN) ==
      INVALID_SET_FILE_POINTER && GetLastError())
      return (ziperr(GetLastError() ? ZEN_READ01 : ZEN_EOF01, pG));
    pG->tempzn = pG->cenbeg;
  }

  if (!pG->AllowGrow)
  {
    diag("in dllzip - ready to open for Exclusive Read", pG);
    if ((pG->zfiles != NULL || pG->zipbeg) && (pG->hInz = CreateFile(pG
      ->zipfile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL |
      FILE_FLAG_SEQUENTIAL_SCAN, NULL)) == INVALID_HANDLE_VALUE)
      return (ziperr(ZEN_NAME03, pG));
    if ((pG->tempzip = tempname(pG)) == NULL)
      return (ziperr(ZEN_MEM11, pG));

    //		if (pG->Verbose)
    Inform(pG, 0, IDIAG, "Temp Filename = %s", pG->tempzip);
    if ((pG->hTempzf = pG->hOutz = CreateFile(pG->tempzip, GENERIC_WRITE, 0,
      NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS |
      FILE_ATTRIBUTE_TEMPORARY, NULL)) == INVALID_HANDLE_VALUE)
      return (ziperr(ZEN_TEMP01, pG));
  }

  if (!pG->AllowGrow)
  {
    TotFiles += KeptCnt;
    TotSize += KeptSize;
  }
  // Pass total number of files and Total Filesize.    (moved)
  user_callback(zacCount, 0, TotFiles, NULL, pG);
  user_callback(zacSize, (long)(TotSize >> 32), ((unsigned)TotSize), NULL, pG);
  pG->BatchStarted = 1;

  if (!pG->AllowGrow && pG->zipbeg)
  {
    // copy a compressed file from old archive to new archive
    user_callback(zacItem, 0, pG->zipbeg, "SFX", pG);
    if ((r = fcopy(pG->hInz, pG->hOutz, pG->zipbeg, pG)) != ZEN_OK)
      return (ziperr(r, pG));
    pG->tempzn = pG->zipbeg;
  }

  // o = 0; /* no ZEN_OPEN errors yet
  // Process zip file, copying from old archive to new archive. Rezip any
  //   marked files
  if (pG->zfiles != NULL)
    diag("going through old zip file", pG);
  w = &pG->zfiles;

  while ((z =  *w) != NULL)
  {
    if (pG->global_abort_sw)
    {
      return (ziperr(ZEN_ABORT, pG));
    }

    if (z->mark == 1)
    {
      // This file is marked
      // if not deleting, rezip it
      if (pG->action != PURGE)
      {
        Inform(pG, 0, 0, "updating: %s", Oem2Iso(z->zname, pG));

        // zipup is in file zipup.c
        if ((r = zipup(z, pG->hOutz, pG)) != ZEN_OK && (int)(char)(r &0xFF) !=
          ZEN_OPEN && (int)(char)(r &0xFF) != ZEN_MISS)
        {
          return (ziperr(r, pG));
        }

        if ((int)(char)(r &0xFF) == ZEN_OPEN || (int)(char)(r &0xFF) ==
          ZEN_MISS)
        {
          if ((int)(char)(r &0xFF) == ZEN_OPEN)
          {
            Inform(pG, r, IWARNING, "could not open for reading: %s", z->name);
            user_callback(4, r, 0, z->name, pG);
          }
          else
          {
            Inform(pG, 0, IWARNING, "file and directory with the same name: %s",
              z->name);
            user_callback(4, r, 0, z->name, pG);
          }

          Inform(pG, 0, IWARNING, "will just copy entry over: %s", z->zname);

          if ((r = zipcopy(z, pG->hInz, pG->hOutz, pG)) != ZEN_OK)
          {
            sprintf(pG->errbuf, "was copying %s", z->zname);
            return (ziperr(r, pG));
          }

          z->mark = 0;
        }

        w = &z->nxt;
        pG->files_acted_on++;
      }
      else
      {
        // desired action is DELETE, this file marked
        // NOTE: no progress bar supt for DELETE yet
        Inform(pG, 0, 0, "deleting: %s", Oem2Iso(z->zname, pG));

        v = z->nxt; // delete entry from list
        FREE(z->name);
        FREE(z->zname);
        if (z->ext)
          FREE(z->extra);
        if (z->cext && z->cextra != z->extra)
          FREE(z->cextra);
        if (z->com)
          FREE(z->comment);
        FREE(z);
        *w = v;
        pG->zcount--;
        pG->files_acted_on++;
      }
    }
    else
    {
      // this file wasn't marked
      // copy the original entry verbatim
      if (!pG->AllowGrow)
      {
        Inform(pG, 0, 0, "keeping: %s", Oem2Iso(z->zname, pG));
        if ((r = zipcopy(z, pG->hInz, pG->hOutz, pG)) != ZEN_OK)
        {
          sprintf(pG->errbuf, "was copying %s", z->zname);

          // user_callback ( zacEndOfBatch, 0, 0, NULL, pG ); // done with a
          // batch of files
          return (ziperr(r, pG));
        }
      }
      w = &z->nxt;
    }
  } // end while

  // Process the "found" list, adding them to the zip file.
  // This is used to add files that weren't already in the archive.
  if (pG->verbose)
  {
    Inform(pG, 0, IDIAG, "Zipping up %d NEW entries from found list", pG
      ->fcount);
  }

  // For each new file to add (src names in found list), make a new entry
  //   for it in the "zfiles" linked list, zip up the new file, then remove the
  //   entry from the found list.
  // The last item in the for loop control deallocates spc for fname that
  //   was just zipped up
  for (f = pG->found; f != NULL; f = fexpel(f, pG))
  {
    // add a new entry to "zfiles" list, before we zip up the file. That way
    //   we'll be ready to update the ZIP file's directory later.
    if (pG->global_abort_sw)
    {
      // user_callback ( zacEndOfBatch, 0, 0, NULL, pG ); // done with a
      // batch of files
      return (ziperr(ZEN_ABORT, pG));
    }

    if ((z = (struct zlist*)MALLOC(sizeof(struct zlist))) == NULL)
    {
      return (ziperr(ZEN_MEM12, pG));
    }

    // RP 1.73 clear all fields
    memset(z, 0, sizeof(struct zlist));

    // Similar names below are confusing: f->name f->zname z->name z->zname
    // z z->nxt = NULL;
    z->name = f->name;
    f->name = NULL;

    z->zname = f->zname;
    f->zname = NULL;

    // z z->ext = z->cext = z->com = 0;
    // z z->extra = z->cextra = z->comment = NULL;
    // pRP173 z->ext = strlen( f->passw ); //Added RAEL
    // pRP173 z->extra = f->passw; //Added RAEL for per file password
    z->passw = f->passw; // p
    f->passw = NULL; // Added RAEL
    z->mark = 1;
    z->dosflag = f->dosflag;
    z->len = f->len; // RCV added.

    // zip it up
    Inform(pG, 0, 0, "  adding: %s", Oem2Iso(z->zname, pG));

    // This is it - try to zip up new file
    if ((r = zipup(z, pG->hOutz, pG)) != ZEN_OK && (int)(char)(r &0xFF) !=
      ZEN_OPEN && (int)(char)(r &0xFF) != ZEN_MISS)
    {
      return (ziperr(r, pG));
    }

    if ((int)(char)(r &0xFF) == ZEN_OPEN || (int)(char)(r &0xFF) == ZEN_MISS)
    {
      // o = 1;
      if ((int)(char)(r &0xFF) == ZEN_OPEN)
      {
        Inform(pG, r, IWARNING, "could not open for reading: %s", z->name);
      }
      else
      {
        Inform(pG, 0, IWARNING, "file and directory with the same name: %s", z
          ->name);
      }

      FREE(z->name);
      FREE(z->zname);
      FREE(z);
    }
    else
    {
      // "zipup" of this file was good
      *w = z;
      w = &z->nxt;
      pG->zcount++;
      pG->files_acted_on++;
    }
  }

  // Write central directory and end header to temporary zip
  diag("writing central directory", pG);
  hi = 0;
  ofs = SetFilePointer(pG->hOutz, 0, &hi, FILE_CURRENT);
  if (hi || (ofs > 0xFFFFFFF0u) || (ofs == INVALID_SET_FILE_POINTER &&
    GetLastError()))
  {
    return ziperr(ZEN_SIZE01, pG);
  }

  k = 0; // keep count of new fnames for ZIPfile's end header
  c = pG->tempzn; // get start of central directory
  n = t = 0;
  altered = 0; // RP 173 - count changes
  for (z = pG->zfiles; z != NULL; z = z->nxt)
  {
    // Handle callback and result for the filecomments... DLL v1.609,
    // Component v1.60L
    if (pG->action != PURGE)
    {
      memset(pG->ewetmp, 0, 513); // Clear all
      strncpy(pG->ewetmp, z->zname, 255); // Copy external filename
      if (z->com)
      // Copy old comment if present
        strncpy(pG->ewetmp + 256, z->comment, min(z->com, 255));
      else
        z->comment = 0;
      user_callback(12, 0, z->com, pG->ewetmp, pG);
      if (pG->callbackdata.error_code)
      {
        // User changed the comment
        FREE(z->comment);
        z->com = pG->callbackdata.fsize;
        if ((z->comment = (char*)MALLOC(z->com + 1)) == NULL)
          return (ziperr(ZEN_MEM37, pG));
        strncpy(z->comment, pG->callbackdata.filenameormsg, z->com + 1);
        altered++;
      }
    }

    if (pG->files_acted_on < altered)
    // RP 173 - comments changed is acted on
      pG->files_acted_on = altered;

    if ((r = putcentral(z, pG->hOutz, pG)) != ZEN_OK)
    {
      // v1.6014
      return (ziperr(r, pG));
    }

    pG->tempzn += 4+CENHEAD + z->nam + z->cext + z->com;
    n += z->len;
    t += z->siz;
    k++;
  }

  if (k == 0)
    Inform(pG, 0, IWARNING, "zip file empty");

  if ((pG->verbose) && (pG->action == ADD) && (!pG->global_error_code) && (pG
    ->files_acted_on > 0))
  {
    Inform(pG, 0, 0, "Total Bytes=%lu, compr bytes=%lu -> %d%% savings", n, t,
      percent(n, t));
  }

  t = pG->tempzn - c; // compute length of central
  diag("writing end of central directory", pG);

  if (k && ((r = putend(k, t, c, pG->hOutz, pG)) != ZEN_OK))
  {
    return (ziperr(r, pG));
  }

  //       if ( pG->hInz != INVALID_HANDLE_VALUE )
  //       {
  Close_Handle(&pG->hInz);
  //         pG->hInz = INVALID_HANDLE_VALUE;
  //       }

  // pG->tempzf = NULL;
  // if ( fclose ( pG->y ) )
  pG->hTempzf = INVALID_HANDLE_VALUE; //NULL;
  //       if ( pG->hOutz != INVALID_HANDLE_VALUE && !CloseHandle( pG->hOutz ) )
  if (!Close_Handle(&pG->hOutz))
  {
    return (ziperr(pG->AllowGrow ? ZEN_WRITE03 : ZEN_TEMP02, pG));
  }

  //       pG->hOutz = INVALID_HANDLE_VALUE;

  #ifdef DYN_ALLOC
    lm_free(pG);
  #endif

  //  if ( pG->verbose )
  //    Inform( pG, 0, IDIAG, "Files closed in: %X out: %x", pG->hInz, pG->hOutz );
  // Replace old zip file with new zip file, leaving only the new one
  //  if ( !pG->AllowGrow )     // && lstrcmp(pG->zipfile, pG->tempzip))
  if (!pG->AllowGrow && (k || pG->action != PURGE))
  // && lstrcmp(pG->zipfile, pG->tempzip))
  {
    diag("replacing old zip file with new zip file", pG);
    if ((r = replace(pG->zipfile, pG->tempzip, pG)) != ZEN_OK)
    {
      Inform(pG, 0, IWARNING, "new zip file left as: %s", pG->tempzip);
      FREE(pG->tempzip);
      pG->tempzip = NULL;

      return (ziperr(r, pG));
    }

    FREE(pG->tempzip);
    pG->tempzip = NULL;
  }

  // 1.78.1.2
  if (!k && pG->action == PURGE)
  // empty file - remove
  {
    a = pG->latest = 0;
    DeleteFile(pG->zipfile);
    if (!pG->AllowGrow)
      DeleteFile(pG->tempzip);
  }

  pG->tempzip = NULL;
  if (a)
    setfileattr(pG->zipfile, a);

  // Reset the archive bit when needed for all successfull zipped files
  if (pG->ResetArchiveBit && pG->action != PURGE)
  {
    unsigned cnt = 0; // 1.71.0.0 added extra callbacks
    diag("resetting archive bits", pG);
    for (z = pG->zfiles; z != NULL; z = z->nxt)
      if (z->mark)
        cnt++;
    if (cnt)
    {
      // new file op.
      // Pass total number of files. filesize.
      user_callback(zacXItem, 1, cnt, "*resetting archive bits", pG);
    }

    cnt = 0;
    for (z = pG->zfiles; z != NULL; z = z->nxt)
    {
      if (z->mark)
      {
        char *fullname;
        if (++cnt == 30)
        {
          user_callback(zacXProgress, 1, cnt, "", pG);
          cnt = 0;
          if (pG->global_abort_sw)
            break;
        }

        fullname = GetFullPath(pG, z->name); // v.16017
        if (!SetFileAttributes(fullname, GetFileAttributes(fullname)
          &~FILE_ATTRIBUTE_ARCHIVE))
        {
          Inform(pG, 0, IWARNING, "Archive bit could not be set for: %s", z
            ->name);
        }
      }
    }

    if (cnt)
    {
      user_callback(zacXProgress, 1, cnt, "", pG); // last few
    }
  }

  finish(pG);
  return 0;
}
Esempio n. 14
0
static int real_archive_files (const char *targ, const char **filenames, 
			       int level, ZipOption opt, int task,
			       GError **gerr)
{
    int attr;             /* attributes of zip file */
    flist *f;             /* steps through found linked list */
    int i;                /* arg counter, root directory flag */
    int k;                /* marked counter, comment size, entry count */
    int openerr = 0;      /* true if there were any ZE_OPEN errors */
    guint32 t;            /* file time, length of central directory */
    zlist **w;            /* pointer to last link in zfiles list */
    zlist *z;             /* steps through zfiles linked list */
    FILE *fr = NULL;      /* for reading from original zipfile */
    char tempzip[FILENAME_MAX]; /* name for temporary zipfile */
    int err = 0;
    zfile zf;

    *tempzip = '\0';

    if (level < 0 || level > 9) {
	fprintf(stderr, "invalid compression level %d: setting to 6\n", level);
	level = 6;
    }

    zfile_init(&zf, level, opt);

    trace(1, "real_archive_files: targ = '%s'\n", targ);

    zf.fname = g_strdup(targ);
    if (zf.fname == NULL) {
	err = ziperr(ZE_MEM, "was processing arguments");
	goto bailout;
    }

    if (task != ZIP_DO_NEW) {
	/* if ZIP_DO_NEW, disregard any existing zipfile */
	err = read_zipfile(&zf, ZIP_DO_ZIP);
	if (err) {
	    err = ziperr(err, zf.fname);
	    goto bailout;
	}
    } 

    /* assemble list of filenames to be added/updated */
    k = 0;
    for (i=0; filenames[i] != NULL; i++) {
	if (!gretl_file_test(filenames[i], G_FILE_TEST_EXISTS)) {
	    err = ziperr(ZE_OPEN, "file '%s' was not found", filenames[i]);
	    goto bailout;
	}
	err = add_filenames(filenames[i], &zf);
	if (err) {
	    ziperr(err, filenames[i]);
	    goto bailout;
	} else {
	    k++;
	}
    }

    if (k == 0) {
	err = ziperr(ZE_NONE, NULL);
	goto bailout;
    }

    if (zf.zcount) {
	free(zf.zsort);
	zf.zsort = NULL;
    }

    /* For each marked entry, check if it exists, and, if updating,
       compare date with entry in existing zipfile.  Unmark if it
       doesn't exist or is too old, else update marked count.
    */
    k = 0; 
    for (z = zfiles; z != NULL; z = z->nxt) {
	if (z->mark == MARK_ZIP) {
	    if (dont_keep_file(z, &zf)) {
		z->mark = MARK_NONE;
	    } else {
		k++;
	    }
	}
    }

    /* Remove entries from "found" list that do not exist or are
       otherwise invalid
    */
    for (f = found; f != NULL; ) {
	t = file_mod_time(f->name, NULL, NULL, NULL, &zf);
	if (t == 0 || !fnamecmp(f->zname, zf.fname)) {
	    f = flist_expel(f, &zf.fcount);
	} else {
	    f = f->nxt;
	}
    }

    err = zipfile_write_check(&zf, task, &attr);
    if (err) {
	goto bailout;
    }

    if (zfiles != NULL || zf.zstart) {
	trace(1, "opening original zip file for reading\n");
	fr = fopen(zf.fname, "rb");
	if (fr == NULL) {
	    err = ziperr(ZE_NAME, zf.fname);
	    goto bailout;
	}
    }

    strcpy(tempzip, zf.fname);
    zf.fp = ztempfile(tempzip);
    if (zf.fp == NULL) {
	fprintf(stderr, " real_archive_files: ztempfile failed\n");
	err = ziperr(ZE_TEMP, tempzip);
	goto bailout;
    }

    if (zf.zstart > 0) {
	/* copy initial chunk of old zipfile as is */
	err = fcopy(fr, zf.fp, zf.zstart);
	if (err != Z_OK) {
	    err = ziperr(err, (err == ZE_TEMP)? tempzip : zf.fname);
	    goto bailout;
	}
    }

    zf.tempzn = zf.zstart;
    trace(2, "after initial read, tempzn = %d\n", (int) zf.tempzn);

    err = process_zfiles(&zf, fr, &w, &openerr);
    if (err) {
	fclose(zf.fp);
	if (fr != NULL) {
	    fclose(fr);
	}
	goto bailout;
    }

    /* Process the edited found list, adding them to the zip file */
    trace(2, "now zipping up new entries, fcount=%u\n", (unsigned) zf.fcount);
  
    for (f = found; f != NULL; f = flist_expel(f, &zf.fcount)) {
	/* add a new zfiles entry and set the name */
	z = zlist_entry_new(f);
	if (z == NULL) {
	    err = ziperr(ZE_MEM, "was adding files to zip file");
	    goto bailout;
	}	    

	err = zipup(&zf, z);

	if (err && err != ZE_OPEN && err != ZE_MISS) {
	    err = ziperr(err, "was zipping %s", z->zname);
	    goto bailout;
	}

	if (err == ZE_OPEN || err == ZE_MISS) {
	    openerr = 1;
	    if (err == ZE_OPEN) {
		perror("zip warning");
	    } 
	    free_zlist_entry(z);
	} else {
	    *w = z;
	    w = &z->nxt;
	    zf.zcount += 1;
	}
    }

    err = write_central_and_end(&zf, tempzip);
    fclose(zf.fp);
    zf.fp = NULL;

    if (fr != NULL) {
	fclose(fr);
    }

    /* Replace old zip file with new zip file, leaving only the new one */
    if (!err) {
	trace(1, "moving %s into position as %s\n", tempzip, zf.fname);
	err = replace_file(zf.fname, tempzip);
	if (err) {
	    ziperr(err, "was replacing %s", zf.fname);
	} else if (attr) {
	    chmod(zf.fname, attr);
	}
    }

 bailout:

    zlib_deflate_free(&zf);

    if (err && *tempzip != '\0') {
	/* clean up */
	gretl_remove(tempzip);
    }

    zip_finish(&zf);

    if (err && gerr != NULL) {
	make_gerr(err, gerr);
    }

    trace(1, "returning err = %d\n", err);

    return err;
}
Esempio n. 15
0
// Process -o and -m options (if specified), free up malloc'ed stuff, and
//   exit with the code e. e :: Exit code.
static void finish(struct Globals *pG)
{
  int r; // return value from trash()
  ulg t; // latest time in zip file
  struct zlist *z; // pointer into zfile list

  // If latest, set time to zip file to latest file in zip file
  if (pG->latest && pG->zipfile && strcmp(pG->zipfile, "-"))
  {
    diag("changing time of zip file to time of latest file in it", pG);

    // find latest time in zip file
    if (pG->zfiles == NULL)
    {
      Inform(pG, 0, IWARNING,
        "zip file is empty, can't make it as old as latest entry");
    }
    else
    {
      t = 0;
      for (z = pG->zfiles; z != NULL; z = z->nxt)
      // Ignore directories in time comparisons
      #ifdef USE_EF_UX_TIME
        if (z->zname[z->nam - 1] != '\\')
        {
          // SLASH
          ztimbuf z_utim;
          ulg z_tim;

          z_tim = (get_ef_ux_ztime(z, &z_utim) ? unix2dostime(&z_utim.modtime):
            z->tim);
          if (t < z_tim)
            t = z_tim;
        }

      #else
        if (z->zname[z->nam - 1] != '\\' && t < z->tim)
          t = z->tim;
        // SLASH
      #endif

      // set modified time of zip file to that time
      if (t != 0)
        stamp(pG->zipfile, t);
      else
      {
        Inform(pG, 0, IWARNING,
          "zip file has only directories, can't make it as old as latest entry")
          ;
      }
    }
  }

  if (pG->tempath != NULL)
  {
    FREE(pG->tempath);
    pG->tempath = NULL;
  }

  if (pG->zipfile != NULL)
  {
    FREE(pG->zipfile);
    pG->zipfile = NULL;
  }

  // If dispose, delete all files in the zfiles list that are marked
  if (pG->dispose && !pG->global_abort_sw)
  {
    // v1.6017
    diag("deleting files that were added to zip file", pG);
    if ((r = trash(pG)) != ZEN_OK)
      ziperr(r, pG);
    return ;
  }

  #ifdef CRYPT                  // RCV: 1.604 added
    if (pG->user_key)
    // p release user password
    {
      FREE(pG->user_key);
      pG->user_key = NULL;
    }

  #endif

  // Done!
  freeup(pG);
}
Esempio n. 16
0
/* ===========================================================================
 * If not in exclude mode, expand the pattern based on the contents
 * of the file system.
 * This function is used while gathering filenames to be added or updated
	*w :: Path/pattern to match.
   Possible return values: ZEN_MISS, ZEN_OK, ZEN_ABORT, ZEN_MEM or ZEN_PARMS.
 */
int Wild( char *w, struct Globals *pG ) {
	zDIR *d;                   /* Stream for reading directory       */
	char *e;                   /* File or directory name found.      */
	char *n;                   /* Constructed name from directory    */
	int   WError;              /* Result of Wild()                   */
	char *p, *a;               /* path originale and fixed.          */
	char *q;                   /* Filename / pattern.                */
	int   r;                   /* Result / temp var.                 */
	char  v[5];                /* space for device current directory.*/
	bool  StopRecurs = false;  /* No recursion if filespec is file.  */

	//	sprintf( pG->ewemsg, "in Wild of win32zip.c, pattern=%s recurse=%d", w, pG->recurse );
	//	diag( pG->ewemsg, pG );

	// "zip -$ foo a:" can be used to force a drive name once. 	// v1.6017
	if ( pG->volume_label == 1 ) {
		pG->volume_label = 2;
		pG->label = getVolumeLabel( pG, (w != NULL && w[ 1 ] == ':') ? to_up( w[ 0 ] ) : '\0', &pG->label_time, &pG->label_mode, &pG->label_utim );
		if ( pG->label != NULL )
			(void)newname( pG->label, 0, pG );
		if ( w == NULL || (w[1] == ':' && w[2] == '\0') ) return ZEN_OK;
	}

	/* Allocate and copy pattern */
	if ( (p = a = MALLOC( lstrlen( w ) + 1) ) == NULL ) return ZEN_MEM19;
	lstrcpy( p, w );

	/* Separate path and name into p and q */
   // We have '\' or '\name' or 'path1\path2\name2' or 'C:\path\name' but NOT 'C:\name'
	if ( (q = strrchr( p, '\\' )) != NULL && (q == p || q[-1] != ':') ) {		// SLASH
		*q++ = '\0';
		if ( *p == '\0' ) p = lstrcpy( v, "\\." );	   /* if path is just '\' SLASH               */
	} else if ( (q = strrchr( p, ':' )) != NULL ) {	/* We have 'C:' or 'C:\' or 'C:\name' */
		*q++ = '\0';
		p = lstrcat( lstrcpy( v, p ), ":" );          /* copy device as path eg. 'C:'       */
		if ( *q == '\\' ) {                          /* -> device:/., name  eg. 'C:\.' SLASH     */
			lstrcat( p, "\\" );		// SLASH
			q++;										         /* name or nothing.                   */
		}
		lstrcat( p, "." );   						         /* eg. 'C:.' or 'C:\.'                */
	} else if ( pG->recurse && (!strcmp( p, "." ) || !strcmp( p, ".." )) ) {
		/* current or parent directory */
		/* Get "zip -r foo ." to work. Allow the dubious "zip -r foo .." but
		 * reject "zip -r -m foo ..".  "dispose" means wipe out source path.
		 */
		if ( pG->dispose && !strcmp( p, ".." ) ) ziperr( ZEN_PARMS15, pG );
		q = (char *)pG->wild_match_all;
	}
	else {  /* no path or device */
		q = p;
		p = lstrcpy( v, "." );
	}
	if ( pG->recurse && *q == '\0' ) q = (char *)pG->wild_match_all;
	/* take out a possibly redundant dir name of "." */
	if ( (r = lstrlen( p )) > 1 && (strcmp( p + r - 2, ":." ) == 0 || strcmp( p + r - 2, "\\." ) == 0) )	// SLASH
		*(p + r - 1) = '\0';

	/* Only filename (not the path) can have special matching characters */
	if ( IsShExp( p ) ) {
		diag( "path has illegal chars", pG );
		FREE( a );
		return ZEN_PARMS16;
	}
	// sprintf( ewemsg, "at break up place in Wild: path=%s  name=%s", p, q );
	// diag( ewemsg );

	if ( !IsShExp( q ) ) {	// Speed up checking if file exits in case there are no wildcards
		struct stat s;       // and no recursion and no archiving v1.6016

		if ( !pG->recurse && !pG->ArchiveFiles ) {
			if ( !LSSTAT( GetFullPath( pG, w ), &s ) )                 /* file exists ? */
				return procname( w, false, pG );
			return ZEN_MISS02;                      /* woops, no wildcards where is the file! */
		}
		if ( pG->norecursefiles ) StopRecurs = true;
	}

	/* Now that we have a dir spec, along with an fspec, we'll step
	 * in the dir specified to see if there's any matches against the fspec.
	 */
	WError = ZEN_MISS02;
	if ( (d = Opendir( p, pG )) != NULL ) {
		while ( (e = readd( d, pG )) != NULL ) {
			if ( pG->global_abort_sw ) {
				WError = ZEN_ABORT;
				break;
			}
			// sprintf( ewemsg, "Found %s: %s", d->d_attr & FILE_ATTRIBUTE_DIRECTORY ? "directory" : "file", e );
			// diag( ewemsg );
			/* if e is NOT '.' or '..', and is a dir or match fspec. */
			if ( strcmp( e, "." ) && strcmp( e, ".." ) && (d->d_attr & FILE_ATTRIBUTE_DIRECTORY || dosmatch( q, e, pG )) ) {
				// diag( "Matched" );
				/* we matched fspec or it's a dir and entry is not '.' or '..' */
				if ( d->d_attr & FILE_ATTRIBUTE_DIRECTORY ) {
					// We do not save dirs or go into dirs if norecursefiles==1 and we a file without * or ? specs.
					if ( !StopRecurs && (pG->dirnames || pG->recurse) ) {
						if ( (n = MALLOC( lstrlen( p ) + lstrlen( e ) + lstrlen( q ) + 3 )) == NULL ) {
							WError = ZEN_MEM20;
							break;
						}
						*n = '\0';
						if ( *p != '.' ) AddSlash( lstrcpy( n, p ) );	// No ./ as first dir.
						lstrcat( n, e );
						if ( pG->dirnames ) {		// Save directory names also.
							r = procname( n, false, pG );
							if ( (int)(char)(r & 0xFF) > ZEN_OK || !pG->recurse ) FREE( n );
							if ( (int)(char)(r & 0xFF) > (int)(char)(WError & 0xFF) ) WError = r;
							if ( (int)(char)(r & 0xFF) > ZEN_OK ) break;
						}
						if ( pG->recurse ) {	// Recursively go into dir and check for other pattern matches.
							r = Wild( lstrcat( AddSlash( n ), q ), pG );	// Add the original pattern.
							FREE( n );
							// We keep a ZEN_OK even when ZEN_MISS occurs.
							if ( (int)(char)(r & 0xFF) > (int)(char)(WError & 0xFF) ) WError = r;
							if ( (int)(char)(r & 0xFF) > ZEN_OK ) break;						// An error, stop processing.
						}
   		      }
				} else {
					if ( (n = MALLOC( lstrlen( p ) + lstrlen( e ) + 2 )) == NULL ) {
						WError = ZEN_MEM21;
						break;
					}
					if ( !strcmp( p, "." ) ) r = procname( e, false, pG );
					else r = procname( lstrcat( AddSlash( lstrcpy( n, p ) ), e ), false, pG );
					FREE( n );
					if ( (int)(char)(r & 0xFF) > (int)(char)(WError & 0xFF) ) WError = r;
					if ( (int)(char)(r & 0xFF) > ZEN_OK ) break;
				}
			} /* end "if (strcmp..." */
		} /* end while */
		Closedir( d );
	} else diag( "can't open dir", pG );
	FREE( a );
	// sprintf( ewemsg, "Wild returned: %d", WError );
	// diag( ewemsg );
	return WError;
}
Esempio n. 17
0
/* ===========================================================================
 * Internal error, should never happen.
 */
void error( char *h, struct Globals *pG ) {
	diag( h, pG );
	ziperr( ZEN_LOGIC04, pG );
}
Esempio n. 18
0
/* ===========================================================================
 * Initialize the "longest match" routines for a new file
 *
 * IN assertion: window_size is > 0 if the input file is already read or
 *    mmap'ed in the window[] array, 0 otherwise. In the first case,
 *    window_size is sufficient to contain the whole input file plus
 *    MIN_LOOKAHEAD bytes (to avoid referencing memory beyond the end
 *    of window[] when looking for matches towards the end).
 */
void IZDeflate::lm_init (int pack_level, ush *flags)
    //int pack_level; /* 0: store, 1: best speed, 9: best compression */
    //ush *flags;     /* general purpose bit flag */
{
    unsigned j;

    if (pack_level < 1 || pack_level > 9) error("bad pack level");

    /* Do not slide the window if the whole input is already in memory
     * (window_size > 0)
     */
    sliding = 0;
    if (window_size == 0L) {
        sliding = 1;
        window_size = (ulg)2L*WSIZE;
    }

    /* Use dynamic allocation if compiler does not like big static arrays: */
#ifdef DYN_ALLOC
    if (window == NULL) {
        window = (uch *) zcalloc(WSIZE,   2*sizeof(uch));
        if (window == NULL) ziperr(ZE_MEM, "window allocation");
    }
    if (prev == NULL) {
        prev   = (Pos *) zcalloc(WSIZE,     sizeof(Pos));
        head   = (Pos *) zcalloc(HASH_SIZE, sizeof(Pos));
        if (prev == NULL || head == NULL) {
            ziperr(ZE_MEM, "hash table allocation");
        }
    }
#endif /* DYN_ALLOC */

    /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
     * prev[] will be initialized on the fly.
     */
    head[HASH_SIZE-1] = NIL;
    memset((char*)head, NIL, (unsigned)(HASH_SIZE-1)*sizeof(*head));

    /* Set the default configuration parameters:
     */
    max_lazy_match   = configuration_table[pack_level].max_lazy;
    good_match       = configuration_table[pack_level].good_length;
#ifndef FULL_SEARCH
    nice_match       = configuration_table[pack_level].nice_length;
#endif
    max_chain_length = configuration_table[pack_level].max_chain;
    if (pack_level <= 2) {
       *flags |= FAST;
    } else if (pack_level >= 8) {
       *flags |= SLOW;
    }
    /* ??? reduce max_chain_length for binary files */

    strstart = 0;
    block_start = 0L;
#if defined(ASMV) && !defined(RISCOS)
    match_init(); /* initialize the asm code */
#endif

    j = WSIZE;
#ifndef MAXSEG_64K
    if (sizeof(int) > 2) j <<= 1; /* Can read 64K in one step */
#endif
    lookahead = (*read_buf)(read_handle, (char*)window, j);

    if (lookahead == 0 || lookahead == (unsigned)EOF) {
       eofile = 1, lookahead = 0;
       return;
    }
    eofile = 0;
    /* Make sure that we always have enough lookahead. This is important
     * if input comes from a device such as a tty.
     */
    if (lookahead < MIN_LOOKAHEAD) fill_window();

    ins_h = 0;
    for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
    /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
     * not important since only literal bytes will be emitted.
     */
}
Esempio n. 19
0
/* =========================================================================== select files to be processed */
int ZipSelect(struct Globals *pG, const ZCL2 *C)
{
  int i; // arg counter, root directory flag
  int k; // next argument type, marked counter,

  const char *p; // steps through option arguments
  int r; // temporary variable
  long g_before; // 1.74 global 'before'
  int argno, arg1;


  if ((p = getenv("TZ")) == NULL ||  *p == '\0')
    pG->extra_fields = 0;
  // disable storing "Unix" time stamps

  SetExclFilters(pG);
  // Process arguments
  diag("ready to read zip file", pG);

  // the read will be done in file: zipfile.c
  if ((r = readzipfile(pG)) != ZEN_OK)
  {
    diag("err returned from \"readzipfile\"", pG);
    return (ziperr(r, pG));
  }

  if (pG->action == UPDATE || pG->action == FRESHEN)
    pG->doall = 1;
  r = 0;
  arg1 =  - 1;
  g_before = pG->before;
  for (argno = 0; !r && argno < C->fTotFileSpecs; argno++)
  {
    char *fspec;
    FileData *fileArg = &C->fFDS[argno];
    if (!fileArg)
      continue;
    fspec = fileArg->fFileSpec;
    if (!fspec ||  *fspec == '>')
      continue;
    pG->FileArg = fileArg;
    pG->key = 0; //pG->user_key;   // set globals
    pG->recurse = fileArg->fRecurse;
    r = C->fLevel;
    r = r < 0 ? 0 : (r > 9 ? 9 : r);
    if (r != pG->level)
    {
      pG->level = r;
      pG->method = r ? DEFLATE : STORE;
      if (pG->verbose)
        Inform(pG, 0, IDIAG, "setting compression level to %d", r);
    }
    // Set the new RootDir if needed; DLL v1.608, Component v1.60L
    if (fileArg->fRootDir)
    {
      // We can't use SetCurrentDirectory() because there is only one cd
      // in each process
      // when a user uses threads it went wrong.
      FREE(pG->OrigCurrentDir); // DLL v1.6017

      pG->OCDlength = lstrlen(fileArg->fRootDir);
      if ((pG->OrigCurrentDir = (char*)MALLOC(pG->OCDlength + 2)) == NULL)
      {
        // RP allow space for '\'
        Inform(pG, ZEN_MEM36, 0, "CurrentDir allocation error");

        return ziperr(ZEN_MEM36, pG);
      }

      lstrcpy(pG->OrigCurrentDir, fileArg->fRootDir);
      if (pG->verbose)
        Inform(pG, 0, IERROR, "Root dir now %s", pG->OrigCurrentDir);
    }
    if (C->fVersion > 178)
    {
      if (fileArg->fLevel)
      {
        r = fileArg->fLevel;
        r = r < 0 ? 0 : (r > 9 ? 9 : r);
        if (r != pG->level)
        {
          pG->level = r;
          pG->method = r ? DEFLATE : STORE;
          if (pG->verbose)
            Inform(pG, 0, IDIAG, "setting compression level to %d", r);
        }
      }
      if (fileArg->fFromDate)
        pG->before = fileArg->fFromDate == (unsigned) - 1 ? 0 : fileArg
          ->fFromDate;
      else
        pG->before = g_before;
    }

    #ifdef USE_STRM_INPUT
      if (arg1 < 0)
      {
        arg1 = argno;
        if (pG->UseInStream)
        {
          // Here we fill in the FoundList from the input stream data
          // newname (fileio.c) adds to found list. If error m!=0 on return
          if ((r = newname(fspec, pG->InStreamSize, pG)) != ZEN_OK)
          {
            if (pG->verbose)
              Inform(pG, 0, IDIAG,
                "Stream filename could not be added in newname call");

            if (pG->zcount)
              FREE(pG->zsort);
            return r;
          }
          break;
        }
      }
    #endif
    #ifdef CRYPT
      if (fileArg->fEncrypt)
      {
        pG->key = fileArg->fPassword;
        if (!pG->key || !*(pG->key))
        {
          // use global
          if ((r = GetUserPW(pG)) != ZEN_OK)
            break;
          pG->key = pG->user_key;
        }
        //       pG->doesEncrypt = 1;			// 1.73
      }
    #endif
    pG->doall = 0; // do selected
    if ((pG->action == ADD) || (pG->action == UPDATE))
    {
      if (pG->verbose)
        Inform(pG, 0, IDIAG, "collecting %s %s", fspec, pG->recurse ? "recurse"
          : " ");
      r = Wild(fspec, pG);
    }
    else
    // Freshen or Delete - must be internal file
    {
      if (pG->verbose)
        Inform(pG, 0, IDIAG, "collecting %s %s", fspec, pG->recurse ? "recurse"
          : " ");
      r = procname(fspec, pG->recurse, pG);
    }
    if (r != ZEN_OK)
    {
      if ((int)(char)(r &0xFF) == ZEN_MISS)
      {
        /* this occurs if new file wasn't found */
        Inform(pG, r, IERROR, "File specification \"%s\" skipped", fspec);
        r = 0;
      }
    }
    if (r)
      return ziperr(r, pG);
  }
  return 0;
}