httpd: add support for listening over a Unix-domain socket

Fixes #266
This commit is contained in:
Nicola Murino
2020-12-29 19:02:56 +01:00
parent 40e759c983
commit 0966d44c0f
8 changed files with 102 additions and 13 deletions

View File

@@ -11,6 +11,7 @@ import (
"fmt"
"net/http"
"path/filepath"
"runtime"
"time"
"github.com/go-chi/chi"
@@ -50,6 +51,7 @@ const (
// MaxRestoreSize defines the max size for the loaddata input file
MaxRestoreSize = 10485760 // 10 MB
maxRequestSize = 1048576 // 1MB
osWindows = "windows"
)
var (
@@ -99,6 +101,17 @@ type apiResponse struct {
Message string `json:"message"`
}
// ShouldBind returns true if there service must be started
func (c Conf) ShouldBind() bool {
if c.BindPort > 0 {
return true
}
if filepath.IsAbs(c.BindAddress) && runtime.GOOS != osWindows {
return true
}
return false
}
// Initialize configures and starts the HTTP server
func (c Conf) Initialize(configDir string) error {
var err error
@@ -128,7 +141,6 @@ func (c Conf) Initialize(configDir string) error {
}
initializeRouter(staticFilesPath, enableWebAdmin)
httpServer := &http.Server{
Addr: fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort),
Handler: router,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
@@ -145,9 +157,9 @@ func (c Conf) Initialize(configDir string) error {
MinVersion: tls.VersionTLS12,
}
httpServer.TLSConfig = config
return httpServer.ListenAndServeTLS("", "")
return utils.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, true)
}
return httpServer.ListenAndServe()
return utils.HTTPListenAndServe(httpServer, c.BindAddress, c.BindPort, false)
}
// ReloadTLSCertificate reloads the TLS certificate and key from the configured paths

View File

@@ -16,6 +16,7 @@ import (
"github.com/go-chi/chi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/drakkan/sftpgo/common"
"github.com/drakkan/sftpgo/dataprovider"
@@ -29,6 +30,21 @@ const (
inactiveURL = "http://127.0.0.1:12345"
)
func TestShouldBind(t *testing.T) {
c := Conf{
BindPort: 10000,
}
require.True(t, c.ShouldBind())
c.BindPort = 0
require.False(t, c.ShouldBind())
if runtime.GOOS != osWindows {
c.BindAddress = "/absolute/path"
require.True(t, c.ShouldBind())
}
}
func TestGetRespStatus(t *testing.T) {
var err error
err = &dataprovider.MethodDisabledError{}
@@ -631,7 +647,7 @@ func TestBasicAuth(t *testing.T) {
SetBaseURLAndCredentials(httpBaseURL, "test3", "password2")
_, _, err = GetVersion(http.StatusUnauthorized)
assert.NoError(t, err)
if runtime.GOOS != "windows" {
if runtime.GOOS != osWindows {
authUserData = append(authUserData, []byte("test5:$apr1$gLnIkRIf$Xr/6aJfmIrihP4b2N2tcs/\n")...)
err = ioutil.WriteFile(authUserFile, authUserData, os.ModePerm)
assert.NoError(t, err)