about summary refs log tree commit diff stats
path: root/internal/listenfd/listenfd.go
blob: 8c723ebf3086fb8195f75a72332a2219d516e661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package listenfd

import (
	"crypto/tls"
	"net"
	"os"
	"strconv"

	"go.alanpearce.eu/website/internal/log"

	"gitlab.com/tozd/go/errors"
)

const fdStart = 3

func GetListener(i uint64, addr string, log *log.Logger) (l net.Listener, err error) {
	l, err = getFDSocket(i)
	if err != nil {
		log.Warn("could not create listener from listenfd", "error", err)
	}

	log.Debug("listener from listenfd?", "passed", l != nil)
	if l == nil {
		l, err = net.Listen("tcp", addr)
		if err != nil {
			return nil, errors.Wrap(err, "could not create listener")
		}
	}

	return
}

func GetListenerTLS(
	i uint64,
	addr string,
	config *tls.Config,
	log *log.Logger,
) (l net.Listener, err error) {
	l, err = GetListener(i, addr, log)
	if err != nil {
		return nil, err
	}

	return tls.NewListener(l, config), nil
}

func getFDSocket(i uint64) (net.Listener, error) {
	lfds, present := os.LookupEnv("LISTEN_FDS")
	if !present {
		return nil, nil
	}

	fds, err := strconv.ParseUint(lfds, 10, 32)
	if err != nil {
		return nil, errors.Wrap(err, "could not parse LISTEN_FDS")
	}
	if i >= fds {
		return nil, errors.Errorf("only %d fds available, requested index %d", fds, i)
	}

	l, err := net.FileListener(os.NewFile(uintptr(i+fdStart), ""))
	if err != nil {
		return nil, errors.Wrap(err, "could not create listener")
	}

	return l, nil
}