You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package upload
  5. import (
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. "code.gitea.io/gitea/modules/log"
  10. )
  11. // ErrFileTypeForbidden not allowed file type error
  12. type ErrFileTypeForbidden struct {
  13. Type string
  14. }
  15. // IsErrFileTypeForbidden checks if an error is a ErrFileTypeForbidden.
  16. func IsErrFileTypeForbidden(err error) bool {
  17. _, ok := err.(ErrFileTypeForbidden)
  18. return ok
  19. }
  20. func (err ErrFileTypeForbidden) Error() string {
  21. return fmt.Sprintf("File type is not allowed: %s", err.Type)
  22. }
  23. // VerifyAllowedContentType validates a file is allowed to be uploaded.
  24. func VerifyAllowedContentType(buf []byte, allowedTypes []string) error {
  25. fileType := http.DetectContentType(buf)
  26. for _, t := range allowedTypes {
  27. t := strings.Trim(t, " ")
  28. if t == "*/*" || t == fileType ||
  29. // Allow directives after type, like 'text/plain; charset=utf-8'
  30. strings.HasPrefix(fileType, t+";") {
  31. return nil
  32. }
  33. }
  34. log.Info("Attachment with type %s blocked from upload", fileType)
  35. return ErrFileTypeForbidden{Type: fileType}
  36. }