-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandBehavior.cs
More file actions
76 lines (67 loc) · 2.29 KB
/
CommandBehavior.cs
File metadata and controls
76 lines (67 loc) · 2.29 KB
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
using WebSocketSharp;
using WebSocketSharp.Server;
namespace PCRemoteControlServer
{
public class CommandBehavior : WebSocketBehavior
{
public static string? Secret { get; set; }
private bool _authenticated;
private string _clientEndpoint = "unknown";
protected override void OnMessage(MessageEventArgs e)
{
var data = e.Data ?? string.Empty;
if (!_authenticated)
{
if (data == Secret)
{
_authenticated = true;
KeyCommandExecutor.Log("Client authenticated: " + _clientEndpoint);
Send("AUTH_OK");
}
else
{
KeyCommandExecutor.Log("Client failed authentication: " + _clientEndpoint);
Send("AUTH_FAIL");
Context.WebSocket.Close(CloseStatusCode.PolicyViolation, "Invalid secret");
}
return;
}
KeyCommandExecutor.ExecuteCommand(data);
Send("OK");
}
protected override void OnOpen()
{
_clientEndpoint = SafeGetClientEndpoint();
_authenticated = string.IsNullOrEmpty(Secret);
var authState = _authenticated ? "(no auth)" : "(awaiting auth)";
KeyCommandExecutor.Log("Client connected: " + _clientEndpoint + " " + authState);
}
protected override void OnClose(CloseEventArgs e)
{
KeyCommandExecutor.Log("Client disconnected: " + _clientEndpoint + " Code=" + e.Code);
}
protected override void OnError(ErrorEventArgs e)
{
if (_clientEndpoint == "unknown")
{
_clientEndpoint = SafeGetClientEndpoint();
}
KeyCommandExecutor.Log("WebSocket error (" + _clientEndpoint + "): " + e.Message);
}
private string SafeGetClientEndpoint()
{
try
{
return Context?.UserEndPoint?.ToString() ?? "unknown";
}
catch (NullReferenceException)
{
return "unknown";
}
catch (ObjectDisposedException)
{
return "unknown";
}
}
}
}