forked from OpenAyame/ayame
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_signal.go
203 lines (182 loc) · 4.88 KB
/
handler_signal.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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/ryanuber/go-glob"
)
const (
writeWait = 10 * time.Second
pongWait = 10 * time.Second
pingPeriod = (pongWait * 9) / 10
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// allow cross orgin
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type SignalMessage struct {
Type string `json:"type"`
RoomId string `json:"roomId"`
ClientId string `json:"clientId"`
Metadata *interface{} `json:"authn_metadata,omitempty"`
Key *string `json:"key,omitempty"`
}
type PingMessage struct {
Type string `json:"type"`
}
func (c *Client) listen(cancel context.CancelFunc) {
defer func() {
cancel()
c.hub.unregister <- &RegisterInfo{
client: c,
roomId: c.roomId,
}
c.conn.Close()
}()
upgrader.CheckOrigin = func(r *http.Request) bool {
if Options.AllowOrigin == "" {
return true
}
origin := r.Header.Get("Origin")
// trim origin
host, err := TrimOriginToHost(origin)
if err != nil {
log.Println("Invalid Origin Header, header=", origin)
}
// check the origin is same with one of Allow Origin in config.yaml
log.Printf("[WS] Request Origin=%s, AllowOrigin=%s", origin, Options.AllowOrigin)
if &Options.AllowOrigin == host {
return true
}
if glob.Glob(Options.AllowOrigin, *host) {
return true
}
return false
}
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
// if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
// log.Printf("ws error: %v", err)
// }
log.Printf("%v", err)
return
}
msg := &SignalMessage{}
json.Unmarshal(message, &msg)
log.Printf("message=%s", message)
switch msg.Type {
case "":
log.Printf("ignore null message")
continue
case "pong":
c.conn.SetReadDeadline(time.Now().Add(pongWait))
case "register":
if msg.ClientId == "" || msg.RoomId == "" {
log.Printf("%s error: clientId=%s, roomId=%s", msg.Type, msg.ClientId, msg.RoomId)
return
}
c.hub.register <- &RegisterInfo{
clientId: msg.ClientId,
client: c,
roomId: msg.RoomId,
key: msg.Key,
metadata: msg.Metadata,
}
// case "onmessage":
default:
if c.clientId == "" || c.roomId == "" {
log.Printf("%s error: client not registered: %v", msg.Type, c)
return
}
}
// Broadcast the signaling message received
broadcast := &Broadcast{
client: c,
roomId: c.roomId,
messages: message,
}
c.hub.broadcast <- broadcast
}
}
func (c *Client) broadcast(ctx context.Context) {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case <-ctx.Done():
// exit the loop if the channel already close
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Printf("%v", err)
return
}
w.Write(message)
w.Close()
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
// if over_ws_ping_pong option is set
if Options.OverWsPingPong {
log.Println("send ping over WS")
pingMsg := &PingMessage{Type: "ping"}
if err := c.SendJSON(pingMsg); err != nil {
log.Printf("%v", err)
return
}
} else {
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Printf("%v", err)
return
}
}
}
}
}
func signalHandler(hub *Hub, w http.ResponseWriter, r *http.Request) {
log.Printf("%s, %s", r.URL.Path, r.RemoteAddr)
defer log.Printf("signalHandler exit")
// allow all CORS for normal http
// w.Header().Set("Access-Control-Allow-Origin", "*")
// w.Header().Set("Access-Control-Allow-Credentials", "true")
// w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
// w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
// allow CORS in websocket, modify it later for security
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
origin := r.Header.Get("Origin")
host, err := TrimOriginToHost(origin)
if err != nil {
log.Println(err)
return
}
client := &Client{hub: hub, conn: c, host: *host, send: make(chan []byte, 256)}
log.Printf("[WS] connected")
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
go client.listen(cancel)
go client.broadcast(ctx)
}