-
Notifications
You must be signed in to change notification settings - Fork 95
/
main.go
91 lines (81 loc) · 2.29 KB
/
main.go
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
package main
import (
"flag"
"log"
"net/http"
"os"
"os/signal"
"path"
"syscall"
"github.com/adrg/xdg"
"github.com/jaksi/sshutils"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
infoLogger *log.Logger
warningLogger *log.Logger
errorLogger *log.Logger
)
func init() {
infoLogger = log.New(os.Stderr, "INFO ", log.LstdFlags)
warningLogger = log.New(os.Stderr, "WARNING ", log.LstdFlags)
errorLogger = log.New(os.Stderr, "ERROR ", log.LstdFlags)
}
func main() {
configFile := flag.String("config", "", "optional config file")
dataDir := flag.String("data_dir", path.Join(xdg.DataHome, "sshesame"), "data directory to store automatically generated host keys in")
flag.Parse()
cfg := &config{}
configString := ""
if *configFile != "" {
configBytes, err := os.ReadFile(*configFile)
if err != nil {
errorLogger.Fatalf("Failed to read config file: %v", err)
}
configString = string(configBytes)
}
err := cfg.load(configString, *dataDir)
if err != nil {
errorLogger.Fatalf("Failed to load config: %v", err)
}
reloadSignals := make(chan os.Signal, 1)
defer close(reloadSignals)
go func() {
for signal := range reloadSignals {
infoLogger.Printf("Reloading config due to %s", signal)
configBytes, err := os.ReadFile(*configFile)
if err != nil {
warningLogger.Printf("Failed to read config file: %v", err)
}
configString = string(configBytes)
err = cfg.load(configString, *dataDir)
if err != nil {
warningLogger.Printf("Failed to reload config: %v", err)
}
}
}()
signal.Notify(reloadSignals, syscall.SIGHUP)
listener, err := sshutils.Listen(cfg.Server.ListenAddress, cfg.sshConfig)
if err != nil {
errorLogger.Fatalf("Failed to listen for connections: %v", err)
}
defer listener.Close()
infoLogger.Printf("Listening on %v", listener.Addr())
if cfg.Logging.MetricsAddress != "" {
http.Handle("/metrics", promhttp.Handler())
infoLogger.Printf("Serving metrics on %v", cfg.Logging.MetricsAddress)
go func() {
if err := http.ListenAndServe(cfg.Logging.MetricsAddress, nil); err != nil {
errorLogger.Fatalf("Failed to serve metrics: %v", err)
}
}()
}
for {
conn, err := listener.Accept()
if err != nil {
warningLogger.Printf("Failed to accept connection: %v", err)
continue
}
go handleConnection(conn, cfg)
}
}