-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.go
116 lines (94 loc) · 2.25 KB
/
pipe.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
package pipe
import (
"fmt"
"github.com/joyqi/ngate/internal/config"
"github.com/joyqi/ngate/pkg/auth"
"github.com/valyala/fasthttp"
"net"
"strconv"
"strings"
"sync"
"time"
)
type Pipe interface {
Serve(auth auth.Auth, bc config.BackendConfig)
}
func New(cfg *config.Config, auth auth.Auth) error {
if len(cfg.Pipes) == 0 {
return fmt.Errorf("empty pipes")
}
wg := &sync.WaitGroup{}
wg.Add(len(cfg.Pipes))
for _, pipeConfig := range cfg.Pipes {
session, err := NewSession(pipeConfig.Session)
if err != nil {
return err
}
addr := net.JoinHostPort(
defaultHost(pipeConfig.Host, "0.0.0.0"),
defaultPort(pipeConfig.Port, 8000))
backendAddr := net.JoinHostPort(
defaultHost(pipeConfig.Backend.Host, "127.0.0.1"),
defaultPort(pipeConfig.Backend.Port, 8000))
frontend := &Frontend{
Addr: addr,
Session: session,
Auth: auth,
Wait: wg,
GroupValid: groupValid(pipeConfig.Access),
BackendHostName: pipeConfig.Backend.HostName,
BackendTimeout: time.Duration(pipeConfig.Backend.Timeout) * time.Millisecond,
BackendProxy: &fasthttp.HostClient{
Addr: backendAddr,
DisableHeaderNamesNormalizing: true,
DisablePathNormalizing: true,
ReadBufferSize: 64 * 1024,
},
}
go frontend.Serve()
}
wg.Wait()
return nil
}
func selectGroups(hostName string, accessConfig []config.AccessConfig) []string {
for _, c := range accessConfig {
if c.HostName == hostName {
return c.Groups
}
}
return nil
}
func existsGroup(group string, selectGroups []string) bool {
for _, g := range selectGroups {
if group == g {
return true
}
}
return false
}
func groupValid(accessConfig []config.AccessConfig) auth.PipeGroupValid {
return func(group string, hostName string) bool {
sg := selectGroups(hostName, accessConfig)
if sg != nil {
for _, g := range strings.Split(group, ",") {
if existsGroup(g, sg) {
return true
}
}
return false
}
return true
}
}
func defaultHost(host string, defaultHost string) string {
if host == "" {
return defaultHost
}
return host
}
func defaultPort(port int, defaultPort int) string {
if port == 0 {
port = defaultPort
}
return strconv.Itoa(port)
}