forked from KirosHan/Palworld-server-protector-DotNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rcon.cs
381 lines (313 loc) · 12.7 KB
/
Rcon.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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using System;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Net;
using System.Security.Cryptography;
using System.Xml.Linq;
namespace Palworld_server_protector_DotNet
{
public class PalUserInfo
{
public string Name { get; set; }
public string Uid { get; set; }
public string SteamId { get; set; }
public PalUserInfo(string row)
{
var splits = row.Split(',');
Name = splits[0];
Uid = splits.Length > 1 ? splits[1] : "";
SteamId = splits.Length > 2 ? splits[2] : "";
}
public override bool Equals(object obj)
{
//return obj is PalUserInfo info && Name == info.Name && Uid == info.Uid && SteamId == info.SteamId;
return obj is PalUserInfo info && Name == info.Name;
}
public override int GetHashCode()
{
//return HashCode.Combine(Name, Uid, SteamId);
return HashCode.Combine(Name);
}
}
internal class Rcon
{
internal static TcpClient Client;
private static NetworkStream networkStream;
static Form form;
[STAThread]
static async Task Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new Form1();
Application.Run(form);
AppDomain.CurrentDomain.ProcessExit += ProcessExit;
}
public static async Task<string> Connect(string address, Int32 port, string pass)
{
Client = new TcpClient();
try
{
await Client.ConnectAsync(address, port);
}
catch(Exception e)
{
Task.Run(() => Logger.AppendToErrorLog($"连接时发生错误: {e.Message}"));
return "连接失败";
}
if (!Client.Connected)
{
Client.Dispose();
Client = null;
return "连接失败";
}
networkStream = Client.GetStream();
Pck auth = new Pck(0xf5, PacketType.AUTH, Encoding.ASCII.GetBytes(pass));
networkStream.Write(auth.ToBytes(), 0, auth.Len);
int size = networkStream.ReadByte();
byte[] data = new byte[size];
await networkStream.ReadAsync(data, 0, size);
if (data[3] != 0xf5)
{
if (Client != null)
{
if (Client.Connected)
{
Client.GetStream().Close();
}
Client.Dispose();
}
return "密码认证失败";
}
var output = await SInfo();
return string.Format("连接成功" + Environment.NewLine + $"{output}");
}
public static async Task<string> SInfo(bool keep = false)
{
if (Client != null)
{
try
{
while (networkStream.DataAvailable) { _ = networkStream.ReadByte(); }
Pck pck = new Pck(0x1f, PacketType.EXECCOMMAND, Encoding.ASCII.GetBytes("info"));
networkStream.Write(pck.ToBytes(), 0, pck.Len);
int size = networkStream.ReadByte();
var data = new byte[size];
await networkStream.ReadAsync(data, 0, size);
if (!keep)
{
return Encoding.UTF8.GetString(data.Skip(11).ToArray());
}
}
catch
{
return "获取失败";
}
}
return "";
}
public static async Task<List<PalUserInfo>> GetPlayers(string address, Int32 port, string pass)
{
var result = new List<PalUserInfo>();
var ensureConnectedResult = await EnsureConnected(address, port, pass);
string resstring = "";
if (ensureConnectedResult != "连接成功")
{
return result; // 如果连接失败,返回失败消息
}
try
{
if (networkStream != null)
{
while (networkStream.DataAvailable) { _ = networkStream.ReadByte(); }
Pck pck = new Pck(0x1f, PacketType.EXECCOMMAND, Encoding.ASCII.GetBytes("showplayers"));
networkStream.Write(pck.ToBytes(), 0, pck.Len);
int size = networkStream.ReadByte();
byte[] data = new byte[size];
await networkStream.ReadAsync(data, 0, size);
resstring = Encoding.UTF8.GetString(data.Skip(34).ToArray());
var lines = resstring.Split('\n');
if (lines.Length < 1)
{
return result;
}
for (int i = 1; i <= lines.Length; i++)
{
var line = lines[i-1];
if (string.IsNullOrEmpty(line))
{
continue;
}
result.Add(new PalUserInfo(line));
}
/* string[] players = resstring.Split('\n');
string output = "";
for (int i = 1; i <= players.Length; i++)
{
output += $"{i}:" + players[i - 1] + Environment.NewLine;
}
return output;*/
}
return result;
}
catch (Exception ex)
{
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x66>>>发送命令时发生错误>>>返回值为[{resstring}]>>>错误信息:{ex.Message}"));
return result;
}
return result;
}
public static async Task<string> Broadcast(string address, Int32 port, string pass, string text)
{
var ensureConnectedResult = await EnsureConnected(address, port, pass);
if (ensureConnectedResult != "连接成功")
{
return ensureConnectedResult; // 如果连接失败,返回失败消息
}
try
{
if (networkStream != null)
{
while (networkStream.DataAvailable) { _ = networkStream.ReadByte(); }
Pck packet = new Pck(0x1f, PacketType.EXECCOMMAND, Encoding.UTF8.GetBytes("broadcast " + text));
networkStream.Write(packet.ToBytes(), 0, packet.Len);
int size = networkStream.ReadByte();
byte[] data = new byte[size];
await networkStream.ReadAsync(data, 0, size);
string resstring = Encoding.UTF8.GetString(data.Skip(11).ToArray());
return resstring;
}
return "";
}
catch (Exception ex)
{
Task.Run(() => Logger.AppendToErrorLog($"发送命令时发生错误:{ex.Message}"));
return "发送失败";
}
return "发送失败";
}
public static async Task Reload()
{
if (Client.Connected)
{
await SInfo(true);
}
}
public static async Task<string> ShutDown(string address, Int32 port, string pass, string time, string text)
{
var ensureConnectedResult = await EnsureConnected(address, port, pass);
if (ensureConnectedResult != "连接成功")
{
return ensureConnectedResult; // 如果连接失败,返回失败消息
}
try
{
if (networkStream != null)
{
while (networkStream.DataAvailable) { _ = networkStream.ReadByte(); }
Pck packet = new Pck(0x1f, PacketType.EXECCOMMAND, Encoding.ASCII.GetBytes("shutdown " + time + " " + text));
networkStream.Write(packet.ToBytes(), 0, packet.Len);
int size = networkStream.ReadByte();
byte[] data = new byte[size];
await networkStream.ReadAsync(data, 0, size);
string resstring = Encoding.UTF8.GetString(data.Skip(11).ToArray());
return resstring;
}
return "";
}
catch (Exception ex)
{
Task.Run(() => Logger.AppendToErrorLog($"发送命令时发生错误: {ex.Message}"));
return "发送失败";
}
return "发送失败";
}
public static async Task<string> SendCommand(string address, Int32 port, string pass,string command)
{
// 检查客户端是否已连接
var ensureConnectedResult = await EnsureConnected(address, port, pass);
try
{
// 清除可用数据,以避免读取残留数据
while (networkStream.DataAvailable) { _ = networkStream.ReadByte(); }
// 创建自定义命令的数据包
Pck packet = new Pck(0x1f, PacketType.EXECCOMMAND, Encoding.UTF8.GetBytes(command));
networkStream.Write(packet.ToBytes(), 0, packet.Len);
// 读取响应大小
int size = networkStream.ReadByte();
if (size == -1) // 检查是否成功读取到数据
{
return "未能接收到命令响应"; // 未能接收到命令的响应
}
byte[] data = new byte[size];
// 异步读取服务器响应
await networkStream.ReadAsync(data, 0, size);
// 将响应转换为字符串并返回
string responseString = Encoding.UTF8.GetString(data.Skip(11).ToArray());
return responseString;
}
catch (Exception ex)
{
// 异常处理,返回错误信息
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x65>>>发送命令时发生错误>>>错误信息:{ex.Message}"));
return $"发送命令时发生错误。"; // 发送命令时发生错误
}
}
// 这个函数尝试确保客户端连接到服务器。如果客户端未连接,它会尝试建立连接。
public static async Task<string> EnsureConnected(string address, Int32 port, string pass)
{
if (Client == null || !Client.Connected)
{
// 尝试连接
return await Connect(address, port, pass);
}
return "连接成功"; // 如果已连接,返回成功消息
}
[Serializable]
public class Pck
{
public int Size;
public int ID;
public PacketType Type;
public byte[] Body;
public Pck(int id, PacketType type, byte[] body)
{
ID = id; Type = type; Body = body.Concat(new byte[] { 0x00, 0x00 }).ToArray(); Size = body.Length + 10;
}
internal byte[] ToBytes()
{
byte[] res = new byte[Size + 4];
BitConverter.GetBytes(Size).CopyTo(res, 0);
BitConverter.GetBytes(ID).CopyTo(res, 4);
BitConverter.GetBytes((int)Type).CopyTo(res, 8);
Body.CopyTo(res, 12);
return res;
}
internal int Len => Body.Length + 12;
}
public enum PacketType : int
{
RESPONSE_VALUE = 0,
AUTH_RESPONSE = 2,
EXECCOMMAND = 2,
AUTH = 3
}
public static void ProcessExit(object sender, EventArgs ea)
{
if (Client != null)
{
if (Client.Connected)
{
Client.GetStream().Close();
}
Client.Dispose();
Client = null;
}
}
}
}