-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathserver.go
306 lines (258 loc) · 7.81 KB
/
server.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
package goquic
import (
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"net"
"net/http"
"runtime"
"time"
"github.com/vanillahsu/go_reuseport"
"golang.org/x/net/http2"
)
type QuicSpdyServer struct {
Addr string
Handler http.Handler
ReadTimeout time.Duration
WriteTimeout time.Duration
MaxHeaderBytes int
Certificate tls.Certificate
Secret string
ServerConfig *SerializedServerConfig
numOfServers int
isSecure bool
statisticsReq [](chan statCallback)
bufpool *BytesBufferPool
}
func (srv *QuicSpdyServer) Statistics() (*ServerStatistics, error) {
if srv.statisticsReq == nil {
return nil, errors.New("Server not started")
}
serverStat := &ServerStatistics{}
dispatcherStatCh := make(chan DispatcherStatistics)
go func() {
for i := 0; i < len(srv.statisticsReq); i++ {
cb := make(statCallback, 1)
srv.statisticsReq[i] <- cb // Send "cb" cannel to dispatcher
dispatcherStat := <-cb // Get return value from "cb" channel
dispatcherStatCh <- dispatcherStat // Send return value to pipeline
}
close(dispatcherStatCh)
}()
for dispatcherStat := range dispatcherStatCh {
serverStat.SessionStatistics = append(serverStat.SessionStatistics, dispatcherStat.SessionStatistics...)
}
return serverStat, nil
}
func (srv *QuicSpdyServer) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
readChanArray := make([](chan UdpData), srv.numOfServers)
writerArray := make([](*ServerWriter), srv.numOfServers)
connArray := make([](*net.UDPConn), srv.numOfServers)
srv.statisticsReq = make([](chan statCallback), srv.numOfServers)
srv.bufpool = NewBytesBufferPool(1000, 3000) // 3000 = MTU (kMaxPacketSize) * 2
if srv.ServerConfig == nil {
srv.ServerConfig = GenerateSerializedServerConfig()
}
if srv.Secret == "" {
srv.Secret = "secret"
}
// N consumers
for i := 0; i < srv.numOfServers; i++ {
rch := make(chan UdpData, 500)
wch := make(chan UdpData, 500) // TODO(serialx, hodduc): Optimize buffer size
statch := make(chan statCallback, 0)
conn, err := reuseport.NewReusablePortPacketConn("udp4", addr)
if err != nil {
return err
}
defer conn.Close()
udp_conn, ok := conn.(*net.UDPConn)
if !ok {
return errors.New("ListenPacket did not return net.UDPConn")
}
udp_conn.SetReadBuffer(1024 * 1024) // 1MB
udp_conn.SetWriteBuffer(1024 * 1024) // 1MB
connArray[i] = udp_conn
listen_addr, err := net.ResolveUDPAddr("udp", udp_conn.LocalAddr().String())
if err != nil {
return err
}
readChanArray[i] = rch
writerArray[i] = NewServerWriter(wch)
srv.statisticsReq[i] = statch
go srv.Serve(listen_addr, writerArray[i], readChanArray[i], srv.statisticsReq[i])
}
// N producers
readFunc := func(conn *net.UDPConn) {
for {
buf := srv.bufpool.Get()
n, peer_addr, err := conn.ReadFromUDP(buf)
if err != nil {
// TODO(serialx): Don't panic and keep calm...
panic(err)
}
// Ignore zero length packet
if n == 0 {
continue
}
var connId uint64 = 0
var parsed bool = false
if len(buf) > 0 {
switch buf[0] & 0x8 {
case 0x8:
// 8-byte connection id
if n >= 9 {
connId = binary.LittleEndian.Uint64(buf[1:9])
parsed = true
}
default: // connection id is omitted
// TODO(hodduc) Use 4-tuple to identify connection when connId is omitted
connId = 0
parsed = true
}
}
if !parsed {
// Ignore strange packet
continue
}
readChanArray[connId%uint64(srv.numOfServers)] <- UdpData{Addr: peer_addr, Buf: buf, N: n}
// TODO(hodduc): Minimize heap uses of buf. Consider using sync.Pool standard library to implement buffer pool.
}
}
// N consumers
writeFunc := func(conn *net.UDPConn, writer *ServerWriter) {
for dat := range writer.Ch {
conn.WriteToUDP(dat.Buf, dat.Addr)
}
}
for i := 0; i < srv.numOfServers-1; i++ {
go writeFunc(connArray[i], writerArray[i])
go readFunc(connArray[i])
}
go writeFunc(connArray[srv.numOfServers-1], writerArray[srv.numOfServers-1])
readFunc(connArray[srv.numOfServers-1])
return nil
}
func (srv *QuicSpdyServer) Serve(listen_addr *net.UDPAddr, writer *ServerWriter, readChan chan UdpData, statChan chan statCallback) error {
runtime.LockOSThread()
proofSource := NewProofSource(srv.Certificate)
cryptoConfig := NewCryptoServerConfig(proofSource, srv.Secret, srv.ServerConfig)
defer DeleteCryptoServerConfig(cryptoConfig)
sessionFnChan := make(chan func())
createSpdySession := func() IncomingDataStreamCreator {
return &SpdyServerSession{server: srv, sessionFnChan: sessionFnChan}
}
dispatcher := CreateQuicDispatcher(writer, createSpdySession, CreateTaskRunner(), cryptoConfig)
for {
select {
case result, ok := <-readChan:
if !ok {
break
}
dispatcher.ProcessPacket(listen_addr, result.Addr, result.Buf[:result.N])
srv.bufpool.Put(result.Buf)
case <-dispatcher.TaskRunner.WaitTimer():
dispatcher.TaskRunner.DoTasks()
case fn, ok := <-sessionFnChan:
if !ok {
break
}
fn()
case statCallback, ok := <-statChan:
if !ok {
break
}
stat := dispatcher.Statistics()
statCallback <- stat
}
}
}
// Provide "Alternate-Protocol" header for QUIC
func AltProtoMiddleware(next http.Handler, port int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Alternate-Protocol is deprecated.
// See https://groups.google.com/a/chromium.org/forum/#!topic/chromium-reviews/aOv41LpPDQY
w.Header().Add("Alternate-Protocol", fmt.Sprintf("%d:quic", port))
w.Header().Add("Alt-Svc", fmt.Sprintf("quic=\":%d\"; ma=86400; v=\"36,35,34,33,32,31,30\"", port))
next.ServeHTTP(w, r)
})
}
func parsePort(addr string) (port int, err error) {
_, portStr, err := net.SplitHostPort(addr)
if err != nil {
return 0, err
}
port, err = net.LookupPort("udp", portStr)
if err != nil {
return 0, err
}
return port, nil
}
func ListenAndServe(addr string, certFile string, keyFile string, numOfServers int, handler http.Handler) error {
if handler == nil {
handler = http.DefaultServeMux
}
if certFile == "" || keyFile == "" {
return errors.New("cert / key should be provided")
}
if server, err := NewServer(addr, certFile, keyFile, numOfServers, handler, handler, nil); err != nil {
return err
} else {
return server.ListenAndServe()
}
}
func ListenAndServeQuicSpdyOnly(addr string, certFile string, keyFile string, numOfServers int, handler http.Handler) error {
if handler == nil {
handler = http.DefaultServeMux
}
if certFile == "" || keyFile == "" {
return errors.New("cert / key should be provided")
}
if server, err := NewServer(addr, certFile, keyFile, numOfServers, handler, nil, nil); err != nil {
return err
} else {
return server.ListenAndServe()
}
}
func NewServer(addr string, certFile string, keyFile string, numOfServers int, quicHandler http.Handler, nonQuicHandler http.Handler, tlsConfig *tls.Config) (*QuicSpdyServer, error) {
port, err := parsePort(addr)
if err != nil {
return nil, err
}
if quicHandler == nil {
return nil, errors.New("quic handler should be provided")
}
if nonQuicHandler != nil {
go func() {
httpServer := &http.Server{Addr: addr, Handler: AltProtoMiddleware(nonQuicHandler, port)}
httpServer.TLSConfig = tlsConfig
http2.ConfigureServer(httpServer, nil)
if certFile != "" && keyFile != "" {
if err := httpServer.ListenAndServeTLS(certFile, keyFile); err != nil {
panic(err)
}
} else {
if err := httpServer.ListenAndServe(); err != nil {
panic(err)
}
}
}()
}
server := &QuicSpdyServer{Addr: addr, Handler: quicHandler, numOfServers: numOfServers}
if certFile != "" && keyFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
server.isSecure = true
server.Certificate = cert
} else {
server.isSecure = false
}
return server, nil
}