public new int AddFriendNoRequest(ToxKey publicKey) { var friendNumber = base.AddFriendNoRequest(publicKey); FriendListChanged(friendNumber, FriendListChangedAction.Add); return(friendNumber); }
public bool sendMsg(ToxId toxid, string msg) { // check if this message is send to itself if (toxid.ToString() == tox.Id.ToString()) { return(false); // this is not allowed } // wait toxcore online int maxOnlineWaitTime = 20000; // 20s int onlineWaitCount = 0; while (!tox.IsConnected) { Thread.Sleep(10); onlineWaitCount += 10; if (onlineWaitCount > maxOnlineWaitTime) { return(false); } } ToxKey toxkey = toxid.PublicKey; int friendNum = tox.GetFriendByPublicKey(toxkey); if (friendNum == -1) { int res = tox.AddFriend(toxid, "add friend"); if (res != (int)ToxErrorFriendAdd.Ok) { return(false); } friendNum = tox.GetFriendByPublicKey(toxkey); } int waitCount = 0; int maxCount = 500; if (connectedList.IndexOf(toxkey.GetString()) == -1) { maxCount = 200 * 1000; // first time wait for 200s } while (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None && waitCount < maxCount) { if (waitCount % 1000 == 0) { Console.WriteLine("target is offline." + waitCount / 1000); } waitCount += 10; Thread.Sleep(10); } if (waitCount == maxCount) { Console.WriteLine("Connect Failed"); connectedList.Remove(toxkey.GetString()); return(false); } connectedList.Add(toxkey.GetString()); int msgRes = tox.SendMessage(friendNum, msg, ToxMessageType.Message); return(msgRes > 0); }
public void Keys_SameByteArray_AreEqual(ToxKeyType keyType, int keySize) { var key = new byte[keySize]; var key1 = new ToxKey(keyType, key); var key2 = new ToxKey(keyType, key); Assert.AreEqual(key1, key2); }
public void GetBytes_InputByteArray_AreNotSame(ToxKeyType keyType, int keySize) { var input = new byte[keySize]; var key = new ToxKey(keyType, input); var result = key.GetBytes(); Assert.AreNotSame(input, result); }
public int AddFriendNoRequest(ToxKey publicKey) { ToxErrorFriendAdd error; var retVal = _tox.AddFriendNoRequest(publicKey, out error); ToxErrorViewModel.Instance.RelayError(error); return(retVal); }
public void RemovePeer(ToxKey publicKey) { var peer = GetPeerByPublicKey(publicKey); if (peer != null) { this.Remove(peer); } }
public bool Save(byte[] img, ToxKey publicKey) { try { File.WriteAllBytes(Path.Combine(Dir, publicKey.GetString() + ".png"), img); return(true); } catch { return(false); } }
/// <summary> /// Initializes a new instance of tox dns3. /// </summary> /// <param name="publicKey">The public key that this instance of toxdns should be initialized with.</param> public ToxDns(ToxKey publicKey) { _toxDns3 = ToxDnsFunctions.New(publicKey.GetBytes()); if (_toxDns3 == null || _toxDns3.IsInvalid) { throw new Exception("Could not create a new tox_dns3 instance with the provided publicKey"); } }
public OneFriendRequestViewModel(IToxModel toxModel, FriendRequestsViewModel friendRequestsViewModel, ToxKey publicKey, string message) { _toxModel = toxModel; _friendRequestsViewModel = friendRequestsViewModel; _publicKey = publicKey; Message = message; }
public new int AddFriendNoRequest(ToxKey publicKey, out ToxErrorFriendAdd error) { var friendNumber = base.AddFriendNoRequest(publicKey, out error); if (error == ToxErrorFriendAdd.Ok) { FriendListChanged(friendNumber, FriendListChangedAction.Add); } return(friendNumber); }
public void Equals_DifferentByteArrays_IsFalse() { var bytes = new byte[ToxConstants.PublicKeySize]; var key1 = new ToxKey(ToxKeyType.Public, bytes); bytes[0] = 100; var key2 = new ToxKey(ToxKeyType.Public, bytes); var equal = key1 == key2; Assert.IsFalse(equal); }
public GroupPeer GetPeerByPublicKey(ToxKey publicKey) { var peers = this.Where(p => p.PublicKey == publicKey).ToArray(); if (peers.Length == 1) { return(peers[0]); } else { return(null); } }
public bool Delete(ToxKey publicKey) { string avatarFilename = Path.Combine(Dir, publicKey.GetString() + ".png"); if (File.Exists(avatarFilename)) { try { File.Delete(avatarFilename); } catch { return(false); } return(true); } else { return(false); } }
public BitmapImage Load(ToxKey publicKey, out byte[] result) { byte[] bytes = LoadBytes(publicKey); if (bytes == null) { result = null; return(null); } MemoryStream stream = new MemoryStream(bytes); using (Bitmap bmp = new Bitmap(stream)) { result = bytes; return(bmp.ToBitmapImage(ImageFormat.Png)); } }
private byte[] LoadBytes(ToxKey publicKey) { try { string avatarFilename = Path.Combine(Dir, publicKey.GetString() + ".png"); if (File.Exists(avatarFilename)) { byte[] bytes = File.ReadAllBytes(avatarFilename); if (bytes.Length > 0) { return(bytes); } } return(null); } catch { return(null); } }
public bool sendMsg(ToxId toxid, byte[] msg, int timeout = 20) { try { lock (sendLock) { // check if this message is send to itself if (toxid.ToString() == tox.Id.ToString()) { return(false); // this is not allowed } // wait toxcore online int maxOnlineWaitTime = 200000; // 200s int onlineWaitCount = 0; while (!tox.IsConnected) { Thread.Sleep(10); onlineWaitCount += 10; if (onlineWaitCount > maxOnlineWaitTime) { return(false); } } ToxKey toxkey = toxid.PublicKey; int friendNum = tox.GetFriendByPublicKey(toxkey); if (friendNum == -1) { int res = tox.AddFriend(toxid, "add friend"); if (res != (int)ToxErrorFriendAdd.Ok) { return(false); } friendNum = tox.GetFriendByPublicKey(toxkey); } if (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None) { return(false); } var mesError = new ToxErrorFriendCustomPacket(); // retry send message int retryCount = 0; while (retryCount < 60) { byte[] msgToSend = new byte[msg.Length + 1]; msgToSend[0] = 170; // The first byte must be in the range 160-191. msg.CopyTo(msgToSend, 1); bool msgRes = tox.FriendSendLosslessPacket(friendNum, msgToSend, out mesError); if (msgRes) { break; } Utils.Utils.Log("Event: " + mesError, true); Console.WriteLine(Utils.Utils.UnixTimeNow() + " Event: " + mesError); if (mesError == ToxErrorFriendCustomPacket.SendQ) { Thread.Sleep(20); continue; } retryCount++; Thread.Sleep(100); } if (retryCount == 60) { tox.DeleteFriend(friendNum); return(false); } return(true); } } catch (Exception e) { Utils.Utils.Log(e.StackTrace, true); return(false); } }
public bool sendMsg(ToxKey toxkey, byte[] msg, int timeout = 20) { return(sendMsg(new ToxId(toxkey.GetBytes(), 100), msg, timeout)); }
public bool sendResponse(ToxResponse res, ToxKey toxkey) { return(sendResponse(res, new ToxId(toxkey.GetBytes(), 100))); }
private static void Main(string[] args) { if (args.Length != 4 && args.Length != 0) { Console.WriteLine("usage: SharpLink [local_port] [target_tox_id] [target_ip] [target_port]"); return; } Skynet.Base.Skynet mSkynet = null; string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string toxFolder = Path.Combine(AppDataFolder, "ToxTunnel"); string toxFile = Path.Combine(toxFolder, "tox.dat"); //Directory.SetCurrentDirectory(exeDir); if (args.Length == 0) { // log to file Utils.setLogFile("toxtunnel_server.log"); } else { // log to file Utils.setLogFile("toxtunnel_client.log"); } // Save tox data for server if (args.Length == 0 && File.Exists(toxFile)) { mSkynet = new Skynet.Base.Skynet(toxFile); } else if (args.Length == 0 && !File.Exists(toxFile)) { mSkynet = new Skynet.Base.Skynet(); mSkynet.Save(toxFile); } else { mSkynet = new Skynet.Base.Skynet(); } // 线程监控程序 Task.Run(() => { while (runningFlag) { int workerThreads, completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); int workerThreadsMax, completionPortThreadsMax; ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax); int workerThreadsMin, completionPortThreadsMin; ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin); ThreadPool.SetMinThreads(workerThreadsMax - workerThreads + 40, workerThreadsMax - workerThreads + 40); Thread.Sleep(2000); } }); if (args.Length == 4) { string localPort = args[0]; string targetToxId = args[1]; string targetIP = args[2]; int targetPort = Convert.ToInt32(args[3]); if (!ToxId.IsValid(targetToxId)) { Console.WriteLine("not a valid id"); Console.WriteLine("usage: SharpLink [local_port] [target_tox_id] [target_ip] [target_port]"); return; } // 连接维护程序 Task.Run(() => { int disconnectCount = 0; while (runningFlag) { IsConnected = mSkynet.HandShake(new ToxId(targetToxId)).GetAwaiter().GetResult(); if (!IsConnected) { var toxid = new ToxId(targetToxId); ToxKey toxkey = toxid.PublicKey; int friendNum = mSkynet.tox.GetFriendByPublicKey(toxkey); if (friendNum != -1 && disconnectCount > 15) { // wait 150s Utils.Log("delete friend " + targetToxId); Console.WriteLine("delete friend " + targetToxId); disconnectCount = 0; mSkynet.DeleteFriend(friendNum); } disconnectCount += 1; } else { disconnectCount = 0; } Thread.Sleep(10 * 1000); } }); // create local socket server IPAddress ip = IPAddress.Parse("0.0.0.0"); var serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(ip, Convert.ToInt32(localPort))); serverSocket.Listen(1000); Task.Factory.StartNew(() => { while (true) { Utils.Log("Event: Waiting socket"); List <byte> tempData = new List <byte>(); Socket clientSocket = serverSocket.Accept(); Task.Factory.StartNew(() => { bool closeFlag = false; LinkClient mlink = null; string tempConnectId = Guid.NewGuid().ToString(); Task.Factory.StartNew(async() => { Task <ToxResponse> sendTask = null; ToxResponse sendRes = null; while (true) { byte[] buf = new byte[32 * 1024]; try { int size = 0; if (clientSocket != null && clientSocket.Connected) { size = clientSocket.Receive(buf); } else { break; } if (mlink == null) { tempData.AddRange(buf.Take(size)); } if (size == 0) { // socket closed if (mlink != null) { mlink.CloseRemote(); mlink.Close(); } if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); if (mlink != null) { Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } else { Utils.Log("Event: Close Connection, ClinetId: null" + ", ConnectId: " + tempConnectId); } } break; } if (mlink != null) { if (sendTask != null) { sendRes = await sendTask; } if (sendTask != null && sendRes == null && !closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); mlink.CloseRemote(); mlink.Close(); Utils.Log("Event: Tox send message failed, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); break; } Utils.Log("Event: LinkClient Start Send Data"); sendTask = mlink.SendAsync(buf, size); Utils.Log("Event: LinkClient Stop Send Data"); } } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); if (mlink != null) { mlink.CloseRemote(); mlink.Close(); } if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); if (mlink != null) { Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } else { Utils.Log("Event: Close Connection, ClinetId: null" + ", ConnectId: " + tempConnectId); } } break; } } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); mlink = LinkClient.Connect(mSkynet, targetToxId, IPAddress.Parse(targetIP), Convert.ToInt32(targetPort), // message handler (msg) => { try { if (clientSocket != null && clientSocket.Connected) { clientSocket.Send(msg, SocketFlags.None); } } catch (Exception e) { Utils.Log("ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } } }, // close handler () => { if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } } ); if (mlink == null) { // connected failed Utils.Log("Event: Connected failed, ClientId: null" + ", ConnectId: " + tempConnectId); if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: null" + ", ConnectId: " + tempConnectId); } return; } if (tempData.Count != 0) { mlink.Send(tempData.ToArray(), tempData.Count); } // check if socket has closed if (closeFlag) { // socket has closed Utils.Log("Event: Close Remote, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); mlink.CloseRemote(); mlink.Close(); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } mSkynet.addNewReqListener("", (req) => { // handle if (req.toNodeId == "" && req.url == "/connect") { Utils.Log("Event: Task Connect to " + req.fromNodeId + ", MessageId: " + req.uuid); Task.Factory.StartNew(() => { // connect to server received, create sockets Utils.Log("Event: Task Started Connect to " + req.fromNodeId); try { string reqStr = Encoding.UTF8.GetString(req.content); string ipstr = reqStr.Split('\n')[0]; string port = reqStr.Split('\n')[1]; Utils.Log("Event: Connect to " + ipstr + " " + port + " " + req.fromNodeId); IPAddress targetIp = IPAddress.Parse(ipstr); Socket mClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool closeFlag = false; mClientSocket.Connect(new IPEndPoint(targetIp, Convert.ToInt32(port))); Utils.Log("Event: Connect to " + ipstr + " " + port + " Success " + req.fromNodeId); var mlink = LinkClient.Connect(mSkynet, req.fromToxId, req.fromNodeId); req.toNodeId = mlink.clientId; Utils.Log("Event: Connect to " + ipstr + " " + port + " Success " + req.fromNodeId + " , mLinkID: " + mlink.clientId); mlink.OnMessage((msg) => { try { Utils.Log("Event: Start Write Message, mLinkID: " + mlink.clientId); if (mClientSocket != null && mClientSocket.Connected) { mClientSocket.Send(msg, SocketFlags.None); } Utils.Log("Event: Write Message Success, mLinkID: " + mlink.clientId); } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Socket" + ipstr + " " + port + " mLinkID " + mlink.clientId); } } }); mlink.OnClose(() => { if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Socket" + ipstr + " " + port + " mLinkID " + mlink.clientId); } }); // send response after all handler has been set mSkynet.sendResponse(req.createResponse(Encoding.UTF8.GetBytes("OK")), new ToxId(req.fromToxId)); Task.Factory.StartNew(async() => { Task <ToxResponse> sendTask = null; ToxResponse sendRes = null; while (true) { byte[] buf = new byte[1024 * 32]; try { Utils.Log("Event: Start Read Data, Clientid: " + mlink.clientId); int size = 0; if (mClientSocket != null && mClientSocket.Connected) { size = mClientSocket.Receive(buf); } else { Utils.Log("Event: Socket already closed" + ipstr + " " + port + " mLinkID " + mlink.clientId); break; } if (size == 0) { if (!closeFlag && mClientSocket.Connected) { Utils.Log("Event: Close Connection, Clientid: " + mlink.clientId); closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); } mlink.CloseRemote(); mlink.Close(); break; } else { Utils.Log("Event: Read Data " + size + ", Clientid: " + mlink.clientId); } if (sendTask != null) { sendRes = await sendTask; } if (sendTask != null && sendRes == null) { // send failed if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); mlink.Close(); Utils.Log("Event: Tox send message failed, Clientid: " + mlink.clientId); break; } } sendTask = mlink.SendAsync(buf, size); } catch (Exception e) { /*if (e.ErrorCode != 10004) // this is not an error * { * Console.WriteLine("Time: " + Utils.UnixTimeNow() + " Event: ERROR " + e.Message); * Console.WriteLine(e.StackTrace); * }*/ Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId); } break; } } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); Utils.Log("Event: Connect to " + ipstr + " " + port + " All Success " + req.fromNodeId + ", mLinkID: " + mlink.clientId); } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); // connected failed string reqStr = Encoding.UTF8.GetString(req.content); string ipstr = reqStr.Split('\n')[0]; string port = reqStr.Split('\n')[1]; Utils.Log("Event: Connect to " + ipstr + " " + port + " failed"); var response = req.createResponse(Encoding.UTF8.GetBytes("failed")); mSkynet.sendResponse(response, new ToxId(response.toToxId)); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } else if (req.toNodeId == "" && req.url == "/handshake") { var response = req.createResponse(Encoding.UTF8.GetBytes("OK")); Utils.Log("Event: HandShake from " + response.toToxId + ", MessageID: " + req.uuid); Utils.Log("Event: Send HandShake response " + response.uuid + ", ToxId: " + response.toToxId); mSkynet.sendResponse(response, new ToxId(response.toToxId)); } }); while (true) { Thread.Sleep(10); } }
public int AddFriendNoRequest(ToxKey Key) { return(0); }
public bool sendMsg(ToxId toxid, byte[] msg) { lock (sendLock) { // check if this message is send to itself if (toxid.ToString() == tox.Id.ToString()) { return(false); // this is not allowed } // wait toxcore online int maxOnlineWaitTime = 20000; // 20s int onlineWaitCount = 0; while (!tox.IsConnected) { Thread.Sleep(10); onlineWaitCount += 10; if (onlineWaitCount > maxOnlineWaitTime) { return(false); } } ToxKey toxkey = toxid.PublicKey; int friendNum = tox.GetFriendByPublicKey(toxkey); if (friendNum == -1) { int res = tox.AddFriend(toxid, "add friend"); if (res != (int)ToxErrorFriendAdd.Ok) { return(false); } friendNum = tox.GetFriendByPublicKey(toxkey); } int waitCount = 0; int maxCount = 500; if (connectedList.IndexOf(toxkey.GetString()) == -1) { maxCount = 200 * 1000; // first time wait for 200s } while (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None && waitCount < maxCount) { if (waitCount % 1000 == 0) { Utils.Utils.LogUtils("Event: target is offline " + waitCount / 1000); } waitCount += 10; Thread.Sleep(10); } if (waitCount == maxCount) { Utils.Utils.LogUtils("Event: Connect Failed"); connectedList.Remove(toxkey.GetString()); return(false); } if (connectedList.IndexOf(toxkey.GetString()) == -1) { connectedList.Add(toxkey.GetString()); } var mesError = new ToxErrorFriendCustomPacket(); // retry send message int retryCount = 0; while (retryCount < 10) { byte[] msgToSend = new byte[msg.Length + 1]; msgToSend [0] = 170; // The first byte must be in the range 160-191. msg.CopyTo(msgToSend, 1); bool msgRes = tox.FriendSendLosslessPacket(friendNum, msgToSend, out mesError); if (msgRes) { break; } Utils.Utils.LogUtils("Event: " + mesError); if (mesError == ToxErrorFriendCustomPacket.SendQ) { Thread.Sleep(10); continue; } retryCount++; Thread.Sleep(100); } if (retryCount == 10) { return(false); } return(true); } }
public bool sendMsg(ToxKey toxkey, string msg) { return(sendMsg(new ToxId(toxkey.GetBytes(), 100), msg)); }
public bool ContainsPeer(ToxKey publicKey) { return(GetPeerByPublicKey(publicKey) != null); }
public GroupPeer(int peerNumber, ToxKey publicKey) { PeerNumber = peerNumber; PublicKey = publicKey; Name = "Unknown"; }
public void Connect(string[] args) { if (args.Length != 4 && args.Length != 0) { Console.WriteLine("usage: SharpLink [local_port] [target_tox_id] [target_ip] [target_port]"); return; } // 线程监控程序 Task.Run(() => { while (runningFlag) { int workerThreads, completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); int workerThreadsMax, completionPortThreadsMax; ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax); int workerThreadsMin, completionPortThreadsMin; ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin); ThreadPool.SetMinThreads(workerThreadsMax - workerThreads + 40, workerThreadsMax - workerThreads + 40); Utils.Log("CurrentThreads: " + (workerThreadsMax - workerThreads), true); Thread.Sleep(2000); } }); if (args.Length == 4) { if (localPort == Convert.ToInt32(args[0]) && targetToxId == args[1] && targetIP == args[2] && targetPort == Convert.ToInt32(args[3])) { // already started return; } localPort = Convert.ToInt32(args[0]); targetToxId = args[1]; targetIP = args[2]; targetPort = Convert.ToInt32(args[3]); if (!ToxId.IsValid(targetToxId)) { Console.WriteLine("not a valid id"); Console.WriteLine("usage: SharpLink [local_port] [target_tox_id] [target_ip] [target_port]"); return; } // start check connection task Task.Run(() => { while (runningFlag) { bool IsConnected = mSkynet.HandShake(new ToxId(targetToxId)).GetAwaiter().GetResult(); if (!IsConnected) { var toxid = new ToxId(targetToxId); ToxKey toxkey = toxid.PublicKey; int friendNum = mSkynet.tox.GetFriendByPublicKey(toxkey); if (friendNum != -1) { mSkynet.tox.DeleteFriend(friendNum); Utils.Log("Event: can not connect, resend friend request"); } mSkynet.HandShake(new ToxId(targetToxId)).GetAwaiter().GetResult(); } Thread.Sleep(60 * 1000); } }); // create local socket server IPAddress ip = IPAddress.Parse("0.0.0.0"); var serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(ip, localPort)); serverSocket.Listen(1000); Task.Factory.StartNew(() => { while (runningFlag) { Utils.Log("Event: Waiting socket"); List <byte> tempData = new List <byte>(); Socket clientSocket = serverSocket.Accept(); Task.Factory.StartNew(() => { bool closeFlag = false; LinkClient mlink = null; string tempConnectId = Guid.NewGuid().ToString(); Task.Factory.StartNew(() => { while (runningFlag) { byte[] buf = new byte[1024 * 512]; try { int size = 0; if (clientSocket != null && clientSocket.Connected) { size = clientSocket.Receive(buf); } else { break; } if (mlink == null) { tempData.AddRange(buf.Take(size)); } if (size == 0) { // socket closed if (mlink != null) { mlink.CloseRemote(); mlink.Close(); } if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); if (mlink != null) { Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } else { Utils.Log("Event: Close Connection, ClinetId: null" + ", ConnectId: " + tempConnectId); } } break; } if (mlink != null) { var res = mlink.Send(buf, size); if (!res && !closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); mlink.CloseRemote(); mlink.Close(); Utils.Log("Event: Tox send message failed, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); break; } } } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); if (mlink != null) { mlink.CloseRemote(); mlink.Close(); } if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); if (mlink != null) { Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } else { Utils.Log("Event: Close Connection, ClinetId: null" + ", ConnectId: " + tempConnectId); } } break; } } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); mlink = LinkClient.Connect(mSkynet, targetToxId, IPAddress.Parse(targetIP), targetPort, // message handler (msg) => { try { if (clientSocket != null && clientSocket.Connected) { clientSocket.Send(msg, SocketFlags.None); } } catch (Exception e) { Utils.Log("ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } } }, // close handler () => { if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); } } ); if (mlink == null) { // connected failed Utils.Log("Event: Connected failed, ClientId: null" + ", ConnectId: " + tempConnectId); if (!closeFlag && clientSocket.Connected) { closeFlag = true; try { clientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event ERROR: " + ex.Message); } clientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: null" + ", ConnectId: " + tempConnectId); } return; } if (tempData.Count != 0) { mlink.Send(tempData.ToArray(), tempData.Count); } // check if socket has closed if (closeFlag) { // socket has closed Utils.Log("Event: Close Remote, ClientId: " + mlink.clientId + ", ConnectId: " + tempConnectId); mlink.CloseRemote(); mlink.Close(); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } mSkynet.addNewReqListener("", (req) => { // handle if (req.toNodeId == "" && req.url == "/connect") { Utils.Log("Event: Task Connect to " + req.fromNodeId + ", MessageId: " + req.uuid); Task.Factory.StartNew(() => { // connect to server received, create sockets Utils.Log("Event: Task Started Connect to " + req.fromNodeId); try { string reqStr = Encoding.UTF8.GetString(req.content); string ipstr = reqStr.Split('\n')[0]; string port = reqStr.Split('\n')[1]; Utils.Log("Event: Connect to " + ipstr + " " + port + " " + req.fromNodeId); IPAddress targetIp = IPAddress.Parse(ipstr); Socket mClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool closeFlag = false; mClientSocket.Connect(new IPEndPoint(targetIp, Convert.ToInt32(port))); Utils.Log("Event: Connect to " + ipstr + " " + port + " Success " + req.fromNodeId); var mlink = LinkClient.Connect(mSkynet, req.fromToxId, req.fromNodeId); req.toNodeId = mlink.clientId; Utils.Log("Event: Connect to " + ipstr + " " + port + " Success " + req.fromNodeId + " , mLinkID: " + mlink.clientId); mlink.OnMessage((msg) => { try { Utils.Log("Event: Start Write Message, mLinkID: " + mlink.clientId); if (mClientSocket != null && mClientSocket.Connected) { mClientSocket.Send(msg, SocketFlags.None); } Utils.Log("Event: Write Message Success, mLinkID: " + mlink.clientId); } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Socket" + ipstr + " " + port + " mLinkID " + mlink.clientId); } } }); mlink.OnClose(() => { if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Socket" + ipstr + " " + port + " mLinkID " + mlink.clientId); } }); // send response after all handler has been set mSkynet.sendResponse(req.createResponse(Encoding.UTF8.GetBytes("OK")), new ToxId(req.fromToxId)); Task.Factory.StartNew(() => { while (runningFlag) { byte[] buf = new byte[1024 * 512]; try { Utils.Log("Event: Start Read Data, Clientid: " + mlink.clientId); int size = 0; if (mClientSocket != null && mClientSocket.Connected) { size = mClientSocket.Receive(buf); } else { Utils.Log("Event: Socket already closed" + ipstr + " " + port + " mLinkID " + mlink.clientId); break; } if (size == 0) { if (!closeFlag && mClientSocket.Connected) { Utils.Log("Event: Close Connection, Clientid: " + mlink.clientId); closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); } mlink.CloseRemote(); mlink.Close(); break; } else { Utils.Log("Event: Read Data " + size + ", Clientid: " + mlink.clientId); } var res = mlink.Send(buf, size); if (!res) { // send failed if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); mlink.Close(); Utils.Log("Event: Tox send message failed, Clientid: " + mlink.clientId); break; } } } catch (Exception e) { /*if (e.ErrorCode != 10004) // this is not an error * { * Console.WriteLine("Time: " + Utils.UnixTimeNow() + " Event: ERROR " + e.Message); * Console.WriteLine(e.StackTrace); * }*/ Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); mlink.CloseRemote(); mlink.Close(); if (!closeFlag && mClientSocket.Connected) { closeFlag = true; try { mClientSocket.Shutdown(SocketShutdown.Both); } catch (SocketException ex) { Utils.Log("Event: " + ex.Message); } mClientSocket.Close(); Utils.Log("Event: Close Connection, ClientId: " + mlink.clientId); } break; } } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); Utils.Log("Event: Connect to " + ipstr + " " + port + " All Success " + req.fromNodeId + ", mLinkID: " + mlink.clientId); } catch (Exception e) { Utils.Log("Event: ERROR " + e.Message); Utils.Log(e.StackTrace); // connected failed string reqStr = Encoding.UTF8.GetString(req.content); string ipstr = reqStr.Split('\n')[0]; string port = reqStr.Split('\n')[1]; Utils.Log("Event: Connect to " + ipstr + " " + port + " failed"); var response = req.createResponse(Encoding.UTF8.GetBytes("failed")); mSkynet.sendResponse(response, new ToxId(response.toToxId)); } }, TaskCreationOptions.LongRunning).ForgetOrThrow(); } else if (req.toNodeId == "" && req.url == "/handshake") { var response = req.createResponse(Encoding.UTF8.GetBytes("OK")); Utils.Log("Event: HandShake from " + response.toToxId + ", MessageID: " + req.uuid, true); Utils.Log("Event: Send HandShake response " + response.uuid + ", ToxId: " + response.toToxId, true); Console.WriteLine("Event: HandShake from " + response.toToxId + ", MessageID: " + req.uuid); mSkynet.sendResponse(response, new ToxId(response.toToxId)); } }); while (runningFlag) { Thread.Sleep(10); } mSkynet.stop(); }
public GroupPeer FindPeer(ToxKey key) { return(_peers.FirstOrDefault(g => g.PublicKey == key)); }
public bool Contains(ToxKey publicKey) { return(File.Exists(Path.Combine(Dir, publicKey.GetString() + ".png"))); }
public GroupPeer(int groupNumber, ToxKey publicKey) { GroupNumber = groupNumber; PublicKey = publicKey; }
/// <summary> /// Initializes a new instance of the <see cref="ToxKeyPair"/> class. /// </summary> /// <param name="public_key"></param> /// <param name="secret_key"></param> internal ToxKeyPair(ToxKey public_key, ToxKey secret_key) { PublicKey = public_key; SecretKey = secret_key; }
/// <summary> /// Initializes a new instance of the <see cref="ToxNode"/> class. /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <param name="publicKey"></param> public ToxNode(string address, int port, ToxKey publicKey) { Address = address; Port = port; PublicKey = publicKey; }