-
Notifications
You must be signed in to change notification settings - Fork 3
/
WebSocketServer.cs
217 lines (195 loc) · 5.64 KB
/
WebSocketServer.cs
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
using CitizenFX.Core;
using CitizenFX.Core.Native;
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using vtortola.WebSockets;
namespace WebSocketServer
{
class WebSocketServer : BaseScript
{
private enum LogLevels { Debug, Info, Warn, Error };
private LogLevels logLevel;
private string authorization;
private List<CallbackDelegate> authorizationHandlers;
private List<WebSocket> webSockets;
private async Task<bool> CheckHttpHeaders(WebSocketHttpRequest request, WebSocketHttpResponse response)
{
await Task.Run(() =>
{
if (authorization.Length > 0)
{
var authHeader = request.Headers["Authorization"];
if (authHeader == null || authHeader != authorization)
{
response.Status = HttpStatusCode.Unauthorized;
Log("Rejected Authorization header: " + authHeader, LogLevels.Debug);
}
}
for (int i = authorizationHandlers.Count - 1; i >= 0; i--)
{
try
{
if (!(bool) authorizationHandlers[i](request.RemoteEndPoint.ToString(), request.Headers.ToString()))
{
response.Status = HttpStatusCode.Unauthorized;
}
}
catch (Exception e)
{
Log("An error occurred while calling an authentication handler: " + e.Message, LogLevels.Debug);
authorizationHandlers.RemoveAt(i);
}
}
});
return true;
}
public WebSocketServer()
{
logLevel = Function.Call<string>(Hash.GET_CONVAR, "websocket_debug", "false") == "true" ? LogLevels.Debug : LogLevels.Info;
authorization = Function.Call<string>(Hash.GET_CONVAR, "websocket_authorization", "");
authorizationHandlers = new List<CallbackDelegate>();
IPAddress listeningHost = IPAddress.Loopback;
IPAddress.TryParse(Function.Call<string>(Hash.GET_CONVAR, "websocket_host", "127.0.0.1"), out listeningHost);
int listeningPort = Function.Call<int>(Hash.GET_CONVAR_INT, "websocket_port", 80);
var endpoint = new IPEndPoint(listeningHost, listeningPort);
var server = new WebSocketEventListener (endpoint, new WebSocketListenerOptions () {
SubProtocols = new String[]{ "text" },
HttpAuthenticationHandler = CheckHttpHeaders
});
server.OnConnect += (ws) =>
{
Log ("Connection from " + ws.RemoteEndpoint.ToString (), LogLevels.Debug);
TriggerEvent("WebSocketServer:onConnect", ws.RemoteEndpoint.ToString ());
lock (webSockets)
{
webSockets.Add(ws);
}
};
server.OnDisconnect += (ws) =>
{
Log ("Disconnection from " + ws.RemoteEndpoint.ToString (), LogLevels.Debug);
TriggerEvent("WebSocketServer:onDisconnect", ws.RemoteEndpoint.ToString ());
lock (webSockets)
{
webSockets.Remove(ws);
}
};
server.OnError += (ws, ex) => Log("Error: " + ex.Message, LogLevels.Debug);
server.OnMessage += (ws, msg) =>
{
Log("Received message: " + msg, LogLevels.Debug);
TriggerEvent("WebSocketServer:onMessage", msg, ws.RemoteEndpoint.ToString ());
};
EventHandlers["onResourceStart"] += new Action<dynamic>((dynamic resourceName) =>
{
if ((string) resourceName == "WebSocketServer")
{
try
{
server.Start();
Tick += server.ListenAsync;
Log("Started at " + endpoint.ToString());
}
catch (Exception e)
{
Log("Can't start server at " + endpoint.ToString() + ": " + e.Message);
}
}
});
EventHandlers["onResourceStop"] += new Action<dynamic>((dynamic resourceName) =>
{
if ((string) resourceName == "WebSocketServer")
{
server.Stop();
server.Dispose();
}
});
EventHandlers["WebSocketServer:addAuthHandler"] += new Action<dynamic>((dynamic handler) =>
{
authorizationHandlers.Add(handler);
});
webSockets = new List<WebSocket>();
EventHandlers["WebSocketServer:broadcast"] += new Action<dynamic>((dynamic message) =>
{
lock (webSockets)
{
foreach (var webSocket in webSockets)
{
if (webSocket.IsConnected)
{
Task.Run(async () =>
{
try
{
await webSocket.WriteStringAsync((string) message, CancellationToken.None);
}
catch (Exception e)
{
Log("An error occurred while sending a message to " + webSocket.RemoteEndpoint.ToString() + ": " + e.Message, LogLevels.Debug);
}
});
}
else
{
webSockets.Remove(webSocket);
}
}
}
});
EventHandlers["WebSocketServer:send"] += new Action<dynamic, dynamic>((dynamic message, dynamic client) =>
{
lock (webSockets)
{
foreach (var webSocket in webSockets)
{
if (webSocket.IsConnected)
{
if (webSocket.RemoteEndpoint.ToString () == client)
{
Task.Run(async () =>
{
try
{
await webSocket.WriteStringAsync((string) message, CancellationToken.None);
}
catch (Exception e)
{
Log("An error occurred while sending a message to " + webSocket.RemoteEndpoint.ToString() + ": " + e.Message, LogLevels.Debug);
}
});
}
}
else
{
webSockets.Remove(webSocket);
}
}
}
});
EventHandlers["WebSocketServer:removeEndpoint"] += new Action<dynamic>((dynamic client) =>
{
lock (webSockets)
{
foreach (var webSocket in webSockets)
{
if (webSocket.IsConnected && webSocket.RemoteEndpoint.ToString() == client)
{
webSockets.Remove(webSocket);
}
}
}
});
}
private void Log(string message, LogLevels level = LogLevels.Info)
{
if (logLevel > level)
{
return;
}
Debug.WriteLine("[WebSocket Server] " + message);
}
}
}