Merge pull request #621 from LaurenceJJones/master

Unix socket implementation
This commit is contained in:
Jannis Mattheis
2024-01-20 10:40:00 +01:00
committed by GitHub
6 changed files with 97 additions and 90 deletions

View File

@@ -28,7 +28,7 @@ jobs:
- run: make build-js - run: make build-js
- uses: golangci/golangci-lint-action@v3 - uses: golangci/golangci-lint-action@v3
with: with:
version: v1.53 version: v1.55
args: --timeout=5m args: --timeout=5m
skip-cache: true skip-cache: true
- run: go mod download - run: go mod download

5
app.go
View File

@@ -51,5 +51,8 @@ func main() {
engine, closeable := router.Create(db, vInfo, conf) engine, closeable := router.Create(db, vInfo, conf)
defer closeable() defer closeable()
runner.Run(engine, conf) if err := runner.Run(engine, conf); err != nil {
fmt.Println("Server error: ", err)
os.Exit(1)
}
} }

View File

@@ -3,13 +3,13 @@
server: server:
keepaliveperiodseconds: 0 # 0 = use Go default (15s); -1 = disable keepalive; set the interval in which keepalive packets will be sent. Only change this value if you know what you are doing. keepaliveperiodseconds: 0 # 0 = use Go default (15s); -1 = disable keepalive; set the interval in which keepalive packets will be sent. Only change this value if you know what you are doing.
listenaddr: "" # the address to bind on, leave empty to bind on all addresses listenaddr: "" # the address to bind on, leave empty to bind on all addresses. Prefix with "unix:" to create a unix socket. Example: "unix:/tmp/gotify.sock".
port: 80 # the port the HTTP server will listen on port: 80 # the port the HTTP server will listen on
ssl: ssl:
enabled: false # if https should be enabled enabled: false # if https should be enabled
redirecttohttps: true # redirect to https if site is accessed by http redirecttohttps: true # redirect to https if site is accessed by http
listenaddr: "" # the address to bind on, leave empty to bind on all addresses listenaddr: "" # the address to bind on, leave empty to bind on all addresses. Prefix with "unix:" to create a unix socket. Example: "unix:/tmp/gotify.sock".
port: 443 # the https port port: 443 # the https port
certfile: # the cert file (leave empty when using letsencrypt) certfile: # the cert file (leave empty when using letsencrypt)
certkey: # the cert key (leave empty when using letsencrypt) certkey: # the cert key (leave empty when using letsencrypt)

View File

@@ -5,6 +5,7 @@ import (
"net/http" "net/http"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings"
"time" "time"
"github.com/gin-contrib/cors" "github.com/gin-contrib/cors"
@@ -29,6 +30,28 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co
g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery(), gerror.Handler(), location.Default()) g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery(), gerror.Handler(), location.Default())
g.NoRoute(gerror.NotFound()) g.NoRoute(gerror.NotFound())
if conf.Server.SSL.Enabled != nil && conf.Server.SSL.RedirectToHTTPS != nil && *conf.Server.SSL.Enabled && *conf.Server.SSL.RedirectToHTTPS {
g.Use(func(ctx *gin.Context) {
if ctx.Request.TLS != nil {
ctx.Next()
return
}
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
ctx.Data(http.StatusBadRequest, "text/plain; charset=utf-8", []byte("Use HTTPS"))
ctx.Abort()
return
}
host := ctx.Request.Host
if idx := strings.LastIndex(host, ":"); idx != -1 {
host = host[:idx]
}
if conf.Server.SSL.Port != 443 {
host = fmt.Sprintf("%s:%d", host, conf.Server.SSL.Port)
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("https://%s%s", host, ctx.Request.RequestURI))
ctx.Abort()
})
}
streamHandler := stream.New( streamHandler := stream.New(
time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins) time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins)
go func() { go func() {

View File

@@ -4,11 +4,12 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"log"
"net" "net"
"net/http" "net/http"
"strconv" "os"
"os/signal"
"strings" "strings"
"syscall"
"time" "time"
"github.com/gotify/server/v2/config" "github.com/gotify/server/v2/config"
@@ -16,71 +17,86 @@ import (
) )
// Run starts the http server and if configured a https server. // Run starts the http server and if configured a https server.
func Run(router http.Handler, conf *config.Configuration) { func Run(router http.Handler, conf *config.Configuration) error {
httpHandler := router shutdown := make(chan error)
go doShutdownOnSignal(shutdown)
httpListener, err := startListening("plain connection", conf.Server.ListenAddr, conf.Server.Port, conf.Server.KeepAlivePeriodSeconds)
if err != nil {
return err
}
defer httpListener.Close()
s := &http.Server{Handler: router}
if *conf.Server.SSL.Enabled { if *conf.Server.SSL.Enabled {
if *conf.Server.SSL.RedirectToHTTPS {
httpHandler = redirectToHTTPS(strconv.Itoa(conf.Server.SSL.Port))
}
addr := fmt.Sprintf("%s:%d", conf.Server.SSL.ListenAddr, conf.Server.SSL.Port)
s := &http.Server{
Addr: addr,
Handler: router,
}
if *conf.Server.SSL.LetsEncrypt.Enabled { if *conf.Server.SSL.LetsEncrypt.Enabled {
certManager := autocert.Manager{ applyLetsEncrypt(s, conf)
Prompt: func(tosURL string) bool { return *conf.Server.SSL.LetsEncrypt.AcceptTOS },
HostPolicy: autocert.HostWhitelist(conf.Server.SSL.LetsEncrypt.Hosts...),
Cache: autocert.DirCache(conf.Server.SSL.LetsEncrypt.Cache),
}
httpHandler = certManager.HTTPHandler(httpHandler)
s.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
} }
fmt.Println("Started Listening for TLS connection on " + addr)
httpsListener, err := startListening("TLS connection", conf.Server.SSL.ListenAddr, conf.Server.SSL.Port, conf.Server.KeepAlivePeriodSeconds)
if err != nil {
return err
}
defer httpsListener.Close()
go func() { go func() {
listener := startListening(addr, conf.Server.KeepAlivePeriodSeconds) err := s.ServeTLS(httpsListener, conf.Server.SSL.CertFile, conf.Server.SSL.CertKey)
log.Fatal(s.ServeTLS(listener, conf.Server.SSL.CertFile, conf.Server.SSL.CertKey)) doShutdown(shutdown, err)
}() }()
} }
addr := fmt.Sprintf("%s:%d", conf.Server.ListenAddr, conf.Server.Port) go func() {
fmt.Println("Started Listening for plain HTTP connection on " + addr) err := s.Serve(httpListener)
server := &http.Server{Addr: addr, Handler: httpHandler} doShutdown(shutdown, err)
}()
log.Fatal(server.Serve(startListening(addr, conf.Server.KeepAlivePeriodSeconds))) err = <-shutdown
fmt.Println("Shutting down:", err)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return s.Shutdown(ctx)
} }
func startListening(addr string, keepAlive int) net.Listener { func doShutdownOnSignal(shutdown chan<- error) {
onSignal := make(chan os.Signal, 1)
signal.Notify(onSignal, os.Interrupt, syscall.SIGTERM)
sig := <-onSignal
doShutdown(shutdown, fmt.Errorf("received signal %s", sig))
}
func doShutdown(shutdown chan<- error, err error) {
select {
case shutdown <- err:
default:
// If there is no one listening on the shutdown channel, then the
// shutdown is already initiated and we can ignore these errors.
}
}
func startListening(connectionType, listenAddr string, port, keepAlive int) (net.Listener, error) {
network, addr := getNetworkAndAddr(listenAddr, port)
lc := net.ListenConfig{KeepAlive: time.Duration(keepAlive) * time.Second} lc := net.ListenConfig{KeepAlive: time.Duration(keepAlive) * time.Second}
conn, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil { l, err := lc.Listen(context.Background(), network, addr)
log.Fatalln("Could not listen on", addr, err) if err == nil {
fmt.Println("Started listening for", connectionType, "on", l.Addr().Network(), l.Addr().String())
} }
return conn return l, err
} }
func redirectToHTTPS(port string) http.HandlerFunc { func getNetworkAndAddr(listenAddr string, port int) (string, string) {
return func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(listenAddr, "unix:") {
if r.Method != "GET" && r.Method != "HEAD" { return "unix", strings.TrimPrefix(listenAddr, "unix:")
http.Error(w, "Use HTTPS", http.StatusBadRequest)
return
}
target := "https://" + changePort(r.Host, port) + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusFound)
} }
return "tcp", fmt.Sprintf("%s:%d", listenAddr, port)
} }
func changePort(hostPort, port string) string { func applyLetsEncrypt(s *http.Server, conf *config.Configuration) {
host, _, err := net.SplitHostPort(hostPort) certManager := autocert.Manager{
if err != nil { Prompt: func(tosURL string) bool { return *conf.Server.SSL.LetsEncrypt.AcceptTOS },
// There is no exported error. HostPolicy: autocert.HostWhitelist(conf.Server.SSL.LetsEncrypt.Hosts...),
if !strings.Contains(err.Error(), "missing port") { Cache: autocert.DirCache(conf.Server.SSL.LetsEncrypt.Cache),
return hostPort
}
host = hostPort
} }
return net.JoinHostPort(host, port) s.Handler = certManager.HTTPHandler(s.Handler)
s.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
} }

View File

@@ -1,35 +0,0 @@
package runner
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRedirect(t *testing.T) {
cases := []struct {
Request string
TLS int
Expect string
}{
{Request: "http://gotify.net/meow", TLS: 443, Expect: "https://gotify.net:443/meow"},
{Request: "http://gotify.net:8080/meow", TLS: 443, Expect: "https://gotify.net:443/meow"},
{Request: "http://gotify.net:8080/meow", TLS: 8443, Expect: "https://gotify.net:8443/meow"},
}
for _, testCase := range cases {
name := fmt.Sprintf("%s -- %d -> %s", testCase.Request, testCase.TLS, testCase.Expect)
t.Run(name, func(t *testing.T) {
req := httptest.NewRequest("GET", testCase.Request, nil)
rec := httptest.NewRecorder()
redirectToHTTPS(fmt.Sprint(testCase.TLS)).ServeHTTP(rec, req)
assert.Equal(t, http.StatusFound, rec.Result().StatusCode)
assert.Equal(t, testCase.Expect, rec.Header().Get("location"))
})
}
}