anyhttp/anyhttp.go

257 lines
6.3 KiB
Go
Raw Normal View History

2023-04-20 16:31:35 -04:00
// Package anyhttp has helpers to serve http from unix sockets and systemd socket activated fds
package anyhttp
import (
"errors"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
2023-04-20 16:31:35 -04:00
"syscall"
)
2023-09-08 19:10:36 -04:00
type AddressType string
var (
UnixSocket AddressType = "UnixSocket"
SystemdFD AddressType = "SystemdFD"
TCP AddressType = "TCP"
Unknown AddressType = "Unknown"
)
2023-04-20 17:56:44 -04:00
// UnixSocketConfig has the configuration for Unix socket
2023-04-20 16:31:35 -04:00
type UnixSocketConfig struct {
2023-04-20 17:56:44 -04:00
// Absolute or relative path of socket, e.g. /run/app.sock
SocketPath string
// Socket file permission
SocketMode fs.FileMode
// Whether to delete existing socket before creating new one
2023-04-20 16:31:35 -04:00
RemoveExisting bool
}
2023-04-20 17:56:44 -04:00
// DefaultUnixSocketConfig has defaults for UnixSocketConfig
2023-04-20 16:31:35 -04:00
var DefaultUnixSocketConfig = UnixSocketConfig{
SocketMode: 0666,
RemoveExisting: true,
}
2023-04-20 17:56:44 -04:00
// NewUnixSocketConfig creates a UnixSocketConfig with the default values and the socketPath passed
2023-04-20 16:31:35 -04:00
func NewUnixSocketConfig(socketPath string) UnixSocketConfig {
usc := DefaultUnixSocketConfig
usc.SocketPath = socketPath
return usc
}
type sysdEnvData struct {
pid int
fdNames []string
fdNamesStr string
numFds int
}
var sysdEnvParser = struct {
sysdOnce sync.Once
data sysdEnvData
err error
}{}
func parse() (sysdEnvData, error) {
p := &sysdEnvParser
p.sysdOnce.Do(func() {
p.data.pid, p.err = strconv.Atoi(os.Getenv("LISTEN_PID"))
if p.err != nil {
p.err = fmt.Errorf("invalid LISTEN_PID, err: %w", p.err)
return
}
p.data.numFds, p.err = strconv.Atoi(os.Getenv("LISTEN_FDS"))
if p.err != nil {
p.err = fmt.Errorf("invalid LISTEN_FDS, err: %w", p.err)
return
}
p.data.fdNamesStr = os.Getenv("LISTEN_FDNAMES")
p.data.fdNames = strings.Split(p.data.fdNamesStr, ":")
})
return p.data, p.err
}
2023-04-20 17:56:44 -04:00
// SysdConfig has the configuration for the socket activated fd
2023-04-20 16:31:35 -04:00
type SysdConfig struct {
2023-04-20 17:56:44 -04:00
// Integer value starting at 0. Either index or name is required
FDIndex *int
// Name configured via FileDescriptorName or the default socket file name. Either index or name is required
FDName *string
// Check process PID matches LISTEN_PID
2023-04-20 16:31:35 -04:00
CheckPID bool
2023-04-20 17:56:44 -04:00
// Unsets the LISTEN* environment variables, so they don't get passed to any child processes
2023-04-20 16:31:35 -04:00
UnsetEnv bool
}
2023-04-20 17:56:44 -04:00
// DefaultSysdConfig has the default values for SysdConfig
2023-04-20 16:31:35 -04:00
var DefaultSysdConfig = SysdConfig{
CheckPID: true,
UnsetEnv: true,
2023-04-20 16:31:35 -04:00
}
2023-04-20 17:56:44 -04:00
// NewSysDConfigWithFDIdx creates SysdConfig with defaults and fdIdx
2023-04-20 16:31:35 -04:00
func NewSysDConfigWithFDIdx(fdIdx int) SysdConfig {
sysc := DefaultSysdConfig
sysc.FDIndex = &fdIdx
return sysc
}
2023-04-20 17:56:44 -04:00
// NewSysDConfigWithFDName creates SysdConfig with defaults and fdName
2023-04-20 16:31:35 -04:00
func NewSysDConfigWithFDName(fdName string) SysdConfig {
sysc := DefaultSysdConfig
sysc.FDName = &fdName
return sysc
}
2023-04-20 17:56:44 -04:00
// GetListener returns the unix socket listener
2023-04-20 16:31:35 -04:00
func (u *UnixSocketConfig) GetListener() (net.Listener, error) {
if u.RemoveExisting {
if err := os.Remove(u.SocketPath); err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
}
l, err := net.Listen("unix", u.SocketPath)
if err != nil {
return nil, err
}
if err = os.Chmod(u.SocketPath, u.SocketMode); err != nil {
return nil, err
}
return l, nil
}
2023-04-20 17:56:44 -04:00
// StartFD is the starting file descriptor number
2023-04-20 16:31:35 -04:00
const StartFD = 3
func makeFdListener(fd int, name string) (net.Listener, error) {
fdFile := os.NewFile(uintptr(fd), name)
l, err := net.FileListener(fdFile)
if err != nil {
return nil, err
}
syscall.CloseOnExec(fd)
return l, nil
}
2023-04-20 17:56:44 -04:00
// GetListener returns the FileListener created with socketed activated fd
2023-04-20 16:31:35 -04:00
func (s *SysdConfig) GetListener() (net.Listener, error) {
if s.UnsetEnv {
defer UnsetSystemdListenVars()
}
envData, err := parse()
2023-04-20 16:31:35 -04:00
if err != nil {
return nil, err
2023-04-20 16:31:35 -04:00
}
if s.CheckPID {
if envData.pid != os.Getpid() {
return nil, fmt.Errorf("unexpected PID, current:%v, LISTEN_PID: %v", os.Getpid(), envData.pid)
}
}
2023-04-20 16:31:35 -04:00
if s.FDIndex != nil {
idx := *s.FDIndex
if idx < 0 || idx >= envData.numFds {
return nil, fmt.Errorf("invalid fd index, expected between 0 and %v, got: %v", envData.numFds, idx)
2023-04-20 16:31:35 -04:00
}
fd := StartFD + idx
if idx < len(envData.fdNames) {
return makeFdListener(fd, envData.fdNames[idx])
2023-04-20 16:31:35 -04:00
}
2023-04-20 17:56:44 -04:00
return makeFdListener(fd, fmt.Sprintf("sysdfd_%d", fd))
2023-04-20 16:31:35 -04:00
}
if s.FDName != nil {
for idx, name := range envData.fdNames {
2023-04-20 16:31:35 -04:00
if name == *s.FDName {
fd := StartFD + idx
return makeFdListener(fd, name)
}
}
return nil, fmt.Errorf("fdName not found: %q, LISTEN_FDNAMES:%q", *s.FDName, envData.fdNamesStr)
2023-04-20 16:31:35 -04:00
}
2023-04-28 15:29:17 -04:00
return nil, errors.New("neither FDIndex nor FDName set")
}
2023-04-20 16:31:35 -04:00
// GetListener gets a unix or systemd socket listener
2023-09-08 19:10:36 -04:00
func GetListener(addr string) (AddressType, net.Listener, error) {
2023-04-20 16:31:35 -04:00
if strings.HasPrefix(addr, "unix/") {
usc := NewUnixSocketConfig(strings.TrimPrefix(addr, "unix/"))
2023-09-08 19:10:36 -04:00
l, err := usc.GetListener()
return UnixSocket, l, err
2023-04-20 16:31:35 -04:00
}
if strings.HasPrefix(addr, "sysd/fdidx/") {
idx, err := strconv.Atoi(strings.TrimPrefix(addr, "sysd/fdidx/"))
if err != nil {
2023-09-08 19:10:36 -04:00
return Unknown, nil, fmt.Errorf("invalid fdidx, addr:%q err: %w", addr, err)
2023-04-20 16:31:35 -04:00
}
sysdc := NewSysDConfigWithFDIdx(idx)
2023-09-08 19:10:36 -04:00
l, err := sysdc.GetListener()
return SystemdFD, l, err
2023-04-20 16:31:35 -04:00
}
if strings.HasPrefix(addr, "sysd/fdname/") {
sysdc := NewSysDConfigWithFDName(strings.TrimPrefix(addr, "sysd/fdname/"))
2023-09-08 19:10:36 -04:00
l, err := sysdc.GetListener()
return SystemdFD, l, err
2023-04-20 16:31:35 -04:00
}
2023-09-08 19:10:36 -04:00
if port, err := strconv.Atoi(addr); err == nil {
if port > 0 && port < 65536 {
addr = fmt.Sprintf(":%v", port)
} else {
return Unknown, nil, fmt.Errorf("invalid port: %v", port)
}
2023-04-20 16:31:35 -04:00
}
2023-09-08 19:10:36 -04:00
if addr == "" {
addr = ":http"
2023-04-20 16:31:35 -04:00
}
2023-09-08 19:10:36 -04:00
l, err := net.Listen("tcp", addr)
return TCP, l, err
}
2023-04-20 16:31:35 -04:00
2023-09-08 19:10:36 -04:00
func ListenAndServeHTTP(addr string, h http.Handler) (AddressType, *http.Server, error) {
addrType, listener, err := GetListener(addr)
if err != nil {
return addrType, nil, err
2023-04-20 16:31:35 -04:00
}
2023-09-08 19:10:36 -04:00
srv := &http.Server{Handler: h}
err = srv.Serve(listener)
return addrType, srv, err
}
2023-04-20 16:31:35 -04:00
2023-09-08 19:10:36 -04:00
// ListenAndServe is the drop-in replacement for `http.ListenAndServe`.
// Supports unix and systemd sockets in addition
func ListenAndServe(addr string, h http.Handler) error {
_, _, err := ListenAndServeHTTP(addr, h)
return err
2023-04-20 16:31:35 -04:00
}
2023-04-20 17:56:44 -04:00
// UnsetSystemdListenVars unsets the LISTEN* environment variables so they are not passed to any child processes
2023-04-20 16:31:35 -04:00
func UnsetSystemdListenVars() {
_ = os.Unsetenv("LISTEN_PID")
_ = os.Unsetenv("LISTEN_FDS")
_ = os.Unsetenv("LISTEN_FDNAMES")
2023-04-20 16:31:35 -04:00
}