-
Notifications
You must be signed in to change notification settings - Fork 473
/
ws_acceptor.go
269 lines (231 loc) · 7.09 KB
/
ws_acceptor.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
// Copyright (c) nano Author and TFG Co. All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package acceptor
import (
"crypto/tls"
"io"
"net"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/topfreegames/pitaya/constants"
"github.com/topfreegames/pitaya/logger"
)
// WSAcceptor struct
type WSAcceptor struct {
addr string
connChan chan net.Conn
listener net.Listener
certFile string
keyFile string
}
// NewWSAcceptor returns a new instance of WSAcceptor
func NewWSAcceptor(addr string, certs ...string) *WSAcceptor {
keyFile := ""
certFile := ""
if len(certs) != 2 && len(certs) != 0 {
panic(constants.ErrInvalidCertificates)
} else if len(certs) == 2 {
certFile = certs[0]
keyFile = certs[1]
}
w := &WSAcceptor{
addr: addr,
connChan: make(chan net.Conn),
certFile: certFile,
keyFile: keyFile,
}
return w
}
// GetAddr returns the addr the acceptor will listen on
func (w *WSAcceptor) GetAddr() string {
if w.listener != nil {
return w.listener.Addr().String()
}
return ""
}
// GetConnChan gets a connection channel
func (w *WSAcceptor) GetConnChan() chan net.Conn {
return w.connChan
}
type connHandler struct {
upgrader *websocket.Upgrader
connChan chan net.Conn
}
func (h *connHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
conn, err := h.upgrader.Upgrade(rw, r, nil)
if err != nil {
logger.Log.Errorf("Upgrade failure, URI=%s, Error=%s", r.RequestURI, err.Error())
return
}
c, err := newWSConn(conn)
if err != nil {
logger.Log.Errorf("Failed to create new ws connection: %s", err.Error())
return
}
h.connChan <- c
}
func (w *WSAcceptor) hasTLSCertificates() bool {
return w.certFile != "" && w.keyFile != ""
}
// ListenAndServe listens and serve in the specified addr
func (w *WSAcceptor) ListenAndServe() {
if w.hasTLSCertificates() {
w.ListenAndServeTLS(w.certFile, w.keyFile)
return
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
listener, err := net.Listen("tcp", w.addr)
if err != nil {
logger.Log.Fatalf("Failed to listen: %s", err.Error())
}
w.listener = listener
w.serve(&upgrader)
}
// ListenAndServeTLS listens and serve in the specified addr using tls
func (w *WSAcceptor) ListenAndServeTLS(cert, key string) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
crt, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
logger.Log.Fatalf("Failed to load x509: %s", err.Error())
}
tlsCfg := &tls.Config{Certificates: []tls.Certificate{crt}}
listener, err := tls.Listen("tcp", w.addr, tlsCfg)
if err != nil {
logger.Log.Fatalf("Failed to listen: %s", err.Error())
}
w.listener = listener
w.serve(&upgrader)
}
func (w *WSAcceptor) serve(upgrader *websocket.Upgrader) {
defer w.Stop()
http.Serve(w.listener, &connHandler{
upgrader: upgrader,
connChan: w.connChan,
})
}
// Stop stops the acceptor
func (w *WSAcceptor) Stop() {
err := w.listener.Close()
if err != nil {
logger.Log.Errorf("Failed to stop: %s", err.Error())
}
}
// wsConn is an adapter to t.Conn, which implements all t.Conn
// interface base on *websocket.Conn
type wsConn struct {
conn *websocket.Conn
typ int // message type
reader io.Reader
}
// newWSConn return an initialized *wsConn
func newWSConn(conn *websocket.Conn) (*wsConn, error) {
c := &wsConn{conn: conn}
t, r, err := conn.NextReader()
if err != nil {
return nil, err
}
c.typ = t
c.reader = r
return c, nil
}
// Read reads data from the connection.
// Read can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetReadDeadline.
func (c *wsConn) Read(b []byte) (int, error) {
n, err := c.reader.Read(b)
if err != nil && err != io.EOF {
return n, err
} else if err == io.EOF {
_, r, err := c.conn.NextReader()
if err != nil {
return 0, err
}
c.reader = r
}
return n, nil
}
// Write writes data to the connection.
// Write can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetWriteDeadline.
func (c *wsConn) Write(b []byte) (int, error) {
err := c.conn.WriteMessage(websocket.BinaryMessage, b)
if err != nil {
return 0, err
}
return len(b), nil
}
// Close closes the connection.
// Any blocked Read or Write operations will be unblocked and return errors.
func (c *wsConn) Close() error {
return c.conn.Close()
}
// LocalAddr returns the local network address.
func (c *wsConn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
// RemoteAddr returns the remote network address.
func (c *wsConn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
// SetDeadline sets the read and write deadlines associated
// with the connection. It is equivalent to calling both
// SetReadDeadline and SetWriteDeadline.
//
// A deadline is an absolute time after which I/O operations
// fail with a timeout (see type Error) instead of
// blocking. The deadline applies to all future and pending
// I/O, not just the immediately following call to Read or
// Write. After a deadline has been exceeded, the connection
// can be refreshed by setting a deadline in the future.
//
// An idle timeout can be implemented by repeatedly extending
// the deadline after successful Read or Write calls.
//
// A zero value for t means I/O operations will not time out.
func (c *wsConn) SetDeadline(t time.Time) error {
if err := c.SetReadDeadline(t); err != nil {
return err
}
return c.SetWriteDeadline(t)
}
// SetReadDeadline sets the deadline for future Read calls
// and any currently-blocked Read call.
// A zero value for t means Read will not time out.
func (c *wsConn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline sets the deadline for future Write calls
// and any currently-blocked Write call.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means Write will not time out.
func (c *wsConn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}