/// <summary> /// new /// </summary> /// <param name="connectionID"></param> /// <param name="socket"></param> /// <param name="host"></param> /// <exception cref="ArgumentNullException">socket is null</exception> /// <exception cref="ArgumentNullException">host is null</exception> public DefaultConnection(long connectionID, Socket socket, IHost host) { if (socket == null) throw new ArgumentNullException("socket"); if (host == null) throw new ArgumentNullException("host"); this.ConnectionID = connectionID; this._socket = socket; this._host = host; this._messageBufferSize = host.MessageBufferSize; try//f**k... { this.LocalEndPoint = (IPEndPoint)socket.LocalEndPoint; this.RemoteEndPoint = (IPEndPoint)socket.RemoteEndPoint; } catch (Exception ex) { Log.Trace.Error("get socket endPoint error.", ex); } //init for send... this._saeSend = host.GetSocketAsyncEventArgs(); this._saeSend.Completed += new EventHandler<SocketAsyncEventArgs>(this.SendAsyncCompleted); this._sendQueue = new SendQueue(); //init for receive... this._saeReceive = host.GetSocketAsyncEventArgs(); this._saeReceive.Completed += new EventHandler<SocketAsyncEventArgs>(this.ReceiveAsyncCompleted); }
/// <summary> /// Wait function. /// </summary> /// <param name="timeOut">time-out in ms</param> /// <param name="cmdId"></param> /// <param name="sendQueueState"></param> /// <returns></returns> public ReceivedCommand WaitForCmd(int timeOut, int cmdId, SendQueue sendQueueState) { lock (_lock) { _receivedCommand = null; _cmdIdToMatch = cmdId; _sendQueueState = sendQueueState; } if (_waiter.WaitOne(timeOut) == EventWaiter.WaitState.TimeOut) { return null; } return _receivedCommand; }
/// <summary> Directly executes the send command operation. </summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand ExecuteSendCommand(SendCommand sendCommand, SendQueue sendQueueState) { // Disable listening, all callbacks are disabled until after command was sent ReceivedCommand ackCommand; lock (_sendCommandDataLock) { if (PrintLfCr) _communicationManager.WriteLine(sendCommand.CommandString()); else _communicationManager.Write(sendCommand.CommandString()); ackCommand = sendCommand.ReqAc ? BlockedTillReply(sendCommand.AckCmdId, sendCommand.Timeout, sendQueueState) : new ReceivedCommand(); } return ackCommand; }
// worker for sending ARP reply packets public void WorkerSender() { var sendQueue = new SendQueue((SpoofingTargets1.Count * 2 * 60) + 60); foreach (Target target1 in SpoofingTargets1) { // send fake replies to the gateway sendQueue.Add(GenerateARPReply(target1.IP, SpoofingTarget2.IP, SpoofingTarget2.PMAC).Bytes); // senda fake replies to targets sendQueue.Add(GenerateARPReply(SpoofingTarget2.IP, target1.IP, target1.PMAC).Bytes); } while (SpoofingStarted) { sendQueue.Transmit(device, SendQueueTransmitModes.Normal); Thread.Sleep(2500); } sendQueue.Dispose(); return; }
/// <summary> /// Cleanly disconnects the server. Pending requests are placed back in a sending queue to be resent upon reconnection /// </summary> public void Disconnect() { // Close the connection superficially CommunicationEstablished = false; try { // Stop the ack processing loop. Logger.Log <MTProtoSender>(Logger.Level.Debug, $"Trying to stop Ack Handler"); if (AckCancellation != null) { AckCancellation.Cancel(); } if (AckHandler != null) { AckHandler.Wait(); } // Close the connection to the server // ToDo: Should we also dispose? Connection.Disconnect(); // Remove any event handlers Logger.Log <MTProtoSender>(Logger.Level.Debug, $"Removing event handlers"); Connection.DataReceivedEvent -= Connection_DataReceivedEvent; // Place all the pending messages back in the queue to resend // Note: Leave pending acks alone. We will pick up where we left off later PendingQueue.Values.ToList().ForEach(x => SendQueue.Add(x)); PendingQueue.Clear(); } catch (Exception ex) { Logger.Log(Logger.Level.Error, $"An error occurred while disconnecting.\n\n{ex.Message}"); } }
public void Add(string table = "UserData") { BackEndServerManager.instance.myInfo.haveCharacters.Add(0); BackEndServerManager.instance.myInfo.haveCharacters.Add(1); BackEndServerManager.instance.myInfo.charactersLevel.InsertRange(index: 0, collection: new List <int>() { 1, 1 }); BackEndServerManager.instance.myInfo.levelExp.InsertRange(index: 0, collection: new List <int>() { 1, 1 }); BackEndServerManager.instance.myInfo.joinTime = System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"); param = new Param(); param.Add("Gold", BackEndServerManager.instance.myInfo.gold); param.Add("Diamond", BackEndServerManager.instance.myInfo.diamond); param.Add("Ads", BackEndServerManager.instance.myInfo.ads); param.Add("Pack", BackEndServerManager.instance.myInfo.pack); param.Add("HaveCharacters", BackEndServerManager.instance.myInfo.haveCharacters); param.Add("NowCharacter", BackEndServerManager.instance.myInfo.nowCharacter); param.Add("CharacterLevel", BackEndServerManager.instance.myInfo.charactersLevel); param.Add("LevelExp", BackEndServerManager.instance.myInfo.levelExp); param.Add("JoinTime", BackEndServerManager.instance.myInfo.joinTime); SendQueue.Enqueue(Backend.GameInfo.Insert, table, param, callback => { if (callback.IsSuccess()) { AddPoint(); AddChest(); AddCard(); LoadChart(); } }); }
private bool HandleSendQueue() { I2NPMessage[] rawdata; lock ( SendRawQueue ) { rawdata = SendRawQueue.ToArray(); SendRawQueue.Clear(); } foreach (var msg in rawdata) { #if LOG_ALL_TUNNEL_TRANSFER if (FilterMessageTypes.Update(new HashedItemGroup((int)msg.MessageType, 0x1701))) { Logging.LogDebug($"OutboundTunnel: Send raw {NextHop.Id32Short} : {msg}"); } #endif Bandwidth.DataSent(msg.Payload.Length); TransportProvider.Send(NextHop, msg); } if (SendQueue.Count == 0) { return(true); } IEnumerable <TunnelMessage> messages; lock ( SendQueue ) { messages = SendQueue.ToArray(); SendQueue.Clear(); } return(CreateTunnelMessageFragments(messages)); }
private void PacketProcessor() { DebugInformation.WriteLine("[PD] Packet processor started."); var localPacketBuffer = new List <EthernetPacket>(); var packetBytes = 0; while (started) { EthernetPacket rawPacket; // wait if there haven't been any new packets put into queue packetsAvailable.WaitOne(); // get packets from queue and add them to the local buffer while (packetBuffer.TryDequeue(out rawPacket) && rawPacket != null) { localPacketBuffer.Add(rawPacket); packetBytes += rawPacket.BytesHighPerformance.BytesLength; // add 16 bytes | TODO: find out why there are always 16 more bytes needed for each packet packetBytes += 16; } packetsAvailable.Reset(); var packetQueue = new SendQueue(packetBytes * packetRouters.Count); // loop through local packet buffer foreach (var packet in localPacketBuffer) { // skip local packets if (iface.IsLocalIPv4Packet(packet)) { continue; } // send to packet readers foreach (IPacketReader reader in packetReaders) { reader.ReadPacket(packet); } // send to packet filters, skip routing step for filtered packets lock (packetFilters) { foreach (IPacketFilter filter in packetFilters) { if (filter.Enabled && filter.FilterPacket(packet)) { continue; } } } // send to packet routers foreach (IPacketRouter router in packetRouters) { var routedPacket = router.RoutePacket(packet); if (routedPacket != null) { packetQueue.Add(routedPacket.Bytes); } } } // send out all the routed packets packetQueue.TransmitAll(iface.PcapDevice); localPacketBuffer.Clear(); packetBytes = 0; } DebugInformation.WriteLine("[PD] Packet processor stopped."); }
/// <summary> /// The internal thread procedure, handling recv and send. /// </summary> protected void ThreadProc() { // cleanup old socket if any if (socket != null) { socket.Close(); socket = null; } // reset the packetcontroller messageController.Reset(); // clean pending messages/exceptions from queues GameMessage message; Exception error; while (SendQueue.TryDequeue(out message)) { ; } while (ReceiveQueue.TryDequeue(out message)) { ; } while (ExceptionQueue.TryDequeue(out error)) { ; } // init a new Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // try connect to server try { socket.Connect(serverAddress, serverPort); } catch (Exception Error) { ExceptionQueue.Enqueue(Error); } // don't go on if no connection if (socket.Connected) { // initialize the socket stream tcpStream = new NetworkStream(socket); // mark running isRunning = true; // start thread loop // this can be broken by calling Disconnect() while (isRunning) { try { bool doSend = false; // processing pending messages to send while (SendQueue.TryDequeue(out message)) { Send(message, false); doSend = true; } // call flush ourself here // so we can send multiple messages above if (doSend) { Flush(); } // read if (socket.Available > 0) { messageController.ReadRecv(tcpStream, socket.Available); } // avoid 100% cpu usage Thread.Sleep(SLEEPTIME); } catch (Exception Error) { // log the exception ExceptionQueue.Enqueue(Error); // stop thread isRunning = false; } } } // cleanup if (socket != null) { socket.Close(); } // reset references socket = null; tcpStream = null; workThread = null; }
/// <summary> Synchronized send a command. </summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue. </param> /// <returns> . </returns> public ReceivedCommand SendCommandSync(SendCommand sendCommand, SendQueue sendQueueState) { // Directly call execute command var resultSendCommand = _communicationManager.ExecuteSendCommand(sendCommand, sendQueueState); InvokeNewLineEvent(NewLineSent, new CommandEventArgs(sendCommand)); return resultSendCommand; }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState = SendQueue.InFrontQueue, ReceiveQueue receiveQueueState = ReceiveQueue.Default) { return SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue); }
public void Queue(BaseScertMessage message) { SendQueue.Enqueue(message); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState = SendQueue.InFrontQueue, ReceiveQueue receiveQueueState = ReceiveQueue.Default) { return(SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue)); }
/// <summary> /// Return false if disconnect/finished /// </summary> void RunClientHandshake() { clientThread.WatchdogTick = DateTime.Now; //Read Handshake var hs = PacketReader.ReadFirstPackage(clientStream); if (hs == null) { //Old status packet LegacyStatus.SendStatus(clientStream); Phase = Phases.FinalClose; return; } var h = new Handshake(hs); Debug.FromClient(this, h); clientThread.State = "Handshake Received " + h; ClientVersion = h.Version; if (h.State == HandshakeState.Status) { RunStatusPing(h); return; } if (h.State == HandshakeState.None) { Close("Invalid handshake state: " + h.State); return; } if (h.State != HandshakeState.Login) { Close("Invalid handshake state: " + h.State); return; } #if DEBUG if (h.Version >= ProtocolVersion.next) { throw new InvalidDataException("new version: " + h.Version); } #endif if (h.Version > MinecraftServer.BackendVersion) { clientThread.State = "Handshake too high version"; Close("We are still running " + MinecraftServer.BackendVersion.ToText() + " we are so very sorry about that"); return; } if (h.Version < MinecraftServer.FrontendVersion) { clientThread.State = "Handshake too low version"; Close("Upgrade your client to " + MinecraftServer.FrontendVersion.ToText()); return; } clientThread.WatchdogTick = DateTime.Now; //Login var l = new LoginStart(PacketReader.ReadHandshake(clientStream)); Debug.FromClient(this, l); clientThread.State = "LoginStart Received " + l.Name; unverifiedUsername = l.Name; if (unverifiedUsername.Length == 0 || unverifiedUsername.Length > 16) { clientThread.State = "Handshake wrong username length"; Close("Bad username"); Console.WriteLine("Wrong username length: " + unverifiedUsername.Length); return; } //Set Compression var compression = new SetCompression(); SendToClientInternal(compression); maxUncompressed = compression.MaxSize; //Send encryption request clientThread.State = "Handshake: Sending encryption request"; //Initiate ID var r = new Random(); ID = new byte[8]; r.NextBytes(ID); SendToClientInternal(new EncryptionRequest(Authentication.McHex(ID), MinecraftServer.RsaBytes)); clientThread.State = "Handshake: Sent encryption request, reading response"; //Read enc response int erSize; var erBuffer = PacketReader.Read(clientStream, out erSize); if (erSize != 0) { erBuffer = Compression.Decompress(erBuffer, erSize); } var er = new EncryptionResponse(erBuffer); Debug.FromClient(this, er); clientThread.State = "Handshake: Got enc resp"; CryptoMC cryptoStream = new CryptoMC(clientStream, er); //Verify user clientThread.State = "Handshake: loading proxy data"; Settings = LoadProxyPlayer(unverifiedUsername); clientThread.State = "Handshake: Verifying login credentials"; var auth = Authentication.VerifyUserLogin(unverifiedUsername, cryptoStream.SharedKey, ID); #warning From here we now need to take care of the id in the response. if (auth == null) { //Unauthorized Log.WriteAuthFail(unverifiedUsername, RemoteEndPoint, ""); Close("Mojang says no"); return; } else { MinecraftUsername = unverifiedUsername; Log.WritePlayer(this, "Login from " + RemoteEndPoint + " " + Country); } clientThread.State = "Handshake: Logged in"; //Get UUID Settings.UUID = auth.id; clientThread.WatchdogTick = DateTime.Now; MineProxy.Inbox.Status(this); //start encryption clientStream = cryptoStream; SendToClientInternal(new LoginSuccess(Settings.UUID, MinecraftUsername)); clientThread.User = MinecraftUsername; clientThread.State = "Logged in"; EntityID = freeEID; //Math.Abs(unverifiedUsername.GetHashCode()); freeEID += 5000; //Login reply to client //No longer, send the vanilla server Login reply instead. Phase = Phases.Gaming; Queue = new SendQueue(this); PlayerList.LoginPlayer(this); SaveProxyPlayer(); string name = h.Host.ToLowerInvariant().Split('.')[0]; if (World.VanillaWorlds.ContainsKey(name)) { SetWorld(World.VanillaWorlds[name]); } else { SetWorld(World.Main); } //Handshake complete }
public ReceivedCommand WaitForCmd(int timeOut, int cmdId, SendQueue sendQueueState) { return _receivedCommandSignal.WaitForCmd(timeOut, cmdId, sendQueueState); }
void GiveCard(int index) { if (index == (int)ChestKind.골드) { SendQueue.Enqueue(Backend.Probability.GetProbability, "976", callback => { { // 그 다음 카드 부분 if (callback.IsSuccess()) { int card = -1; int count = Random.Range((index + 1) * 2, (index + 1) * 5); var log = callback.GetReturnValuetoJSON()["element"]["item"]["S"].ToString(); Debug.Log(log); switch (log) { case "기사": card = 0; break; case "벤전스": card = 1; break; case "도끼": card = 2; break; case "듀얼": card = 3; break; case "스탭": card = 4; break; case "시프": card = 5; break; case "피오라": card = 6; break; case "사이드": card = 7; break; case "스미스": card = 8; break; case "라운드": card = 9; break; case "듀크": card = 10; break; case "빈센트": card = 11; break; case "플레타": card = 12; break; case "더스틴": card = 13; break; case "루이스": card = 14; break; case "윌리": card = 15; break; case "아일린": card = 16; break; case "체이스": card = 17; break; case "랄프": card = 18; break; case "알버트": card = 19; break; case "재클린": card = 20; break; case "앤드류": card = 21; break; case "콜린": card = 22; break; case "찰스": card = 23; break; case "케빈": card = 24; break; case "다비": card = 25; break; case "모냇": card = 26; break; case "조지": card = 27; break; case "아모스": card = 28; break; case "던칸": card = 29; break; case "로랜스": card = 30; break; case "해럴드": card = 31; break; case "스니퍼": card = 32; break; case "레오나드": card = 33; break; case "스팅": card = 34; break; case "비아나": card = 35; break; case "미셀": card = 36; break; case "제이스": card = 37; break; case "안토니": card = 38; break; case "렉스": card = 39; break; case "사무엘": card = 40; break; case "에드윈": card = 41; break; case "로이드": card = 42; break; case "아돌프": card = 43; break; case "아폴로": card = 44; break; case "닐": card = 45; break; case "마샤": card = 46; break; case "리퍼": card = 47; break; case "도글라스": card = 48; break; case "스텔라": card = 49; break; default: break; } if (CheckHaveCard(card)) { Debug.Log("캐릭터 있음 : " + card); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } else { Debug.Log("캐릭터 없음"); BackEndServerManager.instance.myInfo.haveCharacters.Add(card); BackEndServerManager.instance.myInfo.charactersLevel.Add(1); BackEndServerManager.instance.myInfo.levelExp.Add(1); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } cardText.text = log; ShowResultCard(card, count); SetInventory(); } else { Debug.Log("실패 !"); } } }); } else if (index == (int)ChestKind.다이아) { SendQueue.Enqueue(Backend.Probability.GetProbability, "975", callback => { { // 그 다음 카드 부분 if (callback.IsSuccess()) { int card = -1; int count = Random.Range((index + 1) * 2, (index + 1) * 5); var log = callback.GetReturnValuetoJSON()["element"]["item"]["S"].ToString(); Debug.Log(log); switch (log) { case "기사": card = 0; break; case "벤전스": card = 1; break; case "도끼": card = 2; break; case "듀얼": card = 3; break; case "스탭": card = 4; break; case "시프": card = 5; break; case "피오라": card = 6; break; case "사이드": card = 7; break; case "스미스": card = 8; break; case "라운드": card = 9; break; case "듀크": card = 10; break; case "빈센트": card = 11; break; case "플레타": card = 12; break; case "더스틴": card = 13; break; case "루이스": card = 14; break; case "윌리": card = 15; break; case "아일린": card = 16; break; case "체이스": card = 17; break; case "랄프": card = 18; break; case "알버트": card = 19; break; case "재클린": card = 20; break; case "앤드류": card = 21; break; case "콜린": card = 22; break; case "찰스": card = 23; break; case "케빈": card = 24; break; case "다비": card = 25; break; case "모냇": card = 26; break; case "조지": card = 27; break; case "아모스": card = 28; break; case "던칸": card = 29; break; case "로랜스": card = 30; break; case "해럴드": card = 31; break; case "스니퍼": card = 32; break; case "레오나드": card = 33; break; case "스팅": card = 34; break; case "비아나": card = 35; break; case "미셀": card = 36; break; case "제이스": card = 37; break; case "안토니": card = 38; break; case "렉스": card = 39; break; case "사무엘": card = 40; break; case "에드윈": card = 41; break; case "로이드": card = 42; break; case "아돌프": card = 43; break; case "아폴로": card = 44; break; case "닐": card = 45; break; case "마샤": card = 46; break; case "리퍼": card = 47; break; case "도글라스": card = 48; break; case "스텔라": card = 49; break; default: break; } if (CheckHaveCard(card)) { Debug.Log("캐릭터 있음 : " + card); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } else { Debug.Log("캐릭터 없음"); BackEndServerManager.instance.myInfo.haveCharacters.Add(card); BackEndServerManager.instance.myInfo.charactersLevel.Add(1); BackEndServerManager.instance.myInfo.levelExp.Add(1); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } cardText.text = log; ShowResultCard(card, count); SetInventory(); } else { Debug.Log("실패 !"); } } }); } else { SendQueue.Enqueue(Backend.Probability.GetProbability, "977", callback => { { // 그 다음 카드 부분 if (callback.IsSuccess()) { int card = -1; int count = Random.Range((index + 1) * 2, (index + 1) * 5); var log = callback.GetReturnValuetoJSON()["element"]["item"]["S"].ToString(); Debug.Log(log); switch (log) { case "기사": card = 0; break; case "벤전스": card = 1; break; case "도끼": card = 2; break; case "듀얼": card = 3; break; case "스탭": card = 4; break; case "시프": card = 5; break; case "피오라": card = 6; break; case "사이드": card = 7; break; case "스미스": card = 8; break; case "라운드": card = 9; break; case "듀크": card = 10; break; case "빈센트": card = 11; break; case "플레타": card = 12; break; case "더스틴": card = 13; break; case "루이스": card = 14; break; case "윌리": card = 15; break; case "아일린": card = 16; break; case "체이스": card = 17; break; case "랄프": card = 18; break; case "알버트": card = 19; break; case "재클린": card = 20; break; case "앤드류": card = 21; break; case "콜린": card = 22; break; case "찰스": card = 23; break; case "케빈": card = 24; break; case "다비": card = 25; break; case "모냇": card = 26; break; case "조지": card = 27; break; case "아모스": card = 28; break; case "던칸": card = 29; break; case "로랜스": card = 30; break; case "해럴드": card = 31; break; case "스니퍼": card = 32; break; case "레오나드": card = 33; break; case "스팅": card = 34; break; case "비아나": card = 35; break; case "미셀": card = 36; break; case "제이스": card = 37; break; case "안토니": card = 38; break; case "렉스": card = 39; break; case "사무엘": card = 40; break; case "에드윈": card = 41; break; case "로이드": card = 42; break; case "아돌프": card = 43; break; case "아폴로": card = 44; break; case "닐": card = 45; break; case "마샤": card = 46; break; case "리퍼": card = 47; break; case "도글라스": card = 48; break; case "스텔라": card = 49; break; default: break; } if (CheckHaveCard(card)) { Debug.Log("캐릭터 있음 : " + card); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } else { Debug.Log("캐릭터 없음"); BackEndServerManager.instance.myInfo.haveCharacters.Add(card); BackEndServerManager.instance.myInfo.charactersLevel.Add(1); BackEndServerManager.instance.myInfo.levelExp.Add(1); var value = BackEndServerManager.instance.myInfo.haveCharacters.FindIndex(find => find == card); BackEndServerManager.instance.myInfo.levelExp[value] += count; } cardText.text = log; ShowResultCard(card, count); SetInventory(); } else { Debug.Log("실패 !"); } } }); } }
/// <summary> /// Return false if disconnect/finished /// </summary> void RunClientHandshake() { clientThread.WatchdogTick = DateTime.Now; //Read Handshake var hs = PacketReader.ReadFirstPackage(clientStream); if (hs == null) { //Old status packet LegacyStatus.SendStatus(clientStream); Phase = Phases.FinalClose; return; } var h = new Handshake(hs); Debug.FromClient(this, h); clientThread.State = "Handshake Received " + h; ClientVersion = h.Version; if (h.State == HandshakeState.Status) { RunStatusPing(h); return; } if (h.State == HandshakeState.None) { Close("Invalid handshake state: " + h.State); return; } if (h.State != HandshakeState.Login) { Close("Invalid handshake state: " + h.State); return; } #if DEBUG if (h.Version >= ProtocolVersion.next) { throw new InvalidDataException("new version: " + h.Version); } #endif if (h.Version > MinecraftServer.BackendVersion) { clientThread.State = "Handshake too high version"; Close("We are still running " + MinecraftServer.BackendVersion.ToText() + " we are so very sorry about that"); return; } if (h.Version < MinecraftServer.FrontendVersion) { clientThread.State = "Handshake too low version"; Close("Upgrade your client to " + MinecraftServer.FrontendVersion.ToText()); return; } //Login var l = new LoginStart(PacketReader.ReadHandshake(clientStream)); clientThread.State = "LoginStart Received " + l.Name; unverifiedUsername = l.Name; #if DEBUGx var names = new string[] { "travelcraft2012", "nuxas", "drjanitor" }; unverifiedUsername = names[logincount++ % names.Length]; #endif if (unverifiedUsername.Length == 0 || unverifiedUsername.Length > 16) { clientThread.State = "Handshake wrong username length"; Close("Bad username"); Console.WriteLine("Wrong username length: " + unverifiedUsername.Length); return; } //Set Compression var compression = new SetCompression(); SendToClientInternal(compression); maxUncompressed = compression.MaxSize; //Send encryption request clientThread.State = "Handshake: Sending encryption request"; //Initiate ID var r = new Random(); ID = new byte[8]; r.NextBytes(ID); SendToClientInternal(new EncryptionRequest(Authentication.McHex(ID), MinecraftServer.RsaBytes)); clientThread.State = "Handshake: Sent encryption request, reading response"; //Read enc response int erSize; var erBuffer = PacketReader.Read(clientStream, out erSize); if (erSize != 0) { erBuffer = Compression.Decompress(erBuffer, erSize); } var er = new EncryptionResponse(erBuffer); clientThread.State = "Handshake: Got enc resp"; CryptoMC cryptoStream = new CryptoMC(clientStream, er); //Verify user clientThread.WatchdogTick = DateTime.Now; clientThread.State = "Handshake: loading proxy data"; Settings = LoadProxyPlayer(unverifiedUsername); if (IPAddress.IsLoopback(RemoteEndPoint.Address)) { MinecraftUsername = unverifiedUsername; Log.WritePlayer(this, "Succesful login from (local) " + RemoteEndPoint); } else { clientThread.State = "Handshake: Verifying login credentials"; string error = Authentication.VerifyUserLogin(unverifiedUsername, cryptoStream.SharedKey, ID); if (error != null) { //Unauthorized Log.WriteAuthFail(unverifiedUsername, RemoteEndPoint, error); Close("Mojang says " + error); return; } else { MinecraftUsername = unverifiedUsername; Log.WritePlayer(this, "Login from " + RemoteEndPoint + " " + Country); } } clientThread.State = "Handshake: Logged in"; //Get UUID try { Settings.UUID = UsernameUUID.GetUUID(MinecraftUsername); //Saved further down Debug.WriteLine("Real UUID for " + MinecraftUsername + " is " + Settings.UUID); } catch (Exception) { Debug.WriteLine("Failed to get UUID for MinecraftName " + MinecraftUsername); } clientThread.WatchdogTick = DateTime.Now; MineProxy.Inbox.Status(this); //start encryption clientStream = cryptoStream; SendToClientInternal(new LoginSuccess(Settings.UUID, MinecraftUsername)); clientThread.User = MinecraftUsername; clientThread.State = "Logged in"; EntityID = freeEID; //Math.Abs(unverifiedUsername.GetHashCode()); freeEID += 5000; //Login reply to client JoinGame lr = new JoinGame(); lr.ClientVersion = 0; lr.Difficulty = 0; lr.Dimension = 0; lr.EntityID = EntityID; lr.MaxPlayers = (byte)MinecraftServer.PlayerListSlots; lr.GameMode = 0; SendToClient(lr); Phase = Phases.Gaming; Queue = new SendQueue(this); PlayerList.LoginPlayer(this); SaveProxyPlayer(); string name = h.Host.ToLowerInvariant().Split('.')[0]; if (name == "con") { SetWorld(World.Construct); } else { SetWorld(World.Main); } //Handshake complete }
/// <summary> Blocks until acknowledgement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowledge command. </param> /// <param name="sendQueueState"></param> /// <returns> A received command. </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout, SendQueue sendQueueState) { // Wait for matching command return(_receiveCommandQueue.WaitForCmd(timeout, ackCmdId, sendQueueState) ?? new ReceivedCommand()); }
public void SaveData() { //// 1. character 정보 Update-> CentralInfoManager, EnchantManage Param param_character = new Param(); param_character.Add("level", characterStatus.Level); param_character.Add("rebirth", characterStatus.Rebirth); param_character.Add("currExp", characterStatus.CurrExp); param_character.Add("lp", characterStatus.LP); param_character.Add("strength_auto", characterStatus.Strength_Auto); param_character.Add("agility_auto", characterStatus.Agility_Auto); param_character.Add("dex_auto", characterStatus.Dex_Auto); param_character.Add("lucky_auto", characterStatus.Lucky_Auto); param_character.Add("strength_lp", characterStatus.Strength_LP); param_character.Add("agility_lp", characterStatus.Agility_LP); param_character.Add("dex_lp", characterStatus.Dex_LP); param_character.Add("lucky_lp", characterStatus.Lucky_LP); param_character.Add("isBossDungeonEnter", centralInfoManager.isBossDungeonEnter); param_character.Add("isEquipUpgraded", centralInfoManager.isEquipUpgraded); param_character.Add("isAtkBuffTutorial", tutorialManager.isAtkBuffTutorial); param_character.Add("isGoldBuffTutorial", tutorialManager.isGoldBuffTutorial); //yield return GameManager.YieldInstructionCache.WaitForEndOfFrame; //// equip 정보 Update-> CentralInfoManager, EnchantManage int[] equipLook = new int[CentralInfoManager.EQUIPKIND]; var eachEquipCount = TableData.Item_Name.Count / CentralInfoManager.EQUIPKIND; int[] weapon_Level = new int[eachEquipCount]; int[] head_Level = new int[eachEquipCount]; int[] chest_Level = new int[eachEquipCount]; int[] gloves_Level = new int[eachEquipCount]; int[] pants_Level = new int[eachEquipCount]; int[] shoes_Level = new int[eachEquipCount]; int[] back_Level = new int[eachEquipCount]; int[] face_Level = new int[eachEquipCount]; int[] equipState_weapon = new int[eachEquipCount]; int[] equipState_head = new int[eachEquipCount]; int[] equipState_chest = new int[eachEquipCount]; int[] equipState_gloves = new int[eachEquipCount]; int[] equipState_pants = new int[eachEquipCount]; int[] equipState_shoes = new int[eachEquipCount]; int[] equipState_back = new int[eachEquipCount]; int[] equipState_face = new int[eachEquipCount]; double[] weaponStat = new double[eachEquipCount]; double[] headStat = new double[eachEquipCount]; double[] chestStat = new double[eachEquipCount]; double[] glovesStat = new double[eachEquipCount]; double[] pantsStat = new double[eachEquipCount]; double[] shoesStat = new double[eachEquipCount]; double[] backStat = new double[eachEquipCount]; double[] faceStat = new double[eachEquipCount]; for (int i = 0; i < CentralInfoManager.EQUIPKIND; i++) { equipLook[i] = centralInfoManager.equipLook[i]; } for (int i = 0; i < eachEquipCount; i++) { weapon_Level[i] = centralInfoManager.weapon_Level[i]; head_Level[i] = centralInfoManager.head_Level[i]; chest_Level[i] = centralInfoManager.chest_Level[i]; gloves_Level[i] = centralInfoManager.gloves_Level[i]; pants_Level[i] = centralInfoManager.pants_Level[i]; shoes_Level[i] = centralInfoManager.shoes_Level[i]; back_Level[i] = centralInfoManager.back_Level[i]; face_Level[i] = centralInfoManager.face_Level[i]; equipState_weapon[i] = equipManager.equipState_weapon[i]; equipState_head[i] = equipManager.equipState_head[i]; equipState_chest[i] = equipManager.equipState_chest[i]; equipState_gloves[i] = equipManager.equipState_gloves[i]; equipState_pants[i] = equipManager.equipState_pants[i]; equipState_shoes[i] = equipManager.equipState_shoes[i]; equipState_back[i] = equipManager.equipState_back[i]; equipState_face[i] = equipManager.equipState_face[i]; weaponStat[i] = (double)equipManager.weaponStat[i]; headStat[i] = (double)equipManager.headStat[i]; chestStat[i] = (double)equipManager.chestStat[i]; glovesStat[i] = (double)equipManager.glovesStat[i]; pantsStat[i] = (double)equipManager.pantsStat[i]; shoesStat[i] = (double)equipManager.shoesStat[i]; backStat[i] = (double)equipManager.backStat[i]; faceStat[i] = (double)equipManager.faceStat[i]; } param_character.Add("equipLook", equipLook); param_character.Add("weapon_Level", weapon_Level); param_character.Add("head_Level", head_Level); param_character.Add("chest_Level", chest_Level); param_character.Add("gloves_Level", gloves_Level); param_character.Add("pants_Level", pants_Level); param_character.Add("shoes_Level", shoes_Level); param_character.Add("back_Level", back_Level); param_character.Add("face_Level", face_Level); param_character.Add("equipState_weapon", equipState_weapon); param_character.Add("equipState_head", equipState_head); param_character.Add("equipState_chest", equipState_chest); param_character.Add("equipState_gloves", equipState_gloves); param_character.Add("equipState_pants", equipState_pants); param_character.Add("equipState_shoes", equipState_shoes); param_character.Add("equipState_back", equipState_back); param_character.Add("equipState_face", equipState_face); param_character.Add("weaponStat", weaponStat); param_character.Add("headStat", headStat); param_character.Add("chestStat", chestStat); param_character.Add("glovesStat", glovesStat); param_character.Add("pantsStat", pantsStat); param_character.Add("shoesStat", shoesStat); param_character.Add("backStat", backStat); param_character.Add("faceStat", faceStat); ////rank 정보 Insert -> RankManager param_character.Add("accumulatedStage", RankManager.accumulatedStage); param_character.Add("bestStage", RankManager.bestStage); param_character.Add("myStat", RankManager.myStat); param_character.Add("bossDungeonStage", RankManager.bossDungeonStage); param_character.Add("rebirthCount", RankManager.rebirthCount); //yield return GameManager.YieldInstructionCache.WaitForEndOfFrame; //// 2. currency 정보 Update Param param_currency = new Param(); param_currency.Add("gold", currencyManager.Gold.ToString()); param_currency.Add("jewel", currencyManager.Jewel.ToString()); param_currency.Add("token", currencyManager.Token.ToString()); ////item 정보 int[] boxCountList = new int[CentralInfoManager.NUMBEROFBOXKEYKINDS]; int[] keyCountList = new int[CentralInfoManager.NUMBEROFBOXKEYKINDS]; int[] petLevel = new int[PetManager.PETKINDS]; double[] petStat = new double[PetManager.PETKINDS]; string[] isPetBuy = new string[PetManager.PETKINDS]; for (int i = 0; i < CentralInfoManager.NUMBEROFBOXKEYKINDS; i++) { boxCountList[i] = CentralInfoManager.boxCountList[i]; keyCountList[i] = CentralInfoManager.keyCountList[i]; } for (int i = 0; i < PetManager.PETKINDS; i++) { petLevel[i] = petManager.petLevel[i]; petStat[i] = petManager.petStat[i]; isPetBuy[i] = petManager.isPetBuy[i].ToString(); } param_currency.Add("boxCountList", boxCountList); param_currency.Add("keyCountList", keyCountList); param_currency.Add("petLevel", petLevel); param_currency.Add("petStat", petStat); param_currency.Add("isPetBuy", isPetBuy); param_currency.Add("mountingPetIndex", petMenu.mountingPetIndex); param_currency.Add("ticket_nickNameChange", CentralInfoManager.ticket_nickNameChange); param_currency.Add("rebirthCoupon", CentralInfoManager.rebirthCoupon); param_currency.Add("anyOpenKey", CentralInfoManager.anyOpenKey); param_currency.Add("lpPotion", CentralInfoManager.lpPotion); param_currency.Add("rebirthCoupon_DailyCount", CentralInfoManager.rebirthCoupon_DailyCount); param_currency.Add("lpPotion_DailyCount", CentralInfoManager.lpPotion_DailyCount); param_currency.Add("boxOpenCount_ad", centralInfoManager.boxOpenCount_ad); param_currency.Add("boxOpenCoolTime_ad", centralInfoManager.boxOpenCoolTime_ad); param_currency.Add("monthlyJewelProductBuyDate", centralInfoManager.monthlyJewelProductBuyDate); param_currency.Add("monthlyJewelPayments", centralInfoManager.monthlyJewelPayments); //yield return GameManager.YieldInstructionCache.WaitForEndOfFrame; //// 3. setting 정보 Update Param param_setting = new Param(); int[] buffCoolTime = new int[BuffManager.BUFF_KINDS]; int[] buffCoolTimeStandard = new int[BuffManager.BUFF_KINDS]; string[] isBuffing = new string[BuffManager.BUFF_KINDS]; string[] isBuffAdRemoved = new string[BuffManager.BUFF_KINDS]; for (int i = 0; i < BuffManager.BUFF_KINDS; i++) { buffCoolTime[i] = buffManager.buffCoolTime[i]; buffCoolTimeStandard[i] = buffManager.buffCoolTimeStandard[i]; isBuffing[i] = buffManager.isBuffing[i].ToString(); isBuffAdRemoved[i] = centralInfoManager.isBuffAdRemoved[i].ToString(); } param_setting.Add("speedDuration", speedManager.speedDuration); param_setting.Add("speed", speedManager.speed.ToString()); param_setting.Add("buffCoolTime", buffCoolTime); param_setting.Add("buffCoolTimeStandard", buffCoolTimeStandard); param_setting.Add("isBuffing", isBuffing); param_setting.Add("isBuffAdRemoved", isBuffAdRemoved); param_setting.Add("isTheDayClose", NotificationManager.instance.isTheDayClose); ////stage 정보 Update -> SpeedManager, CentralInfoManager param_setting.Add("stageCount", CentralInfoManager.stageCount.ToString()); param_setting.Add("rebirthStartStage", CentralInfoManager.rebirthStartStage.ToString()); param_setting.Add("regionCount", CentralInfoManager.regionCount.ToString()); param_setting.Add("bestStage", CentralInfoManager.bestStage.ToString()); param_setting.Add("ticket_bossDungeon", currencyManager.Ticket_BossDungeon); param_setting.Add("boss_day", CentralInfoManager.boss_day); param_setting.Add("boss_adCount", CentralInfoManager.boss_adCount); param_setting.Add("bossStageCount", CentralInfoManager.bossStageCount); //// param_setting.Add("isHotTimePush_lunch", CentralInfoManager.isHotTimePush_lunch); param_setting.Add("isHotTimePush_afternoon", CentralInfoManager.isHotTimePush_afternoon); param_setting.Add("isDungeonConquer", CentralInfoManager.isDungeonConquer); // yield return GameManager.YieldInstructionCache.WaitForEndOfFrame; saving = true; StartCoroutine(SaveCHKCO()); try { SendQueue.Enqueue(Backend.GameInfo.Update, "character", indate_cha, param_character, updateComplete => { if (updateComplete.IsSuccess()) { saving = true; } else if (!updateComplete.IsSuccess() || updateComplete.IsServerError()) { notSaving = true; } }); SendQueue.Enqueue(Backend.GameInfo.Update, "currency", indate_currency, param_currency, updateComplete => { if (updateComplete.IsSuccess()) { saving = true; } else if (!updateComplete.IsSuccess() || updateComplete.IsServerError()) { notSaving = true; } }); SendQueue.Enqueue(Backend.GameInfo.Update, "setting", indate_setting, param_setting, updateComplete => { if (updateComplete.IsSuccess()) { saving = false; } else if (!updateComplete.IsSuccess() || updateComplete.IsServerError()) { notSaving = true; } }); } catch (System.Exception e) { Debug.Log("저장 catch ##########################"); //RestartSaving(); GameManager.SaveLogToServer("정보 저장 에러 발생", e.ToString(), "에러"); } }
public long PlayDuetStep(long step) { if (step < 0 || step >= Instructions.Count) { return(step); } Instruction cmd = Instructions[(int)step]; long next = step; switch (cmd.CmdType) { case DuetCmds.snd: SendQueue.Enqueue(cmd.A ?? Registers[cmd.RegA]); Sends++; next++; break; case DuetCmds.set: Registers[cmd.RegA] = cmd.B ?? Registers[cmd.RegB]; next++; break; case DuetCmds.add: Registers[cmd.RegA] += cmd.B ?? Registers[cmd.RegB]; next++; break; case DuetCmds.mul: Registers[cmd.RegA] *= cmd.B ?? Registers[cmd.RegB]; next++; break; case DuetCmds.mod: Registers[cmd.RegA] %= cmd.B ?? Registers[cmd.RegB]; next++; break; case DuetCmds.rcv: if (RecieveQueue.Count > 0) { Blocked = false; Registers[cmd.RegA] = RecieveQueue.Dequeue(); next++; } else { Blocked = true; return(next); } break; case DuetCmds.jgz: long test = cmd.A ?? Registers[cmd.RegA]; if (test > 0) { // jump next += cmd.B ?? Registers[cmd.RegB]; } else { next++; } break; default: break; } return(next); }
public YBClient4(ConnectionSettings settings) { _settings = settings; _sendQueue = new SendQueue(settings.SentFolder); }
public void PrepareForCmd(int cmdId, SendQueue sendQueueState) { _receivedCommandSignal.PrepareForWait(cmdId, sendQueueState); }
/// <summary> /// 请求Gram类 /// </summary> /// <returns></returns> public static SendBuffer Instance() { return(new SendBuffer(SendQueue.AcquireBuffer())); }
private async void Start(string serverIp, short serverPort) { Func <RT_MSG_TYPE, CipherContext, ICipher> getCipher = (id, context) => { switch (context) { case CipherContext.RC_CLIENT_SESSION: return(_sessionCipher); case CipherContext.RSA_AUTH: return(AuthKey); default: return(null); } }; _group = new MultithreadEventLoopGroup(); _scertHandler = new ScertServerHandler(); // Initialize on connect _scertHandler.OnChannelActive += async(channel) => { RecvQueue.Clear(); SendQueue.Clear(); State = ClientState.CONNECTED; await OnConnected(channel); }; // _scertHandler.OnChannelInactive += async(channel) => { await OnDisconnected(channel); }; // Queue all incoming messages _scertHandler.OnChannelMessage += (channel, message) => { RecvQueue.Enqueue(message); // Log if id is set if (message.CanLog()) { Logger.Info($"RECV {channel}: {message}"); } }; try { var bootstrap = new Bootstrap(); bootstrap .Group(_group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new ScertEncoder()); pipeline.AddLast(new ScertIEnumerableEncoder()); pipeline.AddLast(new ScertTcpFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, Constants.MEDIUS_MESSAGE_MAXLEN, 1, 2, 0, 0, false)); pipeline.AddLast(new ScertDecoder(_sessionCipher, AuthKey)); pipeline.AddLast(_scertHandler); })); try { _boundChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(serverIp), serverPort)); } catch (Exception e) { Logger.Error($"Failed to connect to server {e}"); State = ClientState.DISCONNECTED; return; } } finally { } }
// 发送消息请求 public string SendRequest(ByteString body, int subcmd, NetResponseCallback response, Action <ResponseEvent> callback, string cmd, string seq) { if (seq.Length == 0) { seq = Guid.NewGuid().ToString(); var sendQueueVal = new SendQueueValue { Time = DateTime.Now, IsSocketSend = false, Cmd = (int)subcmd, resend = () => this.SendRequest(body, subcmd, response, callback, cmd, seq), response = msg => { response(true, msg, callback); DeleteSendQueue(seq); } }; sendQueueVal.sendSuccess = () => { // if(Socket.Id == 1) Debugger.Log("handle send success {0}", seq); sendQueueVal.IsSocketSend = true; }; sendQueueVal.remove = () => { DeleteSendQueue(seq); }; sendQueueVal.sendFail = (errCode, errMsg) => { var errMessage = "消息发送失败," + errMsg + "[" + errCode + "]"; var rspWrap1 = new ClientSendServerRspWrap1 { Seq = seq, ErrCode = errCode, ErrMsg = errMessage }; response(false, new DecodeRspResult { RspWrap1 = rspWrap1, }, callback); DeleteSendQueue(seq); }; AddSendQueue(seq, sendQueueVal); } // PB request = new PB(); var qAppRequest = new ClientSendServerReqWrap1 { Version = RequestHeader.Version, AppName = RequestHeader.AppName, ClientIp = RequestHeader.ClientIp, ServiceIp = RequestHeader.ServiceIp, Business = RequestHeader.Business, AuthKey = RequestHeader.AuthKey, AuthType = RequestHeader.AuthType, AuthIp = RequestHeader.AuthIp, GameId = RequestHeader.GameId, Uid = RequestHeader.Uid, PlayerId = RequestHeader.PlayerId, Cmd = cmd, Seq = seq }; var accessReq = new ClientSendServerReqWrap2(); accessReq.Cmd = (ProtoCmd)subcmd; var data = Pb.EncodeReq(qAppRequest, accessReq, body); if (data.Length > _maxDataLength) { SendQueueValue val = null; SendQueue.TryGetValue(seq + "", out val); var timer = new Timer(); timer.SetTimeout(() => { if (val != null) { val.sendFail((int)QAppProtoErrCode.EcSdkSendFail, "数据长度超限"); } }, 0); return(seq); } var reqData = BuildData(data); return(this.Send(reqData, seq, (ProtoCmd)subcmd)); }
internal void Enqueue(Packet data) { BeginSend.Set(); SendQueue.Enqueue(data); }
public async Task Post(Teste value) { await SendQueue.SendMessagesAsync(value); await SendQueue.Finish(); }
private void ProcessReply(string line) { App.ViewModel.AddDebugLog(string.Format("<{0}", line)); var pattern = "^([A-Z]+)([:][A-Z0-9_]+)?(|.+)?$"; var match = Regex.Match(line, pattern); if (match.Success) { var command = match.Groups[1].Value; var parameter = string.IsNullOrEmpty(match.Groups[2].Value) ? null : match.Groups[2].Value.Substring(1); var addict = string.IsNullOrWhiteSpace(match.Groups[3].Value) ? null : match.Groups[3].Value.Substring(1).Trim(); dynamic json = string.IsNullOrEmpty(addict) ? null : JsonConvert.DeserializeObject <dynamic>(addict, new JsonSerializerSettings { Error = (s, e) => { e.ErrorContext.Handled = true; } }); if (json == null) { json = JsonConvert.DeserializeObject <dynamic>("{}"); } switch (command) { case "BYE": Transport.Shutdown(SocketShutdown.Both); Transport.Close(); break; case "G": foreach (var c in (json as JArray).Cast <JValue>().Select(s => s.Value.ToString().Split('|')).ToList()) { Do(() => { App.ViewModel.GroupsModel.AddCoordinate(c[0], Coordinate.Create(c[1])); }); } break; case "GA": CGroup(); break; case "GD": CGroup(); break; case "GE": CGroup(); break; case "GP": var group = JsonConvert.DeserializeObject <Group>(addict); Do(() => { App.ViewModel.GroupsModel.SetUsers(parameter, group.Users); }); CGpr(parameter); break; case "GPR": break; case "GROUP": Do(() => { lock (App.ViewModel.GroupsModel.Groups) { App.ViewModel.GroupsModel.Groups = JsonConvert.DeserializeObject <List <Group> >(addict); } }); break; case "INIT": if (json["error"] != null) { Disconnect(); } else { Do(() => { App.ViewModel.TrackerId = ((JValue)json["id"]).ToObject <string>(); }); CMd(); } break; case "MD": Status = ConnectionStatus.Connected; while (SendQueue.Count > 0) { Send(SendQueue.Dequeue()); } Do(() => { App.ViewModel.MessageOfTheDay = addict; }); break; case "P": break; case "PP": CP(); break; case "RC": break; case "TO": Do(() => { App.ViewModel.SessionId = ((JValue)json["url"]).ToObject <string>(); }); break; case "T": break; case "TC": Do(() => { App.ViewModel.SessionId = null; }); break; default: if (Debugger.IsAttached) { Debugger.Break(); } break; } } }
public MailMessageItem SaveMessage(int id, IEnumerable <MailAttachment> attachments, IEnumerable <string> to, IEnumerable <string> bcc, IEnumerable <string> cc, string mimeMessageId, string mimeReplyToId, string from, string body, bool importance, IEnumerable <int> tags, string streamId, string subject) { if (id < 1) { id = 0; } var item = new MailSendItem { Attachments = new List <MailAttachment>(attachments), Bcc = new List <string>(bcc), Cc = new List <string>(cc), MimeReplyToId = mimeReplyToId, MimeMessageId = string.IsNullOrEmpty(mimeMessageId) ? MailBoxManager.CreateMessageId() : mimeMessageId, From = from, HtmlBody = body, Important = importance, Labels = new List <int>(tags), StreamId = streamId, Subject = subject, To = new List <string>(to) }; var accounts = MailBoxManager.GetAccountInfo(TenantId, Username).ToAddressData(); var mailAddress = new MailAddress(item.From); var account = accounts.FirstOrDefault(a => a.Email.ToLower().Equals(mailAddress.Address)); if (account == null) { throw new ArgumentException("Mailbox not found"); } if (account.IsGroup) { throw new InvalidOperationException("Saving emails from a group address is forbidden"); } if (id > 0) { var message = GetMessage(id, false, false, false); if (message.Folder != MailFolder.Ids.drafts) { throw new InvalidOperationException("Saving emails is permitted only in the Drafts folder"); } } return(SendQueue.SaveToDraft(TenantId, Username, item, id, account.MailboxId)); }
public ReceivedCommand WaitForCmd(int timeOut, int cmdId, SendQueue sendQueueState) { return(_receivedCommandSignal.WaitForCmd(timeOut, cmdId, sendQueueState)); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState) { return(SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue)); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState) { return SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue); }
/// <summary> /// dispose /// </summary> protected virtual void Free() { var arrPacket = this._sendQueue.Close(); this._sendQueue = null; if (arrPacket != null && arrPacket.Length > 0) { foreach (var packet in arrPacket) this.OnSendCallback(new SendCallbackEventArgs(packet, SendCallbackStatus.Failed)); } this._saeSend.Completed -= new EventHandler<SocketAsyncEventArgs>(this.SendAsyncCompleted); this._saeSend.UserToken = null; this._host.ReleaseSocketAsyncEventArgs(this._saeSend); this._saeSend = null; this._saeReceive.Completed -= new EventHandler<SocketAsyncEventArgs>(this.ReceiveAsyncCompleted); this._saeReceive.UserToken = null; this._host.ReleaseSocketAsyncEventArgs(this._saeReceive); this._saeReceive = null; this._socket = null; this._host = null; }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="useQueue"> Property to optionally bypass the queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState, UseQueue useQueue) { //_sendCommandLogger.LogLine(sendCommand.CommandString()); var synchronizedSend = (sendCommand.ReqAc || useQueue == UseQueue.BypassQueue); if (sendQueueState == SendQueue.ClearQueue ) { // Clear receive queue _receiveCommandQueue.Clear(); } if (receiveQueueState == ReceiveQueue.ClearQueue ) { // Clear send queue _sendCommandQueue.Clear(); } // If synchronized sending, the only way to get command at end of queue is by waiting if (sendQueueState == SendQueue.WaitForEmptyQueue || (synchronizedSend && sendQueueState == SendQueue.AtEndQueue) ) { while (_sendCommandQueue.Count > 0) Thread.Sleep(1); } if (receiveQueueState == ReceiveQueue.WaitForEmptyQueue) { while (_receiveCommandQueue.Count>0) Thread.Sleep(1); } if (synchronizedSend) { return SendCommandSync(sendCommand, sendQueueState); } if (sendQueueState != SendQueue.AtEndQueue) { // Put command at top of command queue _sendCommandQueue.SendCommand(sendCommand); } else { // Put command at bottom of command queue _sendCommandQueue.QueueCommand(sendCommand); } return new ReceivedCommand(); }
public virtual void SendPacket(byte[] datagram) { SendQueue.Enqueue(datagram); }
/// <summary> Blocks until acknowlegdement reply has been received. </summary> /// <param name="ackCmdId"> acknowledgement command ID </param> /// <param name="timeout"> Timeout on acknowlegde command. </param> /// <param name="sendQueueState"></param> /// <returns> A received command. </returns> private ReceivedCommand BlockedTillReply(int ackCmdId, int timeout, SendQueue sendQueueState) { // Disable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Stop; var start = TimeUtils.Millis; var time = start; var acknowledgeCommand = new ReceivedCommand(); while ((time - start < timeout) && !acknowledgeCommand.Ok) { time = TimeUtils.Millis; Thread.Yield(); acknowledgeCommand = CheckForAcknowledge(ackCmdId, sendQueueState); } // Re-enable invoking command callbacks _receiveCommandQueue.ThreadRunState = CommandQueue.ThreadRunStates.Start; return acknowledgeCommand; }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="useQueue"> Property to optionally bypass the queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState, UseQueue useQueue) { var synchronizedSend = (sendCommand.ReqAc || useQueue == UseQueue.BypassQueue); // When waiting for an acknowledge, it is typically best to wait for the ReceiveQueue to be empty // This is thus the default state if (sendCommand.ReqAc && receiveQueueState == ReceiveQueue.Default) { receiveQueueState = ReceiveQueue.WaitForEmptyQueue; } if (sendQueueState == SendQueue.ClearQueue ) { // Clear receive queue _receiveCommandQueue.Clear(); } if (receiveQueueState == ReceiveQueue.ClearQueue ) { // Clear send queue _sendCommandQueue.Clear(); } // If synchronized sending, the only way to get command at end of queue is by waiting if (sendQueueState == SendQueue.WaitForEmptyQueue || (synchronizedSend && sendQueueState == SendQueue.AtEndQueue) ) { SpinWait.SpinUntil(() => _sendCommandQueue.IsEmpty); } if (receiveQueueState == ReceiveQueue.WaitForEmptyQueue) { SpinWait.SpinUntil(() => _receiveCommandQueue.IsEmpty); } if (synchronizedSend) { return SendCommandSync(sendCommand, sendQueueState); } if (sendQueueState != SendQueue.AtEndQueue) { // Put command at top of command queue _sendCommandQueue.SendCommand(sendCommand); } else { // Put command at bottom of command queue _sendCommandQueue.QueueCommand(sendCommand); } return new ReceivedCommand { CommunicationManager = _communicationManager }; }
/// <summary> Listen to the receive queue and check for a specific acknowledge command. </summary> /// <param name="ackCmdId"> acknowledgement command ID. </param> /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param> /// <returns> The first received command that matches the command ID. </returns> private ReceivedCommand CheckForAcknowledge(int ackCmdId, SendQueue sendQueueState) { // Read command from received queue CurrentReceivedCommand = _receiveCommandQueue.DequeueCommand(); if (CurrentReceivedCommand != null) { // Check if received command is valid if (!CurrentReceivedCommand.Ok) return CurrentReceivedCommand; // If valid, check if is same as command we are waiting for if (CurrentReceivedCommand.CmdId == ackCmdId) { // This is command we are waiting for, so return return CurrentReceivedCommand; } // This is not command we are waiting for if (sendQueueState != SendQueue.ClearQueue) { // Add to queue for later processing _receiveCommandQueue.QueueCommand(CurrentReceivedCommand); } } // Return not Ok received command return new ReceivedCommand(); }
// worker function for routing IPv6 packets public void WorkerRouter() { while (SpoofingStarted) { // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying) int bufferSize = 2048; // copy packets to threadRoutingQueue lock (PacketQueueRouting) { foreach (Packet packet in PacketQueueRouting) { threadQueueRouting.Add(packet); bufferSize += packet.Bytes.Length; } PacketQueueRouting.Clear(); } if (threadQueueRouting.Count > 0) { var sendQueue = new SendQueue(bufferSize); // loop through packets and change MAC addresses foreach (Packet packet in threadQueueRouting) { if (packet == null) { continue; } var ethernetPacket = (packet as EthernetPacket); if (ethernetPacket == null) { continue; } var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet)); var sourceIP = ip.SourceAddress.ToString(); var destinationIP = ip.DestinationAddress.ToString(); var destinationMAC = ethernetPacket.DestinationHwAddress.ToString(); if (sourceIP == deviceInfo.IPv6 || destinationIP == deviceInfo.IPv6) { continue; } // skip local network traffic if ((sourceIP.Contains(prefix.Replace("::", ":")) && destinationIP.Contains(prefix.Replace("::", ":"))) || (sourceIP.Contains("fe80::") || destinationIP.Contains("fe80::"))) { continue; } // check for IPv6 - MAC entry existance (check only addresses from this network) and add it if necessary (we need this because scanner cannot pick up IPv6 addresses of all the targets) if (sourceIP.Contains(prefix.Replace("::", ":")) && !IPv6toMACTargets.ContainsKey(sourceIP) && !sourceIP.Contains("fe80::")) { lock (IPv6toMACTargets) { IPv6toMACTargets.Add(sourceIP, ethernetPacket.SourceHwAddress); } } // incoming packets (internet -> nighthawk) - change destination MAC back to target's MAC if (IPv6toMACTargets.ContainsKey(destinationIP) && (destinationMAC != IPv6toMACTargets[destinationIP].ToString())) { ethernetPacket.SourceHwAddress = physicalAddress; ethernetPacket.DestinationHwAddress = IPv6toMACTargets[destinationIP]; if (ethernetPacket.Bytes != null) { sendQueue.Add(packet.Bytes); } } // outgoing packets (targets -> nighthawk) - change destination MAC to gateway's MAC if (IPv6toMACTargets.ContainsKey(sourceIP) && (destinationMAC != IPv6toMACTargets[gatewayIPv6].ToString())) { ethernetPacket.SourceHwAddress = physicalAddress; ethernetPacket.DestinationHwAddress = IPv6toMACTargets[gatewayIPv6]; if (ethernetPacket.Bytes != null) { sendQueue.Add(packet.Bytes); } } } sendQueue.Transmit(device, SendQueueTransmitModes.Normal); sendQueue.Dispose(); threadQueueRouting.Clear(); } else { Thread.Sleep(1); } } return; }
/// <summary> Directly executes the send string operation. </summary> /// <param name="commandsString"> The string to sent. </param> /// <param name="sendQueueState"> Property to optionally clear the send and receive queues. </param> /// <returns> The received command is added for compatibility. It will not yield a response. </returns> public ReceivedCommand ExecuteSendString(String commandsString, SendQueue sendQueueState) { lock (_sendCommandDataLock) { if (PrintLfCr) _communicationManager.WriteLine(commandsString); else { _communicationManager.Write(commandsString); } } return new ReceivedCommand(); }
protected override void ReceiverRunClient() { using (TextReader reader = new StreamReader(base.clientStream)) { clientThread.WatchdogTick = DateTime.Now.AddMinutes(3); MinecraftUsername = LoginPrompt(reader); if (MinecraftUsername == null) { return; } EntityID = 1;//Not used clientThread.User = MinecraftUsername; clientThread.State = "Logged in"; Phase = Phases.Gaming; clientThread.State = "Gaming"; Queue = new SendQueue(this); PlayerList.LoginPlayer(this); clientThread.WatchdogTick = DateTime.Now.AddHours(3); //Logged in string pl = "Players: "; foreach (var p in PlayerList.List) { if (p.Settings.Cloaked != null) { continue; } if (p.MinecraftUsername == "Player") { continue; } pl += p.Name + ", "; } writer.WriteLine(pl); while (true) { string line = reader.ReadLine(); if (line == null) { return; } line = line.Trim(' ', '\n', '\r', '\t'); if (line == "exit") { return; } if (line == "") { continue; } ChatLoop(line); clientThread.WatchdogTick = DateTime.Now.AddHours(3); } } }
public void Send(string content, UInt16 port, string address) { SuzukiMessage msg = new SuzukiMessage(content, port, address); SendQueue.Add(msg); }
public void ConstructPacket(ICaptureDevice device) { // open device SendQueue QPackets = new SendQueue((int)((CaptureFileReaderDevice)device).FileSize); Packet packet; }
/// <summary> /// Initializes a new instance of the <see cref="SendBatchMessagesActivity"/> class. /// </summary> /// <param name="sendQueue">Send queue service.</param> public SendBatchMessagesActivity( SendQueue sendQueue) { this.sendQueue = sendQueue ?? throw new ArgumentNullException(nameof(sendQueue)); }
public YBClient4(ConnectionSettings settings, Action<string> logCallback) { _logCB = logCallback; _settings = settings; _sendQueue = new SendQueue(settings.SentFolder); }
static void Main(string[] args) { //显示SharpPcap版本 string ver = SharpPcap.Version.VersionString; Console.WriteLine("SharpPcap {0}", ver); //获取网络设备 var devices = LivePcapDeviceList.Instance; if (devices.Count < 1) { Console.WriteLine("找不到网络设备"); return; } Console.WriteLine(); Console.WriteLine("以下是目前本计算机上的活动网络设备:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; foreach (LivePcapDevice dev in devices) { Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } //选择要监听的网络设备 Console.WriteLine(); Console.Write("-- 请选择一个需要监听的网络设备: "); i = int.Parse(Console.ReadLine()); LivePcapDevice device = devices[i]; Console.Write("-- 请选择操作:监听通讯[C/c],多线程监听通讯[T/t],监听统计[F/f],发送随机数据包[S/s]? "); string resp = Console.ReadLine().ToUpper(); while (!(resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T") || resp.StartsWith("S"))) { resp = Console.ReadLine().ToUpper(); } try { if (resp.StartsWith("C") || resp.StartsWith("F") || resp.StartsWith("T")) { //监听过滤条件 //string filter = "ip and tcp"; string filter = ""; //连接设备 System.Threading.Thread backgroundThread = null; int readTimeoutMilliseconds = 1000; if (resp.StartsWith("F")) { device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device.SetFilter(filter); device.Mode = CaptureMode.Statistics; //抓包统计 device.OnPcapStatistics += new StatisticsModeEventHandler(device_OnPcapStatistics); //抓包统计回调事件 } else if (resp.StartsWith("C")) { device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device.SetFilter(filter); device.Mode = CaptureMode.Packets; //抓数据包 showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情 device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); //抓数据包回调事件 } else { backgroundThread = new System.Threading.Thread(BackgroundThread); backgroundThread.Start(); device.Open(); device.SetFilter(filter); device.Mode = CaptureMode.Packets; //抓数据包 showDetails = resp.EndsWith("-A"); //当抓数据包时,检查是否要查看详情 device.OnPacketArrival += new PacketArrivalEventHandler(device_OnThreadPacketArrival); //抓数据包回调事件 } Console.WriteLine(); Console.WriteLine("-- 当前TCPdump过滤条件: \"{0}\"", filter); Console.WriteLine("-- 正在监听设备 {0}, 按 '回车' 键以停止监听...", device.Description); //开始监听 device.StartCapture(); //停止监听 Console.ReadLine(); device.StopCapture(); Console.WriteLine("-- 停止监听."); if (backgroundThread != null) { BackgroundThreadStop = true; backgroundThread.Join(); } } else if (resp.StartsWith("S")) { //连接设备 device.Open(); //生成随机数据包 byte[] bytes = GetRandomPacket(); try { //发送数据 device.SendPacket(bytes); SendQueue squeue = new SendQueue(2000); Console.WriteLine("-- 单个数据包发送成功."); for (int j = 0; j < 10; j++) { if (!squeue.Add(bytes)) { Console.WriteLine("-- 警告: 队列大小不足以存放所有数据包,将只发送部分数据包."); break; } } device.SendQueue(squeue, SendQueueTransmitModes.Synchronized); Console.WriteLine("-- 数据包队列发送完毕."); } catch (Exception e) { Console.WriteLine("-- " + e.Message); } } } catch (Exception e) { Console.WriteLine("-- " + e.Message); } finally { if (device.Opened) { //断开设备连接 Console.WriteLine(device.Statistics().ToString()); device.Close(); Console.WriteLine("-- 断开设备连接."); Console.Write("按 '回车' 键以退出..."); Console.Read(); } } }