mirror of
https://github.com/gotify/server.git
synced 2024-01-28 15:20:56 +03:00
feat: listen on unix sockets
With this you can configure a unix socket in server.listenaddr and server.ssl.listenaddr by prefixing the socket path with unix: Co-authored-by: Jannis Mattheis <contact@jmattheis.de>
This commit is contained in:
committed by
Jannis Mattheis
parent
0bfa5ca4d9
commit
d0b3271880
5
app.go
5
app.go
@@ -51,5 +51,8 @@ func main() {
|
||||
engine, closeable := router.Create(db, vInfo, conf)
|
||||
defer closeable()
|
||||
|
||||
runner.Run(engine, conf)
|
||||
if err := runner.Run(engine, conf); err != nil {
|
||||
fmt.Println("Server error: ", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
ssl:
|
||||
enabled: false # if https should be enabled
|
||||
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
|
||||
certfile: # the cert file (leave empty when using letsencrypt)
|
||||
certkey: # the cert key (leave empty when using letsencrypt)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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.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(
|
||||
time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins)
|
||||
go func() {
|
||||
|
||||
118
runner/runner.go
118
runner/runner.go
@@ -4,11 +4,12 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gotify/server/v2/config"
|
||||
@@ -16,71 +17,86 @@ import (
|
||||
)
|
||||
|
||||
// Run starts the http server and if configured a https server.
|
||||
func Run(router http.Handler, conf *config.Configuration) {
|
||||
httpHandler := router
|
||||
func Run(router http.Handler, conf *config.Configuration) error {
|
||||
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.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 {
|
||||
certManager := autocert.Manager{
|
||||
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}
|
||||
applyLetsEncrypt(s, conf)
|
||||
}
|
||||
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() {
|
||||
listener := startListening(addr, conf.Server.KeepAlivePeriodSeconds)
|
||||
log.Fatal(s.ServeTLS(listener, conf.Server.SSL.CertFile, conf.Server.SSL.CertKey))
|
||||
err := s.ServeTLS(httpsListener, conf.Server.SSL.CertFile, conf.Server.SSL.CertKey)
|
||||
doShutdown(shutdown, err)
|
||||
}()
|
||||
}
|
||||
addr := fmt.Sprintf("%s:%d", conf.Server.ListenAddr, conf.Server.Port)
|
||||
fmt.Println("Started Listening for plain HTTP connection on " + addr)
|
||||
server := &http.Server{Addr: addr, Handler: httpHandler}
|
||||
go func() {
|
||||
err := s.Serve(httpListener)
|
||||
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}
|
||||
conn, err := lc.Listen(context.Background(), "tcp", addr)
|
||||
if err != nil {
|
||||
log.Fatalln("Could not listen on", addr, err)
|
||||
|
||||
l, err := lc.Listen(context.Background(), network, addr)
|
||||
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 {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" && r.Method != "HEAD" {
|
||||
http.Error(w, "Use HTTPS", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
target := "https://" + changePort(r.Host, port) + r.URL.RequestURI()
|
||||
http.Redirect(w, r, target, http.StatusFound)
|
||||
func getNetworkAndAddr(listenAddr string, port int) (string, string) {
|
||||
if strings.HasPrefix(listenAddr, "unix:") {
|
||||
return "unix", strings.TrimPrefix(listenAddr, "unix:")
|
||||
}
|
||||
return "tcp", fmt.Sprintf("%s:%d", listenAddr, port)
|
||||
}
|
||||
|
||||
func changePort(hostPort, port string) string {
|
||||
host, _, err := net.SplitHostPort(hostPort)
|
||||
if err != nil {
|
||||
// There is no exported error.
|
||||
if !strings.Contains(err.Error(), "missing port") {
|
||||
return hostPort
|
||||
}
|
||||
host = hostPort
|
||||
func applyLetsEncrypt(s *http.Server, conf *config.Configuration) {
|
||||
certManager := autocert.Manager{
|
||||
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),
|
||||
}
|
||||
return net.JoinHostPort(host, port)
|
||||
s.Handler = certManager.HTTPHandler(s.Handler)
|
||||
s.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
|
||||
}
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user