ExampleForm.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. namespace UdPunching.ExampleW
  11. {
  12. public partial class ExampleForm : Form
  13. {
  14. private const int ReceiveBufferSize = 1500;
  15. private static readonly IPEndPoint AnyEndPoint = new IPEndPoint(IPAddress.Any, 0);
  16. private readonly IReadOnlyDictionary<Guid, RSACng> _peerPublicKeyRegistry;
  17. private IPEndPoint _serverEndPoint;
  18. private RSACng _serverPublicKey;
  19. private SocketAsyncEventArgs _saeReceive;
  20. private Guid _localId;
  21. private RSACng _localPrivateKey;
  22. private Socket _localSocket;
  23. private IPEndPoint _localPublicEndPoint;
  24. private readonly byte[] _keepAliveBuf = new byte[7];// 1flag,1count,1section,4timestamp
  25. private readonly ExchangeMessage _keepAliveMsg = new ExchangeMessage { Id = ExchangeMessageId.KeepAliveReq };
  26. //------------- ctor -------------
  27. public ExampleForm()
  28. {
  29. InitializeComponent();
  30. _peerPublicKeyRegistry = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PeerPublicKey"))
  31. .ToDictionary(
  32. s => new Guid(Path.GetFileNameWithoutExtension(s)),
  33. TransferCodec.LoadKey
  34. );
  35. }
  36. //------------- ui event -------------
  37. private void ExampleForm_Shown(object sender, EventArgs e)
  38. {
  39. _serverPublicKey = new RSACng();
  40. _serverPublicKey.FromXmlString(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerPublicKey.txt")));
  41. var privateKeys = Directory
  42. .GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PrivateKey"))
  43. .Select(Path.GetFileNameWithoutExtension)
  44. .ToArray();
  45. PeerKetyDropDown.DataSource = privateKeys;
  46. PeerToKnockDropDown.DataSource = _peerPublicKeyRegistry.Keys.ToArray();
  47. }
  48. private void StartButton_Click(object sender, EventArgs e)
  49. {
  50. Log("Starting...");
  51. _serverEndPoint = ServerIEndPointTextBox.Text.ParseToIpEndPointV4();
  52. _localId = new Guid(PeerKetyDropDown.Text);
  53. var peerPrivateKeyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PrivateKey", PeerKetyDropDown.Text + ".txt");
  54. _localPrivateKey = TransferCodec.LoadKey(peerPrivateKeyPath);
  55. _localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  56. _localSocket.Bind(AnyEndPoint);
  57. _saeReceive = new SocketAsyncEventArgs();
  58. _saeReceive.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);
  59. _saeReceive.Completed += ReceiveCompleted;
  60. BeginRecv();
  61. KeepAliveTimer.Start();
  62. KeepAliveTimer_Tick(null, null);
  63. PeerKetyDropDown.Enabled = false;
  64. StartButton.Enabled = false;
  65. StopButton.Enabled = true;
  66. KnockButton.Enabled = true;
  67. Log("Started...");
  68. }
  69. private void StopButton_Click(object sender, EventArgs e)
  70. {
  71. Log("Stopping...");
  72. KeepAliveTimer.Stop();
  73. _localSocket?.Dispose();
  74. _saeReceive?.Dispose();
  75. _localPrivateKey?.Dispose();
  76. _localSocket = null;
  77. _saeReceive = null;
  78. _localPrivateKey = null;
  79. PeerKetyDropDown.Enabled = true;
  80. StartButton.Enabled = true;
  81. StopButton.Enabled = false;
  82. KnockButton.Enabled = false;
  83. SendButton.Enabled = false;
  84. Log("Stopped");
  85. }
  86. private void KeepAliveTimer_Tick(object sender, EventArgs e)
  87. {
  88. _keepAliveMsg.TimeStamp = DateTime.Now;
  89. _keepAliveMsg.WriteToBuffer(_keepAliveBuf);
  90. _localSocket.SendExchangeMessageTo(_serverEndPoint, _localPrivateKey, _serverPublicKey, _localId, _keepAliveMsg);
  91. }
  92. private void KnockButton_Click(object sender, EventArgs e)
  93. {
  94. var idToKnock = new Guid(PeerToKnockDropDown.Text);
  95. if (idToKnock == _localId)
  96. {
  97. Log("KNOCK YOUR SELF ???");
  98. return;
  99. }
  100. var msg = new ExchangeMessage(ExchangeMessageId.PeerKnockReq)
  101. {
  102. PeerId = idToKnock
  103. };
  104. _localSocket.SendExchangeMessageTo(_serverEndPoint, _localPrivateKey, _serverPublicKey, _localId, msg);
  105. }
  106. private void SendButton_Click(object sender, EventArgs e)
  107. {
  108. var to = SendToEndPointTextBox.Text.ParseToIpEndPointV4();
  109. var sendMsg = new ExchangeMessage(ExchangeMessageId.DataTransfer);
  110. sendMsg.PayloadBytes = Encoding.UTF8.GetBytes(SendContentTextBox.Text);
  111. var sendBytes = TransferCodec.Encode(_localPrivateKey, _peerPublicKeyRegistry[new Guid(PeerToKnockDropDown.Text)], _localId, sendMsg.ToBytes());
  112. var sent = _localSocket.SendTo(sendBytes, to);
  113. }
  114. //------------- logic -------------
  115. private void ProcessPacket()
  116. {
  117. var peerId = TransferCodec.ReadId(_saeReceive.Buffer);
  118. if (_saeReceive.RemoteEndPoint.IpEndPointEqualsTo(_serverEndPoint))
  119. {
  120. if (BuildInPeerId.Invalid == peerId) throw new InvalidDataException("SERVER ERROR: FAILURE");
  121. if (Guid.Empty != peerId) throw new InvalidDataException("SERVER ERROR: INVALID SERVER PEER ID");
  122. var msgData = TransferCodec.DecodeData(_localPrivateKey, _serverPublicKey, _saeReceive.Buffer);
  123. var msg = new ExchangeMessage(msgData);
  124. switch (msg.Id)
  125. {
  126. case ExchangeMessageId.KeepAliveAckSessionCreated:
  127. _localPublicEndPoint = msg.PeerEndPoint;
  128. Log($"Session Created, public endpoint {_localPublicEndPoint}");
  129. Invoke(new Action(() =>
  130. {
  131. PublicEndPointTextBox.Text = msg.PeerEndPoint.ToString();
  132. }));
  133. break;
  134. case ExchangeMessageId.KeepAliveAckNoChg:
  135. break;
  136. case ExchangeMessageId.PeerKnockReqRelay:
  137. if (false == msg.PeerId.HasValue)
  138. {
  139. Log($"INVALID {msg.Id} was IGNORED: peer id is required");
  140. break;
  141. }
  142. ExchangeMessage msgReply;
  143. if (false == _peerPublicKeyRegistry.TryGetValue(msg.PeerId.Value, out var peerKey))
  144. {
  145. Log($"DENIED {msg.Id}: peer id {msg.PeerId.Value}");
  146. msgReply = new ExchangeMessage(ExchangeMessageId.PeerKnockDenied);
  147. }
  148. else
  149. {
  150. Log($"ACCEPT {msg.Id}: peer id {msg.PeerId.Value} @ {msg.PeerEndPoint}");
  151. msgReply = new ExchangeMessage(ExchangeMessageId.PeerKnockAck) { PeerId = msg.PeerId };
  152. Log($"SENDING CONNECTION REQ to {msg.PeerId} @ {msg.PeerEndPoint}");
  153. var connMsg = new ExchangeMessage(ExchangeMessageId.PeerKnockConnectionReq);
  154. _localSocket.SendExchangeMessageTo(msg.PeerEndPoint, _localPrivateKey, peerKey, _localId, connMsg);
  155. }
  156. _localSocket.SendExchangeMessageTo(_serverEndPoint, _localPrivateKey, _serverPublicKey, _localId, msgReply);
  157. break;
  158. case ExchangeMessageId.PeerKnockAckRelay:
  159. if (false == msg.PeerId.HasValue)
  160. {
  161. Log($"INVALID RESPONSE {msg.Id} was IGNORED: peer id is required");
  162. break;
  163. }
  164. Log($"KNOCK SUCCESS by {msg.PeerId} peer endpont is {msg.PeerEndPoint}");
  165. Invoke(new Action(() =>
  166. {
  167. SendToEndPointTextBox.Text = msg.PeerEndPoint.ToString();
  168. SendButton.Enabled = true;
  169. }));
  170. {
  171. Log($"SENDING CONNECTION REQ to {msg.PeerId} @ {msg.PeerEndPoint}");
  172. var connMsg = new ExchangeMessage(ExchangeMessageId.PeerKnockConnectionReq);
  173. _localSocket.SendExchangeMessageTo(msg.PeerEndPoint, _localPrivateKey, _peerPublicKeyRegistry[msg.PeerId.Value], _localId, connMsg);
  174. }
  175. break;
  176. case ExchangeMessageId.PeerKnockAckRelayed:
  177. Log($"ACCEPT SENT {msg.PeerId}");
  178. break;
  179. case ExchangeMessageId.PeerKnockReqErrPeerNoAvailable:
  180. Log($"KNOCK FAIL: {msg.PeerId}");
  181. break;
  182. case ExchangeMessageId.PeerKnockReqRelayed:
  183. Log($"KNOCK SENT {msg.PeerId}");
  184. break;
  185. case ExchangeMessageId.PeerKnockDeniedRelay:
  186. Log($"KNOCK DENIED by {msg.PeerId}");
  187. break;
  188. default:
  189. throw new ArgumentOutOfRangeException("msg.Id", "SERVER ERROR: NO EXCEPTED MESSAGE FROM SERVER," + msg.Id);
  190. }
  191. }
  192. else
  193. {
  194. if (BuildInPeerId.Invalid == peerId || BuildInPeerId.Server == peerId || false == _peerPublicKeyRegistry.TryGetValue(peerId, out var peerPublicKey))
  195. {
  196. throw new InvalidDataException("PEER ERROR: INVALID PEER ID");
  197. }
  198. var msgData = TransferCodec.DecodeData(_localPrivateKey, peerPublicKey, _saeReceive.Buffer);
  199. var msg = new ExchangeMessage(msgData);
  200. var reply = new ExchangeMessage { TimeStamp = DateTime.Now };
  201. if (false == msg.TimeStamp.HasValue || Math.Abs((DateTime.Now - msg.TimeStamp.Value).TotalSeconds) > 10)
  202. {
  203. Log($"TIMESTAMP ERROR from peer {peerId}");
  204. reply.Id = ExchangeMessageId.ErrTimeStamp;
  205. }
  206. else
  207. {
  208. switch (msg.Id)
  209. {
  210. case ExchangeMessageId.PeerKnockConnectionReq:
  211. reply.Id = ExchangeMessageId.PeerKnockConnectionAck;
  212. break;
  213. case ExchangeMessageId.DataTransfer:
  214. reply.Id = ExchangeMessageId.DataTransferAck;
  215. var payloadString = Encoding.UTF8.GetString(msg.PayloadBytes);
  216. Log($"DATA FROM {peerId}:{payloadString}");
  217. reply.PayloadBytes = payloadString.Length.ToLeInt16Bytes();
  218. break;
  219. case ExchangeMessageId.DataTransferAck:
  220. Log($"DATA ACK LEN:{msg.PayloadBytes.ReadLeInt16()} FROM {peerId}");
  221. return;
  222. default:
  223. Log($"RECV {msg.Id} FROM {peerId} @ {_saeReceive.RemoteEndPoint}");
  224. return;
  225. }
  226. }
  227. _localSocket.SendExchangeMessageTo(_saeReceive.RemoteEndPoint, _localPrivateKey, peerPublicKey, _localId, reply);
  228. }
  229. }
  230. private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
  231. {
  232. if (null == _saeReceive) return;
  233. if (_saeReceive.SocketError == SocketError.Success)
  234. {
  235. try
  236. {
  237. ProcessPacket();
  238. }
  239. catch (InvalidDataException exception)
  240. {
  241. Log($"ERROR ProcessPacket:{exception.Message}");
  242. }
  243. catch (Exception exception)
  244. {
  245. Log($"ERROR ProcessPacket:{exception}");
  246. }
  247. }
  248. else
  249. {
  250. Log($"ERROR SOCKET:{_saeReceive.SocketError}");
  251. }
  252. if (null == _localSocket) return;
  253. if (false == _localSocket.ReceiveFromAsync(_saeReceive)) ReceiveCompleted(null, null);
  254. }
  255. private void BeginRecv()
  256. {
  257. _saeReceive.RemoteEndPoint = AnyEndPoint;
  258. if (false == _localSocket.ReceiveFromAsync(_saeReceive))
  259. {
  260. ReceiveCompleted(null, _saeReceive);
  261. }
  262. }
  263. //------------- util -------------
  264. private void Log(string content)
  265. {
  266. if (InvokeRequired)
  267. {
  268. Invoke(new Action<string>(Log), content);
  269. return;
  270. }
  271. RecvTextBox.Text =
  272. $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {content}"
  273. + $"{Environment.NewLine}"
  274. + RecvTextBox.Text;
  275. RecvTextBox.Refresh();
  276. }
  277. }
  278. }