summaryrefslogtreecommitdiffhomepage
path: root/main.go
blob: 2b955fbf65f911a5ae3c9058cd4999d883015082 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"os/user"
	"path/filepath"
	"strconv"
	"sync"
	"syscall"
	"time"
)

func startServer(
	s *Server,
	listener net.Listener,
	wg *sync.WaitGroup,
	sigCtx context.Context,
) {
	defer wg.Done()

	go func() {
		err := s.Serve(listener)
		if err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server (%s): %s", s.Label(), err)
		}
	}()

	fmt.Printf("Started server (%s)\n", s.Label())

	// Wait until we receive a signal to stop the server.
	<-sigCtx.Done()

	// Gracefully shutdown the server with timeout.
	timeoutCtx, cancelTimeoutCtx := context.WithTimeout(context.Background(), time.Second*10)
	defer cancelTimeoutCtx()
	s.Shutdown(timeoutCtx)

	fmt.Printf("Shutdown server (%s)\n", s.Label())
}

func downgradeToUser(uname string) error {
	// Get gid and uid.
	u, err := user.Lookup(uname)
	if err != nil {
		return err
	}
	// On POSIX system, gid and uid are integers.
	gid, err := strconv.Atoi(u.Gid)
	if err != nil {
		return err
	}
	uid, err := strconv.Atoi(u.Uid)
	if err != nil {
		return err
	}

	// Set gid and uid.
	err = syscall.Setgid(gid)
	if err != nil {
		return err
	}
	err = syscall.Setuid(uid)
	if err != nil {
		return err
	}

	return nil
}

func main() {
	// Check mode
	if len(os.Args) == 3 && os.Args[1] == "-check" {
		configFileName := os.Args[2]
		_, err := LoadConfig(configFileName)
		if err != nil {
			log.Fatalf("%s", err)
		}
		return
	}

	// Load config.
	if len(os.Args) < 2 {
		log.Fatalf("Usage: %s <config file>", os.Args[0])
	}
	configFileName := os.Args[1]
	config, err := LoadConfig(configFileName)
	if err != nil {
		log.Fatalf("Failed to load configuration: %s", err)
	}
	configFileDir := filepath.Dir(configFileName)

	// Set up listeners.
	var listeners []net.Listener
	for _, s := range config.Servers {
		l, err := NewListener(&s)
		if err != nil {
			log.Fatalf("Failed to create listener (%s:%d): %s", s.Host, s.Port, err)
		}
		listeners = append(listeners, l)
	}

	// Set up servers.
	var servers []*Server
	for _, s := range config.Servers {
		// Convert relative paths to absolute paths, based on config file location.
		if s.ACMEChallenge != nil {
			s.ACMEChallenge.Root = filepath.Join(configFileDir, s.ACMEChallenge.Root)
		}
		if s.TLSCertFile != "" {
			s.TLSCertFile = filepath.Join(configFileDir, s.TLSCertFile)
		}
		if s.TLSKeyFile != "" {
			s.TLSKeyFile = filepath.Join(configFileDir, s.TLSKeyFile)
		}
		servers = append(servers, NewServer(&s))
	}

	// Downgrade to non-root user.
	if config.User != "" {
		err := downgradeToUser(config.User)
		if err != nil {
			log.Fatalf("Failed to downgrade to user %s: %s", config.User, err)
		}
	}

	// Catch signals to stop servers.
	sigCtx, cancelSigCtx := signal.NotifyContext(
		context.Background(),
		syscall.SIGTERM, os.Interrupt, os.Kill,
	)
	defer cancelSigCtx()

	// Start servers.
	var wg sync.WaitGroup
	for i, s := range servers {
		wg.Add(1)
		go startServer(s, listeners[i], &wg, sigCtx)
	}
	wg.Wait()
}