forked from vpnhood/VpnHood
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVhUtil.cs
374 lines (308 loc) · 11.6 KB
/
VhUtil.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
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
namespace VpnHood.Common.Utils;
public static class VhUtil
{
public static bool IsConnectionRefusedException(Exception ex)
{
return
ex is SocketException { SocketErrorCode: SocketError.ConnectionRefused } ||
ex.InnerException is SocketException { SocketErrorCode: SocketError.ConnectionRefused };
}
public static bool IsSocketClosedException(Exception ex)
{
return ex is ObjectDisposedException or IOException or SocketException;
}
public static IPEndPoint GetFreeTcpEndPoint(IPAddress ipAddress, int defaultPort = 0)
{
try
{
// check recommended port
var listener = new TcpListener(ipAddress, defaultPort);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return new IPEndPoint(ipAddress, port);
}
catch when (defaultPort != 0)
{
return GetFreeTcpEndPoint(ipAddress);
}
}
public static IPEndPoint GetFreeUdpEndPoint(IPAddress ipAddress, int defaultPort = 0)
{
try
{
// check recommended port
using var udpClient = new UdpClient(new IPEndPoint(ipAddress, defaultPort));
var port = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
return new IPEndPoint(ipAddress, port);
}
catch when (defaultPort != 0)
{
return GetFreeUdpEndPoint(ipAddress);
}
}
public static void DirectoryCopy(string sourcePath, string destinationPath, bool recursive)
{
// Get the subdirectories for the specified directory.
var dir = new DirectoryInfo(sourcePath);
if (!dir.Exists)
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourcePath);
var dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
Directory.CreateDirectory(destinationPath);
// Get the files in the directory and copy them to the new location.
var files = dir.GetFiles();
foreach (var file in files)
{
var tempPath = Path.Combine(destinationPath, file.Name);
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (recursive)
foreach (var item in dirs)
{
var tempPath = Path.Combine(destinationPath, item.Name);
DirectoryCopy(item.FullName, tempPath, recursive);
}
}
public static T[] SafeToArray<T>(object lockObject, IEnumerable<T> collection)
{
lock (lockObject)
return collection.ToArray();
}
public static async Task<T> RunTask<T>(Task<T> task, TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
await RunTask((Task)task, timeout, cancellationToken);
return await task;
}
public static async Task RunTask(Task task, TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
if (timeout == TimeSpan.Zero)
timeout = TimeSpan.FromMilliseconds(-1);
var timeoutTask = Task.Delay(timeout, cancellationToken);
await Task.WhenAny(task, timeoutTask);
cancellationToken.ThrowIfCancellationRequested();
if (timeoutTask.IsCompleted)
throw new TimeoutException();
await task;
}
public static bool IsNullOrEmpty<T>([NotNullWhen(false)] IEnumerable<T>? array)
{
return array == null || !array.Any();
}
public static bool IsNullOrEmpty<T>([NotNullWhen(false)] T[]? array)
{
return array == null || array.Length == 0;
}
public static IEnumerable<string> ParseArguments(string commandLine)
{
if (string.IsNullOrWhiteSpace(commandLine))
yield break;
var sb = new StringBuilder();
var inQuote = false;
foreach (var c in commandLine)
{
if (c == '"' && !inQuote)
{
inQuote = true;
continue;
}
if (c != '"' && !(char.IsWhiteSpace(c) && !inQuote))
{
sb.Append(c);
continue;
}
if (sb.Length > 0)
{
var result = sb.ToString();
sb.Clear();
inQuote = false;
yield return result;
}
}
if (sb.Length > 0)
yield return sb.ToString();
}
public static byte[] GenerateKey()
{
return GenerateKey(128);
}
public static byte[] GenerateKey(int keySizeInBit)
{
using var aes = Aes.Create();
aes.KeySize = keySizeInBit;
aes.GenerateKey();
return aes.Key;
}
public static T JsonDeserialize<T>(string json, JsonSerializerOptions? options = null)
{
return JsonSerializer.Deserialize<T>(json, options) ??
throw new InvalidDataException($"{typeof(T)} could not be deserialized!");
}
public static T? JsonDeserializeFile<T>(string filePath, JsonSerializerOptions? options = null, ILogger? logger = null)
{
try
{
if (!File.Exists(filePath))
return default(T);
var json = File.ReadAllText(filePath);
var appAccount = JsonDeserialize<T>(json, options);
return appAccount;
}
catch (Exception ex)
{
logger?.LogError(ex, "Could not read json file. FilePath: {FilePath}", filePath);
return default(T);
}
}
public static bool JsonEquals(object? obj1, object? obj2)
{
if (obj1 == null && obj2 == null) return true;
if (obj1 == null || obj2 == null) return false;
return JsonSerializer.Serialize(obj1) == JsonSerializer.Serialize(obj2);
}
public static T JsonClone<T>(object obj, JsonSerializerOptions? options = null)
{
var json = JsonSerializer.Serialize(obj, options);
return JsonDeserialize<T>(json, options);
}
public static byte[] EncryptClientId(Guid clientId, byte[] key)
{
// Validate request by shared secret
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = new byte[key.Length];
aes.Padding = PaddingMode.None;
using var cryptor = aes.CreateEncryptor();
return cryptor.TransformFinalBlock(clientId.ToByteArray(), 0, clientId.ToByteArray().Length);
}
public static string GetStringMd5(string value)
{
using var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
return BitConverter.ToString(hash).Replace("-", "");
}
public static string RedactHostName(string hostName)
{
return hostName.Length <= 8
? "***" + hostName[^4..]
: hostName[..2] + "***" + hostName[^4..];
}
public static string RedactEndPoint(IPEndPoint ipEndPoint)
{
return RedactIpAddress(ipEndPoint.Address) + ":" + ipEndPoint.Port;
}
public static string RedactIpAddress(IPAddress ipAddress)
{
var addressBytes = ipAddress.GetAddressBytes();
if (ipAddress.AddressFamily == AddressFamily.InterNetwork &&
!ipAddress.Equals(IPAddress.Any) &&
!ipAddress.Equals(IPAddress.Loopback))
return $"{addressBytes[0]}.*.*.{addressBytes[3]}";
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6 &&
!ipAddress.Equals(IPAddress.IPv6Any) &&
!ipAddress.Equals(IPAddress.IPv6Loopback))
return $"{addressBytes[0]:x2}{addressBytes[1]:x2}:***:{addressBytes[14]:x2}{addressBytes[15]:x2}";
return ipAddress.ToString();
}
public static string FormatBytes(long size, bool use1024 = true)
{
var kb = use1024 ? (long)1024 : 1000;
var mb = kb * kb;
var gb = mb * kb;
var tb = gb * kb;
if (size >= tb) // Terabyte
return (size / tb).ToString("0.## ") + "TB";
if (size >= gb) // Gigabyte
return (size / gb).ToString("0.# ") + "GB";
if (size >= mb) // Megabyte
return (size / mb).ToString("0 ") + "MB";
if (size >= kb) // Kilobyte
return (size / kb).ToString("0 ") + "KB";
if (size > 0) // Kilobyte
return size.ToString("0 ") + "B";
// Byte
return size.ToString("0");
}
public static string FormatBits(long bytes)
{
bytes *= 8; //convertTo bit
// ReSharper disable PossibleLossOfFraction
// Get absolute value
if (bytes >= 0x40000000) // Gigabyte
return ((double)(bytes / 0x40000000)).ToString("0.# ") + "Gbps";
if (bytes >= 0x100000) // Megabyte
return ((double)(bytes / 0x100000)).ToString("0 ") + "Mbps";
if (bytes >= 1024) // Kilobyte
return ((double)(bytes / 1024)).ToString("0 ") + "Kbps";
if (bytes > 0) // Kilobyte
return ((double)bytes).ToString("0 ") + "bps";
// ReSharper restore PossibleLossOfFraction
// Byte
return bytes.ToString("0");
}
public static bool IsInfinite(TimeSpan timeSpan)
{
return timeSpan == TimeSpan.MaxValue || timeSpan == Timeout.InfiniteTimeSpan;
}
public static ValueTask DisposeAsync(IAsyncDisposable? channel)
{
return channel?.DisposeAsync() ?? default;
}
public static void ConfigTcpClient(TcpClient tcpClient, int? sendBufferSize, int? receiveBufferSize, bool? reuseAddress = null)
{
tcpClient.NoDelay = true;
if (sendBufferSize != null) tcpClient.SendBufferSize = sendBufferSize.Value;
if (receiveBufferSize != null) tcpClient.ReceiveBufferSize = receiveBufferSize.Value;
if (reuseAddress != null) tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, reuseAddress.Value);
}
public static bool IsTcpClientHealthy(TcpClient tcpClient)
{
try
{
// Check if the TcpClient is connected
if (!tcpClient.Connected)
return false;
// Check if the underlying socket is connected
var socket = tcpClient.Client;
var healthy = tcpClient.Connected && socket.Connected && !tcpClient.Client.Poll(1, SelectMode.SelectError);
return healthy;
}
catch (Exception)
{
// An error occurred while checking the TcpClient
return false;
}
}
public static string RedactJsonValue(string json, string[] keys)
{
foreach (var key in keys)
{
// array
var jsonLength = json.Length;
var pattern = @"""key""\s*:\s*\[[^\]]*\]".Replace("key", key);
json = Regex.Replace(json, pattern, $"\"{key}\": [\"***\"]");
if (jsonLength != json.Length)
continue;
// single
pattern = "(?<=\"key\":)[^,|}|\r]+(?=,|}|\r)".Replace("key", key);
json = Regex.Replace(json, pattern, " \"***\"");
}
return json;
}
public static DateTime RemoveMilliseconds(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind);
}
}