// handleUploadFile handles native upload of a file.
168476
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
	content := bytes.NewReader(*fi.Data)
	sp := strings.Split(fi.Name, ".")
	mtype := mime.TypeByExtension("." + sp[len(sp)-1])
	if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
		return
	}
	if fi.Comment != "" {
		_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	} else {
		// image and video uploads send no username, we have to do this ourself here #715
		_, err := b.mc.SendText(channel, msg.Username)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	}
	b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
	res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
	if err != nil {
		b.Log.Errorf("file upload failed: %#v", err)
		return
	}

	switch {
	case strings.Contains(mtype, "video"):
		b.Log.Debugf("sendVideo %s", res.ContentURI)
		_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendVideo failed: %#v", err)
		}
	case strings.Contains(mtype, "image"):
		b.Log.Debugf("sendImage %s", res.ContentURI)
		_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendImage failed: %#v", err)
		}
	}
	b.Log.Debugf("result: %#v", res)
}
407608
func (bh *CephBackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {
	if bh.readOnly {
		return nil, fmt.Errorf("AddFile cannot be called on read-only backup")
	}
	reader, writer := io.Pipe()
	bh.waitGroup.Add(1)
	go func() {
		defer bh.waitGroup.Done()

		// ceph bucket name is where the backups will go
		//backup handle dir field contains keyspace/shard value
		bucket := alterBucketName(bh.dir)

		// Give PutObject() the read end of the pipe.
		object := objName(bh.dir, bh.name, filename)
		_, err := bh.client.PutObjectWithContext(ctx, bucket, object, reader, -1, minio.PutObjectOptions{ContentType: "application/octet-stream"})
		if err != nil {
			// Signal the writer that an error occurred, in case it's not done writing yet.
			reader.CloseWithError(err)
			// In case the error happened after the writer finished, we need to remember it.
			bh.errors.RecordError(err)
		}
	}()
	// Give our caller the write end of the pipe.
	return writer, nil
}
745597
func (u *UploadsService) UploadAsset(asset io.ReadCloser, contentType string, contentLength int64) (result *Result) {
	return u.client.upload(u.URL, asset, contentType, contentLength)
}
1201345
func NewUploadHandleFromString(data string) *UploadHandle {
	bref := blob.RefFromString(data)
	r := strings.NewReader(data)
	return &UploadHandle{BlobRef: bref, Size: uint32(len(data)), Contents: r}
}
588173
func (c *Context) FormFile(key string) (*multipart.FileHeader, error) {
	_, fh, err := c.Request.FormFile(key)
	return fh, err
}
837906
func (b *Birc) handleFiles(msg *config.Message) bool {
	if msg.Extra == nil {
		return false
	}
	for _, rmsg := range helper.HandleExtra(msg, b.General) {
		b.Local <- rmsg
	}
	if len(msg.Extra["file"]) == 0 {
		return false
	}
	for _, f := range msg.Extra["file"] {
		fi := f.(config.FileInfo)
		if fi.Comment != "" {
			msg.Text += fi.Comment + ": "
		}
		if fi.URL != "" {
			msg.Text = fi.URL
			if fi.Comment != "" {
				msg.Text = fi.Comment + ": " + fi.URL
			}
		}
		b.Local <- config.Message{Text: msg.Text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event}
	}
	return true
}
296454
func (fbh *FileBackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) {
	if !fbh.readOnly {
		return nil, fmt.Errorf("ReadFile cannot be called on read-write backup")
	}
	p := path.Join(*FileBackupStorageRoot, fbh.dir, fbh.name, filename)
	return os.Open(p)
}
490471
func initUploadHandler(auditConfig services.AuditConfig) (events.UploadHandler, error) {
	if auditConfig.AuditSessionsURI == "" {
		return nil, trace.NotFound("no upload handler is setup")
	}
	uri, err := utils.ParseSessionsURI(auditConfig.AuditSessionsURI)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	switch uri.Scheme {
	case teleport.SchemeS3:
		region := auditConfig.Region
		if uriRegion := uri.Query().Get(teleport.Region); uriRegion != "" {
			region = uriRegion
		}
		handler, err := s3sessions.NewHandler(s3sessions.Config{
			Bucket: uri.Host,
			Region: region,
			Path:   uri.Path,
		})
		if err != nil {
			return nil, trace.Wrap(err)
		}
		return handler, nil
	case teleport.SchemeFile:
		if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil {
			return nil, trace.ConvertSystemError(err)
		}
		handler, err := filesessions.NewHandler(filesessions.Config{
			Directory: uri.Path,
		})
		if err != nil {
			return nil, trace.Wrap(err)
		}
		return handler, nil
	default:
		return nil, trace.BadParameter(
			"unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q",
			uri.Scheme, teleport.SchemeS3, teleport.SchemeFile)
	}
}
1206791
func NewUploadTaskFile(ctx *middleware.Context, handler UploadTaskFileHandler) *UploadTaskFile {
	return &UploadTaskFile{Context: ctx, Handler: handler}
}
16390
func (h *toolsUploadHandler) handleUpload(r io.Reader, toolsVersions []version.Binary, serverRoot string, st *state.State) (*tools.Tools, error) {
	// Check if changes are allowed and the command may proceed.
	blockChecker := common.NewBlockChecker(st)
	if err := blockChecker.ChangeAllowed(); err != nil {
		return nil, errors.Trace(err)
	}
	storage, err := st.ToolsStorage()
	if err != nil {
		return nil, err
	}
	defer storage.Close()

	// Read the tools tarball from the request, calculating the sha256 along the way.
	data, sha256, err := readAndHash(r)
	if err != nil {
		return nil, err
	}
	if len(data) == 0 {
		return nil, errors.BadRequestf("no agent binaries uploaded")
	}

	// TODO(wallyworld): check integrity of tools tarball.

	// Store tools and metadata in tools storage.
	for _, v := range toolsVersions {
		metadata := binarystorage.Metadata{
			Version: v.String(),
			Size:    int64(len(data)),
			SHA256:  sha256,
		}
		logger.Debugf("uploading agent binaries %+v to storage", metadata)
		if err := storage.Add(bytes.NewReader(data), metadata); err != nil {
			return nil, err
		}
	}

	tools := &tools.Tools{
		Version: toolsVersions[0],
		Size:    int64(len(data)),
		SHA256:  sha256,
		URL:     common.ToolsURL(serverRoot, toolsVersions[0]),
	}
	return tools, nil
}
454308
func uploadFile(serverURL, key, filename string) error {
	var r io.ReadCloser
	var size int64
	if len(filename) > 0 {
		f, err := os.Open(filename)
		if err != nil {
			return fmt.Errorf("failed to open upload file %s, %v", filename, err)
		}

		// Get the size of the file so that the constraint of Content-Length
		// can be included with the presigned URL. This can be used by the
		// server or client to ensure the content uploaded is of a certain size.
		//
		// These constraints can further be expanded to include things like
		// Content-Type. Additionally constraints such as X-Amz-Content-Sha256
		// header set restricting the content of the file to only the content
		// the client initially made the request with. This prevents the object
		// from being overwritten or used to upload other unintended content.
		stat, err := f.Stat()
		if err != nil {
			return fmt.Errorf("failed to stat file, %s, %v", filename, err)
		}

		size = stat.Size()
		r = f
	} else {
		buf := &bytes.Buffer{}
		io.Copy(buf, os.Stdin)
		size = int64(buf.Len())

		r = ioutil.NopCloser(buf)
	}
	defer r.Close()

	// Get the Presigned URL from the remote service. Pass in the file's
	// size if it is known so that the presigned URL returned will be required
	// to be used with the size of content requested.
	req, err := getPresignedRequest(serverURL, "PUT", key, size)
	if err != nil {
		return fmt.Errorf("failed to get get presigned request, %v", err)
	}
	req.Body = r

	// Upload the file contents to S3.
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to do GET request, %v", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("failed to put S3 object, %d:%s",
			resp.StatusCode, resp.Status)
	}

	return nil
}
453961
func (sl *Slack) FilesUpload(opt *FilesUploadOpt) (file *UploadedFile, err error) {
	req, err := sl.createFilesUploadRequest(opt)

	if err != nil {
		return
	}

	body, err := sl.DoRequest(req)

	if err != nil {
		return
	}

	res := new(FilesUploadAPIResponse)
	err = json.Unmarshal(body, res)

	if err != nil {
		return
	}

	if res.Ok {
		file = &res.File
	} else {
		err = errors.New(res.Error)
	}

	return
}
271220
func (this *Response) Sendfile(filename string, opt ...interface{}) {
	http.ServeFile(this.Writer, this.req.Request.Request, filename)
}
836862
func (r *Response) serveFile(file string) error {
	log.Debugf("serving file %s", file)

	http.ServeFile(r.writer, r.request, file)
	return nil
}
554544
func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) string {
	var c tgbotapi.Chattable
	for _, f := range msg.Extra["file"] {
		fi := f.(config.FileInfo)
		file := tgbotapi.FileBytes{
			Name:  fi.Name,
			Bytes: *fi.Data,
		}
		re := regexp.MustCompile(".(jpg|png)$")
		if re.MatchString(fi.Name) {
			c = tgbotapi.NewPhotoUpload(chatid, file)
		} else {
			c = tgbotapi.NewDocumentUpload(chatid, file)
		}
		_, err := b.c.Send(c)
		if err != nil {
			b.Log.Errorf("file upload failed: %#v", err)
		}
		if fi.Comment != "" {
			if _, err := b.sendMessage(chatid, msg.Username, fi.Comment); err != nil {
				b.Log.Errorf("posting file comment %s failed: %s", fi.Comment, err)
			}
		}
	}
	return ""
}
897860
func UploadFile(client *FlickrClient, path string, optionalParams *UploadParams) (*UploadResponse, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	return UploadReader(client, file, file.Name(), optionalParams)
}
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
}