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/>.
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(ioutil.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"),
97 username, err = performAuth(w, r, cfg.Auth)
100 username = "user:" + username + " "
102 printErr := func(code int, err error) {
103 fmt.Printf("%s %s \"%s %+q %s\" %d \"%s\" %s\"%s\"\n",
104 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
106 username, r.Header.Get("User-Agent"),
113 printErr(http.StatusUnauthorized, err)
116 printErr(http.StatusInternalServerError, err)
117 http.Error(w, "internal error", http.StatusInternalServerError)
121 if cfg.TLS != nil && len(cfg.TLS.ClientCAs) > 0 {
123 err = errors.New("TLS client authentication required")
124 printErr(http.StatusForbidden, err)
125 http.Error(w, err.Error(), http.StatusForbidden)
128 username += r.TLS.PeerCertificates[0].Subject.String() + " "
132 for _, hook := range cfg.Hooks {
133 if done := hook(w, r); done {
143 if cfg.WebDAV && (r.Method == http.MethodHead ||
144 r.Method == http.MethodOptions ||
145 r.Method == "PROPFIND") {
146 dav := webdav.Handler{
147 FileSystem: webdav.Dir(cfg.Root),
148 LockSystem: webdav.NewMemLS(),
150 wc := &CountResponseWriter{ResponseWriter: w}
152 fmt.Printf("%s %s \"WebDAV %+q\" %d %d %s\"%s\"\n",
153 r.RemoteAddr, host, PathWithQuery(r.URL),
155 username, r.Header.Get("User-Agent"),
160 if !(r.Method == "" || r.Method == http.MethodGet || r.Method == http.MethodHead) {
161 fmt.Printf("%s %s \"%s %+q %s\" %d %s\"%s\"\n",
162 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
163 http.StatusMethodNotAllowed,
164 username, r.Header.Get("User-Agent"),
166 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
170 var contentType string
172 pthOrig := path.Clean(path.Join(cfg.Root, r.URL.Path))
175 fi, err := os.Stat(pth)
182 entries, err := os.ReadDir(pth)
184 printErr(http.StatusInternalServerError, err)
185 http.Error(w, "internal error", http.StatusInternalServerError)
188 fd, err = os.Open(pth)
190 printErr(http.StatusInternalServerError, err)
191 http.Error(w, "internal error", http.StatusInternalServerError)
194 etag, err = ctimeETag(fd)
197 printErr(http.StatusInternalServerError, err)
198 http.Error(w, "internal error", http.StatusInternalServerError)
202 for _, f := range append(cfg.Readmes, Readme) {
203 readme, _ = ioutil.ReadFile(path.Join(pth, f))
208 fd, err = dirList(cfg, r.URL.Path, entries, string(readme))
210 printErr(http.StatusInternalServerError, err)
211 http.Error(w, "internal error", http.StatusInternalServerError)
214 contentType = "text/html; charset=utf-8"
216 for _, index := range append(cfg.Indexes, Index) {
217 p := path.Join(pth, index)
218 if _, err := os.Stat(p); err == nil {
229 fd, err = os.Open(pth)
231 printErr(http.StatusInternalServerError, err)
232 http.Error(w, "internal error", http.StatusInternalServerError)
235 etag, err = ctimeETag(fd)
237 printErr(http.StatusInternalServerError, err)
238 http.Error(w, "internal error", http.StatusInternalServerError)
244 if meta4fi, err := os.Stat(pth + meta4.Ext); err == nil {
245 if meta4fi.Size() > meta4.MaxSize {
248 meta4Raw, err := ioutil.ReadFile(pth + meta4.Ext)
252 base := path.Base(pth)
253 forHTTP, err := meta4.Parse(base, meta4Raw)
257 w.Header().Add("Link", "<"+base+meta4.Ext+
258 `>; rel=describedby; type="application/metalink4+xml"`,
260 for _, u := range forHTTP.URLs {
261 w.Header().Add("Link", "<"+u+">; rel=duplicate")
263 if forHTTP.SHA256 != nil {
264 w.Header().Add("Digest", "SHA-256="+
265 base64.StdEncoding.EncodeToString(forHTTP.SHA256))
267 if forHTTP.SHA512 != nil {
268 w.Header().Add("Digest", "SHA-512="+
269 base64.StdEncoding.EncodeToString(forHTTP.SHA512))
274 if contentType == "" {
275 contentType = mediaType(path.Base(pth), cfg.MIMEs)
277 contentTypeBase := strings.SplitN(contentType, ";", 2)[0]
278 w.Header().Set("Content-Type", contentType)
280 w.Header().Set("Server", Version)
282 w.Header().Set("ETag", etag)
284 var wc http.ResponseWriter
285 var bufCompressed *bytes.Buffer
287 var zstdW *zstd.Encoder
288 if _, ok := CompressibleContentTypes[contentTypeBase]; ok {
289 if strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
290 w.Header().Set("Content-Encoding", "zstd")
291 zstdW = zstdPool.Get().(*zstd.Encoder)
292 defer zstdPool.Put(zstdW)
293 bufCompressed = &bytes.Buffer{}
294 zstdW.Reset(bufCompressed)
296 wc = &gzipResponseWriter{ResponseWriter: w, Writer: zstdW}
297 } else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
298 w.Header().Set("Content-Encoding", "gzip")
299 gz = gzPool.Get().(*gzip.Writer)
301 bufCompressed = &bytes.Buffer{}
302 gz.Reset(bufCompressed)
304 wc = &gzipResponseWriter{ResponseWriter: w, Writer: gz}
306 wc = &CountResponseWriter{ResponseWriter: w}
309 wc = &CountResponseWriter{ResponseWriter: w}
311 http.ServeContent(wc, r, "", fi.ModTime().UTC().Truncate(time.Second), fd)
312 if bufCompressed != nil {
319 size := bufCompressed.Len()
320 w.Header().Set("Content-Length", strconv.Itoa(size))
321 wr := wc.(*gzipResponseWriter)
322 w.WriteHeader(wr.status)
323 w.Write(bufCompressed.Bytes())
324 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
325 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
327 username, r.Header.Get("User-Agent"),
331 wr := wc.(*CountResponseWriter)
332 fmt.Printf("%s %s \"%s %+q %s\" %d %d %s\"%s\"\n",
333 r.RemoteAddr, host, r.Method, PathWithQuery(r.URL), r.Proto,
335 username, r.Header.Get("User-Agent"),
339 func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
340 if containsDotDot(r.URL.Path) {
341 http.Error(w, "invalid URL path", http.StatusBadRequest)
344 host, _, err := net.SplitHostPort(r.Host)
348 h.Handle(w, r, host, Hosts[host])