-
Notifications
You must be signed in to change notification settings - Fork 0
/
nws.go
232 lines (196 loc) · 6.07 KB
/
nws.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
package main
import (
"net"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/vikebot/vbgs/pkg/ntfydistr"
"github.com/gorilla/websocket"
"github.com/vikebot/vbcore"
"github.com/vikebot/vbdb"
"github.com/vikebot/vbgs/vbge"
"go.uber.org/zap"
)
var nwsUpgrader websocket.Upgrader
func nwsInit(start chan bool, shutdown chan bool) {
nwsUpgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := r.Header["Origin"]
if len(origin) == 0 {
return false
}
u, err := url.Parse(origin[0])
if err != nil {
return false
}
return u.Host == config.Network.WS.ValidOrigin
},
}
srv := &http.Server{Addr: config.Network.WS.Addr}
http.HandleFunc("/", nwsHandler)
go func() {
// Wait for start signal
log.Info("nws ready. waiting for start signal")
<-start
go nwsRun(srv)
// Shutdown websocket when signal is received
<-shutdown
err := srv.Shutdown(nil)
if err != nil {
log.Warn("nws shutdown failed", zap.Error(err))
}
}()
}
func nwsRun(srv *http.Server) {
var srvErr error
log.Info("accepting clients on nws listener")
if config.Network.WS.TLS.Active {
srvErr = srv.ListenAndServeTLS(config.Network.WS.TLS.Cert, config.Network.WS.TLS.PKey)
} else {
srvErr = srv.ListenAndServe()
}
if srvErr != nil {
log.Fatal("nws listen failed", zap.Error(srvErr))
}
}
func nwsHandler(w http.ResponseWriter, r *http.Request) {
wsrqid := strings.ToLower(vbcore.FastRandomString(16))
c := &nwsclient{
WSRqID: wsrqid,
Log: log.With(zap.String("wsid", wsrqid)),
}
c.Log.Info("websocket connected", zap.String("ip", r.RemoteAddr))
ws, err := nwsUpgrader.Upgrade(w, r, nil)
if err != nil {
c.Log.Error("failed to upgrade http connection", zap.Error(err))
return
}
defer func() {
c.Log.Info("closing physical websocket connection", zap.String("ip", r.RemoteAddr))
err = ws.Close()
if err != nil {
c.Log.Error("error during closing websocket", zap.Error(err))
}
}()
c.Ws = ws
// authenticate the websocket connection
err = nwsAuthAndValidate(c)
if err != nil {
// see if the error happend due to a closed websocket
if _, ok := err.(*net.OpError); ok || websocket.IsUnexpectedCloseError(err) {
return
}
// no closing error -> log it
c.Log.Warn("unable to send message to client", zap.Error(err))
}
}
func nwsAuthAndValidate(c *nwsclient) error {
// get opening message (should be the watchtoken) from the client
mt, watchtoken, err := c.Ws.ReadMessage()
if err != nil {
c.Log.Warn("failed reading message from websocket", zap.Error(err))
return nil
}
c.Mt = mt
watchtokenStr := string(watchtoken) // TODO: check for legitimacy of watchtoken
// check if the watchtoken exists inside the database
v, exists, success := vbdb.RoundentryFromWatchtokenCtx(watchtokenStr, c.Log)
if !success {
return c.WriteStr("Internal server error")
}
if !exists {
c.Log.Warn("client provided unknown watchtoken", zap.String("watchtoken", string(watchtoken)))
return c.WriteStr("Unknown watchtoken")
}
// user is authenticated correctly
c.UserID = v.UserID
c.Log.Info("websocket authenticated and userID resolved", zap.Int("user_id", v.UserID))
// check if the user's watchtoken was intended for this round
if config.Battle.RoundID != v.RoundID {
c.Log.Warn("valid watchtoken references invalid round",
zap.Int("config_round_id", config.Battle.RoundID),
zap.Int("watchtoken_round_id", v.RoundID))
return c.WriteStr("Unexpected watchtoken. Maybe your round is already over?")
}
// subscribe websocket connection for all notifications to this user and
// send them as long as err isn't a disconnect from the remote websocket.
// Also send all initial informations needed by this specific subscriber,
// as map properties, etc.
dist.GetClient(strconv.Itoa(c.UserID)).Sub(ntfyWebsocketReceiver{
c: c,
}, c.Log)
return nil
}
type ntfyWebsocketReceiver struct {
c *nwsclient
}
func (r ntfyWebsocketReceiver) Init(initClient *ntfydistr.Client) {
// Start the initialization of the current subscriber
r.c.Log.Debug("initing nwsclient subscription for user")
// Construct necessary primitives
var player = battle.Players[r.c.UserID]
viewableMapsize := vbge.Location{
X: vbge.RenderWidth,
Y: vbge.RenderHeight,
}
playerMapentity, err := vbge.GetViewableMapentity(viewableMapsize.X, viewableMapsize.Y, r.c.UserID, battle, true)
if err != nil {
r.c.Log.Error("failed getting mapentity", zap.Error(err))
return
}
// Send the initial game information
r.c.Log.Debug("sending init package to nwsclient")
initClient.Push("initial", struct {
TotalMapsize vbge.Location `json:"totalmapsize"`
ViewableMapsize vbge.Location `json:"viewablemapsize"`
MaxHealth int `json:"maxhealth"`
PlayerMapentity [][]*vbge.EntityResp `json:"playermapentity"`
Startplayer string `json:"startplayer"`
}{
TotalMapsize: vbge.Location{
X: vbge.MapWidth,
Y: vbge.MapHeight,
},
ViewableMapsize: viewableMapsize,
MaxHealth: vbge.MaxHealth,
Startplayer: player.GRenderID,
PlayerMapentity: playerMapentity.Matrix,
}, r.c.Log)
// Set the client's debug flag
r.c.Log.Debug("sending debug flag to nwsclient", zap.Bool("debug", config.Network.WS.Flags.Debug))
initClient.Push("flag", struct {
Name string `json:"name"`
State bool `json:"state"`
}{
"debug",
config.Network.WS.Flags.Debug,
}, r.c.Log)
// Send the current state fo the stats
if config.Network.WS.Flags.Stats {
r.c.Log.Debug("sending stats to nwsclient")
stats, err := getPlayersStats()
if err != nil {
r.c.Log.Error("failed getting stats", zap.Error(err))
return
}
initClient.Push("stats", struct {
Stats playersStats `json:"stats"`
}{
stats,
}, r.c.Log)
}
}
func (r ntfyWebsocketReceiver) Write(notf []byte) (disconnected bool, err error) {
// write provided notification to the websocket connection
err = r.c.Write(notf)
if err == nil {
return
}
// check if the remote party disconnected
if _, ok := err.(*net.OpError); ok || websocket.IsUnexpectedCloseError(err) {
return true, err
}
// unknown error -> just return it
return false, err
}