Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using DateTime = System.DateTime;
  10. namespace TcpRedirector
  11. {
  12. internal class Program
  13. {
  14. private static int _proxyPort;
  15. public static string ProxyHost { get; private set; }
  16. public static int ProxyPort => _proxyPort;
  17. public static IReadOnlyList<byte> TargetHostBytes { get; private set; }
  18. public static IReadOnlyList<byte> TargetPortBytes { get; private set; }
  19. public static bool IsRunning { get; private set; }
  20. private static int Number = 0;
  21. public static int GetNumber()
  22. {
  23. return Interlocked.Increment(ref Number);
  24. }
  25. private static int Main(string[] args)
  26. {
  27. if (args.Length < 6)
  28. {
  29. Console.WriteLine("listenAddress listenPort proxyHost proxyPort targetHost targetPort");
  30. return -1;
  31. }
  32. if (!IPAddress.TryParse(args[0], out var listenAddress)) listenAddress = IPAddress.Any;
  33. if (!int.TryParse(args[1], out var listenPort)) listenPort = 0;
  34. ProxyHost = args[2];
  35. if (!int.TryParse(args[3], out _proxyPort)) _proxyPort = 0;
  36. var targetHost = args[4];
  37. if (!int.TryParse(args[5], out var targetPort)) targetPort = 0;
  38. TargetHostBytes = Encoding.ASCII.GetBytes(targetHost);
  39. TargetPortBytes = new[] { (byte)(targetPort << 8), (byte)targetPort };
  40. Console.Title = $"TR {listenAddress}:{listenPort} via {ProxyHost}:{ProxyPort} to {targetHost}:{targetPort}";
  41. IsRunning = true;
  42. var list = new List<Socks5Forwarder>();
  43. var startup = DateTime.Now;
  44. Task.Run(() =>
  45. {
  46. var listener = new TcpListener(new IPEndPoint(listenAddress, listenPort));
  47. listener.Start();
  48. Task<TcpClient> task = null;
  49. do
  50. {
  51. if (task == null)
  52. {
  53. task = listener.AcceptTcpClientAsync();
  54. }
  55. else if (task.IsCompleted)
  56. {
  57. var client = task.Result;
  58. lock (list)
  59. {
  60. list.Add(new Socks5Forwarder(client));
  61. }
  62. task = null;
  63. }
  64. Thread.Sleep(100);
  65. } while (IsRunning);
  66. listener.Stop();
  67. });
  68. while (IsRunning)
  69. {
  70. Console.Clear();
  71. Console.WriteLine($"UP {(DateTime.Now - startup).CompactFormat()} Since {startup}");
  72. //Print running info
  73. lock (list)
  74. {
  75. Console.WriteLine();
  76. Console.WriteLine($"Connections: {list.Count}");
  77. Console.WriteLine();
  78. foreach (var item in list)
  79. {
  80. Console.WriteLine(
  81. $"#{item.Number:0000}" +
  82. $" {item.CreatedTime:yyyy-MM-dd HH:mm:ss}"+
  83. $" {item.IncomingEndPoint?.ToString() ?? "Unknown",20}" +
  84. $" {item.Status}" +
  85. $" Wai:{(DateTime.Now - item.LastActiveTime).CompactFormat(),6}" +
  86. $" Out:{item.OutgoingBytes.UnitFormat() + "B",10}" +
  87. $" In:{item.IncomingBytes.UnitFormat() + "B",10}" +
  88. ""
  89. );
  90. if (string.IsNullOrWhiteSpace(item.Error) == false) Console.WriteLine($"\t{item.Error}");
  91. }
  92. //remove timeout items
  93. foreach (var item in list.ToArray())
  94. {
  95. if ((DateTime.Now - item.LastActiveTime).TotalMinutes > 1)
  96. {
  97. if (item.Status
  98. is Socks5ForwarderStatus.ERRBERU
  99. or Socks5ForwarderStatus.ERRTOPR
  100. or Socks5ForwarderStatus.ERRTOTA
  101. or Socks5ForwarderStatus.DISCONN
  102. )
  103. {
  104. list.Remove(item);
  105. }
  106. }
  107. }
  108. }
  109. if (Console.KeyAvailable)
  110. {
  111. switch (char.ToUpper(Console.ReadKey(true).KeyChar))
  112. {
  113. case 'Q':
  114. IsRunning = false;
  115. break;
  116. default:
  117. Console.WriteLine("Press Q to exit");
  118. break;
  119. }
  120. }
  121. Thread.Sleep(1000);
  122. }
  123. return 0;
  124. }
  125. }
  126. internal class Socks5Forwarder
  127. {
  128. public int Number { get; }
  129. public Socks5ForwarderStatus Status { get; private set; } = Socks5ForwarderStatus.PENDING;
  130. public DateTime CreatedTime { get; } = DateTime.Now;
  131. public DateTime LastActiveTime { get; set; }
  132. public EndPoint? IncomingEndPoint { get; }
  133. public int IncomingBytes { get; private set; }
  134. public int OutgoingBytes { get; private set; }
  135. public string Error { get; private set; }
  136. public Socks5Forwarder(TcpClient incomingClient)
  137. {
  138. Number = Program.GetNumber();
  139. IncomingEndPoint = incomingClient.Client.RemoteEndPoint;
  140. Task.Run(() =>
  141. {
  142. Status = Socks5ForwarderStatus.CONTOPR;
  143. TcpClient outgoingClient = null;
  144. NetworkStream outgoingStream;
  145. try
  146. {
  147. outgoingClient = new TcpClient(Program.ProxyHost, Program.ProxyPort);
  148. outgoingStream = outgoingClient.GetStream();
  149. LastActiveTime = DateTime.Now;
  150. //socks 5 hand shake
  151. outgoingStream.Write(new byte[] { 5, 1, 0 });
  152. if (outgoingStream.ReadByte() != 5) throw new Exception("Server version error");
  153. if (outgoingStream.ReadByte() != 0) throw new Exception("Server auth method error");
  154. }
  155. catch (Exception e)
  156. {
  157. Status = Socks5ForwarderStatus.ERRTOPR;
  158. Error = e.Message;
  159. goto FINISHED;
  160. }
  161. Status = Socks5ForwarderStatus.CONTOTA;
  162. try
  163. {
  164. LastActiveTime = DateTime.Now;
  165. //socks 5 connection
  166. var connect = new byte[] { 5, 1, 0, 3 }
  167. .Concat(new[] { (byte)Program.TargetHostBytes.Count })
  168. .Concat(Program.TargetHostBytes)
  169. .Concat(Program.TargetPortBytes).ToArray();
  170. outgoingStream.Write(connect);
  171. if (outgoingStream.ReadByte() != 5) throw new Exception("Server version error");
  172. var rep = outgoingStream.ReadByte();
  173. if (rep != 0) throw new Exception($"Server response error:{rep}");
  174. if (outgoingStream.ReadByte() != 0) throw new Exception($"Server response error");
  175. var aty = outgoingStream.ReadByte();
  176. var len = aty switch
  177. {
  178. 1 => 4,
  179. 3 => outgoingStream.ReadByte(),
  180. 4 => 16,
  181. _ => throw new Exception($"Server response AddressTYPE error")
  182. };
  183. for (var i = 0; i < len + 2; i++)
  184. {
  185. if (-1 == outgoingStream.ReadByte()) throw new Exception($"Server response padding error");
  186. }
  187. }
  188. catch (Exception e)
  189. {
  190. Status = Socks5ForwarderStatus.ERRTOTA;
  191. Error = e.Message;
  192. goto FINISHED;
  193. }
  194. NetworkStream incomingStream;
  195. try
  196. {
  197. incomingClient.NoDelay = true;
  198. outgoingClient.NoDelay = true;
  199. incomingStream = incomingClient.GetStream();
  200. }
  201. catch (Exception e)
  202. {
  203. Status = Socks5ForwarderStatus.ERRBERU;
  204. Error = e.Message;
  205. goto FINISHED;
  206. }
  207. Status = Socks5ForwarderStatus.RUNNING;
  208. LastActiveTime = DateTime.Now;
  209. //forward both
  210. var outgoingForward = Task.Run(() =>
  211. {
  212. var buf = new byte[6000];
  213. while (Program.IsRunning)
  214. {
  215. LastActiveTime = DateTime.Now;
  216. int read;
  217. try
  218. {
  219. read = incomingStream.Read(buf, 0, buf.Length);
  220. }
  221. catch (Exception e)
  222. {
  223. Status = Socks5ForwarderStatus.DISCONN;
  224. Error = $"Read Incoming: {e.Message}";
  225. break;
  226. }
  227. if (read == 0)
  228. {
  229. Status = Socks5ForwarderStatus.DISCONN;
  230. Error = "Incoming Closed";
  231. break;
  232. }
  233. OutgoingBytes += read;
  234. try
  235. {
  236. outgoingStream.Write(buf, 0, read);
  237. }
  238. catch (Exception e)
  239. {
  240. Status = Socks5ForwarderStatus.DISCONN;
  241. Error = $"Write Outgoing:{e.Message}";
  242. break;
  243. }
  244. }
  245. });
  246. var incomingForward = Task.Run(() =>
  247. {
  248. var buf = new byte[6000];
  249. while (Program.IsRunning)
  250. {
  251. LastActiveTime = DateTime.Now;
  252. int read;
  253. try
  254. {
  255. read = outgoingStream.Read(buf, 0, buf.Length);
  256. }
  257. catch (Exception e)
  258. {
  259. Status = Socks5ForwarderStatus.DISCONN;
  260. Error = $"Read Outgoing: {e.Message}";
  261. break;
  262. }
  263. if (read == 0)
  264. {
  265. Status = Socks5ForwarderStatus.DISCONN;
  266. Error = "Outgoing disconnected";
  267. break;
  268. }
  269. IncomingBytes += read;
  270. try
  271. {
  272. incomingStream.Write(buf, 0, read);
  273. }
  274. catch (Exception e)
  275. {
  276. Status = Socks5ForwarderStatus.DISCONN;
  277. Error = $"Write Incoming:{e.Message}";
  278. break;
  279. }
  280. }
  281. });
  282. Task.WaitAny(outgoingForward, incomingForward);
  283. FINISHED:
  284. try
  285. {
  286. outgoingClient?.Close();
  287. }
  288. catch
  289. {
  290. //EAT ERROR
  291. }
  292. try
  293. {
  294. incomingClient?.Close();
  295. }
  296. catch
  297. {
  298. //EAT ERROR
  299. }
  300. });
  301. }
  302. }
  303. internal enum Socks5ForwarderStatus
  304. {
  305. PENDING,
  306. CONTOPR,
  307. CONTOTA,
  308. RUNNING,
  309. ERRTOPR,
  310. ERRTOTA,
  311. ERRBERU,
  312. DISCONN,
  313. }
  314. internal static class OutputFormatter
  315. {
  316. public static string CompactFormat(this TimeSpan value)
  317. {
  318. var lst = new List<string>();
  319. if (Math.Abs(value.TotalDays) >= 1) lst.Add($"{value.TotalDays:00}d");
  320. if (Math.Abs(value.Hours) >= 1) lst.Add($"{value.Hours:00}h");
  321. if (Math.Abs(value.Minutes) >= 1 && lst.Count < 2) lst.Add($"{value.Minutes:00}m");
  322. if (Math.Abs(value.Seconds) >= 1 && lst.Count < 2) lst.Add($"{value.Seconds:00}s");
  323. if (lst.Count < 2) lst.Add($"{value.Milliseconds:000}");
  324. return string.Join("", lst);
  325. }
  326. public static string UnitFormat(this int value, int digit = 3)
  327. {
  328. const string unit = " KMGTPE";
  329. var val = (double)value;
  330. var index = 0;
  331. while (val > 1000 && index < unit.Length)
  332. {
  333. val /= 1000;
  334. ++index;
  335. }
  336. return val.ToString("N" + digit) + unit[index];
  337. }
  338. }
  339. }