code.gitea.io/gitea@v1.22.3/modules/public/public.go (about)

     1  // Copyright 2016 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package public
     5  
     6  import (
     7  	"bytes"
     8  	"io"
     9  	"net/http"
    10  	"os"
    11  	"path"
    12  	"strings"
    13  	"time"
    14  
    15  	"code.gitea.io/gitea/modules/assetfs"
    16  	"code.gitea.io/gitea/modules/container"
    17  	"code.gitea.io/gitea/modules/httpcache"
    18  	"code.gitea.io/gitea/modules/log"
    19  	"code.gitea.io/gitea/modules/setting"
    20  	"code.gitea.io/gitea/modules/util"
    21  )
    22  
    23  func CustomAssets() *assetfs.Layer {
    24  	return assetfs.Local("custom", setting.CustomPath, "public")
    25  }
    26  
    27  func AssetFS() *assetfs.LayeredFS {
    28  	return assetfs.Layered(CustomAssets(), BuiltinAssets())
    29  }
    30  
    31  // FileHandlerFunc implements the static handler for serving files in "public" assets
    32  func FileHandlerFunc() http.HandlerFunc {
    33  	assetFS := AssetFS()
    34  	return func(resp http.ResponseWriter, req *http.Request) {
    35  		if req.Method != "GET" && req.Method != "HEAD" {
    36  			resp.WriteHeader(http.StatusMethodNotAllowed)
    37  			return
    38  		}
    39  		handleRequest(resp, req, assetFS, req.URL.Path)
    40  	}
    41  }
    42  
    43  // parseAcceptEncoding parse Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 as compress methods
    44  func parseAcceptEncoding(val string) container.Set[string] {
    45  	parts := strings.Split(val, ";")
    46  	types := make(container.Set[string])
    47  	for _, v := range strings.Split(parts[0], ",") {
    48  		types.Add(strings.TrimSpace(v))
    49  	}
    50  	return types
    51  }
    52  
    53  // setWellKnownContentType will set the Content-Type if the file is a well-known type.
    54  // See the comments of detectWellKnownMimeType
    55  func setWellKnownContentType(w http.ResponseWriter, file string) {
    56  	mimeType := detectWellKnownMimeType(path.Ext(file))
    57  	if mimeType != "" {
    58  		w.Header().Set("Content-Type", mimeType)
    59  	}
    60  }
    61  
    62  func handleRequest(w http.ResponseWriter, req *http.Request, fs http.FileSystem, file string) {
    63  	// actually, fs (http.FileSystem) is designed to be a safe interface, relative paths won't bypass its parent directory, it's also fine to do a clean here
    64  	f, err := fs.Open(util.PathJoinRelX(file))
    65  	if err != nil {
    66  		if os.IsNotExist(err) {
    67  			w.WriteHeader(http.StatusNotFound)
    68  			return
    69  		}
    70  		w.WriteHeader(http.StatusInternalServerError)
    71  		log.Error("[Static] Open %q failed: %v", file, err)
    72  		return
    73  	}
    74  	defer f.Close()
    75  
    76  	fi, err := f.Stat()
    77  	if err != nil {
    78  		w.WriteHeader(http.StatusInternalServerError)
    79  		log.Error("[Static] %q exists, but fails to open: %v", file, err)
    80  		return
    81  	}
    82  
    83  	// need to serve index file? (no at the moment)
    84  	if fi.IsDir() {
    85  		w.WriteHeader(http.StatusNotFound)
    86  		return
    87  	}
    88  
    89  	serveContent(w, req, fi, fi.ModTime(), f)
    90  }
    91  
    92  type GzipBytesProvider interface {
    93  	GzipBytes() []byte
    94  }
    95  
    96  // serveContent serve http content
    97  func serveContent(w http.ResponseWriter, req *http.Request, fi os.FileInfo, modtime time.Time, content io.ReadSeeker) {
    98  	setWellKnownContentType(w, fi.Name())
    99  
   100  	encodings := parseAcceptEncoding(req.Header.Get("Accept-Encoding"))
   101  	if encodings.Contains("gzip") {
   102  		// try to provide gzip content directly from bindata (provided by vfsgen۰CompressedFileInfo)
   103  		if compressed, ok := fi.(GzipBytesProvider); ok {
   104  			rdGzip := bytes.NewReader(compressed.GzipBytes())
   105  			// all gzipped static files (from bindata) are managed by Gitea, so we can make sure every file has the correct ext name
   106  			// then we can get the correct Content-Type, we do not need to do http.DetectContentType on the decompressed data
   107  			if w.Header().Get("Content-Type") == "" {
   108  				w.Header().Set("Content-Type", "application/octet-stream")
   109  			}
   110  			w.Header().Set("Content-Encoding", "gzip")
   111  			httpcache.ServeContentWithCacheControl(w, req, fi.Name(), modtime, rdGzip)
   112  			return
   113  		}
   114  	}
   115  
   116  	httpcache.ServeContentWithCacheControl(w, req, fi.Name(), modtime, content)
   117  	return
   118  }