-
Notifications
You must be signed in to change notification settings - Fork 29
/
listener_http.go
278 lines (235 loc) · 6.52 KB
/
listener_http.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
package nodes
import (
"context"
"crypto/tls"
"errors"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/Tea"
"io"
"log"
"net"
"net/http"
"strings"
"sync/atomic"
"time"
)
var httpErrorLogger = log.New(io.Discard, "", 0)
const HTTPIdleTimeout = 75 * time.Second
type contextKey struct {
key string
}
var HTTPConnContextKey = &contextKey{key: "http-conn"}
type HTTPListener struct {
BaseListener
Listener net.Listener
addr string
isHTTP bool
isHTTPS bool
isHTTP3 bool
httpServer *http.Server
}
func (this *HTTPListener) Serve() error {
this.addr = this.Group.Addr()
this.isHTTP = this.Group.IsHTTP()
this.isHTTPS = this.Group.IsHTTPS()
this.httpServer = &http.Server{
Addr: this.addr,
Handler: this,
ReadHeaderTimeout: 3 * time.Second, // TODO 改成可以配置
IdleTimeout: HTTPIdleTimeout, // TODO 改成可以配置
ConnState: func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
atomic.AddInt64(&this.countActiveConnections, 1)
case http.StateClosed:
atomic.AddInt64(&this.countActiveConnections, -1)
default:
// do nothing
}
},
ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
tlsConn, ok := conn.(*tls.Conn)
if ok {
conn = NewClientTLSConn(tlsConn)
}
return context.WithValue(ctx, HTTPConnContextKey, conn)
},
}
if !Tea.IsTesting() {
this.httpServer.ErrorLog = httpErrorLogger
}
this.httpServer.SetKeepAlivesEnabled(true)
// HTTP协议
if this.isHTTP {
err := this.httpServer.Serve(this.Listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
}
// HTTPS协议
if this.isHTTPS {
this.httpServer.TLSConfig = this.buildTLSConfig()
err := this.httpServer.ServeTLS(this.Listener, "", "")
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
}
return nil
}
func (this *HTTPListener) Close() error {
if this.httpServer != nil {
_ = this.httpServer.Close()
}
return this.Listener.Close()
}
func (this *HTTPListener) Reload(group *serverconfigs.ServerAddressGroup) {
this.Group = group
this.Reset()
}
// ServeHTTPWithAddr 处理HTTP请求
func (this *HTTPListener) ServeHTTP(rawWriter http.ResponseWriter, rawReq *http.Request) {
this.ServeHTTPWithAddr(rawWriter, rawReq, this.addr)
}
// ServeHTTPWithAddr 处理HTTP请求并指定服务地址
func (this *HTTPListener) ServeHTTPWithAddr(rawWriter http.ResponseWriter, rawReq *http.Request, serverAddr string) {
if len(rawReq.Host) > 253 {
http.Error(rawWriter, "Host too long.", http.StatusBadRequest)
time.Sleep(1 * time.Second) // make connection slow down
return
}
var globalServerConfig = sharedNodeConfig.GlobalServerConfig
if globalServerConfig != nil && !globalServerConfig.HTTPAll.SupportsLowVersionHTTP && (rawReq.ProtoMajor < 1 /** 0.x **/ || (rawReq.ProtoMajor == 1 && rawReq.ProtoMinor == 0 /** 1.0 **/)) {
http.Error(rawWriter, rawReq.Proto+" request is not supported.", http.StatusHTTPVersionNotSupported)
time.Sleep(1 * time.Second) // make connection slow down
return
}
// 不支持Connect
if rawReq.Method == http.MethodConnect {
http.Error(rawWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
time.Sleep(1 * time.Second) // make connection slow down
return
}
// 域名
var reqHost = strings.ToLower(strings.TrimRight(rawReq.Host, "."))
// TLS域名
if this.isIP(reqHost) {
if rawReq.TLS != nil {
var serverName = rawReq.TLS.ServerName
if len(serverName) > 0 {
// 端口
var index = strings.LastIndex(reqHost, ":")
if index >= 0 {
reqHost = serverName + reqHost[index:]
} else {
reqHost = serverName
}
}
}
}
// 防止空Host
if len(reqHost) == 0 {
var ctx = rawReq.Context()
if ctx != nil {
addr := ctx.Value(http.LocalAddrContextKey)
if addr != nil {
reqHost = addr.(net.Addr).String()
}
}
}
domain, _, err := net.SplitHostPort(reqHost)
if err != nil {
domain = reqHost
}
server, serverName := this.findNamedServer(domain, false)
if server == nil {
server = this.emptyServer()
} else if !server.CNameAsDomain && server.CNameDomain == domain {
server = this.emptyServer()
} else {
serverName = domain
}
// 绑定连接
var clientConn ClientConnInterface
if server != nil && server.Id > 0 {
var requestConn = rawReq.Context().Value(HTTPConnContextKey)
if requestConn != nil {
var ok bool
clientConn, ok = requestConn.(ClientConnInterface)
if ok {
var goNext = clientConn.SetServerId(server.Id)
if !goNext {
return
}
clientConn.SetUserId(server.UserId)
var userPlanId int64
if server.UserPlan != nil && server.UserPlan.Id > 0 {
userPlanId = server.UserPlan.Id
}
clientConn.SetUserPlanId(userPlanId)
}
}
}
// 检查用户
if server != nil && server.UserId > 0 {
if !SharedUserManager.CheckUserServersIsEnabled(server.UserId) {
rawWriter.WriteHeader(http.StatusNotFound)
_, _ = rawWriter.Write([]byte("The site owner is unavailable."))
return
}
}
// 包装新请求对象
var req = &HTTPRequest{
RawReq: rawReq,
RawWriter: rawWriter,
ReqServer: server,
ReqHost: reqHost,
ServerName: serverName,
ServerAddr: serverAddr,
IsHTTP: this.isHTTP,
IsHTTPS: this.isHTTPS,
IsHTTP3: this.isHTTP3,
nodeConfig: sharedNodeConfig,
}
req.Do()
// fix hijacked connection state
if req.isHijacked && clientConn != nil && this.httpServer.ConnState != nil {
netConn, ok := clientConn.(net.Conn)
if ok {
this.httpServer.ConnState(netConn, http.StateClosed)
}
}
}
// 检查host是否为IP
func (this *HTTPListener) isIP(host string) bool {
// IPv6
if strings.Contains(host, "[") {
return true
}
for _, b := range host {
if b >= 'a' && b <= 'z' {
return false
}
}
return true
}
// 默认的访问日志
func (this *HTTPListener) emptyServer() *serverconfigs.ServerConfig {
var server = &serverconfigs.ServerConfig{
Type: serverconfigs.ServerTypeHTTPProxy,
}
// 检查是否开启访问日志
if sharedNodeConfig != nil {
var globalServerConfig = sharedNodeConfig.GlobalServerConfig
if globalServerConfig != nil && globalServerConfig.HTTPAccessLog.EnableServerNotFound {
var accessLogRef = serverconfigs.NewHTTPAccessLogRef()
accessLogRef.IsOn = true
accessLogRef.Fields = append([]int{}, serverconfigs.HTTPAccessLogDefaultFieldsCodes...)
server.Web = &serverconfigs.HTTPWebConfig{
IsOn: true,
AccessLogRef: accessLogRef,
}
}
}
// TODO 需要对访问频率过多的IP进行惩罚
return server
}