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/>.
37 "github.com/klauspost/compress/zstd"
38 "golang.org/x/net/webdav"
49 New: func() interface{} { return gzip.NewWriter(ioutil.Discard) },
52 New: func() interface{} {
53 w, err := zstd.NewWriter(
55 zstd.WithEncoderLevel(zstd.SpeedDefault),
67 func PathWithQuery(u *url.URL) string {
69 return u.EscapedPath()
71 return u.EscapedPath() + "?" + u.RawQuery
76 func (h Handler) Handle(
77 w http.ResponseWriter, r *http.Request,
78 host string, cfg *HostCfg,
81 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\"\n",
82 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
84 r.Header.Get("User-Agent"),
96 username, err = performAuth(w, r, cfg.Auth)
99 username = "user:" + username + " "
101 printErr := func(code int, err error) {
102 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\" %s\"%s\"\n",
103 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
105 username, r.Header.Get("User-Agent"),
112 printErr(http.StatusUnauthorized, err)
115 printErr(http.StatusInternalServerError, err)
116 http.Error(w, "internal error", http.StatusInternalServerError)
120 if cfg.TLS != nil && len(cfg.TLS.ClientCAs) > 0 {
122 err = errors.New("TLS client authentication required")
123 printErr(http.StatusForbidden, err)
124 http.Error(w, err.Error(), http.StatusForbidden)
127 username += r.TLS.PeerCertificates[0].Subject.String() + " "
131 for _, hook := range cfg.Hooks {
132 if done := hook(w, r); done {
142 if cfg.WebDAV && (r.Method == http.MethodHead ||
143 r.Method == http.MethodOptions ||
144 r.Method == "PROPFIND") {
145 dav := webdav.Handler{
146 FileSystem: webdav.Dir(cfg.Root),
147 LockSystem: webdav.NewMemLS(),
149 wc := &CountResponseWriter{ResponseWriter: w}
151 fmt.Printf("%s %s \"WebDAV %+q\" %d %d %s\"%s\"\n",
152 r.RemoteAddr, host, PathWithQuery(r.URL),
154 username, r.Header.Get("User-Agent"),
159 if !(r.Method == "" || r.Method == http.MethodGet) {
160 fmt.Printf("%s %s \"%s %+q %s\" %d %s\"%s\"\n",
161 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
162 http.StatusMethodNotAllowed,
163 username, r.Header.Get("User-Agent"),
165 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
169 var contentType string
171 pthOrig := path.Clean(path.Join(cfg.Root, r.URL.Path))
174 fi, err := os.Stat(pth)
181 entries, err := os.ReadDir(pth)
183 printErr(http.StatusInternalServerError, err)
184 http.Error(w, "internal error", http.StatusInternalServerError)
187 fd, err = os.Open(pth)
189 printErr(http.StatusInternalServerError, err)
190 http.Error(w, "internal error", http.StatusInternalServerError)
193 etag, err = ctimeETag(fd)
196 printErr(http.StatusInternalServerError, err)
197 http.Error(w, "internal error", http.StatusInternalServerError)
201 for _, f := range append(cfg.Readmes, Readme) {
202 readme, _ = ioutil.ReadFile(path.Join(pth, f))
207 fd, err = dirList(cfg, r.URL.Path, entries, string(readme))
209 printErr(http.StatusInternalServerError, err)
210 http.Error(w, "internal error", http.StatusInternalServerError)
213 contentType = "text/html; charset=utf-8"
215 for _, index := range append(cfg.Indexes, Index) {
216 p := path.Join(pth, index)
217 if _, err := os.Stat(p); err == nil {
228 fd, err = os.Open(pth)
230 printErr(http.StatusInternalServerError, err)
231 http.Error(w, "internal error", http.StatusInternalServerError)
234 etag, err = ctimeETag(fd)
236 printErr(http.StatusInternalServerError, err)
237 http.Error(w, "internal error", http.StatusInternalServerError)
243 if _, err = os.Stat(pth + Meta4Ext); err == nil {
244 w.Header().Set("Link", "<"+path.Base(pth)+Meta4Ext+`>; rel=describedby; type="application/metalink4+xml"`)
247 if contentType == "" {
248 contentType = mediaType(path.Base(pth), cfg.MIMEs)
250 contentTypeBase := strings.SplitN(contentType, ";", 2)[0]
251 w.Header().Set("Content-Type", contentType)
253 w.Header().Set("Server", Version)
255 w.Header().Set("ETag", etag)
257 var wc http.ResponseWriter
258 var bufCompressed *bytes.Buffer
260 var zstdW *zstd.Encoder
261 if _, ok := CompressibleContentTypes[contentTypeBase]; ok {
262 if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
263 w.Header().Set("Content-Encoding", "zstd")
264 zstdW = zstdPool.Get().(*zstd.Encoder)
265 defer zstdPool.Put(zstdW)
266 bufCompressed = &bytes.Buffer{}
267 zstdW.Reset(bufCompressed)
269 wc = &gzipResponseWriter{ResponseWriter: w, Writer: zstdW}
270 } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
271 w.Header().Set("Content-Encoding", "gzip")
272 gz = gzPool.Get().(*gzip.Writer)
274 bufCompressed = &bytes.Buffer{}
275 gz.Reset(bufCompressed)
277 wc = &gzipResponseWriter{ResponseWriter: w, Writer: gz}
279 wc = &CountResponseWriter{ResponseWriter: w}
282 wc = &CountResponseWriter{ResponseWriter: w}
284 http.ServeContent(wc, r, "", fi.ModTime().UTC().Truncate(time.Second), fd)
285 if bufCompressed != nil {
292 size := bufCompressed.Len()
293 w.Header().Set("Content-Length", strconv.Itoa(size))
294 wr := wc.(*gzipResponseWriter)
295 w.WriteHeader(wr.status)
296 w.Write(bufCompressed.Bytes())
297 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
298 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
300 username, r.Header.Get("User-Agent"),
304 wr := wc.(*CountResponseWriter)
305 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
306 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
308 username, r.Header.Get("User-Agent"),
312 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
313 if containsDotDot(r.URL.Path) {
314 http.Error(w, "invalid URL path", http.StatusBadRequest)
317 host, _, err := net.SplitHostPort(r.Host)
321 h.Handle(w, r, host, Hosts[host])