forked from haveachin/infrared
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
412 lines (350 loc) · 9.06 KB
/
config.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package infrared
import (
"bufio"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path/filepath"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/JohnEridium/infrared/process"
"github.com/JohnEridium/infrared/protocol"
"github.com/JohnEridium/infrared/protocol/status"
)
// ProxyConfig is a data representation of a Proxy configuration
type ProxyConfig struct {
sync.RWMutex
watcher *fsnotify.Watcher
removeCallback func()
changeCallback func()
dialer *Dialer
process process.Process
DomainName string `json:"domainName"`
ListenTo string `json:"listenTo"`
ProxyTo string `json:"proxyTo"`
ProxyBind string `json:"proxyBind"`
ProxyProtocol bool `json:"proxyProtocol"`
RealIP bool `json:"realIp"`
Timeout int `json:"timeout"`
DisconnectMessage string `json:"disconnectMessage"`
Docker DockerConfig `json:"docker"`
OnlineStatus StatusConfig `json:"onlineStatus"`
OfflineStatus StatusConfig `json:"offlineStatus"`
CallbackServer CallbackServerConfig `json:"callbackServer"`
}
func (cfg *ProxyConfig) Dialer() (*Dialer, error) {
if cfg.dialer != nil {
return cfg.dialer, nil
}
cfg.dialer = &Dialer{
Dialer: net.Dialer{
Timeout: time.Millisecond * time.Duration(cfg.Timeout),
LocalAddr: &net.TCPAddr{
IP: net.ParseIP(cfg.ProxyBind),
},
},
}
return cfg.dialer, nil
}
type DockerConfig struct {
DNSServer string `json:"dnsServer"`
ContainerName string `json:"containerName"`
Timeout int `json:"timeout"`
Portainer struct {
Address string `json:"address"`
EndpointID string `json:"endpointId"`
Username string `json:"username"`
Password string `json:"password"`
} `json:"portainer"`
}
func (docker DockerConfig) IsDocker() bool {
return docker.ContainerName != ""
}
func (docker DockerConfig) IsPortainer() bool {
return docker.ContainerName != "" &&
docker.Portainer.Address != "" &&
docker.Portainer.EndpointID != ""
}
type PlayerSample struct {
Name string `json:"name"`
UUID string `json:"uuid"`
}
type StatusConfig struct {
cachedPacket *protocol.Packet
VersionName string `json:"versionName"`
ProtocolNumber int `json:"protocolNumber"`
MaxPlayers int `json:"maxPlayers"`
PlayersOnline int `json:"playersOnline"`
PlayerSamples []PlayerSample `json:"playerSamples"`
IconPath string `json:"iconPath"`
MOTD string `json:"motd"`
}
func (cfg StatusConfig) StatusResponsePacket() (protocol.Packet, error) {
if cfg.cachedPacket != nil {
return *cfg.cachedPacket, nil
}
var samples []status.PlayerSampleJSON
for _, sample := range cfg.PlayerSamples {
samples = append(samples, status.PlayerSampleJSON{
Name: sample.Name,
ID: sample.UUID,
})
}
responseJSON := status.ResponseJSON{
Version: status.VersionJSON{
Name: cfg.VersionName,
Protocol: cfg.ProtocolNumber,
},
Players: status.PlayersJSON{
Max: cfg.MaxPlayers,
Online: cfg.PlayersOnline,
Sample: samples,
},
Description: status.DescriptionJSON{
Text: cfg.MOTD,
},
}
if cfg.IconPath != "" {
img64, err := loadImageAndEncodeToBase64String(cfg.IconPath)
if err != nil {
return protocol.Packet{}, err
}
responseJSON.Favicon = fmt.Sprintf("data:image/png;base64,%s", img64)
}
bb, err := json.Marshal(responseJSON)
if err != nil {
return protocol.Packet{}, err
}
packet := status.ClientBoundResponse{
JSONResponse: protocol.String(bb),
}.Marshal()
cfg.cachedPacket = &packet
return packet, nil
}
func loadImageAndEncodeToBase64String(path string) (string, error) {
if path == "" {
return "", nil
}
imgFile, err := os.Open(path)
if err != nil {
return "", err
}
defer imgFile.Close()
fileInfo, err := imgFile.Stat()
if err != nil {
return "", err
}
buffer := make([]byte, fileInfo.Size())
fileReader := bufio.NewReader(imgFile)
_, err = fileReader.Read(buffer)
if err != nil {
return "", nil
}
return base64.StdEncoding.EncodeToString(buffer), nil
}
type CallbackServerConfig struct {
URL string `json:"url"`
Events []string `json:"events"`
}
func DefaultProxyConfig() ProxyConfig {
return ProxyConfig{
DomainName: "localhost",
ListenTo: ":25565",
Timeout: 1000,
DisconnectMessage: "Sorry {{username}}, but the server is offline.",
Docker: DockerConfig{
DNSServer: "127.0.0.11",
Timeout: 300000,
},
OfflineStatus: StatusConfig{
VersionName: "Infrared 1.18",
ProtocolNumber: 757,
MaxPlayers: 20,
MOTD: "Powered by Infrared",
},
}
}
func ReadFilePaths(path string, recursive bool) ([]string, error) {
if recursive {
return readFilePathsRecursively(path)
}
return readFilePaths(path)
}
func readFilePathsRecursively(path string) ([]string, error) {
var filePaths []string
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
filePaths = append(filePaths, path)
return nil
})
return filePaths, err
}
func readFilePaths(path string) ([]string, error) {
var filePaths []string
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
for _, file := range files {
if file.IsDir() {
continue
}
filePaths = append(filePaths, filepath.Join(path, file.Name()))
}
return filePaths, err
}
func LoadProxyConfigsFromPath(path string, recursive bool) ([]*ProxyConfig, error) {
filePaths, err := ReadFilePaths(path, recursive)
if err != nil {
return nil, err
}
var cfgs []*ProxyConfig
for _, filePath := range filePaths {
cfg, err := NewProxyConfigFromPath(filePath)
if err != nil {
return nil, err
}
cfgs = append(cfgs, cfg)
}
return cfgs, nil
}
// NewProxyConfigFromPath loads a ProxyConfig from a file path and then starts watching
// it for changes. On change the ProxyConfig will automatically LoadFromPath itself
func NewProxyConfigFromPath(path string) (*ProxyConfig, error) {
log.Println("Loading", path)
var cfg ProxyConfig
if err := cfg.LoadFromPath(path); err != nil {
return nil, err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
cfg.watcher = watcher
go func() {
defer watcher.Close()
log.Printf("Starting to watch %s", path)
cfg.watch(path, time.Millisecond*50)
log.Printf("Stopping to watch %s", path)
}()
if err := watcher.Add(path); err != nil {
return nil, err
}
return &cfg, err
}
func (cfg *ProxyConfig) watch(path string, interval time.Duration) {
// The interval protects the watcher from write event spams
// This is necessary due to how some text editors handle file safes
tick := time.Tick(interval)
var lastEvent *fsnotify.Event
for {
select {
case <-tick:
if lastEvent == nil {
continue
}
cfg.onConfigWrite(*lastEvent)
lastEvent = nil
case event, ok := <-cfg.watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Remove == fsnotify.Remove {
cfg.removeCallback()
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
lastEvent = &event
}
case err, ok := <-cfg.watcher.Errors:
if !ok {
return
}
log.Printf("Failed watching %s; error %s", path, err)
}
}
}
func (cfg *ProxyConfig) onConfigWrite(event fsnotify.Event) {
log.Println("Updating", event.Name)
if err := cfg.LoadFromPath(event.Name); err != nil {
log.Printf("Failed update on %s; error %s", event.Name, err)
return
}
cfg.OnlineStatus.cachedPacket = nil
cfg.OfflineStatus.cachedPacket = nil
cfg.dialer = nil
cfg.process = nil
cfg.changeCallback()
}
// LoadFromPath loads the ProxyConfig from a file
func (cfg *ProxyConfig) LoadFromPath(path string) error {
cfg.Lock()
defer cfg.Unlock()
var defaultCfg map[string]interface{}
bb, err := json.Marshal(DefaultProxyConfig())
if err != nil {
return err
}
if err := json.Unmarshal(bb, &defaultCfg); err != nil {
return err
}
bb, err = ioutil.ReadFile(path)
if err != nil {
return err
}
var loadedCfg map[string]interface{}
if err := json.Unmarshal(bb, &loadedCfg); err != nil {
log.Println(string(bb))
return err
}
for k, v := range loadedCfg {
defaultCfg[k] = v
}
bb, err = json.Marshal(defaultCfg)
if err != nil {
return err
}
return json.Unmarshal(bb, cfg)
}
func WatchProxyConfigFolder(path string, out chan *ProxyConfig) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
if err := watcher.Add(path); err != nil {
return err
}
defer close(out)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return nil
}
if event.Op&fsnotify.Create == fsnotify.Create {
proxyCfg, err := NewProxyConfigFromPath(event.Name)
if err != nil {
log.Printf("Failed loading %s; error %s", event.Name, err)
continue
}
out <- proxyCfg
}
case err, ok := <-watcher.Errors:
if !ok {
return nil
}
log.Printf("Failed watching %s; error %s", path, err)
}
}
}