1 // godlighty -- highly-customizable HTTP, HTTP/2, HTTPS server
2 // Copyright (C) 2021-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
36 "github.com/klauspost/compress/zstd"
37 "go.stargrave.org/godlighty/meta4"
38 "golang.org/x/net/webdav"
48 New: func() interface{} { return gzip.NewWriter(io.Discard) },
51 New: func() interface{} {
52 w, err := zstd.NewWriter(
54 zstd.WithEncoderLevel(zstd.SpeedDefault),
66 func PathWithQuery(u *url.URL) string {
68 return u.EscapedPath()
70 return u.EscapedPath() + "?" + u.RawQuery
75 func (h Handler) Handle(
76 w http.ResponseWriter, r *http.Request,
77 host string, cfg *HostCfg,
80 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\"\n",
81 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
83 r.Header.Get("User-Agent"),
87 w.Header().Set("Server", Version)
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.ECDSATLS != nil && len(cfg.ECDSATLS.ClientCAs) > 0) ||
121 (cfg.EdDSATLS != nil && len(cfg.EdDSATLS.ClientCAs) > 0) ||
122 (cfg.GOSTTLS != nil && len(cfg.GOSTTLS.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 = mtimeETag(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 = mtimeETag(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 for name, digest := range forHTTP.Hashes {
272 w.Header().Add("Digest", name+"="+base64.StdEncoding.EncodeToString(digest))
274 for _, u := range forHTTP.Torrents {
275 w.Header().Add("Link", "<"+u+`>; rel=describedby; type="application/x-bittorrent"`)
280 if contentType == "" {
281 contentType = mediaType(path.Base(pth), cfg.MIMEs)
283 contentTypeBase := strings.SplitN(contentType, ";", 2)[0]
284 w.Header().Set("Content-Type", contentType)
287 w.Header().Set("ETag", etag)
289 var wc http.ResponseWriter
290 var bufCompressed *bytes.Buffer
292 var zstdW *zstd.Encoder
293 if _, ok := CompressibleContentTypes[contentTypeBase]; ok {
294 if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
295 w.Header().Set("Content-Encoding", "zstd")
296 zstdW = zstdPool.Get().(*zstd.Encoder)
297 defer zstdPool.Put(zstdW)
298 bufCompressed = &bytes.Buffer{}
299 zstdW.Reset(bufCompressed)
301 wc = &gzipResponseWriter{ResponseWriter: w, Writer: zstdW}
302 } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
303 w.Header().Set("Content-Encoding", "gzip")
304 gz = gzPool.Get().(*gzip.Writer)
306 bufCompressed = &bytes.Buffer{}
307 gz.Reset(bufCompressed)
309 wc = &gzipResponseWriter{ResponseWriter: w, Writer: gz}
311 wc = &CountResponseWriter{ResponseWriter: w}
314 wc = &CountResponseWriter{ResponseWriter: w}
316 http.ServeContent(wc, r, "", fi.ModTime().UTC().Truncate(time.Second), fd)
317 if bufCompressed != nil {
324 size := bufCompressed.Len()
325 w.Header().Set("Content-Length", strconv.Itoa(size))
326 wr := wc.(*gzipResponseWriter)
327 w.WriteHeader(wr.status)
328 w.Write(bufCompressed.Bytes())
329 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
330 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
332 username, r.Header.Get("User-Agent"),
336 wr := wc.(*CountResponseWriter)
337 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
338 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
340 username, r.Header.Get("User-Agent"),
344 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
345 if containsDotDot(r.URL.Path) {
346 http.Error(w, "invalid URL path", http.StatusBadRequest)
349 host, _, err := net.SplitHostPort(r.Host)
353 h.Handle(w, r, host, Hosts[host])