2 godlighty -- highly-customizable HTTP, HTTP/2, HTTPS server
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
35 "github.com/klauspost/compress/zstd"
36 "golang.org/x/net/webdav"
47 New: func() interface{} { return gzip.NewWriter(ioutil.Discard) },
50 New: func() interface{} {
51 w, err := zstd.NewWriter(
53 zstd.WithEncoderLevel(zstd.SpeedDefault),
67 func (h Handler) Handle(
68 w http.ResponseWriter, r *http.Request,
69 host string, cfg *HostCfg,
72 fmt.Printf("%s %s \"%s %s %s\" %d \"%s\"\n",
73 r.RemoteAddr, host, r.Method, r.URL.Path, r.Proto,
75 r.Header.Get("User-Agent"),
87 username, err = performAuth(w, r, cfg.Auth)
90 username = "user:" + username + " "
92 printErr := func(code int, err error) {
93 fmt.Printf("%s %s \"%s %s %s\" %d \"%s\" %s\"%s\"\n",
94 r.RemoteAddr, host, r.Method, r.URL.Path, r.Proto,
96 username, r.Header.Get("User-Agent"),
103 printErr(http.StatusUnauthorized, err)
106 printErr(http.StatusInternalServerError, err)
107 http.Error(w, "internal error", http.StatusInternalServerError)
111 if cfg.TLS != nil && len(cfg.TLS.ClientCAs) > 0 {
113 err = errors.New("TLS client authentication required")
114 printErr(http.StatusForbidden, err)
115 http.Error(w, err.Error(), http.StatusForbidden)
118 username += r.TLS.PeerCertificates[0].Subject.String() + " "
122 for _, hook := range cfg.Hooks {
123 if done := hook(w, r); done {
133 if cfg.WebDAV && (r.Method == http.MethodHead ||
134 r.Method == http.MethodOptions ||
135 r.Method == "PROPFIND") {
136 dav := webdav.Handler{
137 FileSystem: webdav.Dir(cfg.Root),
138 LockSystem: webdav.NewMemLS(),
140 wc := &CountResponseWriter{ResponseWriter: w}
142 fmt.Printf("%s %s \"WebDAV %s\" %d %d %s\"%s\"\n",
143 r.RemoteAddr, host, r.URL.Path,
145 username, r.Header.Get("User-Agent"),
150 if !(r.Method == "" || r.Method == http.MethodGet) {
151 fmt.Printf("%s %s \"%s %s %s\" %d %s\"%s\"\n",
152 r.RemoteAddr, host, r.Method, r.URL.Path, r.Proto,
153 http.StatusMethodNotAllowed,
154 username, r.Header.Get("User-Agent"),
156 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
160 var contentType string
162 pthOrig := path.Clean(path.Join(cfg.Root, r.URL.Path))
165 fi, err := os.Stat(pth)
172 entries, err := os.ReadDir(pth)
174 printErr(http.StatusInternalServerError, err)
175 http.Error(w, "internal error", http.StatusInternalServerError)
178 fd, err = os.Open(pth)
180 printErr(http.StatusInternalServerError, err)
181 http.Error(w, "internal error", http.StatusInternalServerError)
184 etag, err = ctimeETag(fd)
187 printErr(http.StatusInternalServerError, err)
188 http.Error(w, "internal error", http.StatusInternalServerError)
192 for _, f := range append(cfg.Readmes, Readme) {
193 readme, _ = ioutil.ReadFile(path.Join(pth, f))
198 fd, err = dirList(cfg, r.URL.Path, entries, string(readme))
200 printErr(http.StatusInternalServerError, err)
201 http.Error(w, "internal error", http.StatusInternalServerError)
204 contentType = "text/html; charset=utf-8"
206 for _, index := range append(cfg.Indexes, Index) {
207 p := path.Join(pth, index)
208 if _, err := os.Stat(p); err == nil {
219 fd, err = os.Open(pth)
221 printErr(http.StatusInternalServerError, err)
222 http.Error(w, "internal error", http.StatusInternalServerError)
225 etag, err = ctimeETag(fd)
227 printErr(http.StatusInternalServerError, err)
228 http.Error(w, "internal error", http.StatusInternalServerError)
234 if _, err = os.Stat(pth + Meta4Ext); err == nil {
235 w.Header().Set("Link", "<"+path.Base(pth)+Meta4Ext+`>; rel=describedby; type="application/metalink4+xml"`)
238 if contentType == "" {
239 contentType = mediaType(path.Base(pth), cfg.MIMEs)
241 contentTypeBase := strings.SplitN(contentType, ";", 2)[0]
242 w.Header().Set("Content-Type", contentType)
244 w.Header().Set("Server", Version)
246 w.Header().Set("ETag", etag)
248 var wc http.ResponseWriter
249 var bufCompressed *bytes.Buffer
251 var zstdW *zstd.Encoder
252 if _, ok := CompressibleContentTypes[contentTypeBase]; ok {
253 if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
254 w.Header().Set("Content-Encoding", "zstd")
255 zstdW = zstdPool.Get().(*zstd.Encoder)
256 defer zstdPool.Put(zstdW)
257 bufCompressed = &bytes.Buffer{}
258 zstdW.Reset(bufCompressed)
260 wc = &gzipResponseWriter{ResponseWriter: w, Writer: zstdW}
261 } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
262 w.Header().Set("Content-Encoding", "gzip")
263 gz = gzPool.Get().(*gzip.Writer)
265 bufCompressed = &bytes.Buffer{}
266 gz.Reset(bufCompressed)
268 wc = &gzipResponseWriter{ResponseWriter: w, Writer: gz}
270 wc = &CountResponseWriter{ResponseWriter: w}
273 wc = &CountResponseWriter{ResponseWriter: w}
275 http.ServeContent(wc, r, "", fi.ModTime().UTC().Truncate(time.Second), fd)
276 if bufCompressed != nil {
283 size := bufCompressed.Len()
284 w.Header().Set("Content-Length", strconv.Itoa(size))
285 wr := wc.(*gzipResponseWriter)
286 w.WriteHeader(wr.status)
287 w.Write(bufCompressed.Bytes())
288 fmt.Printf("%s %s \"%s %s %s\" %d %d %s\"%s\"\n",
289 r.RemoteAddr, host, r.Method, r.URL.Path, r.Proto,
291 username, r.Header.Get("User-Agent"),
295 wr := wc.(*CountResponseWriter)
296 fmt.Printf("%s %s \"%s %s %s\" %d %d %s\"%s\"\n",
297 r.RemoteAddr, host, r.Method, r.URL.Path, r.Proto,
299 username, r.Header.Get("User-Agent"),
303 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
304 if containsDotDot(r.URL.Path) {
305 http.Error(w, "invalid URL path", http.StatusBadRequest)
308 host := strings.SplitN(r.Host, ":", 2)[0]
309 h.Handle(w, r, host, Hosts[host])