2 godlighty -- highly-customizable HTTP, HTTP/2, HTTPS server
3 Copyright (C) 2021-2022 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/>.
38 "github.com/klauspost/compress/zstd"
39 "go.stargrave.org/godlighty/meta4"
40 "golang.org/x/net/webdav"
50 New: func() interface{} { return gzip.NewWriter(io.Discard) },
53 New: func() interface{} {
54 w, err := zstd.NewWriter(
56 zstd.WithEncoderLevel(zstd.SpeedDefault),
68 func PathWithQuery(u *url.URL) string {
70 return u.EscapedPath()
72 return u.EscapedPath() + "?" + u.RawQuery
77 func (h Handler) Handle(
78 w http.ResponseWriter, r *http.Request,
79 host string, cfg *HostCfg,
82 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\"\n",
83 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
85 r.Header.Get("User-Agent"),
89 w.Header().Set("Server", Version)
98 username, err = performAuth(w, r, cfg.Auth)
101 username = "user:" + username + " "
103 printErr := func(code int, err error) {
104 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\" %s\"%s\"\n",
105 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
107 username, r.Header.Get("User-Agent"),
114 printErr(http.StatusUnauthorized, err)
117 printErr(http.StatusInternalServerError, err)
118 http.Error(w, "internal error", http.StatusInternalServerError)
122 if cfg.TLS != nil && len(cfg.TLS.ClientCAs) > 0 {
124 err = errors.New("TLS client authentication required")
125 printErr(http.StatusForbidden, err)
126 http.Error(w, err.Error(), http.StatusForbidden)
129 username += r.TLS.PeerCertificates[0].Subject.String() + " "
133 for _, hook := range cfg.Hooks {
134 if done := hook(w, r); done {
144 pthOrig := path.Clean(path.Join(cfg.Root, r.URL.Path))
146 fi, err := os.Stat(pth)
152 if cfg.WebDAV && (((r.Method == http.MethodHead) && fi.IsDir()) ||
153 r.Method == http.MethodOptions ||
154 r.Method == "PROPFIND") {
155 dav := webdav.Handler{
156 FileSystem: webdav.Dir(cfg.Root),
157 LockSystem: webdav.NewMemLS(),
159 wc := &CountResponseWriter{ResponseWriter: w}
161 fmt.Printf("%s %s \"WebDAV %+q\" %d %d %s\"%s\"\n",
162 r.RemoteAddr, host, PathWithQuery(r.URL),
164 username, r.Header.Get("User-Agent"),
169 if !(r.Method == "" || r.Method == http.MethodGet || r.Method == http.MethodHead) {
170 fmt.Printf("%s %s \"%s %+q %s\" %d %s\"%s\"\n",
171 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
172 http.StatusMethodNotAllowed,
173 username, r.Header.Get("User-Agent"),
175 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
180 var contentType string
185 entries, err := os.ReadDir(pth)
187 printErr(http.StatusInternalServerError, err)
188 http.Error(w, "internal error", http.StatusInternalServerError)
191 fd, err = os.Open(pth)
193 printErr(http.StatusInternalServerError, err)
194 http.Error(w, "internal error", http.StatusInternalServerError)
197 etag, err = ctimeETag(fd)
200 printErr(http.StatusInternalServerError, err)
201 http.Error(w, "internal error", http.StatusInternalServerError)
205 for _, f := range append(cfg.Readmes, Readme) {
206 readme, _ = os.ReadFile(path.Join(pth, f))
211 fd, err = dirList(cfg, r.URL.Path, pth, entries, string(readme))
213 printErr(http.StatusInternalServerError, err)
214 http.Error(w, "internal error", http.StatusInternalServerError)
217 contentType = "text/html; charset=utf-8"
219 for _, index := range append(cfg.Indices, Index) {
220 p := path.Join(pth, index)
221 if _, err := os.Stat(p); err == nil {
223 fi, err = os.Stat(pth)
237 fd, err = os.Open(pth)
239 printErr(http.StatusInternalServerError, err)
240 http.Error(w, "internal error", http.StatusInternalServerError)
243 etag, err = ctimeETag(fd)
245 printErr(http.StatusInternalServerError, err)
246 http.Error(w, "internal error", http.StatusInternalServerError)
252 if meta4fi, err := os.Stat(pth + meta4.Ext); err == nil {
253 if meta4fi.Size() > meta4.MaxSize {
256 meta4Raw, err := os.ReadFile(pth + meta4.Ext)
260 base := path.Base(pth)
261 forHTTP, err := meta4.Parse(base, meta4Raw)
265 w.Header().Add("Link", "<"+base+meta4.Ext+
266 `>; rel=describedby; type="application/metalink4+xml"`,
268 for _, u := range forHTTP.URLs {
269 w.Header().Add("Link", "<"+u+">; rel=duplicate")
271 if forHTTP.SHA256 != nil {
272 w.Header().Add("Digest", "SHA-256="+
273 base64.StdEncoding.EncodeToString(forHTTP.SHA256))
275 if forHTTP.SHA512 != nil {
276 w.Header().Add("Digest", "SHA-512="+
277 base64.StdEncoding.EncodeToString(forHTTP.SHA512))
282 if contentType == "" {
283 contentType = mediaType(path.Base(pth), cfg.MIMEs)
285 contentTypeBase := strings.SplitN(contentType, ";", 2)[0]
286 w.Header().Set("Content-Type", contentType)
289 w.Header().Set("ETag", etag)
291 var wc http.ResponseWriter
292 var bufCompressed *bytes.Buffer
294 var zstdW *zstd.Encoder
295 if _, ok := CompressibleContentTypes[contentTypeBase]; ok {
296 if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
297 w.Header().Set("Content-Encoding", "zstd")
298 zstdW = zstdPool.Get().(*zstd.Encoder)
299 defer zstdPool.Put(zstdW)
300 bufCompressed = &bytes.Buffer{}
301 zstdW.Reset(bufCompressed)
303 wc = &gzipResponseWriter{ResponseWriter: w, Writer: zstdW}
304 } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
305 w.Header().Set("Content-Encoding", "gzip")
306 gz = gzPool.Get().(*gzip.Writer)
308 bufCompressed = &bytes.Buffer{}
309 gz.Reset(bufCompressed)
311 wc = &gzipResponseWriter{ResponseWriter: w, Writer: gz}
313 wc = &CountResponseWriter{ResponseWriter: w}
316 wc = &CountResponseWriter{ResponseWriter: w}
318 http.ServeContent(wc, r, "", fi.ModTime().UTC().Truncate(time.Second), fd)
319 if bufCompressed != nil {
326 size := bufCompressed.Len()
327 w.Header().Set("Content-Length", strconv.Itoa(size))
328 wr := wc.(*gzipResponseWriter)
329 w.WriteHeader(wr.status)
330 w.Write(bufCompressed.Bytes())
331 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
332 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
334 username, r.Header.Get("User-Agent"),
338 wr := wc.(*CountResponseWriter)
339 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
340 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
342 username, r.Header.Get("User-Agent"),
346 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
347 if containsDotDot(r.URL.Path) {
348 http.Error(w, "invalid URL path", http.StatusBadRequest)
351 host, _, err := net.SplitHostPort(r.Host)
355 h.Handle(w, r, host, Hosts[host])