forked from saucepleez/tasktServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketManagement.cs
More file actions
269 lines (198 loc) · 10.6 KB
/
SocketManagement.cs
File metadata and controls
269 lines (198 loc) · 10.6 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
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
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using tasktServer.Models;
using tasktServer.Models.SQL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace tasktServer
{
public class SocketManagement
{
private IMemoryCache cache;
public SocketManagement(IMemoryCache memoryCache)
{
this.cache = memoryCache;
}
private void LogEvent(ApplicationLogs log)
{
using (Models.SQL.tasktserverContext dbContext = new tasktserverContext())
{
try
{
log.LoggedOn = DateTime.Now;
dbContext.ApplicationLogs.Add(log);
dbContext.SaveChanges();
}
catch (Exception ex)
{
throw;
}
}
}
/// <summary>
/// Processes incoming socket messages from taskt clients
/// </summary>
/// <param name="context"></param>
/// <param name="webSocket"></param>
/// <returns></returns>
public async Task ProcessIncomingSocketMessage(HttpContext context, WebSocket webSocket)
{
//create dbcontext
Models.SQL.tasktserverContext dbContext = new tasktserverContext();
//generate GUID for this connection
Guid guid;
guid = Guid.NewGuid();
string connectionGUID = guid.ToString();
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
//get connection information
string connectionID = context.Connection.Id;
string ipAddress = context.Connection.RemoteIpAddress.ToString();
//retrieve value
var arraySegment = new ArraySegment<byte>(buffer, 0, result.Count);
var incomingMessage = System.Text.Encoding.Default.GetString(arraySegment.Array);
incomingMessage = incomingMessage.Substring(0, result.Count);
//convert client data
var clientData = Newtonsoft.Json.JsonConvert.DeserializeObject<SocketPackage>(incomingMessage);
var clientInfo = string.Join(", ", "MACHINE: " + clientData.MACHINE_NAME, "USER: " + clientData.USER_NAME, "MESSAGE: " + clientData.MESSAGE, "IP: " + ipAddress);
if (clientData.MESSAGE.StartsWith("CLIENT_STATUS="))
{
var clientUpdate = clientData.MESSAGE.Replace("CLIENT_STATUS=", "");
var socketClient = ActiveSocketClients.GetClient(clientData.PUBLIC_KEY);
if (socketClient.PingRequest.AwaitingPingReply)
{
socketClient.PingRequest.AwaitingPingReply = false;
socketClient.PingRequest.ClientStatus = clientUpdate;
socketClient.PingRequest.ReadyForUIReporting = true;
}
LogEvent(new ApplicationLogs() { Type = "WORKER UPDATE", Guid = connectionGUID, Message = clientUpdate, LoggedBy = clientData.PUBLIC_KEY });
var worker = dbContext.Workers.Where(f => f.PublicKey == clientData.PUBLIC_KEY).FirstOrDefault();
if (worker != null)
{
worker.LastCommunicationReceived = DateTime.Now;
worker.LastExecutionStatus = clientUpdate;
dbContext.SaveChanges();
}
await SendMessageAsync(webSocket, "ACK", CancellationToken.None);
}
LogEvent(new ApplicationLogs() {Guid = connectionGUID, Message = "ROBOT CONNECTED FROM '" + ipAddress + "'", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
LogEvent(new ApplicationLogs() {Guid = connectionGUID, Message = "CLIENT INFO: " + clientInfo + "", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
//if public key is null or empty we automatically assign
if ((string.IsNullOrEmpty(clientData.PUBLIC_KEY)) || (dbContext.Workers.Where(f => f.PublicKey == clientData.PUBLIC_KEY).FirstOrDefault() == null))
{
LogEvent(new ApplicationLogs() { Guid = connectionGUID, Message = "ROBOT NOT REGISTERED", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
var generatedKeys = tasktServer.Cryptography.CreateKeyPair();
var worker = new Workers() { MachineName = clientData.MACHINE_NAME, UserName = clientData.USER_NAME, AccountStatus = (int)ApprovalStatus.RequiresApproval, LastCommunicationReceived = DateTime.Now, PublicKey = generatedKeys.Item2, PrivateKey = generatedKeys.Item1 };
dbContext.Workers.Add(worker);
dbContext.SaveChanges();
ActiveSocketClients.SetClient(clientData.PUBLIC_KEY, webSocket);
LogEvent(new ApplicationLogs() { Guid = connectionGUID, Message = "ROBOT GIVEN NEW PUBLIC KEY AND AWAITING AUTHORIZATION", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
await SendMessageAsync(webSocket, "ACCEPT_KEY=" + worker.PublicKey, CancellationToken.None);
}
else
{
var knownClient = dbContext.Workers.Where(f => f.PublicKey == clientData.PUBLIC_KEY).FirstOrDefault();
knownClient.LastCommunicationReceived = DateTime.Now;
dbContext.SaveChanges();
ActiveSocketClients.SetClient(clientData.PUBLIC_KEY, webSocket);
switch (knownClient.AccountStatus)
{
case (int)ApprovalStatus.RequiresApproval:
LogEvent(new ApplicationLogs() { Guid = connectionGUID, Message = "RESPONDED WORKER_AWAITING_APPROVAL", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
await SendMessageAsync(webSocket, "WORKER_AWAITING_APPROVAL", CancellationToken.None);
break;
case (int)ApprovalStatus.Disabled:
LogEvent(new ApplicationLogs() { Guid = connectionGUID, Message = "RESPONDED WORKER_DISABLED", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
await SendMessageAsync(webSocket, "WORKER_DISABLED", CancellationToken.None);
break;
case (int)ApprovalStatus.Enabled:
LogEvent(new ApplicationLogs() { Guid = connectionGUID, Message = "RESPONDED WORKER_ENABLED", LoggedBy = "SYSTEM", Type = "SOCKET REQUEST" });
await SendMessageAsync(webSocket, "WORKER_ENABLED", CancellationToken.None);
break;
default:
break;
}
}
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
/// <summary>
/// Sends an outbound socket message containing script data to be executed
/// </summary>
/// <param name="machineName"></param>
/// <param name="scriptName"></param>
/// <returns></returns>
public static string SendScriptToClient(string machineName, string scriptName)
{
List<RobotClient> connectedClients = WorkForceManagement.GetClients();
RobotClient requiredConn = connectedClients.Where(client => client.MachineName == machineName).FirstOrDefault();
if (requiredConn != null)
{
var rpaScriptsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\sharpRPA\\My Scripts\\";
System.Xml.XmlDocument dom = new System.Xml.XmlDocument();
dom.Load(rpaScriptsFolder + scriptName);
byte[] bytes = System.Text.Encoding.Default.GetBytes(dom.OuterXml);
var buffer = new ArraySegment<Byte>(bytes, 0, bytes.Length);
requiredConn.ClientSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
return "Script Sent To Client";
}
else
{
return "Client Not Found";
}
}
/// <summary>
/// Sends a message through a websocket connection
/// </summary>
/// <param name="ws"></param>
/// <param name="data"></param>
/// <param name="cancellation"></param>
/// <returns></returns>
public static async Task SendMessageAsync(WebSocket ws, String data, CancellationToken cancellation)
{
var encoded = Encoding.UTF8.GetBytes(data);
var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);
await ws.SendAsync(buffer, WebSocketMessageType.Text, true, cancellation);
}
}
public static class ActiveSocketClients
{
private static List<Models.SocketConnectionModel> AvailableConnections = new List<SocketConnectionModel>();
public static void SetClient(string publicKey, WebSocket socket)
{
if (AvailableConnections.Count > 0)
{
var existingConnection = AvailableConnections.Where(f => f.PublicKey == publicKey).FirstOrDefault();
if (existingConnection != null)
{
AvailableConnections.Remove(existingConnection);
}
AvailableConnections.Add(new SocketConnectionModel { PublicKey = publicKey, WebSocket = socket });
}
else
{
AvailableConnections.Add(new SocketConnectionModel { PublicKey = publicKey, WebSocket = socket });
}
}
public static SocketConnectionModel GetClient(string publicKey)
{
var requiredConnection = AvailableConnections.Where(f => f.PublicKey == publicKey).FirstOrDefault();
if (requiredConnection == null)
{
return null;
}
else
{
return requiredConnection;
}
}
}
}