/
proxy.go
244 lines (220 loc) · 6.12 KB
/
proxy.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
package server
import (
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"regexp"
"strings"
"sync"
"syscall"
"time"
"git.containerum.net/ch/api-gateway/pkg/gatewayErrors"
"git.containerum.net/ch/api-gateway/pkg/model"
"git.containerum.net/ch/api-gateway/pkg/server/middleware"
"git.containerum.net/ch/api-gateway/pkg/utils/wslimiter"
"github.com/containerum/cherry/adaptors/gonic"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
type proxyTransport struct {
header http.Header
}
const (
wsReadBuffer = 1024
wsWriteBuffer = 1024
httpTimeout = 15 * time.Second
httpKeepAlive = 30 * time.Second
maxWSConnectionsPerIP = 10
)
var (
headersToDelete = []string{"Connection", "Sec-Websocket-Key", "Sec-Websocket-Version", "Sec-Websocket-Extensions", "Upgrade"}
httpDialer = &net.Dialer{
Timeout: httpTimeout,
KeepAlive: httpKeepAlive,
}
httpTransport = http.Transport{DialContext: httpDialer.DialContext}
//wsUpgrader = wslimiter.NewPerIPLimiter(maxWSConnectionsPerIP, &websocket.Upgrader{
// ReadBufferSize: wsReadBuffer,
// WriteBufferSize: wsWriteBuffer,
// CheckOrigin: func(r *http.Request) bool {
// return true
// },
//}, func(r *http.Request) string {
// return r.Header.Get(h.UserIPXHeader)
//})
wsUpgrader = wslimiter.DummyLimiter{
Upgrader: &websocket.Upgrader{
ReadBufferSize: wsReadBuffer,
WriteBufferSize: wsWriteBuffer,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
}
)
func (pt proxyTransport) RoundTrip(r *http.Request) (resp *http.Response, err error) {
if resp, err = httpTransport.RoundTrip(r); err != nil {
return resp, err
}
for header, value := range resp.Header {
if middleware.XHeaderRegexp.MatchString(header) {
middleware.HeaderEntry(header, value).Debug("Header deleted from response")
continue
}
pt.header.Add(header, value[0])
}
resp.Header = pt.header
return resp, err
}
func (s *Server) proxyHandler(route model.Route) gin.HandlerFunc {
return func(c *gin.Context) {
if route.WS {
request := c.Request.URL
target, _ := url.Parse(route.Upstream)
request.Scheme, request.Host = "ws", target.Host
err := s.proxyWS(c, request)
switch err {
case nil:
// pass
case wslimiter.ErrLimitReached:
gonic.Gonic(gatewayErrors.ErrTooManyRequests().AddDetailF("websocket connections limit reached"), c)
}
} else {
p := s.proxyHTTP(&route)
p.ServeHTTP(c.Writer, c.Request)
}
}
}
func (s *Server) proxyHTTP(target *model.Route) *httputil.ReverseProxy {
direct := s.createDirector(target)
return &httputil.ReverseProxy{
Director: direct,
Transport: proxyTransport{
header: http.Header{},
},
}
}
func (s *Server) proxyWS(c *gin.Context, backend *url.URL) error {
conn, connBackend, err := s.makeWSconnections(c, s.addPrefixToBackendURL(backend))
if err != nil {
return err
}
errc := make(chan error, 2)
var once sync.Once
replicateConn := func(dst, src *wslimiter.Conn, dstName, srcName string) {
defer once.Do(func() {
dst.Close()
src.Close()
})
var buf [1024]byte
_, err := io.CopyBuffer(dst.UnderlyingConn(), src.UnderlyingConn(), buf[:])
switch {
case err == nil:
// pass
case isClose(err),
isBrokenPipe(err),
isNetTimeout(err):
// pass
default:
log.WithError(err).Errorf("websocket: replicate bytes from %s to %s failed", srcName, dstName)
}
errc <- err
}
go replicateConn(conn, connBackend, "client", "backend")
go replicateConn(connBackend, conn, "backend", "client")
<-errc
return nil
}
func (s *Server) makeWSconnections(c *gin.Context, backend *url.URL) (conn, connBackend *wslimiter.Conn, err error) {
if conn, err = wsUpgrader.Upgrade(c.Writer, c.Request, nil); err != nil {
log.WithError(err).Error("Unable to upgrade to WebSocket")
return
}
s.deleteHeaders(&c.Request.Header, headersToDelete...)
_connBackend, _, err := websocket.DefaultDialer.Dial(backend.String(), c.Request.Header)
if err != nil {
log.WithError(err).Error("Unable to dial to WebSocket")
return
}
connBackend = &wslimiter.Conn{Conn: _connBackend}
return
}
func (s *Server) deleteHeaders(header *http.Header, keys ...string) {
for _, key := range keys {
middleware.HeaderEntry(key, header.Get(key)).Debug("Header deleted")
header.Del(key)
}
}
func (s *Server) createDirector(target *model.Route) func(r *http.Request) {
return func(r *http.Request) {
targetURL, _ := url.Parse(target.Upstream)
r.URL.Scheme = targetURL.Scheme
if s.options.ServiceHostPrefix == "" {
r.URL.Host = targetURL.Host
} else {
r.URL.Host = s.options.ServiceHostPrefix + "-" + targetURL.Host
}
if target.Strip {
strPath := s.stripPath(r.URL.Path, target.Listen, targetURL.Path)
r.URL.Path = singleJoiningSlash(buildHostURL(*targetURL), strPath)
} else {
r.URL.Path = singleJoiningSlash(targetURL.Path, r.URL.Path)
}
}
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
func (s *Server) stripPath(requestPath, listenPath, upstreamPath string) string {
rSlash, _ := regexp.Compile("/")
listenPath = rSlash.ReplaceAllString(listenPath, `\/`)
re := fmt.Sprintf("^%v", listenPath)
r, _ := regexp.Compile(re)
diffPath := r.ReplaceAllString(requestPath, "")
if diffPath == "" {
return upstreamPath
}
return singleJoiningSlash(upstreamPath, diffPath)
}
func buildHostURL(u url.URL) string {
return u.Scheme + "://" + u.Host
}
//
// Websocket-specific connection errors
//
func isNetTimeout(err error) bool {
netErr, ok := err.(net.Error)
return ok && netErr.Timeout()
}
func isBrokenPipe(err error) bool {
opErr, isOpErr := err.(*net.OpError)
if !isOpErr {
return false
}
syscallErr, ok := opErr.Err.(*os.SyscallError)
return ok && syscallErr.Err == syscall.EPIPE
}
func isClose(err error) bool {
_, isClose := err.(*websocket.CloseError)
if isClose {
return true
}
opErr, isOpErr := err.(*net.OpError)
if !isOpErr {
return false
}
return opErr.Err.Error() == "use of closed network connection"
}