-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
261 lines (213 loc) · 5.34 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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"sync"
"syscall"
"github.com/BurntSushi/toml"
"github.com/kardianos/service"
)
type cfgProxy struct {
Incoming string
Target string
Cert string
Key string
}
type proxyEntry struct {
URL *url.URL
Certificate *tls.Certificate
}
type httpsProxy struct {
DefaultCert string `toml:"default_cert"`
DefaultKey string `toml:"default_key"`
Entries []cfgProxy `toml:"entry"`
}
type tomlConfig struct {
Redirects map[string]string
HTTPSProxy httpsProxy `toml:"https_proxy"`
}
type program struct{}
var (
configFile = flag.String("config", "http-redirector.toml", "Path to configuration file")
port = flag.Int("port", 80, "Redirect server port")
sslPort = flag.Int("sslport", 443, "HTTPS proxy server port")
svcControl = flag.String("service", "", fmt.Sprintf("Service action, from %v", service.ControlAction))
config tomlConfig
proxyMap map[string]*proxyEntry
defaultCert *tls.Certificate
mu sync.RWMutex
server *http.Server
sslServer *http.Server
srvWg sync.WaitGroup
logger service.Logger
)
func readConfig() error {
logger.Infof("Reading config from %s", *configFile)
mu.Lock()
defer mu.Unlock()
config = tomlConfig{} // clear out config
var err error
if _, err = toml.DecodeFile(*configFile, &config); err != nil {
logger.Error(err)
return err
}
if config.HTTPSProxy.DefaultCert != "" && config.HTTPSProxy.DefaultKey != "" {
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(config.HTTPSProxy.DefaultCert, config.HTTPSProxy.DefaultKey); err != nil {
logger.Infof("Could not load cert %s", config.HTTPSProxy.DefaultCert)
return err
}
defaultCert = &cert
}
if len(config.HTTPSProxy.Entries) > 0 {
proxyMap = make(map[string]*proxyEntry)
for _, ent := range config.HTTPSProxy.Entries {
pe := proxyEntry{}
var url *url.URL
if url, err = url.Parse(ent.Target); err != nil {
logger.Infof("Could not parse %s\n", ent.Target)
return err
}
pe.URL = url
if ent.Cert != "" && ent.Key != "" {
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(ent.Cert, ent.Key); err != nil {
logger.Infof("Could not load cert %s", ent.Cert)
return err
}
pe.Certificate = &cert
}
proxyMap[ent.Incoming] = &pe
}
} else {
proxyMap = nil
}
logger.Infof("Read %d redirects and %d proxy entries", len(config.Redirects), len(proxyMap))
return nil
}
func startRedirector() {
logger.Infof("Starting HTTP on port %d", *port)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
mu.RLock()
defer mu.RUnlock()
if redir, ok := config.Redirects[r.Host]; ok {
w.Header().Set("Location", redir)
w.WriteHeader(http.StatusTemporaryRedirect)
} else {
http.NotFound(w, r)
}
})
server = &http.Server{
Addr: fmt.Sprintf(":%d", *port),
Handler: mux,
}
if err := server.ListenAndServe(); err != http.ErrServerClosed {
logger.Errorf("HTTP server ListenAndServe: %v", err)
}
srvWg.Done()
}
func proxyGetCert(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
mu.RLock()
defer mu.RUnlock()
if pe, ok := proxyMap[chi.ServerName]; ok && pe.Certificate != nil {
return pe.Certificate, nil
}
return defaultCert, nil
}
func startSslProxy() {
logger.Infof("Start HTTPS proxy on port %d", *sslPort)
rp := httputil.NewSingleHostReverseProxy(&url.URL{})
rp.Director = func(req *http.Request) {
mu.RLock()
defer mu.RUnlock()
if pe, ok := proxyMap[req.Host]; ok {
req.URL.Scheme = pe.URL.Scheme
req.URL.Host = pe.URL.Host
}
}
sslServer = &http.Server{
Addr: fmt.Sprintf(":%d", *sslPort),
Handler: rp,
TLSConfig: &tls.Config{
GetCertificate: proxyGetCert,
},
}
if err := sslServer.ListenAndServeTLS("", ""); err != http.ErrServerClosed {
logger.Errorf("HTTPS server ListenAndServe: %v", err)
return
}
srvWg.Done()
}
func (p *program) Start(s service.Service) error {
if service.Interactive() {
logger.Info("Running from terminal")
} else {
logger.Info("Running under service manager")
}
if err := readConfig(); err != nil {
return err
}
go p.run()
return nil
}
func (p *program) run() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
// Reload config when SIGHUP is received
for {
<-c
if err := readConfig(); err != nil {
logger.Error(err)
}
}
}()
srvWg.Add(2)
go startRedirector()
go startSslProxy()
srvWg.Wait()
}
func (p *program) Stop(s service.Service) error {
if err := server.Shutdown(context.Background()); err != nil {
logger.Infof("HTTP server Shutdown: %v", err)
}
return nil
}
func main() {
pwd, err := os.Getwd()
if err != nil {
log.Fatal("Unable to get path to current directory")
}
flag.Parse()
svcConfig := &service.Config{
Name: "http-redirector",
DisplayName: "HTTP-redirector",
Description: "Redirects HTTP traffic on the local LAN",
WorkingDirectory: pwd,
Arguments: []string{"-config", *configFile},
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
log.Fatal(err)
}
if logger, err = s.Logger(nil); err != nil {
log.Fatal(err)
}
if *svcControl != "" {
if err := service.Control(s, *svcControl); err != nil {
log.Fatal(err)
}
return
}
s.Run()
}