aboutsummaryrefslogtreecommitdiffstats
path: root/modules/upload/filetype.go
blob: 2ab326d11690f24d72ab92b95c6adc9b092ae25e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package upload

import (
	"fmt"
	"net/http"
	"strings"

	"code.gitea.io/gitea/modules/log"
)

// ErrFileTypeForbidden not allowed file type error
type ErrFileTypeForbidden struct {
	Type string
}

// IsErrFileTypeForbidden checks if an error is a ErrFileTypeForbidden.
func IsErrFileTypeForbidden(err error) bool {
	_, ok := err.(ErrFileTypeForbidden)
	return ok
}

func (err ErrFileTypeForbidden) Error() string {
	return fmt.Sprintf("File type is not allowed: %s", err.Type)
}

// VerifyAllowedContentType validates a file is allowed to be uploaded.
func VerifyAllowedContentType(buf []byte, allowedTypes []string) error {
	fileType := http.DetectContentType(buf)

	for _, t := range allowedTypes {
		t := strings.Trim(t, " ")

		if t == "*/*" || t == fileType ||
			// Allow directives after type, like 'text/plain; charset=utf-8'
			strings.HasPrefix(fileType, t+";") {
			return nil
		}
	}

	log.Info("Attachment with type %s blocked from upload", fileType)
	return ErrFileTypeForbidden{Type: fileType}
}