Guest User

Untitled

a guest
Jan 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.48 KB | None | 0 0
  1. socket = new WebSocket( "ws://192.168.0.7:100/unique_client_name",'chat');
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Security.Cryptography;
  9. using System.Net.Sockets;
  10. using System.Net;
  11. using System.Collections;
  12. using System.Threading;
  13.  
  14. namespace sockerv4
  15. {
  16.  
  17.  
  18. class Program
  19. {
  20. private static byte[] _buffer = new byte[2048];
  21. private static IDictionary<string, Socket> clients = new Dictionary<string, Socket>();
  22.  
  23. private static IList socket_list = new ArrayList();
  24.  
  25. static void Main()
  26. {
  27. Console.WriteLine("Program Start");
  28.  
  29. Socket socket = open_main_socket();
  30.  
  31.  
  32. Console.ReadKey();
  33. }
  34.  
  35. private static Socket open_main_socket()
  36. {
  37.  
  38. try
  39. {
  40.  
  41. IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.0.7"), 100);
  42. Console.WriteLine("Opening Main Socket...");
  43. Socket main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  44. main_socket.Bind(endpoint);
  45. listen_new(main_socket);
  46. clients.Add("main_socket", main_socket);
  47. return main_socket;
  48. }
  49. catch (SocketException e)
  50. {
  51. Console.WriteLine("Socket Error Occured (Main Socket):" + e.Message);
  52. return null;
  53. }
  54.  
  55. }
  56. private static void listen_new(Socket sock)
  57. {
  58.  
  59. try
  60. {
  61. Console.WriteLine("Listening Incoming Connnection...");
  62. sock.Listen(5);
  63. sock.BeginAccept(new AsyncCallback(start_accept_new), sock);
  64. }
  65. catch (SocketException e)
  66. {
  67. Console.WriteLine("Socket Error Occured (Listen New):" + e.Message);
  68. }
  69. }
  70. private static void start_accept_new(IAsyncResult AR)
  71. {
  72. try {
  73. Console.WriteLine("Accepting New Connection....");
  74. Socket sock = ((Socket)AR.AsyncState).EndAccept(AR);
  75. listen_new((Socket)AR.AsyncState);
  76. sock.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(begin_handshake), sock);
  77. } catch (SocketException e)
  78. {
  79. Console.WriteLine("Socket Error Occured(Start Accept New):" + e.Message);
  80. }
  81.  
  82. }
  83. private static void begin_handshake(IAsyncResult AR)
  84. {
  85. Console.WriteLine("Shaking Hands");
  86. Socket sock = ((Socket)AR.AsyncState);
  87. int Data = sock.EndReceive(AR);
  88. byte[] databyte = new byte[Data];
  89. Array.Copy(_buffer, databyte, Data);
  90.  
  91. String text = Encoding.ASCII.GetString(databyte);
  92. List<string> headers = retriveheaders(text);
  93. acceptuser(headers, sock);
  94.  
  95. }
  96. private static void acceptuser(List<string> headers, Socket sock) {
  97.  
  98. ICollection<string> keys = (clients.Keys);
  99. IList user_list = new ArrayList();
  100. user_list = keys.ToList();
  101.  
  102. if (user_list.Contains(headers[0])) {
  103.  
  104. Console.Write("User Already Connectedn");
  105. Socket currentsock;
  106. bool check = clients.TryGetValue(headers[0], out currentsock);
  107.  
  108.  
  109. close_frame(currentsock);
  110. clients.Remove(headers[0]);
  111.  
  112.  
  113. string handshake;
  114. string Key = headers[4].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  115. SHA1 sha = new SHA1CryptoServiceProvider();
  116. clients.Add(headers[0], sock);
  117. byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Key));
  118. handshake = Convert.ToBase64String(hash);
  119. string AcceptKey = "HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Protocol: " + headers[5].Trim() + "rnSec-WebSocket-Accept: " + handshake.Trim() + "rnrn";
  120. send_handshake(AcceptKey, sock);
  121. message_listener(sock);
  122.  
  123. }
  124. else
  125. {
  126.  
  127. string handshake;
  128. string Key = headers[4].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  129. SHA1 sha = new SHA1CryptoServiceProvider();
  130. clients.Add(headers[0], sock);
  131. byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Key));
  132. handshake = Convert.ToBase64String(hash);
  133. string AcceptKey = "HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Protocol: " + headers[5].Trim() + "rnSec-WebSocket-Accept: " + handshake.Trim() + "rnrn";
  134. send_handshake(AcceptKey, sock);
  135. message_listener(sock);
  136. }
  137.  
  138. }
  139.  
  140. private static void close_frame(Socket sock)
  141. {
  142.  
  143. Byte[] frame = new Byte[2];
  144. frame[0] = (Byte)136;
  145. frame[1] = 0;
  146. try
  147. {
  148. sock.Send(frame);
  149.  
  150. }
  151. catch (SocketException e)
  152. {
  153. Console.Write("Error Occured" + e.Message);
  154. }
  155.  
  156.  
  157. }
  158. private static void message_listener(Socket insock)
  159. {
  160. start(insock);
  161.  
  162. void start(Socket sock) {
  163. Console.WriteLine("Looping Handle: " + sock.Handle);
  164. byte[] m_buffer = new byte[5000];
  165. try
  166. {
  167. sock.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ar => { int dat = sock.EndReceive(ar); processdata(m_buffer, dat, ar); }, sock);
  168.  
  169. }
  170. catch (Exception e) {
  171.  
  172. Console.WriteLine("Error Occured Begin Receive: "+ e.Message);
  173. }
  174.  
  175.  
  176. }
  177.  
  178. void processdata(byte[] r_buffer, int size,IAsyncResult AR)
  179. {
  180.  
  181. Socket sockp = ((Socket)AR.AsyncState);
  182.  
  183. Console.WriteLine("Data Received: " + size);
  184. Console.WriteLine("IAsync Result: " + AR.AsyncState);
  185. Console.WriteLine("Opcode"+ (r_buffer[0] & 81));
  186. switch (r_buffer[0]&81) {
  187. case 1:
  188. datadecode(r_buffer);
  189. start(sockp);
  190. break;
  191. case 0:
  192. if (size==6) {
  193. string myKey = clients.FirstOrDefault(x => x.Value == sockp).Key;
  194. if (myKey!=null) {
  195. close_frame(sockp);
  196. sockp.Shutdown(SocketShutdown.Both);
  197. sockp.Close();
  198. sockp.Dispose();
  199. clients.Remove(myKey);
  200. }
  201. else {
  202.  
  203. sockp.Shutdown(SocketShutdown.Both);
  204. sockp.Close();
  205. sockp.Dispose();
  206.  
  207. }
  208.  
  209. }
  210. else {
  211. sockp.Shutdown(SocketShutdown.Both);
  212. sockp.Close();
  213. sockp.Dispose();
  214. string myKey = clients.FirstOrDefault(x => x.Value == sockp).Key;
  215. clients.Remove(myKey);
  216. }
  217. break;
  218. default:
  219. Console.WriteLine("Default Switch");
  220. break;
  221.  
  222. }
  223.  
  224. }
  225.  
  226. }
  227.  
  228. private static void send_data(String data, Socket socket)
  229. {
  230. byte[] r_data = EncodeMessageToSend(data);
  231. try
  232. {
  233. Console.Write("Sending Handshake:n");
  234. socket.BeginSend(r_data, 0, r_data.Length, SocketFlags.None, new AsyncCallback(sent), socket);
  235. }
  236. catch (SocketException e)
  237. {
  238. Console.WriteLine("Socket Error Occured When sending data 1: " + e.Message);
  239. }
  240. }
  241.  
  242.  
  243. private static void send_handshake(String data, Socket socket)
  244. {
  245. byte[] send_key = Encoding.UTF8.GetBytes(data);
  246. try {
  247. Console.Write("Sending Handshake:n");
  248. socket.BeginSend(send_key, 0, send_key.Length, SocketFlags.None, new AsyncCallback(sent), socket);
  249. } catch (SocketException e) {
  250. Console.WriteLine("Socket Error Occured When sending data 1: " + e.Message);
  251. }
  252. }
  253.  
  254. private static void sent(IAsyncResult AR)
  255. {
  256. Socket sock = (Socket)AR.AsyncState;
  257. try {
  258. sock.EndSend(AR);
  259.  
  260. }
  261. catch (SocketException e){
  262.  
  263. Console.WriteLine("Socket Error Occured When sending data 2: " + e.Message);
  264. }
  265. }
  266.  
  267.  
  268. private static List<string> retriveheaders(String Data)
  269. {
  270. Console.Write("Retriveing Headersn");
  271.  
  272. List<string> headers = new List<string>();
  273.  
  274. headers.Add(Regex.Match(Data, "(?<=GET /)(.*)(?= HTTP)").ToString());
  275. headers.Add(Regex.Match(Data, "(?<=Host: )(.*)[?=rn*]").ToString());
  276. headers.Add(Regex.Match(Data, "(?<=Upgrade: )(.*)[?=rn]").ToString());
  277. headers.Add(Regex.Match(Data, "(?<=Connection: )(.*)[?=rn]").ToString());
  278. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Key: )(.*)[?=rn]").ToString());
  279. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Protocol: )(.*)[?=rn]").ToString());
  280. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Version: )(.*)[?=rn]").ToString());
  281. headers.Add(Regex.Match(Data, "(?<=Origin: )(.*)rn").ToString());
  282. headers.Add(Regex.Match(Data, "rn(.*)$").ToString());
  283.  
  284. return headers;
  285.  
  286. }
  287. private static Byte[] EncodeMessageToSend(String message)
  288. {
  289. Byte[] response;
  290. Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
  291. Byte[] frame = new Byte[10];
  292.  
  293. Int32 indexStartRawData = -1;
  294. Int32 length = bytesRaw.Length;
  295.  
  296. frame[0] = (Byte)129;
  297. if (length <= 125)
  298. {
  299. frame[1] = (Byte)length;
  300. indexStartRawData = 2;
  301. }
  302. else if (length >= 126 && length <= 65535)
  303. {
  304. frame[1] = (Byte)126;
  305. frame[2] = (Byte)((length >> 8) & 255);
  306. frame[3] = (Byte)(length & 255);
  307. indexStartRawData = 4;
  308. }
  309. else
  310. {
  311. frame[1] = (Byte)127;
  312. frame[2] = (Byte)((length >> 56) & 255);
  313. frame[3] = (Byte)((length >> 48) & 255);
  314. frame[4] = (Byte)((length >> 40) & 255);
  315. frame[5] = (Byte)((length >> 32) & 255);
  316. frame[6] = (Byte)((length >> 24) & 255);
  317. frame[7] = (Byte)((length >> 16) & 255);
  318. frame[8] = (Byte)((length >> 8) & 255);
  319. frame[9] = (Byte)(length & 255);
  320.  
  321. indexStartRawData = 10;
  322. }
  323.  
  324. response = new Byte[indexStartRawData + length];
  325.  
  326. Int32 i, reponseIdx = 0;
  327.  
  328. //Add the frame bytes to the reponse
  329. for (i = 0; i < indexStartRawData; i++)
  330. {
  331. response[reponseIdx] = frame[i];
  332. reponseIdx++;
  333. }
  334.  
  335. //Add the data bytes to the response
  336. for (i = 0; i < length; i++)
  337. {
  338. response[reponseIdx] = bytesRaw[i];
  339. reponseIdx++;
  340. }
  341.  
  342. return response;
  343. }
  344.  
  345. private static void datadecode(byte[] rawdata)
  346. {
  347. Console.WriteLine("Message Unmaskingn");
  348.  
  349. Thread.Sleep(10000);
  350.  
  351. var fin = rawdata[0] & 0x81;
  352.  
  353. bool res = fin != 129;
  354. Console.WriteLine("Opcode:" + res);
  355. var Lenght = rawdata[1] & 127;
  356. byte b = rawdata[1];
  357. int totalLength = 0;
  358. int keyIndex = 0;
  359. int dataLength = 0;
  360.  
  361.  
  362. if (Lenght <= 125)
  363. {
  364.  
  365. keyIndex = 2;
  366. totalLength = Lenght + 6;
  367. dataLength = Lenght;
  368.  
  369. }
  370.  
  371. if (Lenght == 126)
  372. {
  373.  
  374. dataLength = (int)BitConverter.ToUInt16(new byte[] { rawdata[3], rawdata[2] }, 0);
  375. keyIndex = 4;
  376. totalLength = dataLength + 8;
  377.  
  378. }
  379. if (Lenght == 127)
  380. {
  381.  
  382. dataLength = (int)BitConverter.ToInt64(new byte[] { rawdata[9], rawdata[8], rawdata[7], rawdata[6], rawdata[5], rawdata[4], rawdata[3], rawdata[2] }, 0);
  383. keyIndex = 10;
  384. totalLength = dataLength + 14;
  385.  
  386. }
  387.  
  388. byte[] key = new byte[] { rawdata[keyIndex], rawdata[keyIndex + 1], rawdata[keyIndex + 2], rawdata[keyIndex + 3] };
  389.  
  390. int dataIndex = keyIndex + 4;
  391. int count = 0;
  392.  
  393.  
  394. for (int i = dataIndex; i < totalLength; i++)
  395. {
  396. rawdata[i] = (byte)(rawdata[i] ^ key[count % 4]);
  397. count++;
  398. }
  399.  
  400. string message = Encoding.ASCII.GetString(rawdata, dataIndex, dataLength);
  401.  
  402. Console.WriteLine("Message Recieved:" + message);
  403.  
  404.  
  405. }
  406.  
  407. }
  408. }
Add Comment
Please, Sign In to add comment