// PushFile schedules file upload to the isolate server. Smaller priority
// value means earlier processing.
492805
func (a *Archiver) PushFile(displayName, path string, priority int64) *PendingItem {
	source := func() (io.ReadCloser, error) {
		return os.Open(path)
	}
	return a.push(newItem(a, displayName, path, source, priority))
}
881934
func AddFile(file string, opts ...FileOption) error {
	o := &FileOptions{}
	for _, f := range opts {
		f(o)
	}
	if err := fs.AddFile(file, filesource.DefaultFilePriority, o.Handler); err != nil {
		return err
	}
	return factory.Refresh(fs.GetSourceName())
}
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
}
797670
func (c *Cluster) PushImage(opts docker.PushImageOptions, auth docker.AuthConfiguration) error {
	key := imageKey(opts.Name, opts.Tag)
	img, err := c.storage().RetrieveImage(key)
	if err != nil {
		return err
	}
	node, err := c.getNodeByAddr(img.LastNode)
	if err != nil {
		return err
	}
	node.setPersistentClient()
	return wrapError(node, node.PushImage(opts, auth))
}
1016209
func (s *SCP) SendFile(srcFile, destFile string) error {
	srcFile = filepath.Clean(srcFile)
	destFile = realPath(filepath.Clean(destFile))

	return runSourceSession(s.client, destFile, false, "", false, true, func(s *sourceSession) error {
		osFileInfo, err := os.Stat(srcFile)
		if err != nil {
			return fmt.Errorf("failed to stat source file: err=%s", err)
		}
		fi := newFileInfoFromOS(osFileInfo, "")

		file, err := os.Open(srcFile)
		if err != nil {
			return fmt.Errorf("failed to open source file: err=%s", err)
		}
		// NOTE: file will be closed by WriteFile.
		err = s.WriteFile(fi, file)
		if err != nil {
			return fmt.Errorf("failed to copy file: err=%s", err)
		}
		return nil
	})
}
901589
func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, error) {
	reqPath := r.URL.Path

	// Prevent absolute path access on Windows.
	// TODO remove when stdlib http.Dir fixes this.
	if runtime.GOOS == "windows" && len(reqPath) > 0 && filepath.IsAbs(reqPath[1:]) {
		return http.StatusNotFound, nil
	}

	// open the requested file
	f, err := fs.Root.Open(reqPath)
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// otherwise, maybe the server is under load and ran out of file descriptors?
		backoff := int(3 + rand.Int31()%3) // 3–5 seconds to prevent a stampede
		w.Header().Set("Retry-After", strconv.Itoa(backoff))
		return http.StatusServiceUnavailable, err
	}
	defer f.Close()

	// get information about the file
	d, err := f.Stat()
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// return a different status code than above to distinguish these cases
		return http.StatusInternalServerError, err
	}

	// redirect to canonical path (being careful to preserve other parts of URL and
	// considering cases where a site is defined with a path prefix that gets stripped)
	urlCopy := *r.URL
	pathPrefix, _ := r.Context().Value(caddy.CtxKey("path_prefix")).(string)
	if pathPrefix != "/" {
		urlCopy.Path = pathPrefix + urlCopy.Path
	}
	if urlCopy.Path == "" {
		urlCopy.Path = "/"
	}
	if d.IsDir() {
		// ensure there is a trailing slash
		if urlCopy.Path[len(urlCopy.Path)-1] != '/' {
			for strings.HasPrefix(urlCopy.Path, "//") {
				// prevent path-based open redirects
				urlCopy.Path = strings.TrimPrefix(urlCopy.Path, "/")
			}
			urlCopy.Path += "/"
			http.Redirect(w, r, urlCopy.String(), http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	} else {
		// ensure no trailing slash
		redir := false
		if urlCopy.Path[len(urlCopy.Path)-1] == '/' {
			urlCopy.Path = urlCopy.Path[:len(urlCopy.Path)-1]
			redir = true
		}

		// if an index file was explicitly requested, strip file name from the request
		// ("/foo/index.html" -> "/foo/")
		var requestPage = path.Base(urlCopy.Path)
		for _, indexPage := range fs.IndexPages {
			if requestPage == indexPage {
				urlCopy.Path = urlCopy.Path[:len(urlCopy.Path)-len(indexPage)]
				redir = true
				break
			}
		}

		if redir {
			for strings.HasPrefix(urlCopy.Path, "//") {
				// prevent path-based open redirects
				urlCopy.Path = strings.TrimPrefix(urlCopy.Path, "/")
			}
			http.Redirect(w, r, urlCopy.String(), http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	}

	// use contents of an index file, if present, for directory requests
	if d.IsDir() {
		for _, indexPage := range fs.IndexPages {
			indexPath := path.Join(reqPath, indexPage)
			indexFile, err := fs.Root.Open(indexPath)
			if err != nil {
				continue
			}

			indexInfo, err := indexFile.Stat()
			if err != nil {
				indexFile.Close()
				continue
			}

			// this defer does not leak fds even though we are in a loop,
			// because previous iterations of the loop must have had an
			// err, so there's nothing to close from earlier iterations.
			defer indexFile.Close()

			// close previously-opened file immediately to release fd
			f.Close()

			// switch to using the index file, and we're done here
			d = indexInfo
			f = indexFile
			reqPath = indexPath
			break
		}
	}

	// return Not Found if we either did not find an index file (and thus are
	// still a directory) or if this file is supposed to be hidden
	if d.IsDir() || fs.IsHidden(d) {
		return http.StatusNotFound, nil
	}

	etag := calculateEtag(d)

	// look for compressed versions of the file on disk, if the client supports that encoding
	for _, encoding := range staticEncodingPriority {
		// see if the client accepts a compressed encoding we offer
		acceptEncoding := strings.Split(r.Header.Get("Accept-Encoding"), ",")
		accepted := false
		for _, acc := range acceptEncoding {
			if strings.TrimSpace(acc) == encoding {
				accepted = true
				break
			}
		}

		// if client doesn't support this encoding, don't even bother; try next one
		if !accepted {
			continue
		}

		// see if the compressed version of this file exists
		encodedFile, err := fs.Root.Open(reqPath + staticEncoding[encoding])
		if err != nil {
			continue
		}

		encodedFileInfo, err := encodedFile.Stat()
		if err != nil {
			encodedFile.Close()
			continue
		}

		// close the encoded file when we're done, and close the
		// previously-opened file immediately to release the fd
		defer encodedFile.Close()
		f.Close()

		// the encoded file is now what we're serving
		f = encodedFile
		etag = calculateEtag(encodedFileInfo)
		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Set("Content-Encoding", encoding)
		w.Header().Set("Content-Length", strconv.FormatInt(encodedFileInfo.Size(), 10))
		break
	}

	// Set the ETag returned to the user-agent. Note that a conditional If-None-Match
	// request is handled in http.ServeContent below, which checks against this ETag value.
	w.Header().Set("ETag", etag)

	// Note: Errors generated by ServeContent are written immediately
	// to the response. This usually only happens if seeking fails (rare).
	// Its signature does not bubble the error up to us, so we cannot
	// return it for any logging middleware to record. Oh well.
	http.ServeContent(w, r, d.Name(), d.ModTime(), f)

	return http.StatusOK, nil
}
791955
func copyFile(w io.Writer, file string) error {
	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(w, f)
	return err
}
441484
func (c *Communicator) uploadFile(dst string, src io.Reader, fi *os.FileInfo) error {
	// command format: docker cp /path/to/infile containerid:/path/to/outfile
	log.Printf("Copying to %s on container %s.", dst, c.ContainerID)

	localCmd := exec.Command("docker", "cp", "-",
		fmt.Sprintf("%s:%s", c.ContainerID, filepath.Dir(dst)))

	stderrP, err := localCmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("Failed to open pipe: %s", err)
	}

	stdin, err := localCmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("Failed to open pipe: %s", err)
	}

	if err := localCmd.Start(); err != nil {
		return err
	}

	archive := tar.NewWriter(stdin)
	header, err := tar.FileInfoHeader(*fi, "")
	if err != nil {
		return err
	}
	header.Name = filepath.Base(dst)
	archive.WriteHeader(header)
	numBytes, err := io.Copy(archive, src)
	if err != nil {
		return fmt.Errorf("Failed to pipe upload: %s", err)
	}
	log.Printf("Copied %d bytes for %s", numBytes, dst)

	if err := archive.Close(); err != nil {
		return fmt.Errorf("Failed to close archive: %s", err)
	}
	if err := stdin.Close(); err != nil {
		return fmt.Errorf("Failed to close stdin: %s", err)
	}

	stderrOut, err := ioutil.ReadAll(stderrP)
	if err != nil {
		return err
	}

	if err := localCmd.Wait(); err != nil {
		return fmt.Errorf("Failed to upload to '%s' in container: %s. %s.", dst, stderrOut, err)
	}

	if err := c.fixDestinationOwner(dst); err != nil {
		return err
	}

	return nil
}
1076727
func (handler *UnroutedHandler) PostFile(w http.ResponseWriter, r *http.Request) {
	// Check for presence of application/offset+octet-stream. If another content
	// type is defined, it will be ignored and treated as none was set because
	// some HTTP clients may enforce a default value for this header.
	containsChunk := r.Header.Get("Content-Type") == "application/offset+octet-stream"

	// Only use the proper Upload-Concat header if the concatenation extension
	// is even supported by the data store.
	var concatHeader string
	if handler.composer.UsesConcater {
		concatHeader = r.Header.Get("Upload-Concat")
	}

	// Parse Upload-Concat header
	isPartial, isFinal, partialUploads, err := parseConcat(concatHeader)
	if err != nil {
		handler.sendError(w, r, err)
		return
	}

	// If the upload is a final upload created by concatenation multiple partial
	// uploads the size is sum of all sizes of these files (no need for
	// Upload-Length header)
	var size int64
	var sizeIsDeferred bool
	if isFinal {
		// A final upload must not contain a chunk within the creation request
		if containsChunk {
			handler.sendError(w, r, ErrModifyFinal)
			return
		}

		size, err = handler.sizeOfUploads(partialUploads)
		if err != nil {
			handler.sendError(w, r, err)
			return
		}
	} else {
		uploadLengthHeader := r.Header.Get("Upload-Length")
		uploadDeferLengthHeader := r.Header.Get("Upload-Defer-Length")
		size, sizeIsDeferred, err = handler.validateNewUploadLengthHeaders(uploadLengthHeader, uploadDeferLengthHeader)
		if err != nil {
			handler.sendError(w, r, err)
			return
		}
	}

	// Test whether the size is still allowed
	if handler.config.MaxSize > 0 && size > handler.config.MaxSize {
		handler.sendError(w, r, ErrMaxSizeExceeded)
		return
	}

	// Parse metadata
	meta := ParseMetadataHeader(r.Header.Get("Upload-Metadata"))

	info := FileInfo{
		Size:           size,
		SizeIsDeferred: sizeIsDeferred,
		MetaData:       meta,
		IsPartial:      isPartial,
		IsFinal:        isFinal,
		PartialUploads: partialUploads,
	}

	id, err := handler.composer.Core.NewUpload(info)
	if err != nil {
		handler.sendError(w, r, err)
		return
	}

	info.ID = id

	// Add the Location header directly after creating the new resource to even
	// include it in cases of failure when an error is returned
	url := handler.absFileURL(r, id)
	w.Header().Set("Location", url)

	handler.Metrics.incUploadsCreated()
	handler.log("UploadCreated", "id", id, "size", i64toa(size), "url", url)

	if handler.config.NotifyCreatedUploads {
		handler.CreatedUploads <- info
	}

	if isFinal {
		if err := handler.composer.Concater.ConcatUploads(id, partialUploads); err != nil {
			handler.sendError(w, r, err)
			return
		}
		info.Offset = size

		if handler.config.NotifyCompleteUploads {
			handler.CompleteUploads <- info
		}
	}

	if containsChunk {
		if handler.composer.UsesLocker {
			locker := handler.composer.Locker
			if err := locker.LockUpload(id); err != nil {
				handler.sendError(w, r, err)
				return
			}

			defer locker.UnlockUpload(id)
		}

		if err := handler.writeChunk(id, info, w, r); err != nil {
			handler.sendError(w, r, err)
			return
		}
	} else if !sizeIsDeferred && size == 0 {
		// Directly finish the upload if the upload is empty (i.e. has a size of 0).
		// This statement is in an else-if block to avoid causing duplicate calls
		// to finishUploadIfComplete if an upload is empty and contains a chunk.
		handler.finishUploadIfComplete(info)
	}

	handler.sendResp(w, r, http.StatusCreated)
}
304265
func (self *HttpClient) UploadFile(method, path, fileParam, filePath string, payload []byte, params map[string]string, headers map[string]string) (*HttpResponse, error) {
	var reader io.Reader

	if payload == nil {
		file, err := os.Open(filePath)
		if err != nil {
			return nil, err
		}
		defer file.Close()
		reader = file
	} else {
		reader = bytes.NewReader(payload)
	}

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(fileParam, filepath.Base(filePath))
	if err == nil {
		_, err = io.Copy(part, reader)
	}
	if err == nil {
		for key, val := range params {
			writer.WriteField(key, val)
		}
		err = writer.Close()
	}
	if err != nil {
		return nil, err
	}

	if headers == nil {
		headers = map[string]string{}
	}

	headers["Content-Type"] = writer.FormDataContentType()
	headers["Content-Length"] = strconv.Itoa(body.Len())
	req := self.Request(method, path, body, headers)

	return self.Do(req)
}
526383
func RemoveFile(fp string) {
	if err := os.Remove(fp); err != nil {
		glog.Warningf("unable to remove file %s: %v", fp, err)
	}
}
776298
func (_m *ContainerRuntimeExecutor) CopyFile(containerID string, sourcePath string, destPath string) error {
	ret := _m.Called(containerID, sourcePath, destPath)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
		r0 = rf(containerID, sourcePath, destPath)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
338297
func (ctxt *Context) ServeFile(path string) {
	http.ServeFile(ctxt, ctxt.Request, path)
}
271220
func (this *Response) Sendfile(filename string, opt ...interface{}) {
	http.ServeFile(this.Writer, this.req.Request.Request, filename)
}
1276507
func (tf *TempFactory) Push(value string) string {
	f, _ := ioutil.TempFile(tf.path, ".summon")
	defer f.Close()

	f.Write([]byte(value))
	name := f.Name()
	tf.files = append(tf.files, name)
	return name
}
730054
func UploadFile(c *middleware.Context) {
	if c.Req.Method == "POST" {
		// 32MiB
		e := c.Req.ParseMultipartForm(32 << 30)
		if e != nil {
			color.Red("%s", e)
			return
		}

		file, info, e := c.Req.FormFile("file")
		if e != nil {
			color.Red("%s", e)
			return
		}
		defer file.Close()

		bts, err := ioutil.ReadAll(file)
		if err != nil {
			c.Error(200, err.Error())
			return
		}

		f, err := models.Upload(info.Filename, bts)
		if err != nil {
			c.Error(200, err.Error())
			return
		}

		c.Data["uploaded"] = f
		c.Redirect("/files/upload/new?uploaded=" + fmt.Sprint(f.BlobID))
		return
	}

	if id := c.QueryInt("uploaded"); id != 0 {
		c.Data["uploaded"] = id

	}
	c.HTML(200, "files/new")
}
1013888
func ServeFile(indexFile, dir, file string, res http.ResponseWriter, req *http.Request) error {
	fs := http.Dir(dir)
	f, err := fs.Open(file)

	// log.Printf("opening file from %s for %s -> %s", dir, file, err)

	if err != nil {
		return NewCustomError("http.ServeFile.Status", fmt.Sprintf("%d", http.StatusNotFound))
	}

	ext := strings.ToLower(filepath.Ext(file))

	fi, _ := f.Stat()
	if fi.IsDir() {
		file = filepath.Join(file, indexFile)
		f, err = fs.Open(file)
		if err != nil {
			return NewCustomError("http.ServeFile.Status", fmt.Sprintf("%d", http.StatusForbidden))
		}
		fi, _ = f.Stat()
	}

	// var cext string
	cext := mime.TypeByExtension(ext)

	// log.Printf("Type ext: %s -> %s", ext, cext)
	if cext == "" {
		if types, ok := mediaTypes[ext]; ok {
			cext = types
		} else {
			cext = "text/plain"
		}
	}

	res.Header().Set("Content-Type", cext)

	http.ServeContent(res, req, fi.Name(), fi.ModTime(), f)
	return nil
}