// Add file reader in archive zip
486282
func (z *ZipFile) Add(name string, file io.Reader, info os.FileInfo) error {
	var header *zip.FileHeader
	if info == nil {
		header = &zip.FileHeader{
			Name:   name,
			Flags:  1 << 11, // use utf8 encoding the file Name
			Method: zip.Deflate,
		}
	} else {
		var err error
		header, err = zip.FileInfoHeader(info)
		if err != nil {
			return err
		}
	}
	zipWriter, err := z.Writer.CreateHeader(header)
	if err != nil {
		return err
	}

	_, err = io.Copy(zipWriter, file)
	return err
}
782129
func ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
	fileList := make(map[string][]byte)
	worksheets := 0
	for _, v := range r.File {
		fileList[v.Name] = readFile(v)
		if len(v.Name) > 18 {
			if v.Name[0:19] == "xl/worksheets/sheet" {
				worksheets++
			}
		}
	}
	return fileList, worksheets, nil
}
1153668
func AddToZip(zipWriter *zip.Writer, source string, rootSource string, logger *logrus.Logger) error {
	return AnnotateAddToZip(zipWriter, source, rootSource, nil, logger)
}
926473
func archiveFileVisitor(dir string, tempFile *string, signature *[]byte, archivePath string, filedata io.Reader) error {
	var err error
	filename := path.Base(archivePath)
	archiveDir := path.Dir(archivePath)
	l.Debugf("considering file %s", archivePath)
	switch filename {
	case "syncthing", "syncthing.exe":
		archiveDirs := strings.Split(archiveDir, "/")
		if len(archiveDirs) > 1 {
			// Don't consider "syncthing" files found too deeply, as they may be
			// other things.
			return nil
		}
		l.Debugf("found upgrade binary %s", archivePath)
		*tempFile, err = writeBinary(dir, io.LimitReader(filedata, maxBinarySize))
		if err != nil {
			return err
		}

	case "release.sig":
		l.Debugf("found signature %s", archivePath)
		*signature, err = ioutil.ReadAll(io.LimitReader(filedata, maxSignatureSize))
		if err != nil {
			return err
		}
	}

	return nil
}
56068
func (z *Zip) AddBytes(path string, contents []byte) error {
	z.lock.Lock()
	defer z.lock.Unlock()

	header := &zip.FileHeader{
		Name:   path,
		Method: zip.Deflate,
	}

	header.SetModTime(time.Unix(0, 0))

	zippedFile, err := z.writer.CreateHeader(header)
	if err != nil {
		return err
	}

	_, err = zippedFile.Write(contents)
	return err
}
492675
func Unzip(srcPath, destPath string) error {
	// Open a zip archive for reading
	r, err := zip.OpenReader(srcPath)
	if err != nil {
		return err
	}
	defer r.Close()

	// Iterate through the files in the archive
	for _, f := range r.File {
		// Get files from archive
		rc, err := f.Open()
		if err != nil {
			return err
		}

		dir := filepath.Dir(f.Name)
		// Create directory before create file
		os.MkdirAll(destPath+"/"+dir, os.ModePerm)

		if f.FileInfo().IsDir() {
			continue
		}

		// Write data to file
		fw, _ := os.Create(filepath.Join(destPath, f.Name))
		if err != nil {
			return err
		}
		_, err = io.Copy(fw, rc)

		if fw != nil {
			fw.Close()
		}
		if err != nil {
			return err
		}
	}
	return nil
}
321074
func zipExeReaderPe(rda io.ReaderAt, size int64) (*zip.Reader, error) {
	file, err := pe.NewFile(rda)
	if err != nil {
		return nil, err
	}

	var max int64
	for _, sec := range file.Sections {
		// Check if this section has a zip file
		if zfile, err := zip.NewReader(sec, int64(sec.Size)); err == nil {
			return zfile, nil
		}

		// Otherwise move end of file pointer
		end := int64(sec.Offset + sec.Size)
		if end > max {
			max = end
		}
	}

	// No zip file within binary, try appended to end
	section := io.NewSectionReader(rda, max, size-max)
	return zip.NewReader(section, section.Size())
}
619303
func (z *Zip) AddFile(path string, file *os.File) error {
	path = strings.Replace(path, "\\", "/", -1)

	z.lock.Lock()
	defer z.lock.Unlock()

	info, err := file.Stat()
	if err != nil {
		return err
	}

	if !info.Mode().IsRegular() {
		return errors.New("Only regular files supported: " + path)
	}

	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}
	header.Name = path
	header.Method = zip.Deflate
	header.SetModTime(time.Unix(0, 0))

	zippedFile, err := z.writer.CreateHeader(header)
	if err != nil {
		return err
	}

	_, err = io.Copy(zippedFile, file)
	return err
}
337019
func Unzip(r io.Reader, destPath string) (string, error) {
	var (
		zr  *zip.Reader
		err error
	)

	if f, ok := r.(*os.File); ok {
		fstat, err := f.Stat()
		if err != nil {
			return "", err
		}
		zr, err = zip.NewReader(f, fstat.Size())
	} else {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			return "", err
		}
		memReader := bytes.NewReader(data)
		zr, err = zip.NewReader(memReader, memReader.Size())
	}

	if err != nil {
		return "", err
	}

	return unpackZip(zr, destPath)
}
185693
func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
	calls := gosec.NewCallList()
	calls.Add("path/filepath", "Join")
	return &archive{
		calls:   calls,
		argType: "*archive/zip.File",
		MetaData: gosec.MetaData{
			ID:         id,
			Severity:   gosec.Medium,
			Confidence: gosec.High,
			What:       "File traversal when extracting zip archive",
		},
	}, []ast.Node{(*ast.CallExpr)(nil)}
}
232506
func archive(ctx context.Context, client *isolatedclient.Client, opts *isolate.ArchiveOptions, dumpJSON string, concurrentChecks, concurrentUploads int, al archiveLogger) error {
	// Parse the incoming isolate file.
	deps, rootDir, isol, err := isolate.ProcessIsolate(opts)
	if err != nil {
		return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err)
	}
	log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps))

	// Set up a checker and uploader.
	checker := archiver.NewChecker(ctx, client, concurrentChecks)
	uploader := archiver.NewUploader(ctx, client, concurrentUploads)
	archiver := archiver.NewTarringArchiver(checker, uploader)

	isolSummary, err := archiver.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated)
	if err != nil {
		return fmt.Errorf("isolate %s: %v", opts.Isolate, err)
	}

	// Make sure that all pending items have been checked.
	if err := checker.Close(); err != nil {
		return err
	}

	// Make sure that all the uploads have completed successfully.
	if err := uploader.Close(); err != nil {
		return err
	}

	printSummary(al, isolSummary)
	if err := dumpSummaryJSON(dumpJSON, isolSummary); err != nil {
		return err
	}

	al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), []string{string(isolSummary.Digest)})
	return nil
}
786982
func (assembly *Assembly) AddFile(fieldname, filepath string) error {
	file, err := os.Open(filepath)
	if err != nil {
		return err
	}

	assembly.AddReader(fieldname, filepath, file)
	return nil
}
447490
func (t *Tar) Archive(sources []string, destination string) error {
	err := t.CheckExt(destination)
	if t.writerWrapFn == nil && err != nil {
		return fmt.Errorf("checking extension: %v", err)
	}
	if !t.OverwriteExisting && fileExists(destination) {
		return fmt.Errorf("file already exists: %s", destination)
	}

	// make the folder to contain the resulting archive
	// if it does not already exist
	destDir := filepath.Dir(destination)
	if t.MkdirAll && !fileExists(destDir) {
		err := mkdir(destDir, 0755)
		if err != nil {
			return fmt.Errorf("making folder for destination: %v", err)
		}
	}

	out, err := os.Create(destination)
	if err != nil {
		return fmt.Errorf("creating %s: %v", destination, err)
	}
	defer out.Close()

	err = t.Create(out)
	if err != nil {
		return fmt.Errorf("creating tar: %v", err)
	}
	defer t.Close()

	var topLevelFolder string
	if t.ImplicitTopLevelFolder && multipleTopLevels(sources) {
		topLevelFolder = folderNameFromFileName(destination)
	}

	for _, source := range sources {
		err := t.writeWalk(source, topLevelFolder, destination)
		if err != nil {
			return fmt.Errorf("walking %s: %v", source, err)
		}
	}

	return nil
}
827624
func openArchive(u string) (Archive, error) {
	var (
		r      io.Reader
		closer io.Closer
	)

	if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") {
		resp, err := http.Get(u)
		if err != nil {
			return nil, err
		}
		if resp.StatusCode < 200 || resp.StatusCode >= 300 {
			b, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024))
			resp.Body.Close()
			if err != nil {
				return nil, err
			}
			return nil, &url.Error{
				Op:  "Get",
				URL: u,
				Err: fmt.Errorf("%s: %s", resp.Status, string(b)),
			}
		}
		closer = resp.Body
		r = resp.Body
		if resp.Header.Get("Content-Type") == "application/x-gzip" {
			r, err = gzip.NewReader(r)
			if err != nil {
				resp.Body.Close()
				return nil, err
			}
		}
	} else if u == "-" {
		r = os.Stdin
	} else {
		f, err := os.Open(u)
		if err != nil {
			return nil, err
		}
		closer = f
		r = f
	}

	return &tarArchive{
		tr:     tar.NewReader(r),
		closer: closer,
	}, nil
}
977141
func (t *Trashcan) Archive(filePath string) error {
	return archiveFile(t.folderFs, t.versionsFs, filePath, func(name, tag string) string {
		return name
	})
}
1331092
func (pb *PackageBuilder) AddFile(fpath string) (fname string, err error) {
	fpath, err = filepath.Abs(fpath)
	if err != nil {
		return
	}
	_, err = os.Stat(fpath)
	if err != nil {
		return
	}

	isDestructiveChanges, err := regexp.MatchString("destructiveChanges(Pre|Post)?"+regexp.QuoteMeta(".")+"xml", fpath)
	if err != nil {
		return
	}

	fpath = MetaPathToSourcePath(fpath)
	metaName, fname := getMetaTypeFromPath(fpath)
	if !isDestructiveChanges && !strings.HasSuffix(fpath, "-meta.xml") {
		pb.AddMetaToPackage(metaName, fname)
	}

	// If it's a push, we want to actually add the files
	if pb.IsPush {
		if isDestructiveChanges {
			err = pb.addDestructiveChanges(fpath)
		} else {
			err = pb.addFileToWorkingDir(metaName, fpath)
		}
	}

	return
}
662899
func (b *backups) Add(archive io.Reader, meta *Metadata) (string, error) {
	// Store the archive.
	err := storeArchive(b.storage, meta, archive)
	if err != nil {
		return "", errors.Annotate(err, "while storing backup archive")
	}

	return meta.ID(), nil
}