2021-12-05 14:09:21 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2021-12-05 14:45:22 +00:00
|
|
|
"bytes"
|
2022-08-12 03:06:26 +00:00
|
|
|
"fmt"
|
2021-12-05 14:45:22 +00:00
|
|
|
"net/http"
|
2021-12-05 14:09:21 +00:00
|
|
|
"time"
|
|
|
|
|
2022-07-12 13:32:48 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2021-12-05 14:09:21 +00:00
|
|
|
"github.com/valyala/fasthttp"
|
2021-12-05 14:45:22 +00:00
|
|
|
|
|
|
|
"codeberg.org/codeberg/pages/server/cache"
|
|
|
|
"codeberg.org/codeberg/pages/server/utils"
|
2021-12-05 14:09:21 +00:00
|
|
|
)
|
|
|
|
|
2022-07-12 13:32:48 +00:00
|
|
|
type fasthttpLogger struct{}
|
|
|
|
|
|
|
|
func (fasthttpLogger) Printf(format string, args ...interface{}) {
|
2022-08-12 03:06:26 +00:00
|
|
|
log.Printf("FastHTTP: %s", fmt.Sprintf(format, args...))
|
2022-07-12 13:32:48 +00:00
|
|
|
}
|
|
|
|
|
2021-12-05 14:45:22 +00:00
|
|
|
func SetupServer(handler fasthttp.RequestHandler) *fasthttp.Server {
|
2021-12-05 14:09:21 +00:00
|
|
|
// Enable compression by wrapping the handler with the compression function provided by FastHTTP
|
|
|
|
compressedHandler := fasthttp.CompressHandlerBrotliLevel(handler, fasthttp.CompressBrotliBestSpeed, fasthttp.CompressBestSpeed)
|
|
|
|
|
2021-12-05 14:45:22 +00:00
|
|
|
return &fasthttp.Server{
|
2021-12-05 14:09:21 +00:00
|
|
|
Handler: compressedHandler,
|
|
|
|
DisablePreParseMultipartForm: true,
|
|
|
|
NoDefaultServerHeader: true,
|
|
|
|
NoDefaultDate: true,
|
|
|
|
ReadTimeout: 30 * time.Second, // needs to be this high for ACME certificates with ZeroSSL & HTTP-01 challenge
|
2022-07-12 13:32:48 +00:00
|
|
|
Logger: fasthttpLogger{},
|
2021-12-05 14:09:21 +00:00
|
|
|
}
|
2021-12-05 14:45:22 +00:00
|
|
|
}
|
2021-12-05 14:09:21 +00:00
|
|
|
|
2021-12-05 16:57:54 +00:00
|
|
|
func SetupHTTPACMEChallengeServer(challengeCache cache.SetGetKey) *fasthttp.Server {
|
2021-12-05 14:45:22 +00:00
|
|
|
challengePath := []byte("/.well-known/acme-challenge/")
|
|
|
|
|
|
|
|
return &fasthttp.Server{
|
|
|
|
Handler: func(ctx *fasthttp.RequestCtx) {
|
|
|
|
if bytes.HasPrefix(ctx.Path(), challengePath) {
|
|
|
|
challenge, ok := challengeCache.Get(string(utils.TrimHostPort(ctx.Host())) + "/" + string(bytes.TrimPrefix(ctx.Path(), challengePath)))
|
|
|
|
if !ok || challenge == nil {
|
|
|
|
ctx.SetStatusCode(http.StatusNotFound)
|
|
|
|
ctx.SetBodyString("no challenge for this token")
|
|
|
|
}
|
|
|
|
ctx.SetBodyString(challenge.(string))
|
|
|
|
} else {
|
|
|
|
ctx.Redirect("https://"+string(ctx.Host())+string(ctx.RequestURI()), http.StatusMovedPermanently)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
2021-12-05 14:09:21 +00:00
|
|
|
}
|